Repository: wevm/wagmi Branch: main Commit: 5c7bfb6cf966 Files: 1808 Total size: 6.4 MB Directory structure: gitextract_arunh2_6/ ├── .agents/ │ ├── README.md │ └── skills/ │ └── wagmi-development/ │ └── SKILL.md ├── .changeset/ │ ├── README.md │ ├── brave-hens-rare.md │ ├── config.json │ ├── fix-tempo-webauthn-chain-id.md │ └── upset-trains-lick.md ├── .github/ │ ├── CODEOWNERS │ ├── CONTRIBUTING.md │ ├── DISCUSSION_TEMPLATE/ │ │ └── connector-request.yml │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.yml │ │ ├── config.yml │ │ └── docs_issue.yml │ ├── README.md │ ├── SECURITY.md │ ├── dependabot.yml │ ├── pull_request_template.md │ └── workflows/ │ ├── changesets.yml │ ├── issue-labeled.yml │ ├── lock-issue.yml │ ├── pull-request.yml │ ├── scorecard.yml │ └── verify.yml ├── .gitignore ├── .vscode/ │ ├── extensions.json │ ├── settings.json │ └── workspace.code-workspace ├── FUNDING.json ├── LICENSE ├── biome.json ├── package.json ├── packages/ │ ├── cli/ │ │ ├── CHANGELOG.md │ │ ├── README.md │ │ ├── package.json │ │ ├── src/ │ │ │ ├── cli.ts │ │ │ ├── commands/ │ │ │ │ ├── generate.test.ts │ │ │ │ ├── generate.ts │ │ │ │ ├── init.test.ts │ │ │ │ └── init.ts │ │ │ ├── config.test.ts │ │ │ ├── config.ts │ │ │ ├── errors.ts │ │ │ ├── exports/ │ │ │ │ ├── config.test.ts │ │ │ │ ├── config.ts │ │ │ │ ├── index.test-d.ts │ │ │ │ ├── index.test.ts │ │ │ │ ├── index.ts │ │ │ │ ├── plugins.test.ts │ │ │ │ └── plugins.ts │ │ │ ├── logger.test.ts │ │ │ ├── logger.ts │ │ │ ├── plugins/ │ │ │ │ ├── __fixtures__/ │ │ │ │ │ ├── foundry/ │ │ │ │ │ │ ├── .gitignore │ │ │ │ │ │ ├── foundry.toml │ │ │ │ │ │ └── src/ │ │ │ │ │ │ ├── Counter.sol │ │ │ │ │ │ └── Foo.sol │ │ │ │ │ └── hardhat/ │ │ │ │ │ ├── .gitignore │ │ │ │ │ ├── contracts/ │ │ │ │ │ │ ├── Counter.sol │ │ │ │ │ │ └── Foo.sol │ │ │ │ │ ├── hardhat.config.js │ │ │ │ │ └── package.json │ │ │ │ ├── __snapshots__/ │ │ │ │ │ ├── blockExplorer.test.ts.snap │ │ │ │ │ ├── etherscan.test.ts.snap │ │ │ │ │ ├── fetch.test.ts.snap │ │ │ │ │ ├── routescan.test.ts.snap │ │ │ │ │ └── sourcify.test.ts.snap │ │ │ │ ├── actions.test.ts │ │ │ │ ├── actions.ts │ │ │ │ ├── blockExplorer.test.ts │ │ │ │ ├── blockExplorer.ts │ │ │ │ ├── etherscan.test.ts │ │ │ │ ├── etherscan.ts │ │ │ │ ├── fetch.test.ts │ │ │ │ ├── fetch.ts │ │ │ │ ├── foundry.test.ts │ │ │ │ ├── foundry.ts │ │ │ │ ├── hardhat.test.ts │ │ │ │ ├── hardhat.ts │ │ │ │ ├── react.test.ts │ │ │ │ ├── react.ts │ │ │ │ ├── sourcify.test.ts │ │ │ │ └── sourcify.ts │ │ │ ├── types.ts │ │ │ ├── utils/ │ │ │ │ ├── findConfig.test.ts │ │ │ │ ├── findConfig.ts │ │ │ │ ├── format.test.ts │ │ │ │ ├── format.ts │ │ │ │ ├── getAddressDocString.test.ts │ │ │ │ ├── getAddressDocString.ts │ │ │ │ ├── getIsUsingTypeScript.test.ts │ │ │ │ ├── getIsUsingTypeScript.ts │ │ │ │ ├── loadEnv.test.ts │ │ │ │ ├── loadEnv.ts │ │ │ │ ├── packages.test.ts │ │ │ │ ├── packages.ts │ │ │ │ ├── resolveConfig.test.ts │ │ │ │ └── resolveConfig.ts │ │ │ └── version.ts │ │ ├── test/ │ │ │ ├── constants.ts │ │ │ ├── setup.ts │ │ │ └── utils.ts │ │ ├── tsconfig.build.json │ │ ├── tsconfig.json │ │ └── types/ │ │ └── fixturez.d.ts │ ├── connectors/ │ │ ├── CHANGELOG.md │ │ ├── README.md │ │ ├── package.json │ │ ├── src/ │ │ │ ├── baseAccount.test.ts │ │ │ ├── baseAccount.ts │ │ │ ├── coinbaseWallet.test.ts │ │ │ ├── coinbaseWallet.ts │ │ │ ├── exports/ │ │ │ │ ├── index.test.ts │ │ │ │ └── index.ts │ │ │ ├── metaMask.test.ts │ │ │ ├── metaMask.ts │ │ │ ├── porto.test.ts │ │ │ ├── porto.ts │ │ │ ├── safe.test.ts │ │ │ ├── safe.ts │ │ │ ├── version.ts │ │ │ ├── walletConnect.test.ts │ │ │ └── walletConnect.ts │ │ ├── tsconfig.build.json │ │ └── tsconfig.json │ ├── core/ │ │ ├── CHANGELOG.md │ │ ├── README.md │ │ ├── package.json │ │ ├── src/ │ │ │ ├── actions/ │ │ │ │ ├── call.test.ts │ │ │ │ ├── call.ts │ │ │ │ ├── codegen/ │ │ │ │ │ ├── createReadContract.test-d.ts │ │ │ │ │ ├── createReadContract.test.ts │ │ │ │ │ ├── createReadContract.ts │ │ │ │ │ ├── createSimulateContract.test-d.ts │ │ │ │ │ ├── createSimulateContract.test.ts │ │ │ │ │ ├── createSimulateContract.ts │ │ │ │ │ ├── createWatchContractEvent.test-d.ts │ │ │ │ │ ├── createWatchContractEvent.test.ts │ │ │ │ │ ├── createWatchContractEvent.ts │ │ │ │ │ ├── createWriteContract.test-d.ts │ │ │ │ │ ├── createWriteContract.test.ts │ │ │ │ │ └── createWriteContract.ts │ │ │ │ ├── connect.test-d.ts │ │ │ │ ├── connect.test.ts │ │ │ │ ├── connect.ts │ │ │ │ ├── deployContract.test-d.ts │ │ │ │ ├── deployContract.test.ts │ │ │ │ ├── deployContract.ts │ │ │ │ ├── disconnect.test.ts │ │ │ │ ├── disconnect.ts │ │ │ │ ├── estimateFeesPerGas.test-d.ts │ │ │ │ ├── estimateFeesPerGas.test.ts │ │ │ │ ├── estimateFeesPerGas.ts │ │ │ │ ├── estimateGas.test-d.ts │ │ │ │ ├── estimateGas.test.ts │ │ │ │ ├── estimateGas.ts │ │ │ │ ├── estimateMaxPriorityFeePerGas.test.ts │ │ │ │ ├── estimateMaxPriorityFeePerGas.ts │ │ │ │ ├── getBalance.test.ts │ │ │ │ ├── getBalance.ts │ │ │ │ ├── getBlobBaseFee.test.ts │ │ │ │ ├── getBlobBaseFee.ts │ │ │ │ ├── getBlock.test-d.ts │ │ │ │ ├── getBlock.test.ts │ │ │ │ ├── getBlock.ts │ │ │ │ ├── getBlockNumber.test.ts │ │ │ │ ├── getBlockNumber.ts │ │ │ │ ├── getBlockTransactionCount.test.ts │ │ │ │ ├── getBlockTransactionCount.ts │ │ │ │ ├── getBytecode.test.ts │ │ │ │ ├── getBytecode.ts │ │ │ │ ├── getCallsStatus.test.ts │ │ │ │ ├── getCallsStatus.ts │ │ │ │ ├── getCapabilities.test.ts │ │ │ │ ├── getCapabilities.ts │ │ │ │ ├── getChainId.test.ts │ │ │ │ ├── getChainId.ts │ │ │ │ ├── getChains.test-d.ts │ │ │ │ ├── getChains.test.ts │ │ │ │ ├── getChains.ts │ │ │ │ ├── getClient.test-d.ts │ │ │ │ ├── getClient.test.ts │ │ │ │ ├── getClient.ts │ │ │ │ ├── getConnection.test-d.ts │ │ │ │ ├── getConnection.test.ts │ │ │ │ ├── getConnection.ts │ │ │ │ ├── getConnections.test.ts │ │ │ │ ├── getConnections.ts │ │ │ │ ├── getConnectorClient.test-d.ts │ │ │ │ ├── getConnectorClient.test.ts │ │ │ │ ├── getConnectorClient.ts │ │ │ │ ├── getConnectors.test.ts │ │ │ │ ├── getConnectors.ts │ │ │ │ ├── getContractEvents.test-d.ts │ │ │ │ ├── getContractEvents.test.ts │ │ │ │ ├── getContractEvents.ts │ │ │ │ ├── getEnsAddress.test.ts │ │ │ │ ├── getEnsAddress.ts │ │ │ │ ├── getEnsAvatar.test.ts │ │ │ │ ├── getEnsAvatar.ts │ │ │ │ ├── getEnsName.test.ts │ │ │ │ ├── getEnsName.ts │ │ │ │ ├── getEnsResolver.test.ts │ │ │ │ ├── getEnsResolver.ts │ │ │ │ ├── getEnsText.test.ts │ │ │ │ ├── getEnsText.ts │ │ │ │ ├── getFeeHistory.test.ts │ │ │ │ ├── getFeeHistory.ts │ │ │ │ ├── getGasPrice.test.ts │ │ │ │ ├── getGasPrice.ts │ │ │ │ ├── getProof.test.ts │ │ │ │ ├── getProof.ts │ │ │ │ ├── getPublicClient.test-d.ts │ │ │ │ ├── getPublicClient.test.ts │ │ │ │ ├── getPublicClient.ts │ │ │ │ ├── getStorageAt.test.ts │ │ │ │ ├── getStorageAt.ts │ │ │ │ ├── getTransaction.test-d.ts │ │ │ │ ├── getTransaction.test.ts │ │ │ │ ├── getTransaction.ts │ │ │ │ ├── getTransactionConfirmations.test-d.ts │ │ │ │ ├── getTransactionConfirmations.test.ts │ │ │ │ ├── getTransactionConfirmations.ts │ │ │ │ ├── getTransactionCount.test.ts │ │ │ │ ├── getTransactionCount.ts │ │ │ │ ├── getTransactionReceipt.test-d.ts │ │ │ │ ├── getTransactionReceipt.test.ts │ │ │ │ ├── getTransactionReceipt.ts │ │ │ │ ├── getWalletClient.test-d.ts │ │ │ │ ├── getWalletClient.test.ts │ │ │ │ ├── getWalletClient.ts │ │ │ │ ├── multicall.bench-d.ts │ │ │ │ ├── multicall.test-d.ts │ │ │ │ ├── multicall.test.ts │ │ │ │ ├── multicall.ts │ │ │ │ ├── prepareTransactionRequest.test-d.ts │ │ │ │ ├── prepareTransactionRequest.test.ts │ │ │ │ ├── prepareTransactionRequest.ts │ │ │ │ ├── readContract.bench-d.ts │ │ │ │ ├── readContract.test-d.ts │ │ │ │ ├── readContract.test.ts │ │ │ │ ├── readContract.ts │ │ │ │ ├── readContracts.test-d.ts │ │ │ │ ├── readContracts.test.ts │ │ │ │ ├── readContracts.ts │ │ │ │ ├── reconnect.test.ts │ │ │ │ ├── reconnect.ts │ │ │ │ ├── sendCalls.test.ts │ │ │ │ ├── sendCalls.ts │ │ │ │ ├── sendCallsSync.test.ts │ │ │ │ ├── sendCallsSync.ts │ │ │ │ ├── sendTransaction.test-d.ts │ │ │ │ ├── sendTransaction.test.ts │ │ │ │ ├── sendTransaction.ts │ │ │ │ ├── sendTransactionSync.test.ts │ │ │ │ ├── sendTransactionSync.ts │ │ │ │ ├── showCallsStatus.test.ts │ │ │ │ ├── showCallsStatus.ts │ │ │ │ ├── signMessage.test.ts │ │ │ │ ├── signMessage.ts │ │ │ │ ├── signTransaction.test-d.ts │ │ │ │ ├── signTransaction.test.ts │ │ │ │ ├── signTransaction.ts │ │ │ │ ├── signTypedData.test-d.ts │ │ │ │ ├── signTypedData.test.ts │ │ │ │ ├── signTypedData.ts │ │ │ │ ├── simulateContract.test-d.ts │ │ │ │ ├── simulateContract.test.ts │ │ │ │ ├── simulateContract.ts │ │ │ │ ├── switchChain.test.ts │ │ │ │ ├── switchChain.ts │ │ │ │ ├── switchConnection.test.ts │ │ │ │ ├── switchConnection.ts │ │ │ │ ├── verifyMessage.test.ts │ │ │ │ ├── verifyMessage.ts │ │ │ │ ├── verifyTypedData.test-d.ts │ │ │ │ ├── verifyTypedData.test.ts │ │ │ │ ├── verifyTypedData.ts │ │ │ │ ├── waitForCallsStatus.test.ts │ │ │ │ ├── waitForCallsStatus.ts │ │ │ │ ├── waitForTransactionReceipt.test-d.ts │ │ │ │ ├── waitForTransactionReceipt.test.ts │ │ │ │ ├── waitForTransactionReceipt.ts │ │ │ │ ├── watchAsset.test.ts │ │ │ │ ├── watchAsset.ts │ │ │ │ ├── watchBlockNumber.test-d.ts │ │ │ │ ├── watchBlockNumber.test.ts │ │ │ │ ├── watchBlockNumber.ts │ │ │ │ ├── watchBlocks.test-d.ts │ │ │ │ ├── watchBlocks.test.ts │ │ │ │ ├── watchBlocks.ts │ │ │ │ ├── watchChainId.test.ts │ │ │ │ ├── watchChainId.ts │ │ │ │ ├── watchChains.test.ts │ │ │ │ ├── watchChains.ts │ │ │ │ ├── watchClient.test-d.ts │ │ │ │ ├── watchClient.test.ts │ │ │ │ ├── watchClient.ts │ │ │ │ ├── watchConnection.test.ts │ │ │ │ ├── watchConnection.ts │ │ │ │ ├── watchConnections.test.ts │ │ │ │ ├── watchConnections.ts │ │ │ │ ├── watchConnectors.test.ts │ │ │ │ ├── watchConnectors.ts │ │ │ │ ├── watchContractEvent.test-d.ts │ │ │ │ ├── watchContractEvent.test.ts │ │ │ │ ├── watchContractEvent.ts │ │ │ │ ├── watchPendingTransactions.test-d.ts │ │ │ │ ├── watchPendingTransactions.test.ts │ │ │ │ ├── watchPendingTransactions.ts │ │ │ │ ├── watchPublicClient.test-d.ts │ │ │ │ ├── watchPublicClient.test.ts │ │ │ │ ├── watchPublicClient.ts │ │ │ │ ├── writeContract.bench-d.ts │ │ │ │ ├── writeContract.test-d.ts │ │ │ │ ├── writeContract.ts │ │ │ │ ├── writeContractSync.test.ts │ │ │ │ └── writeContractSync.ts │ │ │ ├── connectors/ │ │ │ │ ├── createConnector.test.ts │ │ │ │ ├── createConnector.ts │ │ │ │ ├── injected.test.ts │ │ │ │ ├── injected.ts │ │ │ │ ├── mock.test.ts │ │ │ │ └── mock.ts │ │ │ ├── createConfig.test-d.ts │ │ │ ├── createConfig.test.ts │ │ │ ├── createConfig.ts │ │ │ ├── createEmitter.test.ts │ │ │ ├── createEmitter.ts │ │ │ ├── createStorage.test-d.ts │ │ │ ├── createStorage.test.ts │ │ │ ├── createStorage.ts │ │ │ ├── errors/ │ │ │ │ ├── base.test.ts │ │ │ │ ├── base.ts │ │ │ │ ├── config.test.ts │ │ │ │ ├── config.ts │ │ │ │ ├── connector.test.ts │ │ │ │ └── connector.ts │ │ │ ├── exports/ │ │ │ │ ├── actions.test.ts │ │ │ │ ├── actions.ts │ │ │ │ ├── chains.ts │ │ │ │ ├── codegen.test.ts │ │ │ │ ├── codegen.ts │ │ │ │ ├── index.test.ts │ │ │ │ ├── index.ts │ │ │ │ ├── internal.test.ts │ │ │ │ ├── internal.ts │ │ │ │ ├── query.test.ts │ │ │ │ ├── query.ts │ │ │ │ └── tempo.ts │ │ │ ├── hydrate.test.ts │ │ │ ├── hydrate.ts │ │ │ ├── query/ │ │ │ │ ├── AGENTS.md │ │ │ │ ├── call.test.ts │ │ │ │ ├── call.ts │ │ │ │ ├── connect.test-d.ts │ │ │ │ ├── connect.test.ts │ │ │ │ ├── connect.ts │ │ │ │ ├── deployContract.test.ts │ │ │ │ ├── deployContract.ts │ │ │ │ ├── disconnect.test.ts │ │ │ │ ├── disconnect.ts │ │ │ │ ├── estimateFeesPerGas.test-d.ts │ │ │ │ ├── estimateFeesPerGas.test.ts │ │ │ │ ├── estimateFeesPerGas.ts │ │ │ │ ├── estimateGas.test-d.ts │ │ │ │ ├── estimateGas.test.ts │ │ │ │ ├── estimateGas.ts │ │ │ │ ├── estimateMaxPriorityFeePerGas.test.ts │ │ │ │ ├── estimateMaxPriorityFeePerGas.ts │ │ │ │ ├── getBalance.test.ts │ │ │ │ ├── getBalance.ts │ │ │ │ ├── getBlobBaseFee.test.ts │ │ │ │ ├── getBlobBaseFee.ts │ │ │ │ ├── getBlock.test-d.ts │ │ │ │ ├── getBlock.test.ts │ │ │ │ ├── getBlock.ts │ │ │ │ ├── getBlockNumber.test.ts │ │ │ │ ├── getBlockNumber.ts │ │ │ │ ├── getBlockTransactionCount.test.ts │ │ │ │ ├── getBlockTransactionCount.ts │ │ │ │ ├── getBytecode.test.ts │ │ │ │ ├── getBytecode.ts │ │ │ │ ├── getCallsStatus.test.ts │ │ │ │ ├── getCallsStatus.ts │ │ │ │ ├── getCapabilities.test.ts │ │ │ │ ├── getCapabilities.ts │ │ │ │ ├── getConnectorClient.test-d.ts │ │ │ │ ├── getConnectorClient.test.ts │ │ │ │ ├── getConnectorClient.ts │ │ │ │ ├── getContractEvents.test-d.ts │ │ │ │ ├── getContractEvents.test.ts │ │ │ │ ├── getContractEvents.ts │ │ │ │ ├── getEnsAddress.test.ts │ │ │ │ ├── getEnsAddress.ts │ │ │ │ ├── getEnsAvatar.test.ts │ │ │ │ ├── getEnsAvatar.ts │ │ │ │ ├── getEnsName.test.ts │ │ │ │ ├── getEnsName.ts │ │ │ │ ├── getEnsResolver.test.ts │ │ │ │ ├── getEnsResolver.ts │ │ │ │ ├── getEnsText.test.ts │ │ │ │ ├── getEnsText.ts │ │ │ │ ├── getFeeHistory.test.ts │ │ │ │ ├── getFeeHistory.ts │ │ │ │ ├── getGasPrice.test.ts │ │ │ │ ├── getGasPrice.ts │ │ │ │ ├── getProof.test.ts │ │ │ │ ├── getProof.ts │ │ │ │ ├── getStorageAt.test.ts │ │ │ │ ├── getStorageAt.ts │ │ │ │ ├── getTransaction.test-d.ts │ │ │ │ ├── getTransaction.test.ts │ │ │ │ ├── getTransaction.ts │ │ │ │ ├── getTransactionConfirmations.test-d.ts │ │ │ │ ├── getTransactionConfirmations.test.ts │ │ │ │ ├── getTransactionConfirmations.ts │ │ │ │ ├── getTransactionCount.test.ts │ │ │ │ ├── getTransactionCount.ts │ │ │ │ ├── getTransactionReceipt.test-d.ts │ │ │ │ ├── getTransactionReceipt.test.ts │ │ │ │ ├── getTransactionReceipt.ts │ │ │ │ ├── getWalletClient.test-d.ts │ │ │ │ ├── getWalletClient.test.ts │ │ │ │ ├── getWalletClient.ts │ │ │ │ ├── infiniteReadContracts.test-d.ts │ │ │ │ ├── infiniteReadContracts.test.ts │ │ │ │ ├── infiniteReadContracts.ts │ │ │ │ ├── prepareTransactionRequest.test-d.ts │ │ │ │ ├── prepareTransactionRequest.test.ts │ │ │ │ ├── prepareTransactionRequest.ts │ │ │ │ ├── readContract.test-d.ts │ │ │ │ ├── readContract.test.ts │ │ │ │ ├── readContract.ts │ │ │ │ ├── readContracts.test-d.ts │ │ │ │ ├── readContracts.test.ts │ │ │ │ ├── readContracts.ts │ │ │ │ ├── reconnect.test.ts │ │ │ │ ├── reconnect.ts │ │ │ │ ├── sendCalls.test.ts │ │ │ │ ├── sendCalls.ts │ │ │ │ ├── sendCallsSync.test.ts │ │ │ │ ├── sendCallsSync.ts │ │ │ │ ├── sendTransaction.test.ts │ │ │ │ ├── sendTransaction.ts │ │ │ │ ├── sendTransactionSync.test.ts │ │ │ │ ├── sendTransactionSync.ts │ │ │ │ ├── showCallsStatus.test.ts │ │ │ │ ├── showCallsStatus.ts │ │ │ │ ├── signMessage.test.ts │ │ │ │ ├── signMessage.ts │ │ │ │ ├── signTransaction.test.ts │ │ │ │ ├── signTransaction.ts │ │ │ │ ├── signTypedData.test.ts │ │ │ │ ├── signTypedData.ts │ │ │ │ ├── simulateContract.test-d.ts │ │ │ │ ├── simulateContract.test.ts │ │ │ │ ├── simulateContract.ts │ │ │ │ ├── switchChain.test.ts │ │ │ │ ├── switchChain.ts │ │ │ │ ├── switchConnection.test.ts │ │ │ │ ├── switchConnection.ts │ │ │ │ ├── types.ts │ │ │ │ ├── utils.test.ts │ │ │ │ ├── utils.ts │ │ │ │ ├── verifyMessage.test.ts │ │ │ │ ├── verifyMessage.ts │ │ │ │ ├── verifyTypedData.test-d.ts │ │ │ │ ├── verifyTypedData.test.ts │ │ │ │ ├── verifyTypedData.ts │ │ │ │ ├── waitForCallsStatus.test.ts │ │ │ │ ├── waitForCallsStatus.ts │ │ │ │ ├── waitForTransactionReceipt.test-d.ts │ │ │ │ ├── waitForTransactionReceipt.test.ts │ │ │ │ ├── waitForTransactionReceipt.ts │ │ │ │ ├── watchAsset.test.ts │ │ │ │ ├── watchAsset.ts │ │ │ │ ├── writeContract.test-d.ts │ │ │ │ ├── writeContract.test.ts │ │ │ │ ├── writeContract.ts │ │ │ │ └── writeContractSync.ts │ │ │ ├── tempo/ │ │ │ │ ├── AGENTS.md │ │ │ │ ├── Connectors.test.ts │ │ │ │ ├── Connectors.ts │ │ │ │ ├── KeyManager.ts │ │ │ │ └── actions/ │ │ │ │ ├── amm.test.ts │ │ │ │ ├── amm.ts │ │ │ │ ├── dex.test.ts │ │ │ │ ├── dex.ts │ │ │ │ ├── faucet.ts │ │ │ │ ├── fee.test.ts │ │ │ │ ├── fee.ts │ │ │ │ ├── index.ts │ │ │ │ ├── nonce.test.ts │ │ │ │ ├── nonce.ts │ │ │ │ ├── policy.test.ts │ │ │ │ ├── policy.ts │ │ │ │ ├── reward.test.ts │ │ │ │ ├── reward.ts │ │ │ │ ├── token.test.ts │ │ │ │ ├── token.ts │ │ │ │ └── utils.ts │ │ │ ├── transports/ │ │ │ │ ├── connector.test.ts │ │ │ │ ├── connector.ts │ │ │ │ ├── fallback.test.ts │ │ │ │ └── fallback.ts │ │ │ ├── types/ │ │ │ │ ├── chain.test-d.ts │ │ │ │ ├── chain.ts │ │ │ │ ├── properties.ts │ │ │ │ ├── query.ts │ │ │ │ ├── register.ts │ │ │ │ ├── utils.test-d.ts │ │ │ │ └── utils.ts │ │ │ ├── utils/ │ │ │ │ ├── cookie.test.ts │ │ │ │ ├── cookie.ts │ │ │ │ ├── deepEqual.test.ts │ │ │ │ ├── deepEqual.ts │ │ │ │ ├── deserialize.test.ts │ │ │ │ ├── deserialize.ts │ │ │ │ ├── extractRpcUrls.test.ts │ │ │ │ ├── extractRpcUrls.ts │ │ │ │ ├── getAction.test.ts │ │ │ │ ├── getAction.ts │ │ │ │ ├── getVersion.test.ts │ │ │ │ ├── getVersion.ts │ │ │ │ ├── serialize.test.ts │ │ │ │ ├── serialize.ts │ │ │ │ └── uid.ts │ │ │ └── version.ts │ │ ├── test/ │ │ │ └── setup.ts │ │ ├── tsconfig.build.json │ │ └── tsconfig.json │ ├── create-wagmi/ │ │ ├── CHANGELOG.md │ │ ├── README.md │ │ ├── package.json │ │ ├── src/ │ │ │ ├── cli.test.ts │ │ │ ├── cli.ts │ │ │ ├── frameworks.ts │ │ │ ├── index.test-d.ts │ │ │ ├── utils.ts │ │ │ └── version.ts │ │ ├── templates/ │ │ │ ├── next/ │ │ │ │ ├── README.md │ │ │ │ ├── _env.local │ │ │ │ ├── _gitignore │ │ │ │ ├── _npmrc │ │ │ │ ├── next-env.d.ts │ │ │ │ ├── next.config.ts │ │ │ │ ├── package.json │ │ │ │ ├── src/ │ │ │ │ │ ├── app/ │ │ │ │ │ │ ├── globals.css │ │ │ │ │ │ ├── layout.tsx │ │ │ │ │ │ ├── page.tsx │ │ │ │ │ │ └── providers.tsx │ │ │ │ │ └── wagmi.ts │ │ │ │ └── tsconfig.json │ │ │ ├── nuxt/ │ │ │ │ ├── _env.local │ │ │ │ ├── _gitignore │ │ │ │ ├── _npmrc │ │ │ │ ├── app.vue │ │ │ │ ├── components/ │ │ │ │ │ ├── Connect.vue │ │ │ │ │ └── Connection.vue │ │ │ │ ├── nuxt.config.ts │ │ │ │ ├── package.json │ │ │ │ ├── plugins/ │ │ │ │ │ └── wagmi.ts │ │ │ │ ├── server/ │ │ │ │ │ └── tsconfig.json │ │ │ │ ├── tsconfig.json │ │ │ │ └── wagmi.ts │ │ │ ├── vite-react/ │ │ │ │ ├── README.md │ │ │ │ ├── _gitignore │ │ │ │ ├── _npmrc │ │ │ │ ├── index.html │ │ │ │ ├── package.json │ │ │ │ ├── src/ │ │ │ │ │ ├── App.tsx │ │ │ │ │ ├── index.css │ │ │ │ │ ├── main.tsx │ │ │ │ │ ├── vite-env.d.ts │ │ │ │ │ └── wagmi.ts │ │ │ │ ├── tsconfig.json │ │ │ │ ├── tsconfig.node.json │ │ │ │ └── vite.config.ts │ │ │ ├── vite-vanilla/ │ │ │ │ ├── _gitignore │ │ │ │ ├── _npmrc │ │ │ │ ├── index.html │ │ │ │ ├── package.json │ │ │ │ ├── src/ │ │ │ │ │ ├── main.ts │ │ │ │ │ ├── style.css │ │ │ │ │ ├── vite-env.d.ts │ │ │ │ │ └── wagmi.ts │ │ │ │ └── tsconfig.json │ │ │ └── vite-vue/ │ │ │ ├── README.md │ │ │ ├── _gitignore │ │ │ ├── _npmrc │ │ │ ├── index.html │ │ │ ├── package.json │ │ │ ├── src/ │ │ │ │ ├── App.vue │ │ │ │ ├── components/ │ │ │ │ │ ├── Connect.vue │ │ │ │ │ └── Connection.vue │ │ │ │ ├── main.ts │ │ │ │ ├── style.css │ │ │ │ ├── vite-env.d.ts │ │ │ │ └── wagmi.ts │ │ │ ├── tsconfig.json │ │ │ ├── tsconfig.node.json │ │ │ └── vite.config.ts │ │ ├── tsconfig.build.json │ │ └── tsconfig.json │ ├── react/ │ │ ├── CHANGELOG.md │ │ ├── README.md │ │ ├── package.json │ │ ├── src/ │ │ │ ├── context.test.tsx │ │ │ ├── context.ts │ │ │ ├── errors/ │ │ │ │ ├── base.test.ts │ │ │ │ ├── base.ts │ │ │ │ ├── context.test.ts │ │ │ │ └── context.ts │ │ │ ├── exports/ │ │ │ │ ├── actions.test.ts │ │ │ │ ├── actions.ts │ │ │ │ ├── chains.ts │ │ │ │ ├── codegen.test.ts │ │ │ │ ├── codegen.ts │ │ │ │ ├── connectors.test.ts │ │ │ │ ├── connectors.ts │ │ │ │ ├── index.test.ts │ │ │ │ ├── index.ts │ │ │ │ ├── query.test.ts │ │ │ │ ├── query.ts │ │ │ │ ├── tempo.test.ts │ │ │ │ └── tempo.ts │ │ │ ├── hooks/ │ │ │ │ ├── AGENTS.md │ │ │ │ ├── codegen/ │ │ │ │ │ ├── createUseReadContract.test-d.ts │ │ │ │ │ ├── createUseReadContract.test.ts │ │ │ │ │ ├── createUseReadContract.ts │ │ │ │ │ ├── createUseSimulateContract.test-d.ts │ │ │ │ │ ├── createUseSimulateContract.test.ts │ │ │ │ │ ├── createUseSimulateContract.ts │ │ │ │ │ ├── createUseWatchContractEvent.test-d.ts │ │ │ │ │ ├── createUseWatchContractEvent.test.ts │ │ │ │ │ ├── createUseWatchContractEvent.ts │ │ │ │ │ ├── createUseWriteContract.test-d.ts │ │ │ │ │ ├── createUseWriteContract.test.ts │ │ │ │ │ └── createUseWriteContract.ts │ │ │ │ ├── useBalance.test-d.ts │ │ │ │ ├── useBalance.test.ts │ │ │ │ ├── useBalance.ts │ │ │ │ ├── useBlobBaseFee.test.ts │ │ │ │ ├── useBlobBaseFee.ts │ │ │ │ ├── useBlock.test-d.ts │ │ │ │ ├── useBlock.test.ts │ │ │ │ ├── useBlock.ts │ │ │ │ ├── useBlockNumber.test-d.ts │ │ │ │ ├── useBlockNumber.test.ts │ │ │ │ ├── useBlockNumber.ts │ │ │ │ ├── useBlockTransactionCount.test-d.ts │ │ │ │ ├── useBlockTransactionCount.test.ts │ │ │ │ ├── useBlockTransactionCount.ts │ │ │ │ ├── useBytecode.test-d.ts │ │ │ │ ├── useBytecode.test.ts │ │ │ │ ├── useBytecode.ts │ │ │ │ ├── useCall.test-d.ts │ │ │ │ ├── useCall.test.ts │ │ │ │ ├── useCall.ts │ │ │ │ ├── useCallsStatus.test.ts │ │ │ │ ├── useCallsStatus.ts │ │ │ │ ├── useCapabilities.test.ts │ │ │ │ ├── useCapabilities.ts │ │ │ │ ├── useChainId.test-d.ts │ │ │ │ ├── useChainId.test.ts │ │ │ │ ├── useChainId.ts │ │ │ │ ├── useChains.test.ts │ │ │ │ ├── useChains.ts │ │ │ │ ├── useClient.test-d.ts │ │ │ │ ├── useClient.test.ts │ │ │ │ ├── useClient.ts │ │ │ │ ├── useConfig.test-d.ts │ │ │ │ ├── useConfig.test.ts │ │ │ │ ├── useConfig.ts │ │ │ │ ├── useConnect.test-d.ts │ │ │ │ ├── useConnect.test.ts │ │ │ │ ├── useConnect.ts │ │ │ │ ├── useConnection.test-d.ts │ │ │ │ ├── useConnection.test.ts │ │ │ │ ├── useConnection.ts │ │ │ │ ├── useConnectionEffect.test.ts │ │ │ │ ├── useConnectionEffect.ts │ │ │ │ ├── useConnections.test.ts │ │ │ │ ├── useConnections.ts │ │ │ │ ├── useConnectorClient.test-d.ts │ │ │ │ ├── useConnectorClient.test.tsx │ │ │ │ ├── useConnectorClient.ts │ │ │ │ ├── useConnectors.test.ts │ │ │ │ ├── useConnectors.ts │ │ │ │ ├── useContractEvents.test-d.ts │ │ │ │ ├── useContractEvents.test.ts │ │ │ │ ├── useContractEvents.ts │ │ │ │ ├── useDeployContract.test-d.ts │ │ │ │ ├── useDeployContract.test.ts │ │ │ │ ├── useDeployContract.ts │ │ │ │ ├── useDisconnect.test-d.ts │ │ │ │ ├── useDisconnect.test.ts │ │ │ │ ├── useDisconnect.ts │ │ │ │ ├── useEnsAddress.test.ts │ │ │ │ ├── useEnsAddress.ts │ │ │ │ ├── useEnsAvatar.test.ts │ │ │ │ ├── useEnsAvatar.ts │ │ │ │ ├── useEnsName.test.ts │ │ │ │ ├── useEnsName.ts │ │ │ │ ├── useEnsResolver.test.ts │ │ │ │ ├── useEnsResolver.ts │ │ │ │ ├── useEnsText.test.ts │ │ │ │ ├── useEnsText.ts │ │ │ │ ├── useEstimateFeesPerGas.test-d.ts │ │ │ │ ├── useEstimateFeesPerGas.test.ts │ │ │ │ ├── useEstimateFeesPerGas.ts │ │ │ │ ├── useEstimateGas.test-d.ts │ │ │ │ ├── useEstimateGas.test.ts │ │ │ │ ├── useEstimateGas.ts │ │ │ │ ├── useEstimateMaxPriorityFeePerGas.test-d.ts │ │ │ │ ├── useEstimateMaxPriorityFeePerGas.test.ts │ │ │ │ ├── useEstimateMaxPriorityFeePerGas.ts │ │ │ │ ├── useFeeHistory.test-d.ts │ │ │ │ ├── useFeeHistory.test.ts │ │ │ │ ├── useFeeHistory.ts │ │ │ │ ├── useGasPrice.test-d.ts │ │ │ │ ├── useGasPrice.test.ts │ │ │ │ ├── useGasPrice.ts │ │ │ │ ├── useInfiniteReadContracts.test-d.ts │ │ │ │ ├── useInfiniteReadContracts.test.ts │ │ │ │ ├── useInfiniteReadContracts.ts │ │ │ │ ├── usePrepareTransactionRequest.test-d.ts │ │ │ │ ├── usePrepareTransactionRequest.test.ts │ │ │ │ ├── usePrepareTransactionRequest.ts │ │ │ │ ├── useProof.test-d.ts │ │ │ │ ├── useProof.test.ts │ │ │ │ ├── useProof.ts │ │ │ │ ├── usePublicClient.test-d.ts │ │ │ │ ├── usePublicClient.test.ts │ │ │ │ ├── usePublicClient.ts │ │ │ │ ├── useReadContract.test-d.ts │ │ │ │ ├── useReadContract.test.ts │ │ │ │ ├── useReadContract.ts │ │ │ │ ├── useReadContracts.test-d.ts │ │ │ │ ├── useReadContracts.test.ts │ │ │ │ ├── useReadContracts.ts │ │ │ │ ├── useReconnect.test-d.ts │ │ │ │ ├── useReconnect.test.ts │ │ │ │ ├── useReconnect.ts │ │ │ │ ├── useSendCalls.test.ts │ │ │ │ ├── useSendCalls.ts │ │ │ │ ├── useSendCallsSync.test.ts │ │ │ │ ├── useSendCallsSync.ts │ │ │ │ ├── useSendTransaction.test-d.ts │ │ │ │ ├── useSendTransaction.test.ts │ │ │ │ ├── useSendTransaction.ts │ │ │ │ ├── useSendTransactionSync.test.ts │ │ │ │ ├── useSendTransactionSync.ts │ │ │ │ ├── useShowCallsStatus.test.ts │ │ │ │ ├── useShowCallsStatus.ts │ │ │ │ ├── useSignMessage.test-d.ts │ │ │ │ ├── useSignMessage.test.ts │ │ │ │ ├── useSignMessage.ts │ │ │ │ ├── useSignTransaction.test-d.ts │ │ │ │ ├── useSignTransaction.test.ts │ │ │ │ ├── useSignTransaction.ts │ │ │ │ ├── useSignTypedData.test-d.ts │ │ │ │ ├── useSignTypedData.test.ts │ │ │ │ ├── useSignTypedData.ts │ │ │ │ ├── useSimulateContract.test-d.ts │ │ │ │ ├── useSimulateContract.test.ts │ │ │ │ ├── useSimulateContract.ts │ │ │ │ ├── useStorageAt.test-d.ts │ │ │ │ ├── useStorageAt.test.ts │ │ │ │ ├── useStorageAt.ts │ │ │ │ ├── useSwitchChain.test-d.ts │ │ │ │ ├── useSwitchChain.test.ts │ │ │ │ ├── useSwitchChain.ts │ │ │ │ ├── useSwitchConnection.test-d.ts │ │ │ │ ├── useSwitchConnection.test.ts │ │ │ │ ├── useSwitchConnection.ts │ │ │ │ ├── useSyncExternalStoreWithTracked.test.tsx │ │ │ │ ├── useSyncExternalStoreWithTracked.ts │ │ │ │ ├── useTransaction.test-d.ts │ │ │ │ ├── useTransaction.test.ts │ │ │ │ ├── useTransaction.ts │ │ │ │ ├── useTransactionConfirmations.test-d.ts │ │ │ │ ├── useTransactionConfirmations.test.ts │ │ │ │ ├── useTransactionConfirmations.ts │ │ │ │ ├── useTransactionCount.test-d.ts │ │ │ │ ├── useTransactionCount.test.ts │ │ │ │ ├── useTransactionCount.ts │ │ │ │ ├── useTransactionReceipt.test-d.ts │ │ │ │ ├── useTransactionReceipt.test.ts │ │ │ │ ├── useTransactionReceipt.ts │ │ │ │ ├── useVerifyMessage.test-d.ts │ │ │ │ ├── useVerifyMessage.test.ts │ │ │ │ ├── useVerifyMessage.ts │ │ │ │ ├── useVerifyTypedData.test-d.ts │ │ │ │ ├── useVerifyTypedData.test.ts │ │ │ │ ├── useVerifyTypedData.ts │ │ │ │ ├── useWaitForCallsStatus.test.ts │ │ │ │ ├── useWaitForCallsStatus.ts │ │ │ │ ├── useWaitForTransactionReceipt.test-d.ts │ │ │ │ ├── useWaitForTransactionReceipt.test.ts │ │ │ │ ├── useWaitForTransactionReceipt.ts │ │ │ │ ├── useWalletClient.test-d.ts │ │ │ │ ├── useWalletClient.test.tsx │ │ │ │ ├── useWalletClient.ts │ │ │ │ ├── useWatchAsset.test-d.ts │ │ │ │ ├── useWatchAsset.test.ts │ │ │ │ ├── useWatchAsset.ts │ │ │ │ ├── useWatchBlockNumber.test-d.ts │ │ │ │ ├── useWatchBlockNumber.test.ts │ │ │ │ ├── useWatchBlockNumber.ts │ │ │ │ ├── useWatchBlocks.test-d.ts │ │ │ │ ├── useWatchBlocks.test.ts │ │ │ │ ├── useWatchBlocks.ts │ │ │ │ ├── useWatchContractEvent.test-d.ts │ │ │ │ ├── useWatchContractEvent.test.ts │ │ │ │ ├── useWatchContractEvent.ts │ │ │ │ ├── useWatchPendingTransactions.test-d.ts │ │ │ │ ├── useWatchPendingTransactions.test.ts │ │ │ │ ├── useWatchPendingTransactions.ts │ │ │ │ ├── useWriteContract.test-d.ts │ │ │ │ ├── useWriteContract.test.ts │ │ │ │ ├── useWriteContract.ts │ │ │ │ ├── useWriteContractSync.test-d.ts │ │ │ │ ├── useWriteContractSync.test.ts │ │ │ │ └── useWriteContractSync.ts │ │ │ ├── hydrate.ts │ │ │ ├── tempo/ │ │ │ │ ├── AGENTS.md │ │ │ │ ├── Connectors.test.ts │ │ │ │ ├── hooks/ │ │ │ │ │ ├── amm.test.ts │ │ │ │ │ ├── amm.ts │ │ │ │ │ ├── dex.test.ts │ │ │ │ │ ├── dex.ts │ │ │ │ │ ├── faucet.ts │ │ │ │ │ ├── fee.test.ts │ │ │ │ │ ├── fee.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── nonce.test.ts │ │ │ │ │ ├── nonce.ts │ │ │ │ │ ├── policy.test.ts │ │ │ │ │ ├── policy.ts │ │ │ │ │ ├── reward.test.ts │ │ │ │ │ ├── reward.ts │ │ │ │ │ ├── token.test.ts │ │ │ │ │ └── token.ts │ │ │ │ └── utils.ts │ │ │ ├── types/ │ │ │ │ └── properties.ts │ │ │ ├── utils/ │ │ │ │ ├── getVersion.test.ts │ │ │ │ ├── getVersion.ts │ │ │ │ └── query.ts │ │ │ └── version.ts │ │ ├── test/ │ │ │ └── setup.ts │ │ ├── tsconfig.build.json │ │ └── tsconfig.json │ ├── register-tests/ │ │ ├── react/ │ │ │ ├── package.json │ │ │ ├── src/ │ │ │ │ ├── config.ts │ │ │ │ ├── createUseSimulateContract.test-d.ts │ │ │ │ ├── createUseWriteContract.test-d.ts │ │ │ │ ├── useBlock.test-d.ts │ │ │ │ ├── useChainId.test-d.ts │ │ │ │ ├── useChains.test-d.ts │ │ │ │ ├── useClient.test-d.ts │ │ │ │ ├── useConfig.test-d.ts │ │ │ │ ├── useConnect.test-d.ts │ │ │ │ ├── useConnection.test-d.ts │ │ │ │ ├── usePrepareTransactionRequest.test-d.ts │ │ │ │ ├── usePublicClient.ts │ │ │ │ ├── useReadContract.test-d.ts │ │ │ │ ├── useReadContracts.test-d.ts │ │ │ │ ├── useSendTransaction.test-d.ts │ │ │ │ ├── useSimulateContract.test-d.ts │ │ │ │ ├── useSwitchChain.test-d.ts │ │ │ │ ├── useTransaction.test-d.ts │ │ │ │ ├── useTransactionConfirmations.test-d.ts │ │ │ │ ├── useTransactionReceipt.test-d.ts │ │ │ │ ├── useWaitForTransactionReceipt.test-d.ts │ │ │ │ └── useWriteContract.test-d.ts │ │ │ └── tsconfig.json │ │ ├── solid/ │ │ │ ├── package.json │ │ │ ├── src/ │ │ │ │ ├── config.ts │ │ │ │ ├── useChainId.test-d.ts │ │ │ │ ├── useChains.test-d.ts │ │ │ │ ├── useClient.test-d.ts │ │ │ │ ├── useConfig.test-d.ts │ │ │ │ ├── useConnect.test-d.ts │ │ │ │ ├── useConnection.test-d.ts │ │ │ │ └── useSwitchChain.test-d.ts │ │ │ └── tsconfig.json │ │ └── vue/ │ │ ├── package.json │ │ ├── src/ │ │ │ ├── config.ts │ │ │ ├── useChainId.test-d.ts │ │ │ ├── useChains.test-d.ts │ │ │ ├── useClient.test-d.ts │ │ │ ├── useConfig.test-d.ts │ │ │ ├── useConnect.test-d.ts │ │ │ ├── useConnection.test-d.ts │ │ │ ├── useReadContract.test-d.ts │ │ │ ├── useSendTransaction.test-d.ts │ │ │ ├── useSimulateContract.test-d.ts │ │ │ ├── useSwitchChain.test-d.ts │ │ │ ├── useTransaction.test-d.ts │ │ │ ├── useTransactionReceipt.test-d.ts │ │ │ ├── useWaitForTransaction.test-d.ts │ │ │ └── useWriteContract.test-d.ts │ │ └── tsconfig.json │ ├── solid/ │ │ ├── CHANGELOG.md │ │ ├── README.md │ │ ├── package.json │ │ ├── src/ │ │ │ ├── context.ts │ │ │ ├── errors/ │ │ │ │ ├── base.test.ts │ │ │ │ ├── base.ts │ │ │ │ ├── context.test.ts │ │ │ │ └── context.ts │ │ │ ├── exports/ │ │ │ │ ├── actions.test.ts │ │ │ │ ├── actions.ts │ │ │ │ ├── chains.ts │ │ │ │ ├── connectors.test.ts │ │ │ │ ├── connectors.ts │ │ │ │ ├── index.ts │ │ │ │ ├── query.test.ts │ │ │ │ └── query.ts │ │ │ ├── hydrate.ts │ │ │ ├── primitives/ │ │ │ │ ├── useBalance.test-d.ts │ │ │ │ ├── useBalance.test.ts │ │ │ │ ├── useBalance.ts │ │ │ │ ├── useBlockNumber.test-d.ts │ │ │ │ ├── useBlockNumber.test.ts │ │ │ │ ├── useBlockNumber.ts │ │ │ │ ├── useChainId.test-d.ts │ │ │ │ ├── useChainId.test.ts │ │ │ │ ├── useChainId.ts │ │ │ │ ├── useChains.test.ts │ │ │ │ ├── useChains.ts │ │ │ │ ├── useClient.test-d.ts │ │ │ │ ├── useClient.test.ts │ │ │ │ ├── useClient.ts │ │ │ │ ├── useConfig.test-d.ts │ │ │ │ ├── useConfig.test.ts │ │ │ │ ├── useConfig.ts │ │ │ │ ├── useConnect.test-d.ts │ │ │ │ ├── useConnect.test.ts │ │ │ │ ├── useConnect.ts │ │ │ │ ├── useConnection.test-d.ts │ │ │ │ ├── useConnection.test.ts │ │ │ │ ├── useConnection.ts │ │ │ │ ├── useConnectionEffect.test.ts │ │ │ │ ├── useConnectionEffect.ts │ │ │ │ ├── useConnections.test.ts │ │ │ │ ├── useConnections.ts │ │ │ │ ├── useConnectorClient.test-d.ts │ │ │ │ ├── useConnectorClient.test.ts │ │ │ │ ├── useConnectorClient.ts │ │ │ │ ├── useConnectors.test.ts │ │ │ │ ├── useConnectors.ts │ │ │ │ ├── useDisconnect.test-d.ts │ │ │ │ ├── useDisconnect.test.ts │ │ │ │ ├── useDisconnect.ts │ │ │ │ ├── useReconnect.test-d.ts │ │ │ │ ├── useReconnect.test.ts │ │ │ │ ├── useReconnect.ts │ │ │ │ ├── useSwitchChain.test-d.ts │ │ │ │ ├── useSwitchChain.test.ts │ │ │ │ ├── useSwitchChain.ts │ │ │ │ ├── useSwitchConnection.test-d.ts │ │ │ │ ├── useSwitchConnection.test.ts │ │ │ │ ├── useSwitchConnection.ts │ │ │ │ ├── useWatchBlockNumber.test-d.ts │ │ │ │ ├── useWatchBlockNumber.test.ts │ │ │ │ └── useWatchBlockNumber.ts │ │ │ ├── utils/ │ │ │ │ ├── getVersion.test.ts │ │ │ │ ├── getVersion.ts │ │ │ │ └── query.ts │ │ │ └── version.ts │ │ ├── test/ │ │ │ └── setup.ts │ │ ├── tsconfig.build.json │ │ └── tsconfig.json │ ├── test/ │ │ ├── package.json │ │ ├── src/ │ │ │ ├── chains.ts │ │ │ ├── clients.ts │ │ │ ├── config.ts │ │ │ ├── constants.ts │ │ │ ├── exports/ │ │ │ │ ├── index.test-d.ts │ │ │ │ ├── index.test.ts │ │ │ │ ├── index.ts │ │ │ │ ├── react.ts │ │ │ │ ├── solid.ts │ │ │ │ ├── tempo.ts │ │ │ │ └── vue.ts │ │ │ ├── regex.ts │ │ │ ├── setup.global.ts │ │ │ ├── setup.global.types.ts │ │ │ ├── setup.ts │ │ │ ├── tempo/ │ │ │ │ ├── config.ts │ │ │ │ ├── setup.global.ts │ │ │ │ └── setup.ts │ │ │ ├── utils.ts │ │ │ └── vite-env.d.ts │ │ ├── tsconfig.build.json │ │ └── tsconfig.json │ └── vue/ │ ├── CHANGELOG.md │ ├── README.md │ ├── package.json │ ├── src/ │ │ ├── composables/ │ │ │ ├── useBalance.test-d.ts │ │ │ ├── useBalance.test.ts │ │ │ ├── useBalance.ts │ │ │ ├── useBlockNumber.test-d.ts │ │ │ ├── useBlockNumber.test.ts │ │ │ ├── useBlockNumber.ts │ │ │ ├── useBytecode.test-d.ts │ │ │ ├── useBytecode.test.ts │ │ │ ├── useBytecode.ts │ │ │ ├── useChainId.test-d.ts │ │ │ ├── useChainId.test.ts │ │ │ ├── useChainId.ts │ │ │ ├── useChains.test.ts │ │ │ ├── useChains.ts │ │ │ ├── useClient.test-d.ts │ │ │ ├── useClient.test.ts │ │ │ ├── useClient.ts │ │ │ ├── useConfig.test-d.ts │ │ │ ├── useConfig.test.ts │ │ │ ├── useConfig.ts │ │ │ ├── useConnect.test-d.ts │ │ │ ├── useConnect.test.ts │ │ │ ├── useConnect.ts │ │ │ ├── useConnection.test-d.ts │ │ │ ├── useConnection.test.ts │ │ │ ├── useConnection.ts │ │ │ ├── useConnectionEffect.test.ts │ │ │ ├── useConnectionEffect.ts │ │ │ ├── useConnections.test.ts │ │ │ ├── useConnections.ts │ │ │ ├── useConnectorClient.test-d.ts │ │ │ ├── useConnectorClient.test.ts │ │ │ ├── useConnectorClient.ts │ │ │ ├── useConnectors.test.ts │ │ │ ├── useConnectors.ts │ │ │ ├── useDisconnect.test-d.ts │ │ │ ├── useDisconnect.test.ts │ │ │ ├── useDisconnect.ts │ │ │ ├── useEnsAddress.test.ts │ │ │ ├── useEnsAddress.ts │ │ │ ├── useEnsAvatar.test.ts │ │ │ ├── useEnsAvatar.ts │ │ │ ├── useEnsName.test.ts │ │ │ ├── useEnsName.ts │ │ │ ├── useEstimateGas.test-d.ts │ │ │ ├── useEstimateGas.test.ts │ │ │ ├── useEstimateGas.ts │ │ │ ├── useReadContract.test-d.ts │ │ │ ├── useReadContract.test.ts │ │ │ ├── useReadContract.ts │ │ │ ├── useReconnect.test-d.ts │ │ │ ├── useReconnect.test.ts │ │ │ ├── useReconnect.ts │ │ │ ├── useSendTransaction.test-d.ts │ │ │ ├── useSendTransaction.test.ts │ │ │ ├── useSendTransaction.ts │ │ │ ├── useSignMessage.test-d.ts │ │ │ ├── useSignMessage.test.ts │ │ │ ├── useSignMessage.ts │ │ │ ├── useSignTransaction.test-d.ts │ │ │ ├── useSignTransaction.test.ts │ │ │ ├── useSignTransaction.ts │ │ │ ├── useSignTypedData.test-d.ts │ │ │ ├── useSignTypedData.test.ts │ │ │ ├── useSignTypedData.ts │ │ │ ├── useSimulateContract.test-d.ts │ │ │ ├── useSimulateContract.test.ts │ │ │ ├── useSimulateContract.ts │ │ │ ├── useSwitchChain.test-d.ts │ │ │ ├── useSwitchChain.test.ts │ │ │ ├── useSwitchChain.ts │ │ │ ├── useSwitchConnection.test-d.ts │ │ │ ├── useSwitchConnection.test.ts │ │ │ ├── useSwitchConnection.ts │ │ │ ├── useTransaction.test-d.ts │ │ │ ├── useTransaction.test.ts │ │ │ ├── useTransaction.ts │ │ │ ├── useTransactionReceipt.test-d.ts │ │ │ ├── useTransactionReceipt.test.ts │ │ │ ├── useTransactionReceipt.ts │ │ │ ├── useWaitForTransactionReceipt.test-d.ts │ │ │ ├── useWaitForTransactionReceipt.test.ts │ │ │ ├── useWaitForTransactionReceipt.ts │ │ │ ├── useWatchBlockNumber.test-d.ts │ │ │ ├── useWatchBlockNumber.test.ts │ │ │ ├── useWatchBlockNumber.ts │ │ │ ├── useWatchContractEvent.test-d.ts │ │ │ ├── useWatchContractEvent.test.ts │ │ │ ├── useWatchContractEvent.ts │ │ │ ├── useWriteContract.test-d.ts │ │ │ ├── useWriteContract.test.ts │ │ │ └── useWriteContract.ts │ │ ├── errors/ │ │ │ ├── base.test.ts │ │ │ ├── base.ts │ │ │ ├── plugin.test.ts │ │ │ └── plugin.ts │ │ ├── exports/ │ │ │ ├── actions.test.ts │ │ │ ├── actions.ts │ │ │ ├── chains.ts │ │ │ ├── connectors.test.ts │ │ │ ├── connectors.ts │ │ │ ├── index.test.ts │ │ │ ├── index.ts │ │ │ ├── nuxt.test.ts │ │ │ ├── nuxt.ts │ │ │ ├── query.test.ts │ │ │ └── query.ts │ │ ├── nuxt/ │ │ │ ├── module.ts │ │ │ └── runtime/ │ │ │ └── composables.ts │ │ ├── plugin.ts │ │ ├── types/ │ │ │ ├── properties.ts │ │ │ └── ref.ts │ │ ├── utils/ │ │ │ ├── cloneDeep.ts │ │ │ ├── getVersion.test.ts │ │ │ ├── getVersion.ts │ │ │ ├── query.ts │ │ │ └── updateState.ts │ │ └── version.ts │ ├── test/ │ │ └── setup.ts │ ├── tsconfig.build.json │ └── tsconfig.json ├── playgrounds/ │ ├── next/ │ │ ├── .gitignore │ │ ├── next.config.ts │ │ ├── package.json │ │ ├── src/ │ │ │ ├── app/ │ │ │ │ ├── contracts.ts │ │ │ │ ├── globals.css │ │ │ │ ├── layout.tsx │ │ │ │ ├── page.tsx │ │ │ │ └── providers.tsx │ │ │ └── wagmi.ts │ │ └── tsconfig.json │ ├── nuxt/ │ │ ├── .gitignore │ │ ├── app.vue │ │ ├── components/ │ │ │ ├── Connect.vue │ │ │ └── Connection.vue │ │ ├── nuxt.config.ts │ │ ├── package.json │ │ ├── plugins/ │ │ │ └── wagmi.ts │ │ ├── server/ │ │ │ └── tsconfig.json │ │ ├── tsconfig.json │ │ └── wagmi.ts │ ├── solid-start/ │ │ ├── .gitignore │ │ ├── app.config.ts │ │ ├── package.json │ │ ├── src/ │ │ │ ├── app.css │ │ │ ├── app.tsx │ │ │ ├── contracts.ts │ │ │ ├── entry-client.tsx │ │ │ ├── entry-server.tsx │ │ │ ├── global.d.ts │ │ │ └── wagmi.ts │ │ └── tsconfig.json │ ├── tanstack-start/ │ │ ├── package.json │ │ ├── src/ │ │ │ ├── contracts.ts │ │ │ ├── index.css │ │ │ ├── routeTree.gen.ts │ │ │ ├── router.tsx │ │ │ ├── routes/ │ │ │ │ ├── __root.tsx │ │ │ │ └── index.tsx │ │ │ └── wagmi.ts │ │ ├── tsconfig.json │ │ ├── vite.config.ts │ │ ├── worker-configuration.d.ts │ │ └── wrangler.jsonc │ ├── vite-core/ │ │ ├── .gitignore │ │ ├── index.html │ │ ├── package.json │ │ ├── src/ │ │ │ ├── App.tsx │ │ │ ├── index.css │ │ │ ├── main.tsx │ │ │ ├── vite-env.d.ts │ │ │ └── wagmi.ts │ │ ├── tsconfig.json │ │ ├── tsconfig.node.json │ │ └── vite.config.ts │ ├── vite-react/ │ │ ├── .gitignore │ │ ├── index.html │ │ ├── package.json │ │ ├── public/ │ │ │ └── manifest.json │ │ ├── src/ │ │ │ ├── App.tsx │ │ │ ├── contracts.ts │ │ │ ├── index.css │ │ │ ├── main.tsx │ │ │ ├── vite-env.d.ts │ │ │ └── wagmi.ts │ │ ├── tsconfig.json │ │ ├── tsconfig.node.json │ │ ├── vite.config.ts │ │ └── wagmi.config.ts │ ├── vite-solid/ │ │ ├── .gitignore │ │ ├── index.html │ │ ├── package.json │ │ ├── src/ │ │ │ ├── App.tsx │ │ │ ├── contracts.ts │ │ │ ├── index.css │ │ │ ├── index.tsx │ │ │ ├── vite-env.d.ts │ │ │ └── wagmi.ts │ │ ├── tsconfig.json │ │ ├── tsconfig.node.json │ │ └── vite.config.ts │ └── vite-vue/ │ ├── .gitignore │ ├── index.html │ ├── package.json │ ├── src/ │ │ ├── App.vue │ │ ├── components/ │ │ │ ├── Balance.vue │ │ │ ├── BlockNumber.vue │ │ │ ├── Client.vue │ │ │ ├── Connect.vue │ │ │ ├── Connection.vue │ │ │ ├── Connections.vue │ │ │ ├── ConnectorClient.vue │ │ │ ├── ReadContract.vue │ │ │ ├── SendTransaction.vue │ │ │ ├── SwitchChain.vue │ │ │ ├── SwitchConnection.vue │ │ │ └── WriteContract.vue │ │ ├── contracts.ts │ │ ├── main.ts │ │ ├── style.css │ │ ├── vite-env.d.ts │ │ └── wagmi.ts │ ├── tsconfig.json │ ├── tsconfig.node.json │ └── vite.config.ts ├── pnpm-workspace.yaml ├── scripts/ │ ├── formatPackageJson.ts │ ├── generateProxyPackages.ts │ ├── preconstruct.ts │ ├── restorePackageJson.ts │ ├── updateBlockExplorerPluginChains.ts │ ├── updateVersion.ts │ └── updateViemVersion.ts ├── site/ │ ├── .gitignore │ ├── .vitepress/ │ │ ├── config.ts │ │ ├── sidebar.ts │ │ └── theme/ │ │ ├── components/ │ │ │ ├── AsideSponsors.vue │ │ │ ├── Banner.vue │ │ │ ├── HomeBanner.vue │ │ │ └── HomePage.vue │ │ ├── composables/ │ │ │ └── useSponsors.ts │ │ ├── index.ts │ │ └── style.css │ ├── AGENTS.md │ ├── cli/ │ │ ├── api/ │ │ │ ├── commands/ │ │ │ │ ├── generate.md │ │ │ │ └── init.md │ │ │ ├── commands.md │ │ │ ├── plugins/ │ │ │ │ ├── actions.md │ │ │ │ ├── blockExplorer.md │ │ │ │ ├── etherscan.md │ │ │ │ ├── fetch.md │ │ │ │ ├── foundry.md │ │ │ │ ├── hardhat.md │ │ │ │ ├── react.md │ │ │ │ └── sourcify.md │ │ │ └── plugins.md │ │ ├── config/ │ │ │ ├── configuring-cli.md │ │ │ └── options.md │ │ ├── create-wagmi.md │ │ ├── getting-started.md │ │ ├── guides/ │ │ │ └── migrate-from-v1-to-v2.md │ │ ├── installation.md │ │ └── why.md │ ├── components/ │ │ ├── Browsers.vue │ │ ├── PackageMetadata.vue │ │ └── SearchChains.vue │ ├── core/ │ │ ├── api/ │ │ │ ├── actions/ │ │ │ │ ├── call.md │ │ │ │ ├── connect.md │ │ │ │ ├── deployContract.md │ │ │ │ ├── disconnect.md │ │ │ │ ├── estimateFeesPerGas.md │ │ │ │ ├── estimateGas.md │ │ │ │ ├── estimateMaxPriorityFeePerGas.md │ │ │ │ ├── getBalance.md │ │ │ │ ├── getBlobBaseFee.md │ │ │ │ ├── getBlock.md │ │ │ │ ├── getBlockNumber.md │ │ │ │ ├── getBlockTransactionCount.md │ │ │ │ ├── getBytecode.md │ │ │ │ ├── getCallsStatus.md │ │ │ │ ├── getCapabilities.md │ │ │ │ ├── getChainId.md │ │ │ │ ├── getChains.md │ │ │ │ ├── getClient.md │ │ │ │ ├── getConnection.md │ │ │ │ ├── getConnections.md │ │ │ │ ├── getConnectorClient.md │ │ │ │ ├── getConnectors.md │ │ │ │ ├── getContractEvents.md │ │ │ │ ├── getEnsAddress.md │ │ │ │ ├── getEnsAvatar.md │ │ │ │ ├── getEnsName.md │ │ │ │ ├── getEnsResolver.md │ │ │ │ ├── getEnsText.md │ │ │ │ ├── getFeeHistory.md │ │ │ │ ├── getGasPrice.md │ │ │ │ ├── getProof.md │ │ │ │ ├── getPublicClient.md │ │ │ │ ├── getStorageAt.md │ │ │ │ ├── getTransaction.md │ │ │ │ ├── getTransactionConfirmations.md │ │ │ │ ├── getTransactionCount.md │ │ │ │ ├── getTransactionReceipt.md │ │ │ │ ├── getWalletClient.md │ │ │ │ ├── multicall.md │ │ │ │ ├── prepareTransactionRequest.md │ │ │ │ ├── readContract.md │ │ │ │ ├── readContracts.md │ │ │ │ ├── reconnect.md │ │ │ │ ├── sendCalls.md │ │ │ │ ├── sendTransaction.md │ │ │ │ ├── showCallsStatus.md │ │ │ │ ├── signMessage.md │ │ │ │ ├── signTransaction.md │ │ │ │ ├── signTypedData.md │ │ │ │ ├── simulateContract.md │ │ │ │ ├── switchChain.md │ │ │ │ ├── switchConnection.md │ │ │ │ ├── verifyMessage.md │ │ │ │ ├── verifyTypedData.md │ │ │ │ ├── waitForCallsStatus.md │ │ │ │ ├── waitForTransactionReceipt.md │ │ │ │ ├── watchAsset.md │ │ │ │ ├── watchBlockNumber.md │ │ │ │ ├── watchBlocks.md │ │ │ │ ├── watchChainId.md │ │ │ │ ├── watchClient.md │ │ │ │ ├── watchConnection.md │ │ │ │ ├── watchConnections.md │ │ │ │ ├── watchConnectors.md │ │ │ │ ├── watchContractEvent.md │ │ │ │ ├── watchPendingTransactions.md │ │ │ │ ├── watchPublicClient.md │ │ │ │ ├── writeContract.md │ │ │ │ └── writeContracts.md │ │ │ ├── actions.md │ │ │ ├── chains.md │ │ │ ├── connectors/ │ │ │ │ ├── baseAccount.md │ │ │ │ ├── coinbaseWallet.md │ │ │ │ ├── injected.md │ │ │ │ ├── metaMask.md │ │ │ │ ├── mock.md │ │ │ │ ├── porto.md │ │ │ │ ├── safe.md │ │ │ │ └── walletConnect.md │ │ │ ├── connectors.md │ │ │ ├── createConfig.md │ │ │ ├── createConnector.md │ │ │ ├── createStorage.md │ │ │ ├── errors.md │ │ │ ├── transports/ │ │ │ │ ├── custom.md │ │ │ │ ├── fallback.md │ │ │ │ ├── http.md │ │ │ │ ├── unstable_connector.md │ │ │ │ └── webSocket.md │ │ │ ├── transports.md │ │ │ └── utilities/ │ │ │ ├── cookieToInitialState.md │ │ │ ├── deserialize.md │ │ │ └── serialize.md │ │ ├── getting-started.md │ │ ├── guides/ │ │ │ ├── chain-properties.md │ │ │ ├── error-handling.md │ │ │ ├── ethers.md │ │ │ ├── faq.md │ │ │ ├── framework-adapters.md │ │ │ ├── migrate-from-v1-to-v2.md │ │ │ ├── migrate-from-v2-to-v3.md │ │ │ ├── testing.md │ │ │ └── viem.md │ │ ├── installation.md │ │ ├── typescript.md │ │ └── why.md │ ├── dev/ │ │ ├── contributing.md │ │ └── creating-connectors.md │ ├── index.md │ ├── package.json │ ├── react/ │ │ ├── api/ │ │ │ ├── WagmiProvider.md │ │ │ ├── actions.md │ │ │ ├── chains.md │ │ │ ├── connectors/ │ │ │ │ ├── baseAccount.md │ │ │ │ ├── coinbaseWallet.md │ │ │ │ ├── injected.md │ │ │ │ ├── metaMask.md │ │ │ │ ├── mock.md │ │ │ │ ├── porto.md │ │ │ │ ├── safe.md │ │ │ │ └── walletConnect.md │ │ │ ├── connectors.md │ │ │ ├── createConfig.md │ │ │ ├── createStorage.md │ │ │ ├── errors.md │ │ │ ├── hooks/ │ │ │ │ ├── useBalance.md │ │ │ │ ├── useBlobBaseFee.md │ │ │ │ ├── useBlock.md │ │ │ │ ├── useBlockNumber.md │ │ │ │ ├── useBlockTransactionCount.md │ │ │ │ ├── useBytecode.md │ │ │ │ ├── useCall.md │ │ │ │ ├── useCallsStatus.md │ │ │ │ ├── useCapabilities.md │ │ │ │ ├── useChainId.md │ │ │ │ ├── useChains.md │ │ │ │ ├── useClient.md │ │ │ │ ├── useConfig.md │ │ │ │ ├── useConnect.md │ │ │ │ ├── useConnection.md │ │ │ │ ├── useConnectionEffect.md │ │ │ │ ├── useConnections.md │ │ │ │ ├── useConnectorClient.md │ │ │ │ ├── useConnectors.md │ │ │ │ ├── useContractEvents.md │ │ │ │ ├── useDeployContract.md │ │ │ │ ├── useDisconnect.md │ │ │ │ ├── useEnsAddress.md │ │ │ │ ├── useEnsAvatar.md │ │ │ │ ├── useEnsName.md │ │ │ │ ├── useEnsResolver.md │ │ │ │ ├── useEnsText.md │ │ │ │ ├── useEstimateFeesPerGas.md │ │ │ │ ├── useEstimateGas.md │ │ │ │ ├── useEstimateMaxPriorityFeePerGas.md │ │ │ │ ├── useFeeHistory.md │ │ │ │ ├── useGasPrice.md │ │ │ │ ├── useInfiniteReadContracts.md │ │ │ │ ├── usePrepareTransactionRequest.md │ │ │ │ ├── useProof.md │ │ │ │ ├── usePublicClient.md │ │ │ │ ├── useReadContract.md │ │ │ │ ├── useReadContracts.md │ │ │ │ ├── useReconnect.md │ │ │ │ ├── useSendCalls.md │ │ │ │ ├── useSendTransaction.md │ │ │ │ ├── useShowCallsStatus.md │ │ │ │ ├── useSignMessage.md │ │ │ │ ├── useSignTransaction.md │ │ │ │ ├── useSignTypedData.md │ │ │ │ ├── useSimulateContract.md │ │ │ │ ├── useStorageAt.md │ │ │ │ ├── useSwitchChain.md │ │ │ │ ├── useSwitchConnection.md │ │ │ │ ├── useTransaction.md │ │ │ │ ├── useTransactionConfirmations.md │ │ │ │ ├── useTransactionCount.md │ │ │ │ ├── useTransactionReceipt.md │ │ │ │ ├── useVerifyMessage.md │ │ │ │ ├── useVerifyTypedData.md │ │ │ │ ├── useWaitForCallsStatus.md │ │ │ │ ├── useWaitForTransactionReceipt.md │ │ │ │ ├── useWalletClient.md │ │ │ │ ├── useWatchAsset.md │ │ │ │ ├── useWatchBlockNumber.md │ │ │ │ ├── useWatchBlocks.md │ │ │ │ ├── useWatchContractEvent.md │ │ │ │ ├── useWatchPendingTransactions.md │ │ │ │ ├── useWriteContract.md │ │ │ │ └── useWriteContracts.md │ │ │ ├── hooks.md │ │ │ ├── transports/ │ │ │ │ ├── custom.md │ │ │ │ ├── fallback.md │ │ │ │ ├── http.md │ │ │ │ ├── unstable_connector.md │ │ │ │ └── webSocket.md │ │ │ ├── transports.md │ │ │ └── utilities/ │ │ │ ├── cookieToInitialState.md │ │ │ ├── deserialize.md │ │ │ └── serialize.md │ │ ├── comparisons.md │ │ ├── getting-started.md │ │ ├── guides/ │ │ │ ├── chain-properties.md │ │ │ ├── connect-wallet.md │ │ │ ├── error-handling.md │ │ │ ├── ethers.md │ │ │ ├── faq.md │ │ │ ├── migrate-from-v1-to-v2.md │ │ │ ├── migrate-from-v2-to-v3.md │ │ │ ├── read-from-contract.md │ │ │ ├── send-transaction.md │ │ │ ├── ssr.md │ │ │ ├── tanstack-query.md │ │ │ ├── testing.md │ │ │ ├── viem.md │ │ │ └── write-to-contract.md │ │ ├── installation.md │ │ ├── typescript.md │ │ └── why.md │ ├── shared/ │ │ ├── connectors/ │ │ │ ├── baseAccount.md │ │ │ ├── coinbaseWallet.md │ │ │ ├── injected.md │ │ │ ├── metaMask.md │ │ │ ├── mock.md │ │ │ ├── porto.md │ │ │ ├── safe.md │ │ │ └── walletConnect.md │ │ ├── create-chain.md │ │ ├── createConfig.md │ │ ├── createStorage.md │ │ ├── errors.md │ │ ├── faq.md │ │ ├── getConnection-return-type.md │ │ ├── installation.md │ │ ├── migrate-from-v2-to-v3.md │ │ ├── mutation-imports.md │ │ ├── mutation-options.md │ │ ├── mutation-result.md │ │ ├── query-imports.md │ │ ├── query-options.md │ │ ├── query-result.md │ │ ├── tempo-write-parameters.md │ │ ├── transports/ │ │ │ ├── custom.md │ │ │ ├── fallback.md │ │ │ ├── http.md │ │ │ ├── unstable_connector.md │ │ │ └── webSocket.md │ │ └── utilities/ │ │ ├── cookieToInitialState.md │ │ ├── deserialize.md │ │ └── serialize.md │ ├── snippets/ │ │ ├── abi-event.ts │ │ ├── abi-infinite-read.ts │ │ ├── abi-read.ts │ │ ├── abi-write.ts │ │ ├── core/ │ │ │ ├── config-chain-properties.ts │ │ │ ├── config-tempo.ts │ │ │ └── config.ts │ │ ├── react/ │ │ │ ├── app.tsx │ │ │ ├── config-chain-properties.ts │ │ │ ├── config-tempo.ts │ │ │ └── config.ts │ │ ├── solid/ │ │ │ └── config.ts │ │ ├── typedData.ts │ │ └── vue/ │ │ ├── App.vue │ │ ├── config-chain-properties.ts │ │ ├── config.ts │ │ └── main.ts │ ├── solid/ │ │ ├── api/ │ │ │ ├── WagmiProvider.md │ │ │ ├── actions.md │ │ │ ├── chains.md │ │ │ ├── connectors/ │ │ │ │ ├── baseAccount.md │ │ │ │ ├── injected.md │ │ │ │ ├── metaMask.md │ │ │ │ ├── mock.md │ │ │ │ ├── porto.md │ │ │ │ ├── safe.md │ │ │ │ └── walletConnect.md │ │ │ ├── connectors.md │ │ │ ├── createConfig.md │ │ │ ├── createStorage.md │ │ │ ├── errors.md │ │ │ ├── primitives/ │ │ │ │ ├── useBalance.md │ │ │ │ ├── useBlockNumber.md │ │ │ │ ├── useChainId.md │ │ │ │ ├── useChains.md │ │ │ │ ├── useClient.md │ │ │ │ ├── useConfig.md │ │ │ │ ├── useConnect.md │ │ │ │ ├── useConnection.md │ │ │ │ ├── useConnectionEffect.md │ │ │ │ ├── useConnections.md │ │ │ │ ├── useConnectorClient.md │ │ │ │ ├── useConnectors.md │ │ │ │ ├── useDisconnect.md │ │ │ │ ├── useReconnect.md │ │ │ │ ├── useSwitchChain.md │ │ │ │ ├── useSwitchConnection.md │ │ │ │ └── useWatchBlockNumber.md │ │ │ ├── primitives.md │ │ │ ├── transports/ │ │ │ │ ├── custom.md │ │ │ │ ├── fallback.md │ │ │ │ ├── http.md │ │ │ │ └── webSocket.md │ │ │ └── transports.md │ │ ├── getting-started.md │ │ ├── guides/ │ │ │ ├── connect-wallet.md │ │ │ ├── error-handling.md │ │ │ ├── tanstack-query.md │ │ │ └── viem.md │ │ ├── installation.md │ │ ├── typescript.md │ │ └── why.md │ ├── tempo/ │ │ ├── actions/ │ │ │ ├── amm.burn.md │ │ │ ├── amm.getLiquidityBalance.md │ │ │ ├── amm.getPool.md │ │ │ ├── amm.mint.md │ │ │ ├── amm.rebalanceSwap.md │ │ │ ├── amm.watchBurn.md │ │ │ ├── amm.watchMint.md │ │ │ ├── amm.watchRebalanceSwap.md │ │ │ ├── dex.buy.md │ │ │ ├── dex.cancel.md │ │ │ ├── dex.createPair.md │ │ │ ├── dex.getBalance.md │ │ │ ├── dex.getBuyQuote.md │ │ │ ├── dex.getOrder.md │ │ │ ├── dex.getSellQuote.md │ │ │ ├── dex.getTickLevel.md │ │ │ ├── dex.place.md │ │ │ ├── dex.placeFlip.md │ │ │ ├── dex.sell.md │ │ │ ├── dex.watchFlipOrderPlaced.md │ │ │ ├── dex.watchOrderCancelled.md │ │ │ ├── dex.watchOrderFilled.md │ │ │ ├── dex.watchOrderPlaced.md │ │ │ ├── dex.withdraw.md │ │ │ ├── faucet.fund.md │ │ │ ├── fee.getUserToken.md │ │ │ ├── fee.setUserToken.md │ │ │ ├── fee.watchSetUserToken.md │ │ │ ├── index.md │ │ │ ├── nonce.getNonce.md │ │ │ ├── nonce.watchNonceIncremented.md │ │ │ ├── policy.create.md │ │ │ ├── policy.getData.md │ │ │ ├── policy.isAuthorized.md │ │ │ ├── policy.modifyBlacklist.md │ │ │ ├── policy.modifyWhitelist.md │ │ │ ├── policy.setAdmin.md │ │ │ ├── policy.watchAdminUpdated.md │ │ │ ├── policy.watchBlacklistUpdated.md │ │ │ ├── policy.watchCreate.md │ │ │ ├── policy.watchWhitelistUpdated.md │ │ │ ├── reward.claim.md │ │ │ ├── reward.distribute.md │ │ │ ├── reward.getUserRewardInfo.md │ │ │ ├── reward.setRecipient.md │ │ │ ├── reward.watchRewardDistributed.md │ │ │ ├── reward.watchRewardRecipientSet.md │ │ │ ├── token.approve.md │ │ │ ├── token.burn.md │ │ │ ├── token.burnBlocked.md │ │ │ ├── token.changeTransferPolicy.md │ │ │ ├── token.create.md │ │ │ ├── token.getAllowance.md │ │ │ ├── token.getBalance.md │ │ │ ├── token.getMetadata.md │ │ │ ├── token.grantRoles.md │ │ │ ├── token.hasRole.md │ │ │ ├── token.mint.md │ │ │ ├── token.pause.md │ │ │ ├── token.renounceRoles.md │ │ │ ├── token.revokeRoles.md │ │ │ ├── token.setRoleAdmin.md │ │ │ ├── token.setSupplyCap.md │ │ │ ├── token.transfer.md │ │ │ ├── token.unpause.md │ │ │ ├── token.watchAdminRole.md │ │ │ ├── token.watchApprove.md │ │ │ ├── token.watchBurn.md │ │ │ ├── token.watchCreate.md │ │ │ ├── token.watchMint.md │ │ │ ├── token.watchRole.md │ │ │ └── token.watchTransfer.md │ │ ├── chains.md │ │ ├── connectors/ │ │ │ ├── dangerous_secp256k1.md │ │ │ ├── index.md │ │ │ └── webAuthn.md │ │ ├── getting-started.md │ │ ├── hooks/ │ │ │ ├── amm.useBurn.md │ │ │ ├── amm.useLiquidityBalance.md │ │ │ ├── amm.useMint.md │ │ │ ├── amm.usePool.md │ │ │ ├── amm.useRebalanceSwap.md │ │ │ ├── amm.useWatchBurn.md │ │ │ ├── amm.useWatchMint.md │ │ │ ├── amm.useWatchRebalanceSwap.md │ │ │ ├── dex.useBalance.md │ │ │ ├── dex.useBuy.md │ │ │ ├── dex.useBuyQuote.md │ │ │ ├── dex.useCancel.md │ │ │ ├── dex.useCreatePair.md │ │ │ ├── dex.useOrder.md │ │ │ ├── dex.usePlace.md │ │ │ ├── dex.usePlaceFlip.md │ │ │ ├── dex.useSell.md │ │ │ ├── dex.useSellQuote.md │ │ │ ├── dex.useTickLevel.md │ │ │ ├── dex.useWatchFlipOrderPlaced.md │ │ │ ├── dex.useWatchOrderCancelled.md │ │ │ ├── dex.useWatchOrderFilled.md │ │ │ ├── dex.useWatchOrderPlaced.md │ │ │ ├── dex.useWithdraw.md │ │ │ ├── faucet.useFund.md │ │ │ ├── fee.useSetUserToken.md │ │ │ ├── fee.useUserToken.md │ │ │ ├── fee.useWatchSetUserToken.md │ │ │ ├── index.md │ │ │ ├── nonce.useNonce.md │ │ │ ├── nonce.useWatchNonceIncremented.md │ │ │ ├── policy.useCreate.md │ │ │ ├── policy.useData.md │ │ │ ├── policy.useIsAuthorized.md │ │ │ ├── policy.useModifyBlacklist.md │ │ │ ├── policy.useModifyWhitelist.md │ │ │ ├── policy.useSetAdmin.md │ │ │ ├── policy.useWatchAdminUpdated.md │ │ │ ├── policy.useWatchBlacklistUpdated.md │ │ │ ├── policy.useWatchCreate.md │ │ │ ├── policy.useWatchWhitelistUpdated.md │ │ │ ├── reward.useClaim.md │ │ │ ├── reward.useDistribute.md │ │ │ ├── reward.useSetRecipient.md │ │ │ ├── reward.useUserRewardInfo.md │ │ │ ├── reward.useWatchRewardDistributed.md │ │ │ ├── reward.useWatchRewardRecipientSet.md │ │ │ ├── token.useApprove.md │ │ │ ├── token.useBurn.md │ │ │ ├── token.useBurnBlocked.md │ │ │ ├── token.useChangeTransferPolicy.md │ │ │ ├── token.useCreate.md │ │ │ ├── token.useGetAllowance.md │ │ │ ├── token.useGetBalance.md │ │ │ ├── token.useGetMetadata.md │ │ │ ├── token.useGrantRoles.md │ │ │ ├── token.useHasRole.md │ │ │ ├── token.useMint.md │ │ │ ├── token.usePause.md │ │ │ ├── token.useRenounceRoles.md │ │ │ ├── token.useRevokeRoles.md │ │ │ ├── token.useSetRoleAdmin.md │ │ │ ├── token.useSetSupplyCap.md │ │ │ ├── token.useTransfer.md │ │ │ ├── token.useUnpause.md │ │ │ ├── token.useWatchAdminRole.md │ │ │ ├── token.useWatchApprove.md │ │ │ ├── token.useWatchBurn.md │ │ │ ├── token.useWatchCreate.md │ │ │ ├── token.useWatchMint.md │ │ │ ├── token.useWatchRole.md │ │ │ └── token.useWatchTransfer.md │ │ └── keyManagers/ │ │ ├── http.md │ │ ├── index.md │ │ └── localStorage.md │ ├── tsconfig.json │ ├── uno.config.ts │ ├── vercel.json │ └── vue/ │ ├── api/ │ │ ├── Nuxt.md │ │ ├── WagmiPlugin.md │ │ ├── actions.md │ │ ├── chains.md │ │ ├── composables/ │ │ │ ├── useBalance.md │ │ │ ├── useBlockNumber.md │ │ │ ├── useBytecode.md │ │ │ ├── useChainId.md │ │ │ ├── useChains.md │ │ │ ├── useClient.md │ │ │ ├── useConfig.md │ │ │ ├── useConnect.md │ │ │ ├── useConnection.md │ │ │ ├── useConnectionEffect.md │ │ │ ├── useConnections.md │ │ │ ├── useConnectorClient.md │ │ │ ├── useConnectors.md │ │ │ ├── useDisconnect.md │ │ │ ├── useEnsAddress.md │ │ │ ├── useEnsAvatar.md │ │ │ ├── useEnsName.md │ │ │ ├── useEstimateGas.md │ │ │ ├── useReadContract.md │ │ │ ├── useReconnect.md │ │ │ ├── useSendTransaction.md │ │ │ ├── useSignMessage.md │ │ │ ├── useSignTransaction.md │ │ │ ├── useSignTypedData.md │ │ │ ├── useSimulateContract.md │ │ │ ├── useSwitchChain.md │ │ │ ├── useSwitchConnection.md │ │ │ ├── useTransaction.md │ │ │ ├── useTransactionReceipt.md │ │ │ ├── useWaitForTransactionReceipt.md │ │ │ ├── useWatchBlockNumber.md │ │ │ ├── useWatchContractEvent.md │ │ │ └── useWriteContract.md │ │ ├── composables.md │ │ ├── connectors/ │ │ │ ├── baseAccount.md │ │ │ ├── coinbaseWallet.md │ │ │ ├── injected.md │ │ │ ├── metaMask.md │ │ │ ├── mock.md │ │ │ ├── porto.md │ │ │ ├── safe.md │ │ │ └── walletConnect.md │ │ ├── connectors.md │ │ ├── createConfig.md │ │ ├── createStorage.md │ │ ├── errors.md │ │ ├── transports/ │ │ │ ├── custom.md │ │ │ ├── fallback.md │ │ │ ├── http.md │ │ │ ├── unstable_connector.md │ │ │ └── webSocket.md │ │ ├── transports.md │ │ └── utilities/ │ │ ├── deserialize.md │ │ └── serialize.md │ ├── getting-started.md │ ├── guides/ │ │ ├── chain-properties.md │ │ ├── connect-wallet.md │ │ ├── error-handling.md │ │ ├── faq.md │ │ ├── read-from-contract.md │ │ ├── send-transaction.md │ │ ├── ssr.md │ │ ├── tanstack-query.md │ │ ├── viem.md │ │ └── write-to-contract.md │ ├── installation.md │ ├── typescript.md │ └── why.md ├── tsconfig.base.json ├── tsconfig.json └── vitest.config.ts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .agents/README.md ================================================ @_@ ================================================ FILE: .agents/skills/wagmi-development/SKILL.md ================================================ --- name: wagmi-development description: Creates Wagmi features across all layers - core actions, query options, framework bindings. Use when adding new actions, hooks, or working across packages/core, packages/react, packages/vue. --- # Wagmi Development Full-stack patterns for adding Wagmi features. This skill covers Viem-based actions only (not Wagmi config actions). ## Layer Overview 1. **Core Action** (`packages/core/src/actions/`) - Base functionality wrapping Viem 2. **Query Options** (`packages/core/src/query/`) - TanStack Query integration 3. **Framework Bindings** - React (`packages/react/src/hooks/`), Vue (`packages/vue/src/composables/`) --- ## 1. Core Action ### Structure ```ts import { type MyActionErrorType as viem_MyActionErrorType, type MyActionParameters as viem_MyActionParameters, type MyActionReturnType as viem_MyActionReturnType, myAction as viem_myAction, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter, ConnectorParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type MyActionParameters = Compute< ChainIdParameter & viem_MyActionParameters > export type MyActionReturnType = viem_MyActionReturnType export type MyActionErrorType = viem_MyActionErrorType /** https://wagmi.sh/core/api/actions/myAction */ export async function myAction( config: config, parameters: MyActionParameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_myAction, 'myAction') return action(rest) } ``` ### Key Rules - **Viem imports**: Prefix with `viem_` (e.g., `viem_getBalance`) - **Client access**: - Read-only: `config.getClient({ chainId })` - Wallet: `await getConnectorClient(config, { chainId, connector, account })` - Mixed: Use `getConnectorClient` for account, `getClient` for action (see `estimateGas.ts`) - **Parameters**: Add `ChainIdParameter` always. Add `ConnectorParameter` for wallet actions. - **Type params**: Mirror Viem's type params for inference. Use `const` modifier for literal inference (abi, args). - **Spread**: Omit wagmi-specific props (`chainId`, `connector`) when calling Viem action. ### Testing **Runtime tests** (`action.test.ts`): ```ts import { abi, address, config } from '@wagmi/test' import { expect, test } from 'vitest' import { myAction } from './myAction.js' test('default', async () => { await expect(myAction(config, { /* required params */ })).resolves.toMatchInlineSnapshot(`...`) }) test('parameters: chainId', async () => { /* test chainId param */ }) test('behavior: error case', async () => { /* test error handling */ }) ``` **Type tests** (`action.test-d.ts`) - only if action has type inference: ```ts import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { myAction } from './myAction.js' test('default', async () => { const result = await myAction(config, { /* params */ }) expectTypeOf(result).toEqualTypeOf() }) ``` **Type benchmarks** (`action.bench-d.ts`) - only if action has type inference: ```ts import { attest } from '@ark/attest' import { test } from 'vitest' import type { MyActionParameters } from './myAction.js' test('default', () => { type Result = MyActionParameters const res = {} as Result attest.instantiations([12345, 'instantiations']) attest(res.args).type.toString.snap(`readonly [account: \`0x\${string}\`]`) }) ``` **Wallet action tests**: Connect before, disconnect after: ```ts test('default', async () => { await connect(config, { connector }) await expect(myAction(config, { /* params */ })).resolves.toMatchInlineSnapshot(`...`) await disconnect(config, { connector }) }) ``` --- ## 2. Query Options Query (read-only) or Mutation (wallet) options for TanStack Query. ### Query Structure ```ts import { type MyActionErrorType, type MyActionParameters, type MyActionReturnType, myAction, } from '../actions/myAction.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions, structuralSharing } from './utils.js' export type MyActionOptions< config extends Config, selectData = MyActionData, > = Compute> & ScopeKeyParameter> & QueryParameter> export function myActionQueryOptions< config extends Config, selectData = MyActionData, >( config: config, options: MyActionOptions = {}, ): MyActionQueryOptions { return { ...options.query, enabled: Boolean(options.requiredParam && (options.query?.enabled ?? true)), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.requiredParam) throw new Error('requiredParam is required') const result = await myAction(config, { ...(parameters as MyActionParameters), requiredParam: parameters.requiredParam, }) return result ?? null }, queryKey: myActionQueryKey(options), structuralSharing, // include when returning complex objects/arrays } } export type MyActionQueryFnData = Compute export type MyActionData = MyActionQueryFnData export function myActionQueryKey( options: Compute> & ScopeKeyParameter> = {}, ) { return ['myAction', filterQueryOptions(options)] as const } export type MyActionQueryKey = ReturnType> export type MyActionQueryOptions< config extends Config, selectData = MyActionData, > = QueryOptions> ``` ### Mutation Structure ```ts import type { MutationOptions, MutationParameter } from '../types/query.js' export type MyActionOptions = MutationParameter< MyActionData, MyActionErrorType, MyActionVariables, context > export function myActionMutationOptions( config: config, options: MyActionOptions = {}, ): MyActionMutationOptions { return { ...options.mutation, mutationFn: async (variables) => { return myAction(config, variables) }, mutationKey: ['myAction'], } } export type MyActionMutationOptions = MutationOptions< MyActionData, MyActionErrorType, MyActionVariables > ``` ### Key Rules - **ExactPartial vs UnionExactPartial**: Use `ExactPartial` for simple types, `UnionExactPartial` for complex unions (contract actions) - **enabled**: Based on required params being truthy - **structuralSharing**: Include when action returns objects/arrays - **filterQueryOptions**: Filters common non-serializable props. Skip props like `onReplaced` manually in query key. - **Query key**: Always `['actionName', filterQueryOptions(options)]` ### Testing ```ts import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { myActionQueryOptions } from './myAction.js' test('default', () => { expect(myActionQueryOptions(config, {})).toMatchInlineSnapshot(` { "enabled": false, "queryFn": [Function], "queryKey": ["myAction", {}], } `) }) test('enabled', () => { expect(myActionQueryOptions(config, { requiredParam: 'value' }).enabled).toBe(true) }) test('queryFn: calls query fn', async () => { const options = myActionQueryOptions(config, { requiredParam: 'value' }) const result = await options.queryFn({ queryKey: options.queryKey } as any) expect(result).toMatchInlineSnapshot(`...`) }) ``` --- ## 3. Framework Bindings ### React Query Hook ```ts 'use client' import type { Config, MyActionErrorType, ResolvedRegister } from '@wagmi/core' import type { Compute } from '@wagmi/core/internal' import { type MyActionData, type MyActionOptions, myActionQueryOptions, } from '@wagmi/core/query' import type { ConfigParameter } from '../types/properties.js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseMyActionParameters< config extends Config = Config, selectData = MyActionData, > = Compute & ConfigParameter> export type UseMyActionReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useMyAction */ export function useMyAction< config extends Config = ResolvedRegister['config'], selectData = MyActionData, >( parameters: UseMyActionParameters = {}, ): UseMyActionReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = myActionQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, query: parameters.query, }) return useQuery(options) } ``` ### React Mutation Hook ```ts 'use client' import { useMutation } from '@tanstack/react-query' import type { Config, ResolvedRegister, MyActionErrorType } from '@wagmi/core' import { type MyActionData, type MyActionMutate, type MyActionMutateAsync, type MyActionOptions, type MyActionVariables, myActionMutationOptions, } from '@wagmi/core/query' import type { ConfigParameter } from '../types/properties.js' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseMyActionParameters = MyActionOptions & ConfigParameter export type UseMyActionReturnType = UseMutationReturnType< MyActionData, MyActionErrorType, MyActionVariables, context, MyActionMutate, MyActionMutateAsync > /** https://wagmi.sh/react/api/hooks/useMyAction */ export function useMyAction< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: UseMyActionParameters = {}, ): UseMyActionReturnType { const config = useConfig(parameters) const options = myActionMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseMyActionReturnType return { ...mutation, mutate: mutation.mutate as Return['mutate'], mutateAsync: mutation.mutateAsync as Return['mutateAsync'], } } ``` ### Vue Composable (Query) ```ts import type { Config, MyActionErrorType, ResolvedRegister } from '@wagmi/core' import type { Compute } from '@wagmi/core/internal' import { type MyActionData, type MyActionOptions, myActionQueryOptions, } from '@wagmi/core/query' import { computed } from 'vue' import type { ConfigParameter } from '../types/properties.js' import type { DeepMaybeRef } from '../types/ref.js' import { deepUnref } from '../utils/cloneDeep.js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseMyActionParameters< config extends Config = Config, selectData = MyActionData, > = Compute & ConfigParameter>> export type UseMyActionReturnType = UseQueryReturnType /** https://wagmi.sh/vue/api/composables/useMyAction */ export function useMyAction< config extends Config = ResolvedRegister['config'], selectData = MyActionData, >( parameters: UseMyActionParameters = {}, ): UseMyActionReturnType { const params = computed(() => deepUnref(parameters)) const config = useConfig(params) const chainId = useChainId({ config }) const options = computed(() => myActionQueryOptions(config as any, { ...params.value, chainId: params.value.chainId ?? chainId.value, query: params.value.query, }), ) return useQuery(options as any) as any } ``` ### Framework Rules | Rule | React | Vue | |------|-------|-----| | Top directive | `'use client'` | None | | Parameters wrapper | `Compute<...>` | `Compute>` | | Reactivity | Direct | `computed()` + `deepUnref()` | | Doc URL | `wagmi.sh/react/api/hooks/` | `wagmi.sh/vue/api/composables/` | **Shared rules:** - `ResolvedRegister['config']`: Use in function signature only, not type defs - No `enabled`/`structuralSharing` in hooks: Handled by queryOptions ### Testing **Query hook test-d.ts**: ```ts import { abi } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useMyAction } from './useMyAction.js' test('select data', () => { const result = useMyAction({ /* params */ query: { select(data) { expectTypeOf(data).toEqualTypeOf() return data }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ``` **Mutation hook test-d.ts**: ```ts import { expectTypeOf, test } from 'vitest' import { useMyAction } from './useMyAction.js' test('context', () => { const { mutate } = useMyAction({ mutation: { onMutate(variables) { expectTypeOf(variables).toMatchTypeOf<{ /* expected shape */ }>() return { foo: 'bar' } }, onError(error, variables, context) { /* test types */ }, onSuccess(data, variables, context) { /* test types */ }, onSettled(data, error, variables, context) { /* test types */ }, }, }) mutate({ /* params */ }, { onSuccess(data, variables, context) { /* test inference */ }, }) }) ``` --- ## Exports Add to `exports/index.ts` in respective package: ```ts // packages/core/src/exports/index.ts export { type MyActionParameters, type MyActionReturnType, type MyActionErrorType, myAction, } from '../actions/myAction.js' // packages/core/src/exports/query.ts export { type MyActionData, type MyActionOptions, type MyActionQueryFnData, type MyActionQueryKey, type MyActionQueryOptions, myActionQueryKey, myActionQueryOptions, } from '../query/myAction.js' // packages/react/src/exports/index.ts export { type UseMyActionParameters, type UseMyActionReturnType, useMyAction, } from '../hooks/useMyAction.js' ``` --- ## Verification ```bash # Format pnpm format # Type check (all or filtered) pnpm check:types pnpm --filter @wagmi/core check:types pnpm --filter wagmi check:types # Test (all or filtered) pnpm test pnpm test --project core pnpm test --project react # Update test snapshots pnpm vitest -u # Type benchmarks pnpm bench:types # Viem version mismatch in test snapshots pnpm version:update:viem # Build (all or filtered) pnpm run clean && pnpm build pnpm --filter @wagmi/core build ``` ================================================ FILE: .changeset/README.md ================================================ # Changesets Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works with multi-package repos, or single-package repos to help you version and publish your code. You can find the full documentation for it [in our repository](https://github.com/changesets/changesets) We have a quick list of common questions to get you started engaging with this project in [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) ================================================ FILE: .changeset/brave-hens-rare.md ================================================ --- "wagmi": minor "@wagmi/vue": patch "@wagmi/solid": patch --- Update MetaMask connector from `@metamask/sdk` to the new `@metamask/connect-evm`. ```bash npm install @metamask/connect-evm npm uninstall @metamask/sdk ``` ================================================ FILE: .changeset/config.json ================================================ { "$schema": "https://unpkg.com/@changesets/config@3.0.5/schema.json", "changelog": [ "@svitejs/changesets-changelog-github-compact", { "repo": "wevm/wagmi" } ], "commit": false, "access": "public", "fixed": [], "linked": [], "baseBranch": "main", "updateInternalDependencies": "minor", "ignore": [ "*-register", "@wagmi/test", "site", "next-app", "nuxt-app", "vite-*" ] } ================================================ FILE: .changeset/fix-tempo-webauthn-chain-id.md ================================================ --- "@wagmi/core": patch --- Fixed chainId not being passed to Tempo webAuthn key authorization ================================================ FILE: .changeset/upset-trains-lick.md ================================================ --- "@wagmi/connectors": major --- Migrated MetaMask connector from `@metamask/sdk` to the new `@metamask/connect-evm` package. ## Breaking Changes ### New Peer Dependency You must install `@metamask/connect-evm` as a peer dependency: ```bash npm install @metamask/connect-evm # or pnpm add @metamask/connect-evm ``` ### Parameter Changes The connector parameters have been simplified and changed to align with the new SDK. **Removed options:** - `dappMetadata` - Use `dapp` instead - `logging` - Use `debug` instead - `headless` - Use `ui.headless` instead - `checkInstallationImmediately` - `checkInstallationOnAllCalls` - `preferDesktop` - Use `ui.preferExtension` instead - `openDeeplink` - Use `mobile.preferredOpenLink` instead - `extensionOnly` - `infuraAPIKey` - `communicationLayerPreference` - `communicationServerUrl` - `enableAnalytics` - `shouldShimWeb3` - `storage` - `timer` - `i18nOptions` - `modals` - All communication layer options **New options:** - `dapp` - Dapp identification (`{ name: string, url?: string, iconUrl?: string }`) - `debug` - Enable debug logging (boolean) - `mobile` - Mobile-specific options: - `preferredOpenLink` - Custom function to open deeplinks (required for React Native) - `useDeeplink` - Use `metamask://` deeplink vs `https://metamask.app.link` universal link - `ui` - UI configuration options: - `headless` - Disable built-in UI - `preferExtension` - Prefer browser extension over mobile - `showInstallModal` - Show install modal when MetaMask is not installed - `transport` - Transport configuration: - `extensionId` - Extension ID for browser extension transport **Preserved options:** - `connectAndSign` - Shortcut to connect and sign a message - `connectWith` - Connect with any RPC method ### Migration Example **Before:** ```ts import { metaMask } from 'wagmi/connectors' metaMask({ dappMetadata: { name: 'My DApp', url: 'https://mydapp.com', iconUrl: 'https://mydapp.com/icon.png', }, logging: { sdk: true }, }) ``` **After:** ```ts import { metaMask } from 'wagmi/connectors' metaMask({ dapp: { name: 'My DApp', url: 'https://mydapp.com', iconUrl: 'https://mydapp.com/icon.png', }, debug: true, }) ``` ================================================ FILE: .github/CODEOWNERS ================================================ @tmm @jxom /packages/connectors/src/gemini @mikelxc /packages/connectors/src/metaMask @wenfix @ffmcgee725 @jiexi @adonesky1 @chakra-guy /packages/connectors/src/safe @DaniSomoza @dasanra @mikhailxyz @yagopv /packages/connectors/src/walletConnect @ganchoradkov @glitch-txs @ignaciosantise @tomiir ================================================ FILE: .github/CONTRIBUTING.md ================================================ [View Contributing Guide on wagmi.sh](https://wagmi.sh/dev/contributing) ================================================ FILE: .github/DISCUSSION_TEMPLATE/connector-request.yml ================================================ title: '[Connector Request] ' body: - type: markdown attributes: value: | Thanks for your interest in contributing a new Connector to the Wagmi! If you haven't already, please read the [Contributing Guidelines](https://wagmi.sh/dev/contributing). Once you submit the form, the Wagmi team will follow up in the discussion thread to discuss next steps. Please note that in order for connector requests to be accepted, the team creating the Connector must [sponsor Wagmi](https://github.com/sponsors/wevm). It takes time and effort to maintain third-party connectors. Wagmi is an OSS project that depends on sponsors and grants to continue our work. Please get in touch via [dev@wevm.dev](mailto:dev@wevm.dev) if you have questions about sponsoring. - type: textarea attributes: label: What **novel use-case** does the Connector provide? description: | A novel use-case is likely one that is not already covered by or not easily extended from another Connector (such as the `injected` or `walletConnect`). Examples of **novel** use-cases could be a connector that integrates with: - the injected `window.ethereum` provider (a la `injected`) - a series of wallets via QR Codes or Mobile Deep Links (a la `walletConnect`) - a wallet with it's own SDK (a la `coinbaseWallet`) - hardware wallet(s) via Web USB/Bluetooth - an Externally Owned Account via a private key or some other method Examples of **nonnovel** use-cases would be a connector that: - extends another connector (e.g. `walletConnect`) with no significant differences in functionality other than branding, etc. placeholder: Info on what makes this connector different. validations: required: true - type: textarea attributes: label: Are the Connector's integrations production-ready and generally available? description: Connectors are intended to be used by consumers in production as part of Wagmi. As such, the Connector and all dependencies must be production-ready and generally available. This means your connector should not rely on non-production software or be restricted to a limited group of users. For example, if your connector requires a wallet that has a closed beta, it is not ready for inclusion in Wagmi. placeholder: Info about the Connector and any dependencies (e.g. browser extension, wallet app, npm package). validations: required: true - type: checkboxes attributes: label: Are you committed to actively maintaining the Connector? description: It is critical connectors are updated in a timely manner and actively maintained so that users of Wagmi can rely on them in production settings. The Wagmi core team will provide as much assistance as possible to keep connectors up-to-date with breaking changes from Wagmi, but it is your responsibility to ensure that any dependencies and issues/discussions related to the Connector are handled in a timely manner. If this is not done, the Connector could be removed from the future versions. options: - label: Yes, my team is or I am committed to actively maintaining the Connector. required: true - type: textarea attributes: label: Additional comments description: Feel free to jot down any additional info you think might be helpful. placeholder: Additional comments, questions, feedback. ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.yml ================================================ name: Bug Report description: Report bugs or issues. body: - type: markdown attributes: value: | Thanks for taking the time to fill out this bug report! The more info you provide, the more we can help you. If you are a [Wagmi Sponsor](https://github.com/sponsors/wevm?metadata_campaign=gh_issue), your issues are prioritized. - type: checkboxes attributes: label: Check existing issues description: By submitting this issue, you checked there isn't [already an issue](https://github.com/wevm/wagmi/issues) for this bug. options: - label: I checked there isn't [already an issue](https://github.com/wevm/wagmi/issues) for the bug I encountered. required: true - type: textarea attributes: label: Describe the bug description: Clear and concise description of the bug. If you intend to submit a PR for this issue, tell us in the description. Thanks! placeholder: I am doing… What I expect is… What is actually happening… validations: required: true - type: input id: reproduction attributes: label: Link to Minimal Reproducible Example description: "Please provide a link that can reproduce the problem: [new.wagmi.sh](https://new.wagmi.sh) for runtime issues or [TypeScript Playground](https://www.typescriptlang.org/play) for type issues. For most issues, you will likely get asked to provide a minimal reproducible example so why not add one now :) If a report is vague (e.g. just snippets, generic error message, screenshot, etc.) and has no reproduction, it will receive a \"Needs Reproduction\" label and be auto-closed." placeholder: https://new.wagmi.sh validations: required: false - type: textarea attributes: label: Steps To Reproduce description: Steps or code snippets to reproduce the behavior. validations: required: false - type: dropdown attributes: label: What Wagmi package(s) are you using? multiple: true options: - 'wagmi' - '@wagmi/cli' - '@wagmi/connectors' - '@wagmi/core' - '@wagmi/vue' - 'create-wagmi' validations: required: true - type: input attributes: label: Wagmi Package(s) Version(s) description: What version of the Wagmi packages you selected above are you using? If using multiple, separate with comma (e.g. `wagmi@x.y.z, @wagmi/cli@x.y.z`). placeholder: x.y.z (do not write `latest`) validations: required: true - type: input attributes: label: Viem Version description: What version of [Viem](https://viem.sh) are you using? placeholder: x.y.z (do not write `latest`) validations: required: true - type: input attributes: label: TypeScript Version description: What version of TypeScript are you using? Wagmi requires `typescript@>=5`. placeholder: x.y.z (do not write `latest`) validations: required: false - type: textarea attributes: label: Anything else? description: Anything that will give us more context about the issue you are encountering. Framework version (e.g. React, Vue), app framework (e.g. Next.js, Nuxt), bundler, etc. validations: required: false ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false contact_links: - name: Get Help url: https://github.com/wevm/wagmi/discussions/new?category=q-a about: Ask a question and discuss with other community members. - name: Feature Request url: https://github.com/wevm/wagmi/discussions/new?category=ideas about: Request features or brainstorm ideas for new functionality. - name: Connector Request url: https://github.com/wevm/wagmi/discussions/new?category=connector-request about: Kick off a request for a new connector ================================================ FILE: .github/ISSUE_TEMPLATE/docs_issue.yml ================================================ name: Documentation Issue description: Tell us about missing or incorrect documentation. labels: ['Area: Docs'] body: - type: markdown attributes: value: | Thank you for submitting a documentation request. It helps make Wagmi better. If it's a small change, like misspelling or example that needs updating, feel free to submit a PR instead of creating this issue. - type: dropdown attributes: label: What is the type of issue? multiple: true options: - Documentation is missing - Documentation is incorrect - Documentation is confusing - Example code is not working - Something else - type: textarea attributes: label: What is the issue? validations: required: true - type: textarea attributes: label: Where did you find it? description: Please provide the URL(s) where you found this issue. validations: required: true ================================================ FILE: .github/README.md ================================================

wagmi logo

Reactive primitives for Ethereum apps

Version OpenSSF Best Practices OpenSSF Best Practices
MIT License Downloads per month Best of JS Code coverage

--- ## Documentation For documentation and guides, visit [wagmi.sh](https://wagmi.sh). ## Community For help, discussion about best practices, or any other conversation that would benefit from being searchable: [Discuss Wagmi on GitHub](https://github.com/wevm/wagmi/discussions) For casual chit-chat with others using the framework: [Join the Wagmi Discord](https://discord.gg/SghfWBKexF) ## Contributing Contributions to Wagmi are greatly appreciated! If you're interested in contributing to Wagmi, please read the [Contributing Guide](https://wagmi.sh/dev/contributing) **before submitting a pull request**. ## Sponsors If you find Wagmi useful or use it for work, please consider [sponsoring Wagmi](https://github.com/sponsors/wevm?metadata_campaign=gh_readme_support). Thank you 🙏

paradigm logo tempo logo

family logo context logo Dynamic logo Sushi logo Stripe logo Privy logo pancake logo pimlico logo zora logo syndicate logo relay logo polymarket logo sequence logo web3auth logo

[Sponsor Wagmi](https://github.com/sponsors/wevm?metadata_campaign=gh_readme_support_bottom)

Powered by Vercel ================================================ FILE: .github/SECURITY.md ================================================ # Security Policy ## Reporting a Vulnerability Contact [dev@wevm.dev](mailto:dev@wevm.dev). ================================================ FILE: .github/dependabot.yml ================================================ version: 2 updates: - package-ecosystem: 'github-actions' directory: '/' schedule: interval: 'monthly' ================================================ FILE: .github/pull_request_template.md ================================================ ================================================ FILE: .github/workflows/changesets.yml ================================================ name: Changesets on: push: branches: [main] permissions: contents: read concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: verify: name: Verify permissions: contents: write uses: ./.github/workflows/verify.yml secrets: inherit changesets: name: Publish needs: verify # prevents this action from running on forks if: github.repository == 'wevm/wagmi' permissions: contents: write # to create release (changesets/action) id-token: write # OpenID Connect token needed for provenance pull-requests: write # to create pull request (changesets/action) runs-on: ubuntu-latest timeout-minutes: 5 steps: - name: Clone repository uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 with: # This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits fetch-depth: 0 - name: Install dependencies uses: wevm/actions/.github/actions/pnpm@f7ad7f00e16e73322562922c241f21f0c7ffbbec with: node-version: 24.5 - name: PR or publish uses: changesets/action@e0145edc7d9d8679003495b11f87bd8ef63c0cba # v1.5.3 with: title: 'chore: version packages' commit: 'chore: version packages' createGithubReleases: ${{ github.ref == 'refs/heads/main' }} publish: pnpm changeset:publish version: pnpm changeset:version env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Publish canary release if: steps.changesets.outputs.published != 'true' continue-on-error: true env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | git reset --hard origin/main pnpm changeset version --no-git-tag --snapshot canary pnpm changeset:prepublish pnpm changeset publish --no-git-tag --snapshot canary --tag canary ================================================ FILE: .github/workflows/issue-labeled.yml ================================================ name: Issue Labeled permissions: issues: write on: issues: types: [labeled] jobs: issue-labeled: if: ${{ github.repository_owner == 'wevm' }} uses: wevm/actions/.github/workflows/issue-labeled.yml@f7ad7f00e16e73322562922c241f21f0c7ffbbec with: needs-reproduction-body: | Hello @${{ github.event.issue.user.login }}. Please provide a [minimal reproduction](https://stackoverflow.com/help/minimal-reproducible-example) using [StackBlitz](https://new.wagmi.sh), [TypeScript Playground](https://www.typescriptlang.org/play) (for type issues), or a separate minimal GitHub repository. [Minimal reproductions are required](https://antfu.me/posts/why-reproductions-are-required) as they save us a lot of time reproducing your config/environment and issue, and allow us to help you faster. Once a minimal reproduction is added, a team member will confirm it works, then re-open the issue. ================================================ FILE: .github/workflows/lock-issue.yml ================================================ name: Lock Issue permissions: issues: write on: schedule: - cron: '0 0 * * *' jobs: lock-issue: if: ${{ github.repository_owner == 'wevm' }} uses: wevm/actions/.github/workflows/lock-issue.yml@f7ad7f00e16e73322562922c241f21f0c7ffbbec with: issue-comment: | This issue has been locked since it has been closed for more than 14 days. If you found a concrete bug or regression related to it, please open a new [bug report](https://github.com/wevm/wagmi/issues/new?template=bug_report.yml) with a reproduction against the latest Wagmi version. If you have any questions or comments you can create a new [discussion thread](https://github.com/wevm/wagmi/discussions). ================================================ FILE: .github/workflows/pull-request.yml ================================================ name: Pull Request on: pull_request: types: [opened, reopened, synchronize, ready_for_review] permissions: contents: read concurrency: group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} cancel-in-progress: true jobs: verify: name: Verify permissions: contents: write uses: ./.github/workflows/verify.yml secrets: inherit publish: name: Publish preview release # prevents this action from running on forks if: github.repository == 'wevm/wagmi' permissions: contents: read runs-on: ubuntu-latest timeout-minutes: 5 steps: - name: Clone repository uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 - name: Install dependencies uses: wevm/actions/.github/actions/pnpm@f7ad7f00e16e73322562922c241f21f0c7ffbbec with: node-version: 24.5 - name: Publish to pkg.pr.new run: | pnpm changeset:prepublish pnpx pkg-pr-new publish --pnpm --compact './packages/*' env: PKG_PR_NEW: true size: name: Size permissions: contents: read pull-requests: write runs-on: ubuntu-latest timeout-minutes: 5 steps: - name: Clone repository uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 - name: Install dependencies uses: wevm/actions/.github/actions/pnpm@f7ad7f00e16e73322562922c241f21f0c7ffbbec with: node-version: 24.5 - name: Report build size uses: preactjs/compressed-size-action@946a292cd35bd1088e0d7eb92b69d1a8d5b5d76a with: pattern: 'packages/**/dist/**' repo-token: ${{ secrets.GITHUB_TOKEN }} ================================================ FILE: .github/workflows/scorecard.yml ================================================ name: Scorecard on: # For Branch-Protection check. Only the default branch is supported. See # https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection branch_protection_rule: # To guarantee Maintained check is occasionally updated. See # https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained schedule: - cron: '22 13 * * 0' push: branches: [ "main" ] # Declare default permissions as read only. permissions: read-all jobs: analysis: name: Scorecard analysis runs-on: ubuntu-latest # `publish_results: true` only works when run from the default branch. conditional can be removed if disabled. if: github.event.repository.default_branch == github.ref_name || github.event_name == 'pull_request' permissions: # Needed to upload the results to code-scanning dashboard. security-events: write # Needed to publish results and get a badge (see publish_results below). id-token: write steps: - name: "Checkout code" uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 with: persist-credentials: false - name: "Run analysis" uses: ossf/scorecard-action@f49aabe0b5af0936a0987cfb85d86b75731b0186 # v2.4.1 with: results_file: results.sarif results_format: sarif publish_results: true - name: "Upload artifact" uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # v4.6.1 with: name: SARIF file path: results.sarif retention-days: 5 - name: "Upload to code-scanning" uses: github/codeql-action/upload-sarif@80cb6b56b93de3e779c7d476d9100d06fb87c877 # codeql-bundle-v2.23.2 with: sarif_file: results.sarif ================================================ FILE: .github/workflows/verify.yml ================================================ name: Verify on: workflow_call: workflow_dispatch: permissions: contents: read jobs: check: name: Check permissions: contents: write runs-on: ubuntu-latest timeout-minutes: 5 steps: - name: Clone repository uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 with: token: ${{ secrets.GH_PTOKEN }} - name: Install dependencies uses: wevm/actions/.github/actions/pnpm@f7ad7f00e16e73322562922c241f21f0c7ffbbec with: node-version: 24.5 - name: Audit dependencies run: pnpm audit - name: Check repo run: pnpm check:repo - name: Check code run: pnpm check - name: Update package versions run: pnpm version:update - uses: stefanzweifel/git-auto-commit-action@778341af668090896ca464160c2def5d1d1a3eb0 # v6.0.1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: commit_message: 'chore: format' commit_user_name: 'github-actions[bot]' commit_user_email: 'github-actions[bot]@users.noreply.github.com' build: name: Build permissions: contents: read needs: check runs-on: ubuntu-latest timeout-minutes: 5 steps: - name: Clone repository uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 - name: Install dependencies uses: wevm/actions/.github/actions/pnpm@f7ad7f00e16e73322562922c241f21f0c7ffbbec with: node-version: 24.5 - name: Build run: pnpm clean && pnpm build - name: Publint run: pnpm test:build - name: Check for unused files, dependencies, and exports run: pnpm knip --production types: name: Types permissions: contents: read needs: check runs-on: ubuntu-latest timeout-minutes: 5 strategy: matrix: typescript-version: ['5.7.3', '5.8.3', '5.9.3', 'latest'] viem-version: ['2.46.0', 'latest'] steps: - name: Clone repository uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 - name: Install dependencies uses: wevm/actions/.github/actions/pnpm@f7ad7f00e16e73322562922c241f21f0c7ffbbec with: node-version: 24.5 - run: pnpm add -D -w typescript@${{ matrix.typescript-version }} viem@${{ matrix.viem-version }} - name: Link packages run: pnpm preconstruct - name: Check types run: pnpm check:types - name: Bench types run: pnpm bench:types # Redundant with `pnpm check:types` # If Vitest adds special features in the future, e.g. type coverage, can add this back! # - name: Test types # run: pnpm test:typecheck test: name: Test permissions: contents: read runs-on: ubuntu-latest timeout-minutes: 20 strategy: max-parallel: 4 matrix: shard: [1, 2, 3, 4] total-shards: [4] steps: - name: Clone repository uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 - name: Install dependencies uses: wevm/actions/.github/actions/pnpm@f7ad7f00e16e73322562922c241f21f0c7ffbbec with: node-version: 24.5 - name: Setup Docker uses: docker/setup-docker-action@v4 - name: Set up foundry uses: foundry-rs/foundry-toolchain@50d5a8956f2e319df19e6b57539d7e2acb9f8c1e # v1.5.0 with: version: nightly - name: Cache Playwright uses: actions/cache@9255dc7a253b0ccc959486e2bca901246202afeb id: playwright-cache with: path: ~/.cache/ms-playwright key: ${{ runner.os }}-playwright-${{ hashFiles('pnpm-lock.yaml') }} - name: Install Playwright if: steps.playwright-cache.outputs.cache-hit != 'true' run: pnpm exec playwright install chromium --with-deps - name: Pull Tempo Docker image run: docker pull ghcr.io/tempoxyz/tempo:latest - name: Run tests uses: nick-fields/retry@ce71cc2ab81d554ebbe88c79ab5975992d79ba08 with: command: CI=true pnpm test:cov --shard=${{ matrix.shard }}/${{ matrix.total-shards }} --retry=3 --bail=1 max_attempts: 3 timeout_minutes: 5 env: VITE_MAINNET_FORK_URL: ${{ secrets.VITE_MAINNET_FORK_URL }} VITE_OPTIMISM_FORK_URL: ${{ secrets.VITE_OPTIMISM_FORK_URL }} - name: Upload coverage reports to Codecov uses: codecov/codecov-action@5a1091511ad55cbe89839c7260b706298ca349f7 with: token: ${{ secrets.CODECOV_TOKEN }} ================================================ FILE: .gitignore ================================================ *.vitest-temp.json .DS_Store .attest .next .nuxt .pnpm-debug.log* .tanstack .wrangler _ cache coverage dist node_modules tsconfig.tsbuildinfo # local env files .env .env.local .env.development.local .env.test.local .env.production.local .envrc # proxy packages packages/cli/config packages/cli/plugins packages/core/actions packages/core/chains packages/core/codegen packages/core/experimental packages/core/internal packages/core/query packages/core/tempo packages/react/actions packages/react/chains packages/react/codegen packages/react/connectors packages/react/experimental packages/react/internal packages/react/query packages/react/tempo packages/solid/actions packages/solid/chains packages/solid/connectors packages/solid/internal packages/solid/query packages/vue/actions packages/vue/chains packages/vue/connectors packages/vue/internal packages/vue/nuxt packages/vue/query .vercel .env*.local ================================================ FILE: .vscode/extensions.json ================================================ { "recommendations": [ "biomejs.biome", "orta.vscode-twoslash-queries", "Vue.volar" ] } ================================================ FILE: .vscode/settings.json ================================================ { "editor.defaultFormatter": "biomejs.biome", "editor.formatOnSave": true, "typescript.enablePromptUseWorkspaceTsdk": true, "typescript.preferences.importModuleSpecifier": "shortest", "typescript.tsdk": "node_modules/typescript/lib", "editor.codeActionsOnSave": { "source.fixAll.biome": "explicit" }, "[javascript][javascriptreact][json][typescript][typescriptreact]": { "editor.defaultFormatter": "biomejs.biome" }, "[vue]": { "editor.defaultFormatter": "Vue.volar" } } ================================================ FILE: .vscode/workspace.code-workspace ================================================ { "folders": [ { "name": "docs", "path": "../docs" }, { "name": "packages", "path": "../packages" }, { "name": "playgrounds", "path": "../playgrounds" } ] } ================================================ FILE: FUNDING.json ================================================ { "drips": { "ethereum": { "ownedBy": "0xd2135CfB216b74109775236E36d4b433F1DF507B" } }, "opRetro": { "projectId": "0xc0615947773148cbc340b175fb9afc98dbb4e0acd31d018b1ee41a5538785abf" } } ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2022-present weth, LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: biome.json ================================================ { "$schema": "./node_modules/@biomejs/biome/configuration_schema.json", "files": { "includes": [ "**", "!**/CHANGELOG.md", "!**/pnpm-lock.yaml", "!**/routeTree.gen.ts", "!**/tsconfig.base.json", "!**/worker-configuration.d.ts" ] }, "formatter": { "enabled": true, "formatWithErrors": false, "indentStyle": "space", "indentWidth": 2, "lineWidth": 80 }, "linter": { "includes": ["**", "!**/packages/create-wagmi/templates/**/*"], "enabled": true, "rules": { "recommended": true, "a11y": { "useButtonType": "off" }, "complexity": { "noImportantStyles": "off" }, "correctness": { "noUnusedVariables": "error", "useExhaustiveDependencies": "error" }, "performance": { "noBarrelFile": "error", "noReExportAll": "error", "noDelete": "off" }, "style": { "noNonNullAssertion": "off", "noParameterAssign": "error", "useAsConstAssertion": "error", "useDefaultParameterLast": "error", "useEnumInitializers": "error", "useSelfClosingElements": "error", "useSingleVarDeclarator": "error", "noUnusedTemplateLiteral": "error", "useNumberNamespace": "error", "noInferrableTypes": "error", "noUselessElse": "error", "useConsistentArrayType": { "level": "error", "options": { "syntax": "shorthand" } } }, "suspicious": { "noArrayIndexKey": "off", "noConfusingVoidType": "off", "noExplicitAny": "off", "noConsole": { "level": "error", "options": { "allow": ["log"] } }, "noTsIgnore": "off" } } }, "javascript": { "formatter": { "quoteStyle": "single", "trailingCommas": "all", "semicolons": "asNeeded" } }, "assist": { "actions": { "source": { "organizeImports": "on" } } }, "overrides": [ { "includes": ["**/*.vue"], "linter": { "rules": { "correctness": { "noUnusedImports": "off", "noUnusedVariables": "off" } } } }, { "includes": ["site/snippets/**"], "linter": { "rules": { "correctness": { "noUnusedImports": "off" } } } }, { "includes": ["scripts/**/*.ts"], "linter": { "rules": { "suspicious": { "noConsole": { "level": "off", "options": { "allow": ["log"] } } } } } }, { "includes": ["playgrounds/**"], "linter": { "rules": { "style": { "useNodejsImportProtocol": "off" } } } } ], "vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true } } ================================================ FILE: package.json ================================================ { "name": "workspace", "private": true, "type": "module", "scripts": { "build": "pnpm run --filter @wagmi/core --filter @wagmi/cli --filter create-wagmi build && pnpm run --filter @wagmi/connectors build && pnpm run --filter wagmi --filter @wagmi/solid --filter @wagmi/vue build", "bench:types": "TYPES=true vitest bench-d.ts", "changeset:prepublish": "pnpm clean && pnpm version:update && pnpm build && node scripts/formatPackageJson.ts && node scripts/generateProxyPackages.ts", "changeset:publish": "pnpm changeset:prepublish && changeset publish", "changeset:version": "changeset version && pnpm version:update && pnpm format", "check": "biome check --write", "check:repo": "sherif -i viem", "check:types": "pnpm run --r --parallel check:types && tsc --noEmit", "check:unused": "pnpm clean && knip", "clean": "pnpm run --r --parallel clean && rm -rf packages/**/*.json.tmp", "deps": "pnpx taze -r", "deps:ci": "pnpx actions-up", "dev": "pnpm dev:react", "dev:cli": "pnpm --filter cli dev", "dev:core": "pnpm --filter vite-core dev", "dev:create-wagmi": "pnpm --filter create-wagmi dev", "dev:next": "pnpm --filter next-app dev", "dev:nuxt": "pnpm --filter nuxt-app dev", "dev:react": "pnpm --filter vite-react dev", "dev:solid": "pnpm --filter vite-solid dev", "dev:solid-start": "pnpm --filter solid-start-app dev", "dev:start": "pnpm --filter tanstack-start dev", "dev:vue": "pnpm --filter vite-vue dev", "docs:dev": "pnpm --filter site dev", "format": "biome format --write", "postinstall": "pnpm preconstruct", "preconstruct": "node scripts/preconstruct.ts", "preinstall": "pnpx only-allow pnpm", "prepare": "pnpm simple-git-hooks", "test": "vitest", "test:build": "node scripts/generateProxyPackages.ts && pnpm run --r --parallel test:build", "test:cov": "vitest run --coverage", "test:update": "vitest --update", "version:update": "node scripts/updateVersion.ts", "version:update:viem": "node scripts/updateViemVersion.ts" }, "devDependencies": { "@arethetypeswrong/cli": "^0.16.4", "@ark/attest": "^0.56.0", "@biomejs/biome": "^2.2.4", "@changesets/cli": "^3.0.0-next.0", "@svitejs/changesets-changelog-github-compact": "^1.2.0", "@types/node": "^24.5.1", "@vitejs/plugin-react": "catalog:", "@vitest/browser": "^4.0.16", "@vitest/browser-playwright": "^4.0.16", "@vitest/coverage-v8": "^4.0.16", "@wagmi/test": "workspace:*", "happy-dom": "^20.0.0", "knip": "^5.69.0", "playwright": "1.56.1", "prool": "^0.2.3", "publint": "^0.3.18", "react": "catalog:", "react-dom": "catalog:", "sherif": "^1.0.0", "simple-git-hooks": "^2.11.1", "solid-js": "catalog:", "testcontainers": "^11.13.0", "typescript": "^5.9.3", "viem": "2.47.5", "vite-plugin-react-fallback-throttle": "^0.1.1", "vite-plugin-solid": "catalog:", "vitest": "^4.0.16", "vitest-browser-react": "^2.0.2" }, "packageManager": "pnpm@10.22.0", "devEngines": { "runtime": { "name": "node", "version": "^24.5.1", "onFail": "download" } }, "simple-git-hooks": { "pre-commit": "pnpm check" }, "knip": { "ignore": [ "**/templates/**", "**/hardhat.config.js", "packages/**/*.bench-d.ts", "scripts/**" ], "ignoreWorkspaces": [ "packages/register-tests/**", "packages/test", "playgrounds/**", "site/**" ], "workspaces": { "packages/cli": { "entry": [ "src/cli.ts!", "src/exports/{config,index,plugins}.ts!", "types/*.d.ts!" ], "ignore": [ "test/{constants,setup,utils}.ts" ] }, "packages/connectors": { "entry": "src/exports/index.ts!", "ignoreDependencies": [ "@base-org/account", "@coinbase/wallet-sdk", "@metamask/connect-evm", "@safe-global/safe-apps-provider", "@safe-global/safe-apps-sdk", "@wagmi/core", "@walletconnect/ethereum-provider", "porto" ] }, "packages/core": { "entry": "src/exports/{actions,chains,codegen,experimental,index,internal,query,tempo}.ts!", "ignore": [ "test/setup.ts" ], "ignoreDependencies": [ "@tanstack/query-core", "ox" ] }, "packages/create-wagmi": { "entry": "src/cli.ts!" }, "packages/react": { "entry": [ "src/exports/{actions,chains,codegen,connectors,experimental,index,query,tempo}.ts!", "src/exports/actions/experimental.ts!" ], "ignore": [ "test/setup.ts" ] }, "packages/test": { "entry": [ "src/setup.ts!", "src/setup.global.ts!", "src/setup.global.types.ts!", "src/exports/{index,react,tempo}.ts!", "src/tempo/setup.ts!", "src/tempo/setup.global.ts!" ] }, "packages/vue": { "entry": [ "src/exports/{actions,chains,connectors,index,nuxt,query}.ts!", "src/exports/actions/experimental.ts!" ], "ignore": [ "src/nuxt/runtime/*", "test/setup.ts" ], "ignoreDependencies": [ "nuxt" ] }, "packages/solid": { "entry": [ "src/exports/{actions,chains,connectors,index,query}.ts!", "src/exports/actions/experimental.ts!" ], "ignore": [ "test/setup.ts" ] } } } } ================================================ FILE: packages/cli/CHANGELOG.md ================================================ # @wagmi/cli ## 2.10.0 ### Minor Changes - **Breaking:** Removed `routescan` plugin (former sponsor). If you still need this plugin, vendor the [source code](https://github.com/wevm/wagmi/blob/ed2d473172e8d063f29400b8edcec33e5d21a659/packages/cli/src/plugins/routescan.ts) into your project directly. ([`9dbdd82`](https://github.com/wevm/wagmi/commit/9dbdd8277808eb361fe7fe01ea34e4c6bb85c7a5)) ## 2.9.0 ### Minor Changes - Added `includeBroadcasts` option to Foundry plugin to automatically populate deployments mapping from `run-latest.json` files in the `broadcast/` directory. ([#4908](https://github.com/wevm/wagmi/pull/4908)) ## 2.8.0 ### Minor Changes - Added option to React plugin to disable generating hooks for each function/event in ABI. ([#4866](https://github.com/wevm/wagmi/pull/4866)) ## 2.7.1 ### Patch Changes - Bumped chains for block explorer plugins. ([`ed2d473`](https://github.com/wevm/wagmi/commit/ed2d473172e8d063f29400b8edcec33e5d21a659)) ## 2.7.0 ### Minor Changes - Updated block explorer plugins supported chains. ([#4830](https://github.com/wevm/wagmi/pull/4830)) ## 2.6.0 ### Minor Changes - Bumped internal deps. ([#4808](https://github.com/wevm/wagmi/pull/4808)) ## 2.5.1 ### Patch Changes - [#4773](https://github.com/wevm/wagmi/pull/4773) [`d4c367ca46c508598c997cf229a31593a1e2b8b8`](https://github.com/wevm/wagmi/commit/d4c367ca46c508598c997cf229a31593a1e2b8b8) Thanks [@tmm](https://github.com/tmm)! - Fixed issue with codegen actions/hooks, where `syncConnectedChain: false` did not work as intended. ## 2.5.0 ### Minor Changes - [`1edb09f7b69da3d7819d0e070e875e2c6fe8015d`](https://github.com/wevm/wagmi/commit/1edb09f7b69da3d7819d0e070e875e2c6fe8015d) Thanks [@tmm](https://github.com/tmm)! - Added testnets to `routescan` plugin ## 2.4.0 ### Minor Changes - [#4757](https://github.com/wevm/wagmi/pull/4757) [`aec8a61ef0dfe02421d514bd130505ec13f8d3a0`](https://github.com/wevm/wagmi/commit/aec8a61ef0dfe02421d514bd130505ec13f8d3a0) Thanks [@tmm](https://github.com/tmm)! - Added Routescan plugin. ## 2.3.2 ### Patch Changes - [#4727](https://github.com/wevm/wagmi/pull/4727) [`910e6c6180bd632e65bad348bd0814de5a8cfa4b`](https://github.com/wevm/wagmi/commit/910e6c6180bd632e65bad348bd0814de5a8cfa4b) Thanks [@reallesee](https://github.com/reallesee)! - `fetch` plugin: cleared timeout on fetch error ## 2.3.1 ### Patch Changes - [#4655](https://github.com/wevm/wagmi/pull/4655) [`43241c8417f3c342036bb46ec8e507d052ae2691`](https://github.com/wevm/wagmi/commit/43241c8417f3c342036bb46ec8e507d052ae2691) Thanks [@tmm](https://github.com/tmm)! - Bumped internal deps. ## 2.3.0 ### Minor Changes - [#4629](https://github.com/wevm/wagmi/pull/4629) [`66dec7d75d580b3121ebc7e8162c1f9ae37cfd41`](https://github.com/wevm/wagmi/commit/66dec7d75d580b3121ebc7e8162c1f9ae37cfd41) Thanks [@allezxandre](https://github.com/allezxandre)! - Upgraded to Sourcify v2 API in `sourcify` plugin ## 2.2.1 ### Patch Changes - [`7b0dbe3886c1a7c6dbbdab945d7436ec20ad8f93`](https://github.com/wevm/wagmi/commit/7b0dbe3886c1a7c6dbbdab945d7436ec20ad8f93) Thanks [@tmm](https://github.com/tmm)! - Updated block explorer chains. ## 2.2.0 ### Minor Changes - [#4503](https://github.com/wevm/wagmi/pull/4503) [`8fce8a6f97aa2ee5fd1bda6a3ece422b10324b5a`](https://github.com/wevm/wagmi/commit/8fce8a6f97aa2ee5fd1bda6a3ece422b10324b5a) Thanks [@tmm](https://github.com/tmm)! - Updated Etherscan Plugin to use Etherscan API v2. - [#4507](https://github.com/wevm/wagmi/pull/4507) [`6f09cc57935891e1c67d6df3459f6998985c69dc`](https://github.com/wevm/wagmi/commit/6f09cc57935891e1c67d6df3459f6998985c69dc) Thanks [@tmm](https://github.com/tmm)! - Added `tryFetchProxyImplementation` flag to Etherscan Plugin to enable fetching the implementation ABI instead of the proxy ABI. ## 2.1.22 ### Patch Changes - [#4462](https://github.com/wevm/wagmi/pull/4462) [`0b2238d27cecbcd33aee64fb0e30ddc18b6ddf74`](https://github.com/wevm/wagmi/commit/0b2238d27cecbcd33aee64fb0e30ddc18b6ddf74) Thanks [@groninge01](https://github.com/groninge01)! - Added Sonic to Etherscan plugin. ## 2.1.21 ### Patch Changes - [#4457](https://github.com/wevm/wagmi/pull/4457) [`21ec74da7f93fc13e253d7b35ddeddc23422a6c1`](https://github.com/wevm/wagmi/commit/21ec74da7f93fc13e253d7b35ddeddc23422a6c1) Thanks [@tmm](https://github.com/tmm)! - Removed internal dependency. ## 2.1.20 ### Patch Changes - [#4450](https://github.com/wevm/wagmi/pull/4450) [`7b9a6bb35881b657a00bdd7ccd7edea32660f5bf`](https://github.com/wevm/wagmi/commit/7b9a6bb35881b657a00bdd7ccd7edea32660f5bf) Thanks [@tmm](https://github.com/tmm)! - Removed internal usage of `fs-extra`. ## 2.1.19 ### Patch Changes - [#4449](https://github.com/wevm/wagmi/pull/4449) [`3fa5c238baa13d948e89974b0bb8530f8fa264fd`](https://github.com/wevm/wagmi/commit/3fa5c238baa13d948e89974b0bb8530f8fa264fd) Thanks [@tmm](https://github.com/tmm)! - Removed `ora` for `nanospinner`. ## 2.1.18 ### Patch Changes - [#4399](https://github.com/wevm/wagmi/pull/4399) [`bc18673e4c272e3b60a1b6016934fe3fbeb6d93a`](https://github.com/wevm/wagmi/commit/bc18673e4c272e3b60a1b6016934fe3fbeb6d93a) Thanks [@tmm](https://github.com/tmm)! - Added Polygon Amoy to Sourcify and Etherscan plugins. ## 2.1.17 ### Patch Changes - [#4370](https://github.com/wevm/wagmi/pull/4370) [`cb58b1ea3ad40e77210f24eb598f9d2306db998c`](https://github.com/wevm/wagmi/commit/cb58b1ea3ad40e77210f24eb598f9d2306db998c) Thanks [@talentlessguy](https://github.com/talentlessguy)! - Bumped internal dependencies. ## 2.1.16 ### Patch Changes - [#4224](https://github.com/wevm/wagmi/pull/4224) [`b0eb89c2a0781bb3434996fa53ee7ceb3bb44db9`](https://github.com/wevm/wagmi/commit/b0eb89c2a0781bb3434996fa53ee7ceb3bb44db9) Thanks [@roderik](https://github.com/roderik)! - Fixed package detection for Bun. ## 2.1.15 ### Patch Changes - [`0bb8b562ae04ecfeb2d6b2f1b980ebae31dc127e`](https://github.com/wevm/wagmi/commit/0bb8b562ae04ecfeb2d6b2f1b980ebae31dc127e) Thanks [@tmm](https://github.com/tmm)! - Improved TypeScript `'exactOptionalPropertyTypes'` support. ## 2.1.14 ### Patch Changes - [#4120](https://github.com/wevm/wagmi/pull/4120) [`59407bf1276a46e6f1f22a370dde71c92524cd0f`](https://github.com/wevm/wagmi/commit/59407bf1276a46e6f1f22a370dde71c92524cd0f) Thanks [@tmm](https://github.com/tmm)! - Fixed an issue where the Foundry and Hardhat plugins' `exclude` option was ignored. ## 2.1.13 ### Patch Changes - [`7264d1f450727f6ba0cbea8aa1c7a83e22a5bf20`](https://github.com/wevm/wagmi/commit/7264d1f450727f6ba0cbea8aa1c7a83e22a5bf20) Thanks [@tmm](https://github.com/tmm)! - Fixed generate not exiting for long-running processes. ## 2.1.12 ### Patch Changes - [`ac038b29623ccb0d2fee40d9f943c8df28138dac`](https://github.com/wevm/wagmi/commit/ac038b29623ccb0d2fee40d9f943c8df28138dac) Thanks [@tmm](https://github.com/tmm)! - Updated Foundry default excludes. ## 2.1.11 ### Patch Changes - [#4084](https://github.com/wevm/wagmi/pull/4084) [`b54203bf8fa911e6f14b9675980cf38fb95d7d3e`](https://github.com/wevm/wagmi/commit/b54203bf8fa911e6f14b9675980cf38fb95d7d3e) Thanks [@tmm](https://github.com/tmm)! - Reduced internal dependencies. ## 2.1.10 ### Patch Changes - [#4051](https://github.com/wevm/wagmi/pull/4051) [`275e78b0e585f0ec9da2f9661ce9990aed18e9f4`](https://github.com/wevm/wagmi/commit/275e78b0e585f0ec9da2f9661ce9990aed18e9f4) Thanks [@tmm](https://github.com/tmm)! - Updated Sourcify plugin internals. ## 2.1.9 ### Patch Changes - [`f9346dbcffaf57a8949cb96e43df111a89d733b1`](https://github.com/wevm/wagmi/commit/f9346dbcffaf57a8949cb96e43df111a89d733b1) Thanks [@tmm](https://github.com/tmm)! - Updated Foundry plugin default excludes. ## 2.1.8 ### Patch Changes - [#3957](https://github.com/wevm/wagmi/pull/3957) [`7d00680f73b090eb34af928ae74277bec1973953`](https://github.com/wevm/wagmi/commit/7d00680f73b090eb34af928ae74277bec1973953) Thanks [@cstoneham](https://github.com/cstoneham)! - Added Blast to Etherscan plugin ## 2.1.7 ### Patch Changes - [`1122678bbad0232590bd4060a73752de2c84982d`](https://github.com/wevm/wagmi/commit/1122678bbad0232590bd4060a73752de2c84982d) Thanks [@tmm](https://github.com/tmm)! - Published unpublished changes in [#3756](https://github.com/wevm/wagmi/pull/3756). ## 2.1.6 ### Patch Changes - [#3756](https://github.com/wevm/wagmi/pull/3756) [`c7d6f467`](https://github.com/wevm/wagmi/commit/c7d6f4679125fd2f6cca5b5ef362abf47e37f934) Thanks [@jrfrantz](https://github.com/jrfrantz)! - Added basescan to etherscan cli plugin ## 2.1.5 ### Patch Changes - [`e1ca4e63`](https://github.com/wevm/wagmi/commit/e1ca4e637ae6cec7f5902b0a2c0e0efc3b751a1d) Thanks [@tmm](https://github.com/tmm)! - Added title to CLI process. - [#3723](https://github.com/wevm/wagmi/pull/3723) [`d6bc98ca`](https://github.com/wevm/wagmi/commit/d6bc98ca0ce9081f192f62e0b0fcfea3cb07a2bb) Thanks [@leecobaby](https://github.com/leecobaby)! - Broadened TypeScript detection. ## 2.1.4 ### Patch Changes - [#3737](https://github.com/wevm/wagmi/pull/3737) [`11020fed`](https://github.com/wevm/wagmi/commit/11020fedfc68639eace241e328331cff43bf91af) Thanks [@oskarvu](https://github.com/oskarvu)! - Added Gnosis to Etherscan plugin. ## 2.1.3 ### Patch Changes - [#3660](https://github.com/wevm/wagmi/pull/3660) [`11a22a23`](https://github.com/wevm/wagmi/commit/11a22a23d88c025cde9c91610e9ddf62cd4fa650) Thanks [@JazzBashara](https://github.com/JazzBashara)! - Replaced SnowTrace with SnowScan for the Etherscan plugin ## 2.1.2 ### Patch Changes - [#3641](https://github.com/wevm/wagmi/pull/3641) [`0a866403`](https://github.com/wevm/wagmi/commit/0a866403182ea6b8ba7f976c45be294e48fb7de8) Thanks [@cmwhited](https://github.com/cmwhited)! - Added Arbitrum Sepolia testnet to Etherscan plugin - [#3633](https://github.com/wevm/wagmi/pull/3633) [`a1d3d1ab`](https://github.com/wevm/wagmi/commit/a1d3d1ab2b023c61c0dbb5d7bf867a9fca673630) Thanks [@pegahcarter](https://github.com/pegahcarter)! - Added Fraxtal to Etherscan plugin - [#3616](https://github.com/wevm/wagmi/pull/3616) [`2a9f4473`](https://github.com/wevm/wagmi/commit/2a9f4473adc5bcdddf388389387ed5459583769e) Thanks [@petermazzocco](https://github.com/petermazzocco)! - Added Holesky Testnet to Etherscan Plugin ## 2.1.1 ### Patch Changes - [#3579](https://github.com/wevm/wagmi/pull/3579) [`a057919c`](https://github.com/wevm/wagmi/commit/a057919ca3942adeed90af2e343403dc5274e84c) Thanks [@FaisalAli19](https://github.com/FaisalAli19)! - Added Optimism Sepolia Etherscan support ## 2.1.0 ### Minor Changes - [#3506](https://github.com/wevm/wagmi/pull/3506) [`134eb4a1`](https://github.com/wevm/wagmi/commit/134eb4a1e0e29aab87bd5c7cdf05b06dfd7c4fc4) Thanks [@vmaark](https://github.com/vmaark)! - Added resolution of TypeScript Wagmi CLI config to determine if TypeScript generated output is allowed. ## 2.0.4 ### Patch Changes - [#3462](https://github.com/wevm/wagmi/pull/3462) [`d25573ea`](https://github.com/wevm/wagmi/commit/d25573ea03358f967953e37c176b220a7b341769) Thanks [@cruzdanilo](https://github.com/cruzdanilo)! - Upgraded dependencies ## 2.0.3 ### Patch Changes - [#3410](https://github.com/wevm/wagmi/pull/3410) [`55e31c3e`](https://github.com/wevm/wagmi/commit/55e31c3e96c2cbd1d9eb44e5a89f4365489c8310) Thanks [@o-az](https://github.com/o-az)! - Fixed actions plugin issue where `functionName` was used instead of `eventName` for generated contract event actions. ## 2.0.2 ### Patch Changes - [#3371](https://github.com/wevm/wagmi/pull/3371) [`8294d9e5`](https://github.com/wevm/wagmi/commit/8294d9e5b358018ba869b2018cd7ed95462e021f) Thanks [@iceanddust](https://github.com/iceanddust)! - Fixed prop name when generating contract event watch hooks ## 2.0.1 ### Major Changes - [#3333](https://github.com/wevm/wagmi/pull/3333) [`b3a0baaa`](https://github.com/wevm/wagmi/commit/b3a0baaaee7decf750d376aab2502cd33ca4825a) Thanks [@tmm](https://github.com/tmm)! - Wagmi CLI 2.0. [Breaking Changes & Migration Guide](https://wagmi.sh/cli/guides/migrate-from-v1-to-v2) ## 1.5.2 ### Patch Changes - [#3051](https://github.com/wagmi-dev/wagmi/pull/3051) [`4704d351`](https://github.com/wagmi-dev/wagmi/commit/4704d351164d39704a4e375c06525554fcc8340e) Thanks [@oxSaturn](https://github.com/oxSaturn)! - Fixed ESM require issue for prettier ## 1.5.1 ### Patch Changes - [#3035](https://github.com/wagmi-dev/wagmi/pull/3035) [`187bf96c`](https://github.com/wagmi-dev/wagmi/commit/187bf96c9fd31675b9d17a7cb4d4e24eea3fa777) Thanks [@cruzdanilo](https://github.com/cruzdanilo)! - ignore foundry invariant lib ## 1.5.0 ### Minor Changes - [#2956](https://github.com/wevm/wagmi/pull/2956) [`2abeb285`](https://github.com/wevm/wagmi/commit/2abeb285674af3e539cc2550b1f5027b1eb0c895) Thanks [@tmm](https://github.com/tmm)! - Replaced `@wagmi/chains` with `viem/chains`. ## 1.4.1 ### Patch Changes - [#2962](https://github.com/wevm/wagmi/pull/2962) [`8ac5b572`](https://github.com/wevm/wagmi/commit/8ac5b57254f77eeb0e07dd83f7d49f396d4581d8) Thanks [@tmm](https://github.com/tmm)! - Fixed esbuild version ## 1.4.0 ### Minor Changes - [#2946](https://github.com/wevm/wagmi/pull/2946) [`1c3228bf`](https://github.com/wevm/wagmi/commit/1c3228bf3fe99b0900b2c9a223c9b81c70bdcd90) Thanks [@tomquirk](https://github.com/tomquirk)! - Added default chain ID to generated `useContractRead` hook. ### Patch Changes - [#2547](https://github.com/wevm/wagmi/pull/2547) [`8c3889fe`](https://github.com/wevm/wagmi/commit/8c3889fe82c5a1ddb29e74e3863ea6f4917b777a) Thanks [@Iamshankhadeep](https://github.com/Iamshankhadeep)! - Deterministic CLI output - [#2958](https://github.com/wevm/wagmi/pull/2958) [`b31f36d5`](https://github.com/wevm/wagmi/commit/b31f36d522a634f53d44349d6a9ea47f59d84d7a) Thanks [@tmm](https://github.com/tmm)! - Removed generated file header - [#2960](https://github.com/wevm/wagmi/pull/2960) [`5d4c4592`](https://github.com/wevm/wagmi/commit/5d4c4592009568cd0b096906a424f27469721a42) Thanks [@tmm](https://github.com/tmm)! - Updated esbuild version ## 1.3.0 ### Minor Changes - [#2616](https://github.com/wevm/wagmi/pull/2616) [`c282a8f7`](https://github.com/wevm/wagmi/commit/c282a8f786d57fec77c931fe99dc20220e843bc8) Thanks [@portdeveloper](https://github.com/portdeveloper)! - Added sepolia chain id ## 1.2.1 ### Patch Changes - [#2607](https://github.com/wevm/wagmi/pull/2607) [`79335b4c`](https://github.com/wevm/wagmi/commit/79335b4c0fcd5e8152a2a1d28314c634db9d9cbf) Thanks [@roninjin10](https://github.com/roninjin10)! - Fixed opitmism goerli chain id ## 1.2.0 ### Minor Changes - [#2536](https://github.com/wevm/wagmi/pull/2536) [`85e9760a`](https://github.com/wevm/wagmi/commit/85e9760a140cb169ac6236d9466b96e2105dd193) Thanks [@tmm](https://github.com/tmm)! - Changed `Address` type import from ABIType to viem. ## 1.1.0 ### Minor Changes - [#2482](https://github.com/wevm/wagmi/pull/2482) [`8764b54a`](https://github.com/wevm/wagmi/commit/8764b54aab68020063946112e8fe52aff650c99c) Thanks [@tmm](https://github.com/tmm)! - Bumped minimum TypeScript version to v5.0.4. ### Patch Changes - [#2484](https://github.com/wevm/wagmi/pull/2484) [`3adf1f4f`](https://github.com/wevm/wagmi/commit/3adf1f4feab863cb7b5d52c81ad46f7e4eb56f09) Thanks [@jxom](https://github.com/jxom)! - Updated `abitype` to 0.8.7 - [#2484](https://github.com/wevm/wagmi/pull/2484) [`3adf1f4f`](https://github.com/wevm/wagmi/commit/3adf1f4feab863cb7b5d52c81ad46f7e4eb56f09) Thanks [@jxom](https://github.com/jxom)! - Updated references. ## 1.0.3 ### Patch Changes - [#2441](https://github.com/wevm/wagmi/pull/2441) [`326edee4`](https://github.com/wevm/wagmi/commit/326edee4bc85db84a7a4e3768e33785849ab8d8e) Thanks [@tmm](https://github.com/tmm)! - Fixed internal type issue ## 1.0.2 ### Patch Changes - [#2430](https://github.com/wevm/wagmi/pull/2430) [`71d92029`](https://github.com/wevm/wagmi/commit/71d92029ee4344842cd41698858a330fee95b6e0) Thanks [@tmm](https://github.com/tmm)! - Added message when command is not found. ## 1.0.1 ### Patch Changes - [`ea651cd7`](https://github.com/wevm/wagmi/commit/ea651cd7fc75b7866272605467db11fd6e1d81af) Thanks [@jxom](https://github.com/jxom)! - Downgraded abitype. ## 1.0.0 ### Major Changes - [#2235](https://github.com/wevm/wagmi/pull/2235) [`5be0655c`](https://github.com/wevm/wagmi/commit/5be0655c8e48b25d38009022461fbf611af54349) Thanks [@jxom](https://github.com/jxom)! - Released v1. Read [Migration Guide](https://next.wagmi.sh/react/migration-guide#1xx-breaking-changes). ## 1.0.0-next.7 ### Patch Changes - Fixed react plugin generic. ## 1.0.0-next.6 ### Major Changes - Updated references. ## 1.0.0-next.5 ### Major Changes - Added `config.setConnectors` ## 1.0.0-next.4 ### Major Changes - Updated viem. Removed `goerli` export from main entrypoint. ## 1.0.0-next.3 ### Major Changes - Updated references. ## 1.0.0-next.2 ### Major Changes - Updated dependencies ### Patch Changes - Updated dependencies []: - @wagmi/chains@1.0.0-next.0 ## 1.0.0-next.1 ### Major Changes - updated viem ## 1.0.0-next.0 ### Major Changes - [`a7dda00c`](https://github.com/wevm/wagmi/commit/a7dda00c5b546f8b2c42b527e4d9ac1b9e9ab1fb) Thanks [@jxom](https://github.com/jxom)! - Released v1. ### Patch Changes - Updated dependencies [[`a7dda00c`](https://github.com/wevm/wagmi/commit/a7dda00c5b546f8b2c42b527e4d9ac1b9e9ab1fb)]: - @wagmi/core@1.0.0-next.0 - wagmi@1.0.0-next.0 ## 0.1.15 ### Patch Changes - [#2145](https://github.com/wevm/wagmi/pull/2145) [`2520743c`](https://github.com/wevm/wagmi/commit/2520743c417a158a00d5edca13a9aa92cefb0cfd) Thanks [@tmm](https://github.com/tmm)! - Fixed issue using Hardhat Plugin with npm. ## 0.1.14 ### Patch Changes - [#2039](https://github.com/wevm/wagmi/pull/2039) [`bac893ab`](https://github.com/wevm/wagmi/commit/bac893ab26012d4d8741c4f80e8b8813aee26f0c) Thanks [@tmm](https://github.com/tmm)! - Updated references. - [#2039](https://github.com/wevm/wagmi/pull/2039) [`bac893ab`](https://github.com/wevm/wagmi/commit/bac893ab26012d4d8741c4f80e8b8813aee26f0c) Thanks [@tmm](https://github.com/tmm)! - Fixed Actions plugin `overridePackageName` option. ## 0.1.13 ### Patch Changes - [#2000](https://github.com/wevm/wagmi/pull/2000) [`01254765`](https://github.com/wevm/wagmi/commit/01254765eb37b77aca26500c00c721f08a260912) Thanks [@tmm](https://github.com/tmm)! - Fixed React plugin name conflict. ## 0.1.12 ### Patch Changes - [#1992](https://github.com/wevm/wagmi/pull/1992) [`efc93cad`](https://github.com/wevm/wagmi/commit/efc93cadacdb9c9960644dabe4ae837d384df52b) Thanks [@tmm](https://github.com/tmm)! - Refactored internals from ethers to viem. ## 0.1.11 ### Patch Changes - [#1916](https://github.com/wevm/wagmi/pull/1916) [`950490fd`](https://github.com/wevm/wagmi/commit/950490fd132b3fb5b3455e77b58d70f134b8e5c9) Thanks [@technophile-04](https://github.com/technophile-04)! - Updated React plugin to use `Address` type instead of hardcoding `` `0x{string}` ``. ## 0.1.10 ### Patch Changes - [#1892](https://github.com/wevm/wagmi/pull/1892) [`d3d6973b`](https://github.com/wevm/wagmi/commit/d3d6973ba9407e490140d2434eb83aad88d6e10d) Thanks [@greg-schrammel](https://github.com/greg-schrammel)! - Fixed generated read hooks `select` type. ## 0.1.9 ### Patch Changes - [#1886](https://github.com/wevm/wagmi/pull/1886) [`36e119c6`](https://github.com/wevm/wagmi/commit/36e119c6d4bc28a7ae15c9602d0c613bc9681356) Thanks [@roninjin10](https://github.com/roninjin10)! - Fixed package detection for yarn^3 ## 0.1.8 ### Patch Changes - [#1884](https://github.com/wevm/wagmi/pull/1884) [`cc03bb44`](https://github.com/wevm/wagmi/commit/cc03bb44268874f95203de67f6d32586e34c0857) Thanks [@roninjin10](https://github.com/roninjin10)! - Added better compatibility for yarn@^3 in `@wagmi/cli`. ## 0.1.7 ### Patch Changes - [#1841](https://github.com/wevm/wagmi/pull/1841) [`cb707f01`](https://github.com/wevm/wagmi/commit/cb707f01cbdcc62a70cf5c8a162d77948d6b6a56) Thanks [@tmm](https://github.com/tmm)! - Added [Sourcify](https://sourcify.dev) CLI plugin. ## 0.1.6 ### Patch Changes - [#1803](https://github.com/wevm/wagmi/pull/1803) [`09b13538`](https://github.com/wevm/wagmi/commit/09b13538abcde879034293cae39551c30cc81445) Thanks [@shotaronowhere](https://github.com/shotaronowhere)! - Swapped deprecated Arbitrum Rinkeby for Arbitrum Goerli URL for Etherscan Plugin. ## 0.1.5 ### Patch Changes - [#1788](https://github.com/wevm/wagmi/pull/1788) [`c3e16d82`](https://github.com/wevm/wagmi/commit/c3e16d82c9c39b8b1c2f3c51037e11d642a20cd6) Thanks [@tmm](https://github.com/tmm)! - Fixed CLI import ## 0.1.4 ### Patch Changes - [#1779](https://github.com/wevm/wagmi/pull/1779) [`97346750`](https://github.com/wevm/wagmi/commit/973467505dc2bb46198a3e9fe6072306170d24c0) Thanks [@tmm](https://github.com/tmm)! - Made `project` optional for Foundry plugin ## 0.1.3 ### Patch Changes - [#1754](https://github.com/wevm/wagmi/pull/1754) [`298728b5`](https://github.com/wevm/wagmi/commit/298728b5918fa15b6b5b082597204a268d4b01f1) Thanks [@tmm](https://github.com/tmm)! - Updated project resolution for Foundry and Hardhat plugins. - [#1738](https://github.com/wevm/wagmi/pull/1738) [`37c221d0`](https://github.com/wevm/wagmi/commit/37c221d0f4d175084e23a6b172d72f177bfa0c81) Thanks [@roninjin10](https://github.com/roninjin10)! - Added automatic Foundry config detection for artifacts directory. ## 0.1.2 ### Patch Changes - [#1743](https://github.com/wevm/wagmi/pull/1743) [`379315fa`](https://github.com/wevm/wagmi/commit/379315fa359c3118b5d200ec50db3812b0cdd984) Thanks [@kyscott18](https://github.com/kyscott18)! - Add celoscan to `etherscan` plugin ## 0.1.1 ### Patch Changes - [#1736](https://github.com/wevm/wagmi/pull/1736) [`7c43e431`](https://github.com/wevm/wagmi/commit/7c43e431e2eb970610cc6490cee6a4093655a683) Thanks [@tmm](https://github.com/tmm)! - Fixed generated address object key type. ## 0.1.0 ### Minor Changes - [#1732](https://github.com/wevm/wagmi/pull/1732) [`01e21897`](https://github.com/wevm/wagmi/commit/01e2189747a5c22dc758c6d719b4145adc2a643c) Thanks [@tmm](https://github.com/tmm)! - Initial release ================================================ FILE: packages/cli/README.md ================================================ # @wagmi/cli Manage and generate code from Ethereum ABIs ## Installation ```bash pnpm add @wagmi/cli ``` ## Documentation For documentation and guides, visit [wagmi.sh](https://wagmi.sh). ================================================ FILE: packages/cli/package.json ================================================ { "name": "@wagmi/cli", "description": "Manage and generate code from Ethereum ABIs", "version": "2.10.0", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/wevm/wagmi.git", "directory": "packages/cli" }, "scripts": { "build": "pnpm run build:esm+types", "build:esm+types": "tsc --project tsconfig.build.json --outDir ./dist/esm --declaration --declarationMap --declarationDir ./dist/types", "check:types": "tsc --noEmit", "clean": "rm -rf dist tsconfig.tsbuildinfo config plugins", "dev": "bun src/cli.ts", "test:build": "publint --strict && attw --pack --ignore-rules cjs-resolves-to-esm" }, "files": [ "dist/**", "!dist/**/*.tsbuildinfo", "src/**/*.ts", "!src/**/*.test.ts", "!src/**/*.test-d.ts", "/config", "/plugins" ], "bin": { "wagmi": "./dist/esm/cli.js" }, "sideEffects": false, "type": "module", "main": "./dist/esm/exports/index.js", "types": "./dist/types/exports/index.d.ts", "typings": "./dist/types/exports/index.d.ts", "exports": { ".": { "types": "./dist/types/exports/index.d.ts", "default": "./dist/esm/exports/index.js" }, "./config": { "types": "./dist/types/exports/config.d.ts", "default": "./dist/esm/exports/config.js" }, "./plugins": { "types": "./dist/types/exports/plugins.d.ts", "default": "./dist/esm/exports/plugins.js" }, "./package.json": "./package.json" }, "typesVersions": { "*": { "config": [ "./dist/types/exports/config.d.ts" ], "plugins": [ "./dist/types/exports/plugins.d.ts" ] } }, "peerDependencies": { "typescript": ">=5.7.3" }, "peerDependenciesMeta": { "typescript": { "optional": true } }, "dependencies": { "abitype": "^1.1.1", "bundle-require": "^5.1.0", "cac": "^6.7.14", "change-case": "^5.4.4", "chokidar": "4.0.1", "dedent": "^0.7.0", "dotenv": "^16.3.1", "dotenv-expand": "^10.0.0", "esbuild": "~0.25.4", "escalade": "3.2.0", "fdir": "^6.1.1", "nanospinner": "1.2.2", "pathe": "^1.1.2", "picocolors": "^1.0.0", "picomatch": "^3.0.0", "prettier": "^3.0.3", "viem": "2.x", "zod": "^4.1.11" }, "devDependencies": { "@types/dedent": "^0.7.2", "@types/node": "^24.5.1", "fixturez": "^1.1.0", "msw": "^2.4.9" }, "contributors": [ "awkweb.eth ", "jxom.eth " ], "funding": "https://github.com/sponsors/wevm", "keywords": [ "wagmi", "eth", "ethereum", "dapps", "wallet", "web3", "cli" ] } ================================================ FILE: packages/cli/src/cli.ts ================================================ #!/usr/bin/env node import { cac } from 'cac' import { type Generate, generate } from './commands/generate.js' import { type Init, init } from './commands/init.js' import * as logger from './logger.js' import { version } from './version.js' const cli = cac('wagmi') cli .command('generate', 'generate code based on configuration') .option('-c, --config ', '[string] path to config file') .option('-r, --root ', '[string] root path to resolve config from') .option('-w, --watch', '[boolean] watch for changes') .example((name) => `${name} generate`) .action(async (options: Generate) => { await generate(options) if (!options.watch) process.exit(0) }) cli .command('init', 'create configuration file') .option('-c, --config ', '[string] path to config file') .option('-r, --root ', '[string] root path to resolve config from') .example((name) => `${name} init`) .action(async (options: Init) => { await init(options) process.exit(0) }) cli.help() cli.version(version) void (async () => { try { process.title = 'node (wagmi)' } catch {} try { // Parse CLI args without running command cli.parse(process.argv, { run: false }) if (!cli.matchedCommand) { if (cli.args.length === 0) { if (!cli.options.help && !cli.options.version) cli.outputHelp() } else throw new Error(`Unknown command: ${cli.args.join(' ')}`) } await cli.runMatchedCommand() } catch (error) { logger.error(`\n${(error as Error).message}`) process.exit(1) } })() ================================================ FILE: packages/cli/src/commands/generate.test.ts ================================================ import { readFile } from 'node:fs/promises' import dedent from 'dedent' import { resolve } from 'pathe' import { afterEach, beforeEach, expect, test, vi } from 'vitest' import { createFixture, typecheck, watchConsole } from '../../test/utils.js' import { generate } from './generate.js' let console: ReturnType beforeEach(() => { console = watchConsole() vi.useFakeTimers() const date = new Date(2023, 0, 30, 12) vi.setSystemTime(date) }) afterEach(() => { vi.restoreAllMocks() vi.useRealTimers() }) test('generates output', async () => { const { dir } = await createFixture({ files: { tsconfig: true, 'wagmi.config.js': dedent` export default { out: 'generated.js', contracts: [ { abi: [], name: 'Foo', }, ], } `, }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await generate() expect(console.formatted).toMatchInlineSnapshot(` "- Validating plugins √ Validating plugins - Resolving contracts √ Resolving contracts - Running plugins √ Running plugins - Writing to generated.js √ Writing to generated.js" `) }) test('generates typescript output', async () => { const { dir, paths } = await createFixture({ files: { tsconfig: true, 'wagmi.config.ts': dedent` export default { out: 'generated.ts', contracts: [ { abi: [], name: 'Foo', }, ], } `, }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await generate() expect(console.formatted).toMatchInlineSnapshot(` "- Validating plugins √ Validating plugins - Resolving contracts √ Resolving contracts - Running plugins √ Running plugins - Writing to generated.ts √ Writing to generated.ts" `) await expect(typecheck(paths.tsconfig)).resolves.toMatchInlineSnapshot('""') }) test('generates output with plugin', async () => { const { dir } = await createFixture({ files: { tsconfig: true, 'wagmi.config.ts': dedent` export default { out: 'generated.ts', contracts: [ { abi: [], name: 'Foo', }, ], plugins: [ { name: 'Test', async run({ contracts, isTypeScript, outputs }) { return { imports: '/* imports test */', prepend: '/* prepend test */', content: '/* content test */', } }, }, ], } `, }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await generate() expect(console.formatted).toMatchInlineSnapshot(` "- Validating plugins √ Validating plugins - Resolving contracts √ Resolving contracts - Running plugins √ Running plugins - Writing to generated.ts √ Writing to generated.ts" `) /* eslint-disable no-irregular-whitespace */ await expect( readFile(resolve(dir, 'generated.ts'), 'utf8'), ).resolves.toMatchInlineSnapshot(` "/* imports test */ /* prepend test */ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Foo ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// export const fooAbi = [] as const ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Test ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* content test */ " `) /* eslint-enable no-irregular-whitespace */ }) test('behavior: invalid cli options', async () => { const { dir } = await createFixture() const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await expect( generate({ // @ts-expect-error possible to pass untyped options through from cli config: 1, }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [Error: Invalid option - Invalid input: expected string, received number at \`config\`] `) }) test('behavior: config not found', async () => { const { dir } = await createFixture() const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await expect(generate()).rejects.toThrowErrorMatchingInlineSnapshot( '[Error: Config not found]', ) }) test('behavior: config not found for path', async () => { const { dir } = await createFixture() const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) try { await generate({ config: 'wagmi.config.js' }) } catch (error) { expect( (error as Error).message.replace(dir, 'path/to/project'), ).toMatchInlineSnapshot('"Config not found at wagmi.config.js"') } }) test('behavior: config out not unique', async () => { const { dir } = await createFixture({ files: { 'wagmi.config.js': dedent` export default [ { out: 'generated.ts', contracts: [ { abi: [], name: 'Foo', }, ] }, { out: 'generated.ts', contracts: [ { abi: [], name: 'Foo', }, ], }, ] `, }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await expect(generate()).rejects.toThrowErrorMatchingInlineSnapshot( `[Error: out "generated.ts" must be unique.]`, ) }) test('behavior: config contract names not unique', async () => { const { dir } = await createFixture({ files: { 'wagmi.config.js': dedent` export default { out: 'generated.ts', contracts: [ { abi: [], name: 'Foo', }, { abi: [], name: 'Foo', }, ], } `, }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await expect(generate()).rejects.toThrowErrorMatchingInlineSnapshot( `[Error: Contract name "Foo" must be unique.]`, ) }) test('behavior: displays message if no contracts found', async () => { const { dir } = await createFixture({ files: { 'wagmi.config.js': "export default { out: 'generated.ts' }", }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await generate() expect(console.formatted).toMatchInlineSnapshot( ` "- Validating plugins √ Validating plugins - Resolving contracts × Resolving contracts No contracts found." `, ) }) test('behavior: throws when abi is invalid', async () => { const { dir } = await createFixture({ files: { 'wagmi.config.js': dedent` export default { out: 'generated.ts', contracts: [ { abi: [{ type: 'function', name: 'balanceOf', stateMutability: 'view', inputs: [{ type: 'address' }], }], name: 'Foo', }, ], } `, }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await expect(generate()).rejects.toThrowErrorMatchingInlineSnapshot(` [Error: Invalid ABI for contract "Foo" - Invalid input at \`[0]\`] `) }) test('behavior: throws when address is invalid', async () => { const { dir } = await createFixture({ files: { 'wagmi.config.js': dedent` export default { out: 'generated.ts', contracts: [ { abi: [], address: '0xfoo', name: 'Foo', }, ], } `, }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await expect(generate()).rejects.toThrowErrorMatchingInlineSnapshot(` [Error: Invalid address for contract "Foo" - Invalid input] `) }) test('behavior: throws when multichain address is invalid', async () => { const { dir } = await createFixture({ files: { 'wagmi.config.js': dedent` export default { out: 'generated.ts', contracts: [ { abi: [], address: { 1: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 5: '0xfoo', }, name: 'Foo', }, ], } `, }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await expect(generate()).rejects.toThrowErrorMatchingInlineSnapshot(` [Error: Invalid address for contract "Foo" - Invalid address at \`5\`] `) }) test('behavior: displays message if using --watch flag without watchers configured', async () => { const { dir } = await createFixture({ files: { 'wagmi.config.js': dedent` export default { out: 'generated.ts', contracts: [ { abi: [], name: 'Foo', }, ], } `, }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await generate({ watch: true }) expect(console.formatted).toMatchInlineSnapshot(` "- Validating plugins √ Validating plugins - Resolving contracts √ Resolving contracts - Running plugins √ Running plugins - Writing to generated.ts √ Writing to generated.ts Used --watch flag, but no plugins are watching." `) }) test.todo('behavior: save config file logs change') test.todo('behavior: updates on add file') test.todo('behavior: updates on change file') test.todo('behavior: updates on unlink file') test.todo('behavior: runs watch command') test.todo('behavior: shuts down watch on SIGINT/SIGTERM') ================================================ FILE: packages/cli/src/commands/generate.ts ================================================ import { mkdir, writeFile } from 'node:fs/promises' import { Abi as AbiSchema } from 'abitype/zod' import { camelCase } from 'change-case' import type { ChokidarOptions, FSWatcher } from 'chokidar' import { watch } from 'chokidar' import { default as dedent } from 'dedent' import { basename, dirname, resolve } from 'pathe' import pc from 'picocolors' import { type Abi, type Address, getAddress } from 'viem' import { z } from 'zod' import type { Contract, ContractConfig, Plugin, Watch } from '../config.js' import { fromZodError } from '../errors.js' import * as logger from '../logger.js' import { findConfig } from '../utils/findConfig.js' import { format } from '../utils/format.js' import { getAddressDocString } from '../utils/getAddressDocString.js' import { getIsUsingTypeScript } from '../utils/getIsUsingTypeScript.js' import { resolveConfig } from '../utils/resolveConfig.js' const Generate = z.object({ /** Path to config file */ config: z.string().optional(), /** Directory to search for config file */ root: z.string().optional(), /** Watch for file system changes to config and plugins */ watch: z.boolean().optional(), }) export type Generate = z.infer export async function generate(options: Generate = {}) { // Validate command line options try { await Generate.parseAsync(options) } catch (error) { if (error instanceof z.ZodError) throw fromZodError(error, { prefix: 'Invalid option' }) throw error } // Get cli config file const configPath = await findConfig(options) if (!configPath) { if (options.config) throw new Error(`Config not found at ${pc.gray(options.config)}`) throw new Error('Config not found') } const resolvedConfigs = await resolveConfig({ configPath }) const isTypeScript = await getIsUsingTypeScript() type Watcher = FSWatcher & { config?: Watch } const watchers: Watcher[] = [] const watchWriteDelay = 100 const watchOptions = { atomic: true, // awaitWriteFinish: true, ignoreInitial: true, persistent: true, } satisfies ChokidarOptions const outNames = new Set() const isArrayConfig = Array.isArray(resolvedConfigs) const configs = isArrayConfig ? resolvedConfigs : [resolvedConfigs] for (const config of configs) { if (isArrayConfig) logger.log(`Using config ${pc.gray(basename(configPath))}`) if (!config.out) throw new Error('out is required.') if (outNames.has(config.out)) throw new Error(`out "${config.out}" must be unique.`) outNames.add(config.out) // Collect contracts and watch configs from plugins const plugins = (config.plugins ?? []).map((x, i) => ({ ...x, id: `${x.name}-${i}`, })) const spinner = logger.spinner('Validating plugins') spinner.start() for (const plugin of plugins) { await plugin.validate?.() } spinner.success() // Add plugin contracts to config contracts const contractConfigs = config.contracts ?? [] const watchConfigs: Watch[] = [] spinner.start('Resolving contracts') for (const plugin of plugins) { if (plugin.watch) watchConfigs.push(plugin.watch) if (plugin.contracts) { const contracts = await plugin.contracts() contractConfigs.push(...contracts) } } // Get contracts from config const contractNames = new Set() const contractMap = new Map() for (const contractConfig of contractConfigs) { if (contractNames.has(contractConfig.name)) throw new Error( `Contract name "${contractConfig.name}" must be unique.`, ) const contract = await getContract({ ...contractConfig, isTypeScript }) contractMap.set(contract.name, contract) contractNames.add(contractConfig.name) } // Sort contracts by name Ascending (low to high) as the key is `String` const sortedAscContractMap = new Map([...contractMap].sort()) const contracts = [...sortedAscContractMap.values()] if (!contracts.length && !options.watch) { spinner.error() logger.warn('No contracts found.') return } spinner.success() // Run plugins const imports = [] const prepend = [] const content = [] type Output = { plugin: Pick } & Awaited>> const outputs: Output[] = [] spinner.start('Running plugins') for (const plugin of plugins) { if (!plugin.run) continue const result = await plugin.run({ contracts, isTypeScript, outputs, }) outputs.push({ plugin: { name: plugin.name }, ...result, }) if (!result.imports && !result.prepend && !result.content) continue content.push(getBannerContent({ name: plugin.name }), result.content) result.imports && imports.push(result.imports) result.prepend && prepend.push(result.prepend) } spinner.success() // Write output to file spinner.start(`Writing to ${pc.gray(config.out)}`) await writeContracts({ content, contracts, imports, prepend, filename: config.out, }) spinner.success() if (options.watch) { if (!watchConfigs.length) { logger.log(pc.gray('Used --watch flag, but no plugins are watching.')) continue } logger.log() logger.log('Setting up watch process') // Watch for changes let timeout: NodeJS.Timeout | null for (const watchConfig of watchConfigs) { const paths = typeof watchConfig.paths === 'function' ? await watchConfig.paths() : watchConfig.paths const watcher = watch(paths, watchOptions) // Watch for changes to files, new files, and deleted files watcher.on('all', async (event, path) => { if (event !== 'change' && event !== 'add' && event !== 'unlink') return let needsWrite = false if (event === 'change' || event === 'add') { const eventFn = event === 'change' ? watchConfig.onChange : watchConfig.onAdd const config = await eventFn?.(path) if (!config) return const contract = await getContract({ ...config, isTypeScript }) contractMap.set(contract.name, contract) needsWrite = true } else if (event === 'unlink') { const name = await watchConfig.onRemove?.(path) if (!name) return contractMap.delete(name) needsWrite = true } // Debounce writes if (needsWrite) { if (timeout) clearTimeout(timeout) timeout = setTimeout(async () => { timeout = null // Sort contracts by name Ascending (low to high) as the key is `String` const sortedAscContractMap = new Map([...contractMap].sort()) const contracts = [...sortedAscContractMap.values()] const imports = [] const prepend = [] const content = [] const outputs: Output[] = [] for (const plugin of plugins) { if (!plugin.run) continue const result = await plugin.run({ contracts, isTypeScript, outputs, }) outputs.push({ plugin: { name: plugin.name }, ...result, }) if (!result.imports && !result.prepend && !result.content) continue content.push( getBannerContent({ name: plugin.name }), result.content, ) result.imports && imports.push(result.imports) result.prepend && prepend.push(result.prepend) } const spinner = logger.spinner( `Writing to ${pc.gray(config.out)}`, ) spinner.start() await writeContracts({ content, contracts, imports, prepend, filename: config.out, }) spinner.success() }, watchWriteDelay) needsWrite = false } }) // Run parallel command on ready if (watchConfig.command) watcher.on('ready', async () => { await watchConfig.command?.() }) ;(watcher as Watcher).config = watchConfig watchers.push(watcher) } } } if (!watchers.length) return // Watch `@wagmi/cli` config file for changes const watcher = watch(configPath).on('change', async (path) => { logger.log( `> Found a change to config ${pc.gray( basename(path), )}. Restart process for changes to take effect.`, ) }) watchers.push(watcher) // Display message and close watchers on exit process.once('SIGINT', shutdown) process.once('SIGTERM', shutdown) async function shutdown() { logger.log() logger.log('Shutting down watch process') const promises = [] for (const watcher of watchers) { if (watcher.config?.onClose) promises.push(watcher.config?.onClose?.()) promises.push(watcher.close()) } await Promise.allSettled(promises) process.exit(0) } } async function getContract({ abi, address, name, isTypeScript, }: ContractConfig & { isTypeScript: boolean }): Promise { const constAssertion = isTypeScript ? ' as const' : '' const abiName = `${camelCase(name)}Abi` try { abi = (await AbiSchema.parseAsync(abi)) as Abi } catch (error) { if (error instanceof z.ZodError) throw fromZodError(error, { prefix: `Invalid ABI for contract "${name}"`, }) throw error } const docString = typeof address === 'object' ? dedent`\n /** ${getAddressDocString({ address })} */ ` : '' let content = dedent` ${getBannerContent({ name })} ${docString} export const ${abiName} = ${JSON.stringify(abi)}${constAssertion} ` let meta: Contract['meta'] = { abiName } if (address) { let resolvedAddress: Address | Record try { const Address = z .string() .regex(/^0x[a-fA-F0-9]{40}$/, { message: 'Invalid address' }) .transform((val) => getAddress(val)) as z.ZodType
const MultiChainAddress = z.record(z.string(), Address) const AddressSchema = z.union([Address, MultiChainAddress]) resolvedAddress = await AddressSchema.parseAsync(address) } catch (error) { if (error instanceof z.ZodError) throw fromZodError(error, { prefix: `Invalid address for contract "${name}"`, }) throw error } const addressName = `${camelCase(name)}Address` const configName = `${camelCase(name)}Config` meta = { ...meta, addressName, configName, } const addressContent = typeof resolvedAddress === 'string' ? JSON.stringify(resolvedAddress) : // Remove quotes from chain id key JSON.stringify(resolvedAddress, null, 2).replace(/"(\d*)":/gm, '$1:') content = dedent` ${content} ${docString} export const ${addressName} = ${addressContent}${constAssertion} ${docString} export const ${configName} = { address: ${addressName}, abi: ${abiName} }${constAssertion} ` } return { abi, address, content, meta, name } } async function writeContracts({ content, contracts, imports, prepend, filename, }: { content: string[] contracts: Contract[] imports: string[] prepend: string[] filename: string }) { // Assemble code let code = dedent` ${imports.join('\n\n') ?? ''} ${prepend.join('\n\n') ?? ''} ` for (const contract of contracts) { code = dedent` ${code} ${contract.content} ` } code = dedent` ${code} ${content.join('\n\n') ?? ''} ` // Format and write output const cwd = process.cwd() const outPath = resolve(cwd, filename) await mkdir(dirname(outPath), { recursive: true }) const formatted = await format(code) await writeFile(outPath, formatted) } function getBannerContent({ name }: { name: string }) { return dedent` ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ${name} ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ` } ================================================ FILE: packages/cli/src/commands/init.test.ts ================================================ import { existsSync } from 'node:fs' import { mkdir, readFile } from 'node:fs/promises' import { resolve } from 'pathe' import { afterEach, beforeEach, expect, test, vi } from 'vitest' import { createFixture, watchConsole } from '../../test/utils.js' import { defaultConfig } from '../config.js' import { init } from './init.js' let console: ReturnType beforeEach(() => { console = watchConsole() }) afterEach(() => { vi.restoreAllMocks() }) test('creates config file', async () => { const { dir } = await createFixture() const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) const configFile = await init() expect(existsSync(configFile)).toBeTruthy() expect(await readFile(configFile, 'utf-8')).toMatchInlineSnapshot(` "// @ts-check /** @type {import('@wagmi/cli').Config} */ export default { out: 'src/generated.js', contracts: [], plugins: [], } " `) expect( console.formatted.replaceAll(dir, 'path/to/project'), ).toMatchInlineSnapshot(` "- Creating config √ Creating config Config created at wagmi.config.js" `) }) test('parameters: config', async () => { const { dir } = await createFixture() const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) const configFile = await init({ config: 'foo.config.ts', }) expect(existsSync(configFile)).toBeTruthy() expect(await readFile(configFile, 'utf-8')).toMatchInlineSnapshot(` "// @ts-check /** @type {import('@wagmi/cli').Config} */ export default { out: 'src/generated.js', contracts: [], plugins: [], } " `) expect( console.formatted.replaceAll(dir, 'path/to/project'), ).toMatchInlineSnapshot(` "- Creating config √ Creating config Config created at foo.config.ts" `) }) test('parameters: content', async () => { const { dir } = await createFixture({ files: { 'tsconfig.json': '{}', }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) const configFile = await init({ content: { ...defaultConfig, out: 'foo/bar/baz.ts', }, }) expect(existsSync(configFile)).toBeTruthy() expect(await readFile(configFile, 'utf-8')).toMatchInlineSnapshot(` "import { defineConfig } from '@wagmi/cli' export default defineConfig({ out: 'foo/bar/baz.ts', contracts: [], plugins: [], }) " `) expect( console.formatted.replaceAll(dir, 'path/to/project'), ).toMatchInlineSnapshot(` "- Creating config √ Creating config Config created at wagmi.config.ts" `) }) test('parameters: root', async () => { const { dir } = await createFixture() const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) mkdir(resolve(dir, 'foo')) const configFile = await init({ root: 'foo/', }) expect(existsSync(configFile)).toBeTruthy() expect(await readFile(configFile, 'utf-8')).toMatchInlineSnapshot(` "// @ts-check /** @type {import('@wagmi/cli').Config} */ export default { out: 'src/generated.js', contracts: [], plugins: [], } " `) expect( console.formatted.replaceAll(dir, 'path/to/project'), ).toMatchInlineSnapshot(` "- Creating config √ Creating config Config created at foo/wagmi.config.js" `) }) test('behavior: creates config file in TypeScript format', async () => { const { dir } = await createFixture({ files: { 'tsconfig.json': '{}', }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) const configFile = await init() expect(existsSync(configFile)).toBeTruthy() expect(await readFile(configFile, 'utf-8')).toMatchInlineSnapshot(` "import { defineConfig } from '@wagmi/cli' export default defineConfig({ out: 'src/generated.ts', contracts: [], plugins: [], }) " `) expect( console.formatted.replaceAll(dir, 'path/to/project'), ).toMatchInlineSnapshot(` "- Creating config √ Creating config Config created at wagmi.config.ts" `) }) test('behavior: displays config file location when config exists', async () => { const { dir } = await createFixture({ files: { 'wagmi.config.ts': '', }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) const configFile = await init() expect( console.formatted.replaceAll(configFile, 'path/to/project/wagmi.config.ts'), ).toMatchInlineSnapshot('"Config already exists at wagmi.config.ts"') }) ================================================ FILE: packages/cli/src/commands/init.ts ================================================ import { writeFile } from 'node:fs/promises' import dedent from 'dedent' import { relative, resolve } from 'pathe' import pc from 'picocolors' import { z } from 'zod' import { type Config, defaultConfig } from '../config.js' import { fromZodError } from '../errors.js' import * as logger from '../logger.js' import { findConfig } from '../utils/findConfig.js' import { format } from '../utils/format.js' import { getIsUsingTypeScript } from '../utils/getIsUsingTypeScript.js' export type Init = { /** Path to config file */ config?: string /** Watch for file system changes to config and plugins */ content?: Config /** Directory to init config file */ root?: string } const Init = z.object({ config: z.string().optional(), content: z.object({}).optional(), root: z.string().optional(), }) export async function init(options: Init = {}) { // Validate command line options try { await Init.parseAsync(options) } catch (error) { if (error instanceof z.ZodError) throw fromZodError(error, { prefix: 'Invalid option' }) throw error } // Check for existing config file const configPath = await findConfig(options) if (configPath) { logger.info( `Config already exists at ${pc.gray( relative(process.cwd(), configPath), )}`, ) return configPath } const spinner = logger.spinner('Creating config') spinner.start() // Check if project is using TypeScript const isUsingTypeScript = await getIsUsingTypeScript() const rootDir = resolve(options.root || process.cwd()) let outPath: string if (options.config) { outPath = resolve(rootDir, options.config) } else { const extension = isUsingTypeScript ? 'ts' : 'js' outPath = resolve(rootDir, `wagmi.config.${extension}`) } let content: string if (isUsingTypeScript) { const config = options.content ?? defaultConfig content = dedent(` import { defineConfig } from '@wagmi/cli' export default defineConfig(${JSON.stringify(config)}) `) } else { const config = options.content ?? { ...defaultConfig, out: defaultConfig.out.replace('.ts', '.js'), } content = dedent(` // @ts-check /** @type {import('@wagmi/cli').Config} */ export default ${JSON.stringify(config, null, 2).replace( /"(\d*)":/gm, '$1:', )} `) } const formatted = await format(content) await writeFile(outPath, formatted) spinner.success() logger.success( `Config created at ${pc.gray(relative(process.cwd(), outPath))}`, ) return outPath } ================================================ FILE: packages/cli/src/config.test.ts ================================================ import { expect, test, vi } from 'vitest' import { type Config, defineConfig } from './config.js' test('object', () => { const config: Config = { contracts: [], out: 'wagmi.ts', plugins: [], } expect(defineConfig(config)).toEqual(config) }) test('array', () => { const config: Config = { contracts: [], out: 'wagmi.ts', plugins: [], } expect(defineConfig([config, config])).toEqual([config, config]) }) test('function', () => { const config = vi.fn().mockImplementation(() => ({ contracts: [], out: 'wagmi.ts', plugins: [], })) expect(defineConfig(config)).toEqual(config) }) test('async function', () => { const config = vi.fn().mockImplementation(async () => ({ contracts: [], out: 'wagmi.ts', plugins: [], })) expect(defineConfig(config)).toEqual(config) }) ================================================ FILE: packages/cli/src/config.ts ================================================ import type { Abi, Address } from 'viem' import type { Compute, MaybeArray, MaybePromise } from './types.js' export type ContractConfig< chainId extends number = number, requiredChainId extends number | undefined = undefined, > = { /** * Contract ABI */ abi: Abi /** * Contract address or addresses. * * Accepts an object `{ [chainId]: address }` to support multiple chains. * * @example * '0x314159265dd8dbb310642f98f50c066173c1259b' * * @example * { * 1: '0x314159265dd8dbb310642f98f50c066173c1259b', * 5: '0x112234455c3a32fd11230c42e7bccd4a84e02010', * } */ address?: | Address | (requiredChainId extends number ? Record & Partial> : Record) | undefined /** * Name of contract. */ name: string } export type Contract = Compute< ContractConfig & { /** Generated string content */ content: string /** Meta info about contract */ meta: { abiName: string addressName?: string | undefined configName?: string | undefined } } > export type Watch = { /** Command to run along with watch process */ command?: (() => MaybePromise) | undefined /** Paths to watch for changes. */ paths: string[] | (() => MaybePromise) /** Callback that fires when file is added */ onAdd?: | ((path: string) => MaybePromise) | undefined /** Callback that fires when file changes */ onChange: (path: string) => MaybePromise /** Callback that fires when watcher is shutdown */ onClose?: (() => MaybePromise) | undefined /** Callback that fires when file is removed */ onRemove?: ((path: string) => MaybePromise) | undefined } export type Plugin = { /** Contracts provided by plugin */ contracts?: (() => MaybePromise) | undefined /** Plugin name */ name: string /** Run plugin logic */ run?: | ((config: { /** All resolved contracts from config and plugins */ contracts: Contract[] /** Whether TypeScript is detected in project */ isTypeScript: boolean /** Previous plugin outputs */ outputs: readonly { plugin: Pick imports?: string prepend?: string content: string }[] }) => MaybePromise<{ imports?: string prepend?: string content: string }>) | undefined /** * Validate plugin configuration or other @wagmi/cli settings require for plugin. */ validate?: (() => MaybePromise) | undefined /** File system watch config */ watch?: Watch | undefined } export type Config = { /** Contracts to use in commands */ contracts?: ContractConfig[] | undefined /** Output file path */ out: string /** Plugins to run */ plugins?: Plugin[] | undefined } export function defineConfig( config: MaybeArray | (() => MaybePromise>), ) { return config } export const defaultConfig = { out: 'src/generated.ts', contracts: [], plugins: [], } satisfies Config ================================================ FILE: packages/cli/src/errors.ts ================================================ import type * as z from 'zod' class ValidationError extends Error { details: z.core.$ZodIssue[] constructor( message: string, options: { details: z.core.$ZodIssue[] }, ) { super(message) this.details = options.details } } // From https://github.com/causaly/zod-validation-error export function fromZodError( zError: z.ZodError, { maxIssuesInMessage = 99, issueSeparator = '\n- ', prefixSeparator = '\n- ', prefix = 'Validation Error', }: { maxIssuesInMessage?: number issueSeparator?: string prefixSeparator?: string prefix?: string } = {}, ): ValidationError { function joinPath(arr: Array): string { return arr.reduce((acc, value) => { if (typeof value === 'number') return `${acc}[${value}]` const separator = acc === '' ? '' : '.' return acc + separator + value.toString() }, '') } const reason = zError.issues // limit max number of issues printed in the reason section .slice(0, maxIssuesInMessage) // format error message .map((issue) => { const { message, path } = issue if (path.length > 0) return `${message} at \`${joinPath(path)}\`` return message }) // concat as string .join(issueSeparator) const message = reason ? [prefix, reason].join(prefixSeparator) : prefix return new ValidationError(message, { details: zError.issues, }) } ================================================ FILE: packages/cli/src/exports/config.test.ts ================================================ import { expect, test } from 'vitest' import * as Exports from './config.js' test('exports', () => { expect(Object.keys(Exports)).toMatchInlineSnapshot(` [ "defaultConfig", "defineConfig", ] `) }) ================================================ FILE: packages/cli/src/exports/config.ts ================================================ // biome-ignore lint/performance/noBarrelFile: entrypoint module export { type Config, type Contract, type ContractConfig, defaultConfig, defineConfig, type Plugin, type Watch, } from '../config.js' ================================================ FILE: packages/cli/src/exports/index.test-d.ts ================================================ import { expectTypeOf } from 'vitest' // noop test because vitest typecheck fails unless each workspace project has type test expectTypeOf(1).toEqualTypeOf() ================================================ FILE: packages/cli/src/exports/index.test.ts ================================================ import { expect, test } from 'vitest' import * as Exports from './index.js' test('exports', () => { expect(Object.keys(Exports)).toMatchInlineSnapshot(` [ "defineConfig", "logger", "loadEnv", "version", ] `) }) ================================================ FILE: packages/cli/src/exports/index.ts ================================================ // biome-ignore lint/performance/noBarrelFile: entrypoint module export { type Config, type ContractConfig, defineConfig, type Plugin, } from '../config.js' // biome-ignore lint/performance/noReExportAll: entrypoint module export * as logger from '../logger.js' export { loadEnv } from '../utils/loadEnv.js' export { version } from '../version.js' ================================================ FILE: packages/cli/src/exports/plugins.test.ts ================================================ import { expect, test } from 'vitest' import * as Exports from './plugins.js' test('exports', () => { expect(Object.keys(Exports)).toMatchInlineSnapshot(` [ "actions", "blockExplorer", "etherscan", "fetch", "foundry", "foundryDefaultExcludes", "hardhat", "hardhatDefaultExcludes", "react", "sourcify", ] `) }) ================================================ FILE: packages/cli/src/exports/plugins.ts ================================================ // biome-ignore lint/performance/noBarrelFile: entrypoint module export { type ActionsConfig, actions } from '../plugins/actions.js' export { type BlockExplorerConfig, blockExplorer, } from '../plugins/blockExplorer.js' export { type EtherscanConfig, etherscan } from '../plugins/etherscan.js' export { type FetchConfig, fetch } from '../plugins/fetch.js' export { type FoundryConfig, foundry, foundryDefaultExcludes, } from '../plugins/foundry.js' export { type HardhatConfig, hardhat, hardhatDefaultExcludes, } from '../plugins/hardhat.js' export { type ReactConfig, react } from '../plugins/react.js' export { type SourcifyConfig, sourcify } from '../plugins/sourcify.js' ================================================ FILE: packages/cli/src/logger.test.ts ================================================ import { afterEach, expect, test, vi } from 'vitest' import { watchConsole } from '../test/utils.js' import * as logger from './logger.js' const mockLog = vi.fn() afterEach(() => { vi.restoreAllMocks() }) test.each(['success', 'info', 'log', 'warn', 'error'])('%s()', (level) => { const spy = vi.spyOn(logger, level as any) spy.mockImplementation(mockLog) const loggerFn = (logger as any)[level] loggerFn(level) expect(spy).toHaveBeenCalledWith(level) }) test('spinner', () => { const console = watchConsole() const spinner = logger.spinner('start') spinner.start() spinner.success('success') spinner.error('error') expect(console.formatted).toMatchInlineSnapshot(` "- start √ success × error" `) }) ================================================ FILE: packages/cli/src/logger.ts ================================================ import { format as utilFormat } from 'node:util' import { createSpinner } from 'nanospinner' import pc from 'picocolors' function format(args: any[]) { return utilFormat(...args) .split('\n') .join('\n') } export function success(...args: any[]) { console.log(pc.green(format(args))) } export function info(...args: any[]) { // biome-ignore lint/suspicious/noConsole: logger console.info(pc.blue(format(args))) } export function log(...args: any[]) { console.log(pc.white(format(args))) } export function warn(...args: any[]) { // biome-ignore lint/suspicious/noConsole: logger console.warn(pc.yellow(format(args))) } export function error(...args: any[]) { // biome-ignore lint/suspicious/noConsole: logger console.error(pc.red(format(args))) } export function spinner(text: string) { return createSpinner(text, { color: 'yellow', }) } ================================================ FILE: packages/cli/src/plugins/__fixtures__/foundry/.gitignore ================================================ # Compiler files cache/ out/ # Ignores development broadcast logs !/broadcast /broadcast/*/31337/ /broadcast/**/dry-run/ # Dotenv file .env ================================================ FILE: packages/cli/src/plugins/__fixtures__/foundry/foundry.toml ================================================ [profile.default] libs = ['lib'] out = 'out' solc = '0.8.13' src = 'src' # See more config options https://github.com/foundry-rs/foundry/blob/master/crates/config/README.md#all-options ================================================ FILE: packages/cli/src/plugins/__fixtures__/foundry/src/Counter.sol ================================================ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; contract Counter { uint256 public number; function setNumber(uint256 newNumber) public { number = newNumber; } function increment() public { number++; } } ================================================ FILE: packages/cli/src/plugins/__fixtures__/foundry/src/Foo.sol ================================================ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; contract Foo { string public bar; function setFoo(string memory baz) public { bar = baz; } } ================================================ FILE: packages/cli/src/plugins/__fixtures__/hardhat/.gitignore ================================================ node_modules .env coverage coverage.json typechain typechain-types # Hardhat files cache artifacts ================================================ FILE: packages/cli/src/plugins/__fixtures__/hardhat/contracts/Counter.sol ================================================ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; contract Counter { uint256 public number; function setNumber(uint256 newNumber) public { number = newNumber; } function increment() public { number++; } } ================================================ FILE: packages/cli/src/plugins/__fixtures__/hardhat/contracts/Foo.sol ================================================ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; contract Foo { string public bar; function setFoo(string memory baz) public { bar = baz; } } ================================================ FILE: packages/cli/src/plugins/__fixtures__/hardhat/hardhat.config.js ================================================ import { defineConfig } from 'hardhat/config' export default defineConfig({ solidity: '0.8.17', }) ================================================ FILE: packages/cli/src/plugins/__fixtures__/hardhat/package.json ================================================ { "name": "hardhat-fixture", "private": true, "type": "module", "devDependencies": { "hardhat": "^3.0.0" } } ================================================ FILE: packages/cli/src/plugins/__snapshots__/blockExplorer.test.ts.snap ================================================ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`fetches ABI 1`] = ` [ { "abi": [ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": true, "internalType": "address", "name": "approved", "type": "address", }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": true, "internalType": "address", "name": "operator", "type": "address", }, { "indexed": false, "internalType": "bool", "name": "approved", "type": "bool", }, ], "name": "ApprovalForAll", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address", }, { "indexed": true, "internalType": "address", "name": "to", "type": "address", }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "approve", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address", }, ], "name": "balanceOf", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "getApproved", "outputs": [ { "internalType": "address", "name": "", "type": "address", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address", }, { "internalType": "address", "name": "operator", "type": "address", }, ], "name": "isApprovedForAll", "outputs": [ { "internalType": "bool", "name": "", "type": "bool", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "name", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "ownerOf", "outputs": [ { "internalType": "address", "name": "", "type": "address", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, { "internalType": "bytes", "name": "_data", "type": "bytes", }, ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "operator", "type": "address", }, { "internalType": "bool", "name": "approved", "type": "bool", }, ], "name": "setApprovalForAll", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "bytes4", "name": "interfaceId", "type": "bytes4", }, ], "name": "supportsInterface", "outputs": [ { "internalType": "bool", "name": "", "type": "bool", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "symbol", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "tokenURI", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "pure", "type": "function", }, { "inputs": [], "name": "totalSupply", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "transferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "address": "0xaf0326d92b97df1221759476b072abfd8084f9be", "name": "WagmiMintExample", }, ] `; exports[`fetches ABI with multichain deployment 1`] = ` [ { "abi": [ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": true, "internalType": "address", "name": "approved", "type": "address", }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": true, "internalType": "address", "name": "operator", "type": "address", }, { "indexed": false, "internalType": "bool", "name": "approved", "type": "bool", }, ], "name": "ApprovalForAll", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address", }, { "indexed": true, "internalType": "address", "name": "to", "type": "address", }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "approve", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address", }, ], "name": "balanceOf", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "getApproved", "outputs": [ { "internalType": "address", "name": "", "type": "address", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address", }, { "internalType": "address", "name": "operator", "type": "address", }, ], "name": "isApprovedForAll", "outputs": [ { "internalType": "bool", "name": "", "type": "bool", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "name", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "ownerOf", "outputs": [ { "internalType": "address", "name": "", "type": "address", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, { "internalType": "bytes", "name": "_data", "type": "bytes", }, ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "operator", "type": "address", }, { "internalType": "bool", "name": "approved", "type": "bool", }, ], "name": "setApprovalForAll", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "bytes4", "name": "interfaceId", "type": "bytes4", }, ], "name": "supportsInterface", "outputs": [ { "internalType": "bool", "name": "", "type": "bool", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "symbol", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "tokenURI", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "pure", "type": "function", }, { "inputs": [], "name": "totalSupply", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "transferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "address": { "1": "0xaf0326d92b97df1221759476b072abfd8084f9be", "10": "0xaf0326d92b97df1221759476b072abfd8084f9be", }, "name": "WagmiMintExample", }, ] `; ================================================ FILE: packages/cli/src/plugins/__snapshots__/etherscan.test.ts.snap ================================================ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`fetches ABI 1`] = ` [ { "abi": [ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": true, "internalType": "address", "name": "approved", "type": "address", }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": true, "internalType": "address", "name": "operator", "type": "address", }, { "indexed": false, "internalType": "bool", "name": "approved", "type": "bool", }, ], "name": "ApprovalForAll", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address", }, { "indexed": true, "internalType": "address", "name": "to", "type": "address", }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "approve", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address", }, ], "name": "balanceOf", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "getApproved", "outputs": [ { "internalType": "address", "name": "", "type": "address", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address", }, { "internalType": "address", "name": "operator", "type": "address", }, ], "name": "isApprovedForAll", "outputs": [ { "internalType": "bool", "name": "", "type": "bool", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "name", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "ownerOf", "outputs": [ { "internalType": "address", "name": "", "type": "address", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, { "internalType": "bytes", "name": "_data", "type": "bytes", }, ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "operator", "type": "address", }, { "internalType": "bool", "name": "approved", "type": "bool", }, ], "name": "setApprovalForAll", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "bytes4", "name": "interfaceId", "type": "bytes4", }, ], "name": "supportsInterface", "outputs": [ { "internalType": "bool", "name": "", "type": "bool", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "symbol", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "tokenURI", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "pure", "type": "function", }, { "inputs": [], "name": "totalSupply", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "transferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "address": { "1": "0xaf0326d92b97df1221759476b072abfd8084f9be", }, "name": "WagmiMintExample", }, ] `; exports[`fetches ABI with multichain deployment 1`] = ` [ { "abi": [ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": true, "internalType": "address", "name": "approved", "type": "address", }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": true, "internalType": "address", "name": "operator", "type": "address", }, { "indexed": false, "internalType": "bool", "name": "approved", "type": "bool", }, ], "name": "ApprovalForAll", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address", }, { "indexed": true, "internalType": "address", "name": "to", "type": "address", }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "approve", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address", }, ], "name": "balanceOf", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "getApproved", "outputs": [ { "internalType": "address", "name": "", "type": "address", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address", }, { "internalType": "address", "name": "operator", "type": "address", }, ], "name": "isApprovedForAll", "outputs": [ { "internalType": "bool", "name": "", "type": "bool", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "name", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "ownerOf", "outputs": [ { "internalType": "address", "name": "", "type": "address", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, { "internalType": "bytes", "name": "_data", "type": "bytes", }, ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "operator", "type": "address", }, { "internalType": "bool", "name": "approved", "type": "bool", }, ], "name": "setApprovalForAll", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "bytes4", "name": "interfaceId", "type": "bytes4", }, ], "name": "supportsInterface", "outputs": [ { "internalType": "bool", "name": "", "type": "bool", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "symbol", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "tokenURI", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "pure", "type": "function", }, { "inputs": [], "name": "totalSupply", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "transferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "address": { "1": "0xaf0326d92b97df1221759476b072abfd8084f9be", "10": "0xaf0326d92b97df1221759476b072abfd8084f9be", }, "name": "WagmiMintExample", }, ] `; exports[`tryFetchProxyImplementation: fetches ABI 1`] = ` [ { "abi": [ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": true, "internalType": "address", "name": "approved", "type": "address", }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": true, "internalType": "address", "name": "operator", "type": "address", }, { "indexed": false, "internalType": "bool", "name": "approved", "type": "bool", }, ], "name": "ApprovalForAll", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address", }, { "indexed": true, "internalType": "address", "name": "to", "type": "address", }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "approve", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address", }, ], "name": "balanceOf", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "getApproved", "outputs": [ { "internalType": "address", "name": "", "type": "address", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address", }, { "internalType": "address", "name": "operator", "type": "address", }, ], "name": "isApprovedForAll", "outputs": [ { "internalType": "bool", "name": "", "type": "bool", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "name", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "ownerOf", "outputs": [ { "internalType": "address", "name": "", "type": "address", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, { "internalType": "bytes", "name": "_data", "type": "bytes", }, ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "operator", "type": "address", }, { "internalType": "bool", "name": "approved", "type": "bool", }, ], "name": "setApprovalForAll", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "bytes4", "name": "interfaceId", "type": "bytes4", }, ], "name": "supportsInterface", "outputs": [ { "internalType": "bool", "name": "", "type": "bool", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "symbol", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "tokenURI", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "pure", "type": "function", }, { "inputs": [], "name": "totalSupply", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "transferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "address": { "1": "0xaf0326d92b97df1221759476b072abfd8084f9be", }, "name": "WagmiMintExample", }, ] `; exports[`tryFetchProxyImplementation: fetches implementation ABI 1`] = ` [ { "abi": [ { "constant": false, "inputs": [ { "name": "newImplementation", "type": "address", }, ], "name": "upgradeTo", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function", }, { "constant": false, "inputs": [ { "name": "newImplementation", "type": "address", }, { "name": "data", "type": "bytes", }, ], "name": "upgradeToAndCall", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function", }, { "constant": true, "inputs": [], "name": "implementation", "outputs": [ { "name": "", "type": "address", }, ], "payable": false, "stateMutability": "view", "type": "function", }, { "constant": false, "inputs": [ { "name": "newAdmin", "type": "address", }, ], "name": "changeAdmin", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function", }, { "constant": true, "inputs": [], "name": "admin", "outputs": [ { "name": "", "type": "address", }, ], "payable": false, "stateMutability": "view", "type": "function", }, { "inputs": [ { "name": "_implementation", "type": "address", }, ], "payable": false, "stateMutability": "nonpayable", "type": "constructor", }, { "payable": true, "stateMutability": "payable", "type": "fallback", }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "previousAdmin", "type": "address", }, { "indexed": false, "name": "newAdmin", "type": "address", }, ], "name": "AdminChanged", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "implementation", "type": "address", }, ], "name": "Upgraded", "type": "event", }, ], "address": { "1": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", }, "name": "FiatToken", }, ] `; ================================================ FILE: packages/cli/src/plugins/__snapshots__/fetch.test.ts.snap ================================================ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`fetches ABI 1`] = ` [ { "abi": [ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": true, "internalType": "address", "name": "approved", "type": "address", }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": true, "internalType": "address", "name": "operator", "type": "address", }, { "indexed": false, "internalType": "bool", "name": "approved", "type": "bool", }, ], "name": "ApprovalForAll", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address", }, { "indexed": true, "internalType": "address", "name": "to", "type": "address", }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "approve", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address", }, ], "name": "balanceOf", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "getApproved", "outputs": [ { "internalType": "address", "name": "", "type": "address", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address", }, { "internalType": "address", "name": "operator", "type": "address", }, ], "name": "isApprovedForAll", "outputs": [ { "internalType": "bool", "name": "", "type": "bool", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "name", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "ownerOf", "outputs": [ { "internalType": "address", "name": "", "type": "address", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, { "internalType": "bytes", "name": "_data", "type": "bytes", }, ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "operator", "type": "address", }, { "internalType": "bool", "name": "approved", "type": "bool", }, ], "name": "setApprovalForAll", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "bytes4", "name": "interfaceId", "type": "bytes4", }, ], "name": "supportsInterface", "outputs": [ { "internalType": "bool", "name": "", "type": "bool", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "symbol", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "tokenURI", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "pure", "type": "function", }, { "inputs": [], "name": "totalSupply", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "transferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "address": "0xaf0326d92b97df1221759476b072abfd8084f9be", "name": "WagmiMintExample", }, ] `; ================================================ FILE: packages/cli/src/plugins/__snapshots__/routescan.test.ts.snap ================================================ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`fetches ABI 1`] = ` [ { "abi": [ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": true, "internalType": "address", "name": "approved", "type": "address", }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": true, "internalType": "address", "name": "operator", "type": "address", }, { "indexed": false, "internalType": "bool", "name": "approved", "type": "bool", }, ], "name": "ApprovalForAll", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address", }, { "indexed": true, "internalType": "address", "name": "to", "type": "address", }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "approve", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address", }, ], "name": "balanceOf", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "getApproved", "outputs": [ { "internalType": "address", "name": "", "type": "address", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address", }, { "internalType": "address", "name": "operator", "type": "address", }, ], "name": "isApprovedForAll", "outputs": [ { "internalType": "bool", "name": "", "type": "bool", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "name", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "ownerOf", "outputs": [ { "internalType": "address", "name": "", "type": "address", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, { "internalType": "bytes", "name": "_data", "type": "bytes", }, ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "operator", "type": "address", }, { "internalType": "bool", "name": "approved", "type": "bool", }, ], "name": "setApprovalForAll", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "bytes4", "name": "interfaceId", "type": "bytes4", }, ], "name": "supportsInterface", "outputs": [ { "internalType": "bool", "name": "", "type": "bool", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "symbol", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "tokenURI", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "pure", "type": "function", }, { "inputs": [], "name": "totalSupply", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "transferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "address": { "1": "0xaf0326d92b97df1221759476b072abfd8084f9be", }, "name": "WagmiMintExample", }, ] `; exports[`fetches ABI with multichain deployment 1`] = ` [ { "abi": [ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": true, "internalType": "address", "name": "approved", "type": "address", }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": true, "internalType": "address", "name": "operator", "type": "address", }, { "indexed": false, "internalType": "bool", "name": "approved", "type": "bool", }, ], "name": "ApprovalForAll", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address", }, { "indexed": true, "internalType": "address", "name": "to", "type": "address", }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "approve", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address", }, ], "name": "balanceOf", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "getApproved", "outputs": [ { "internalType": "address", "name": "", "type": "address", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address", }, { "internalType": "address", "name": "operator", "type": "address", }, ], "name": "isApprovedForAll", "outputs": [ { "internalType": "bool", "name": "", "type": "bool", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "name", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "ownerOf", "outputs": [ { "internalType": "address", "name": "", "type": "address", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, { "internalType": "bytes", "name": "_data", "type": "bytes", }, ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "operator", "type": "address", }, { "internalType": "bool", "name": "approved", "type": "bool", }, ], "name": "setApprovalForAll", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "bytes4", "name": "interfaceId", "type": "bytes4", }, ], "name": "supportsInterface", "outputs": [ { "internalType": "bool", "name": "", "type": "bool", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "symbol", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "tokenURI", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "pure", "type": "function", }, { "inputs": [], "name": "totalSupply", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "transferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "address": { "1": "0xaf0326d92b97df1221759476b072abfd8084f9be", "10": "0xaf0326d92b97df1221759476b072abfd8084f9be", }, "name": "WagmiMintExample", }, ] `; exports[`tryFetchProxyImplementation: fetches ABI 1`] = ` [ { "abi": [ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": true, "internalType": "address", "name": "approved", "type": "address", }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "Approval", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address", }, { "indexed": true, "internalType": "address", "name": "operator", "type": "address", }, { "indexed": false, "internalType": "bool", "name": "approved", "type": "bool", }, ], "name": "ApprovalForAll", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address", }, { "indexed": true, "internalType": "address", "name": "to", "type": "address", }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "Transfer", "type": "event", }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "approve", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address", }, ], "name": "balanceOf", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "getApproved", "outputs": [ { "internalType": "address", "name": "", "type": "address", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address", }, { "internalType": "address", "name": "operator", "type": "address", }, ], "name": "isApprovedForAll", "outputs": [ { "internalType": "bool", "name": "", "type": "bool", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "name", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "ownerOf", "outputs": [ { "internalType": "address", "name": "", "type": "address", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, { "internalType": "bytes", "name": "_data", "type": "bytes", }, ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "operator", "type": "address", }, { "internalType": "bool", "name": "approved", "type": "bool", }, ], "name": "setApprovalForAll", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [ { "internalType": "bytes4", "name": "interfaceId", "type": "bytes4", }, ], "name": "supportsInterface", "outputs": [ { "internalType": "bool", "name": "", "type": "bool", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "symbol", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "tokenURI", "outputs": [ { "internalType": "string", "name": "", "type": "string", }, ], "stateMutability": "pure", "type": "function", }, { "inputs": [], "name": "totalSupply", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address", }, { "internalType": "address", "name": "to", "type": "address", }, { "internalType": "uint256", "name": "tokenId", "type": "uint256", }, ], "name": "transferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "address": { "1": "0xaf0326d92b97df1221759476b072abfd8084f9be", }, "name": "WagmiMintExample", }, ] `; exports[`tryFetchProxyImplementation: fetches implementation ABI 1`] = ` [ { "abi": [ { "constant": false, "inputs": [ { "name": "newImplementation", "type": "address", }, ], "name": "upgradeTo", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function", }, { "constant": false, "inputs": [ { "name": "newImplementation", "type": "address", }, { "name": "data", "type": "bytes", }, ], "name": "upgradeToAndCall", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function", }, { "constant": true, "inputs": [], "name": "implementation", "outputs": [ { "name": "", "type": "address", }, ], "payable": false, "stateMutability": "view", "type": "function", }, { "constant": false, "inputs": [ { "name": "newAdmin", "type": "address", }, ], "name": "changeAdmin", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function", }, { "constant": true, "inputs": [], "name": "admin", "outputs": [ { "name": "", "type": "address", }, ], "payable": false, "stateMutability": "view", "type": "function", }, { "inputs": [ { "name": "_implementation", "type": "address", }, ], "payable": false, "stateMutability": "nonpayable", "type": "constructor", }, { "payable": true, "stateMutability": "payable", "type": "fallback", }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "previousAdmin", "type": "address", }, { "indexed": false, "name": "newAdmin", "type": "address", }, ], "name": "AdminChanged", "type": "event", }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "implementation", "type": "address", }, ], "name": "Upgraded", "type": "event", }, ], "address": { "1": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", }, "name": "FiatToken", }, ] `; ================================================ FILE: packages/cli/src/plugins/__snapshots__/sourcify.test.ts.snap ================================================ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`fetches ABI 1`] = ` [ { "abi": [ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor", }, { "inputs": [ { "name": "pubkey", "type": "bytes", }, { "name": "withdrawal_credentials", "type": "bytes", }, { "name": "amount", "type": "bytes", }, { "name": "signature", "type": "bytes", }, { "name": "index", "type": "bytes", }, ], "name": "DepositEvent", "type": "event", }, { "inputs": [ { "name": "pubkey", "type": "bytes", }, { "name": "withdrawal_credentials", "type": "bytes", }, { "name": "signature", "type": "bytes", }, { "name": "deposit_data_root", "type": "bytes32", }, ], "name": "deposit", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [], "name": "get_deposit_count", "outputs": [ { "type": "bytes", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "get_deposit_root", "outputs": [ { "type": "bytes32", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "name": "interfaceId", "type": "bytes4", }, ], "name": "supportsInterface", "outputs": [ { "type": "bool", }, ], "stateMutability": "pure", "type": "function", }, ], "address": { "1": "0x00000000219ab540356cbb839cbe05303d7705fa", }, "name": "DepositContract", }, ] `; exports[`fetches ABI with multichain deployment 1`] = ` [ { "abi": [ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor", }, { "inputs": [ { "name": "pubkey", "type": "bytes", }, { "name": "withdrawal_credentials", "type": "bytes", }, { "name": "amount", "type": "bytes", }, { "name": "signature", "type": "bytes", }, { "name": "index", "type": "bytes", }, ], "name": "DepositEvent", "type": "event", }, { "inputs": [ { "name": "pubkey", "type": "bytes", }, { "name": "withdrawal_credentials", "type": "bytes", }, { "name": "signature", "type": "bytes", }, { "name": "deposit_data_root", "type": "bytes32", }, ], "name": "deposit", "outputs": [], "stateMutability": "payable", "type": "function", }, { "inputs": [], "name": "get_deposit_count", "outputs": [ { "type": "bytes", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [], "name": "get_deposit_root", "outputs": [ { "type": "bytes32", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "name": "interfaceId", "type": "bytes4", }, ], "name": "supportsInterface", "outputs": [ { "type": "bool", }, ], "stateMutability": "pure", "type": "function", }, ], "address": { "100": "0xC4c622862a8F548997699bE24EA4bc504e5cA865", "137": "0xC4c622862a8F548997699bE24EA4bc504e5cA865", }, "name": "Community", }, ] `; ================================================ FILE: packages/cli/src/plugins/actions.test.ts ================================================ import { erc20Abi } from 'viem' import { expect, test } from 'vitest' import { actions } from './actions.js' test('default', async () => { const result = await actions().run?.({ contracts: [ { name: 'erc20', abi: erc20Abi, content: '', meta: { abiName: 'erc20Abi', }, }, ], isTypeScript: true, outputs: [], }) expect(result?.imports).toMatchInlineSnapshot(` "import { createReadContract, createWriteContract, createSimulateContract, createWatchContractEvent } from '@wagmi/core/codegen' " `) expect(result?.content).toMatchInlineSnapshot(` "/** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const readErc20 = /*#__PURE__*/ createReadContract({ abi: erc20Abi }) /** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"allowance"\` */ export const readErc20Allowance = /*#__PURE__*/ createReadContract({ abi: erc20Abi, functionName: 'allowance' }) /** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"balanceOf"\` */ export const readErc20BalanceOf = /*#__PURE__*/ createReadContract({ abi: erc20Abi, functionName: 'balanceOf' }) /** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"decimals"\` */ export const readErc20Decimals = /*#__PURE__*/ createReadContract({ abi: erc20Abi, functionName: 'decimals' }) /** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"name"\` */ export const readErc20Name = /*#__PURE__*/ createReadContract({ abi: erc20Abi, functionName: 'name' }) /** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"symbol"\` */ export const readErc20Symbol = /*#__PURE__*/ createReadContract({ abi: erc20Abi, functionName: 'symbol' }) /** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"totalSupply"\` */ export const readErc20TotalSupply = /*#__PURE__*/ createReadContract({ abi: erc20Abi, functionName: 'totalSupply' }) /** * Wraps __{@link writeContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const writeErc20 = /*#__PURE__*/ createWriteContract({ abi: erc20Abi }) /** * Wraps __{@link writeContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"approve"\` */ export const writeErc20Approve = /*#__PURE__*/ createWriteContract({ abi: erc20Abi, functionName: 'approve' }) /** * Wraps __{@link writeContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transfer"\` */ export const writeErc20Transfer = /*#__PURE__*/ createWriteContract({ abi: erc20Abi, functionName: 'transfer' }) /** * Wraps __{@link writeContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transferFrom"\` */ export const writeErc20TransferFrom = /*#__PURE__*/ createWriteContract({ abi: erc20Abi, functionName: 'transferFrom' }) /** * Wraps __{@link simulateContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const simulateErc20 = /*#__PURE__*/ createSimulateContract({ abi: erc20Abi }) /** * Wraps __{@link simulateContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"approve"\` */ export const simulateErc20Approve = /*#__PURE__*/ createSimulateContract({ abi: erc20Abi, functionName: 'approve' }) /** * Wraps __{@link simulateContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transfer"\` */ export const simulateErc20Transfer = /*#__PURE__*/ createSimulateContract({ abi: erc20Abi, functionName: 'transfer' }) /** * Wraps __{@link simulateContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transferFrom"\` */ export const simulateErc20TransferFrom = /*#__PURE__*/ createSimulateContract({ abi: erc20Abi, functionName: 'transferFrom' }) /** * Wraps __{@link watchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ */ export const watchErc20Event = /*#__PURE__*/ createWatchContractEvent({ abi: erc20Abi }) /** * Wraps __{@link watchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ and \`eventName\` set to \`"Approval"\` */ export const watchErc20ApprovalEvent = /*#__PURE__*/ createWatchContractEvent({ abi: erc20Abi, eventName: 'Approval' }) /** * Wraps __{@link watchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ and \`eventName\` set to \`"Transfer"\` */ export const watchErc20TransferEvent = /*#__PURE__*/ createWatchContractEvent({ abi: erc20Abi, eventName: 'Transfer' })" `) }) test('address', async () => { const result = await actions().run?.({ contracts: [ { name: 'erc20', abi: erc20Abi, content: '', meta: { abiName: 'erc20Abi', addressName: 'erc20Address', }, }, ], isTypeScript: true, outputs: [], }) expect(result?.content).toMatchInlineSnapshot(` "/** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const readErc20 = /*#__PURE__*/ createReadContract({ abi: erc20Abi, address: erc20Address }) /** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"allowance"\` */ export const readErc20Allowance = /*#__PURE__*/ createReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'allowance' }) /** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"balanceOf"\` */ export const readErc20BalanceOf = /*#__PURE__*/ createReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'balanceOf' }) /** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"decimals"\` */ export const readErc20Decimals = /*#__PURE__*/ createReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'decimals' }) /** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"name"\` */ export const readErc20Name = /*#__PURE__*/ createReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'name' }) /** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"symbol"\` */ export const readErc20Symbol = /*#__PURE__*/ createReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'symbol' }) /** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"totalSupply"\` */ export const readErc20TotalSupply = /*#__PURE__*/ createReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'totalSupply' }) /** * Wraps __{@link writeContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const writeErc20 = /*#__PURE__*/ createWriteContract({ abi: erc20Abi, address: erc20Address }) /** * Wraps __{@link writeContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"approve"\` */ export const writeErc20Approve = /*#__PURE__*/ createWriteContract({ abi: erc20Abi, address: erc20Address, functionName: 'approve' }) /** * Wraps __{@link writeContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transfer"\` */ export const writeErc20Transfer = /*#__PURE__*/ createWriteContract({ abi: erc20Abi, address: erc20Address, functionName: 'transfer' }) /** * Wraps __{@link writeContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transferFrom"\` */ export const writeErc20TransferFrom = /*#__PURE__*/ createWriteContract({ abi: erc20Abi, address: erc20Address, functionName: 'transferFrom' }) /** * Wraps __{@link simulateContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const simulateErc20 = /*#__PURE__*/ createSimulateContract({ abi: erc20Abi, address: erc20Address }) /** * Wraps __{@link simulateContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"approve"\` */ export const simulateErc20Approve = /*#__PURE__*/ createSimulateContract({ abi: erc20Abi, address: erc20Address, functionName: 'approve' }) /** * Wraps __{@link simulateContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transfer"\` */ export const simulateErc20Transfer = /*#__PURE__*/ createSimulateContract({ abi: erc20Abi, address: erc20Address, functionName: 'transfer' }) /** * Wraps __{@link simulateContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transferFrom"\` */ export const simulateErc20TransferFrom = /*#__PURE__*/ createSimulateContract({ abi: erc20Abi, address: erc20Address, functionName: 'transferFrom' }) /** * Wraps __{@link watchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ */ export const watchErc20Event = /*#__PURE__*/ createWatchContractEvent({ abi: erc20Abi, address: erc20Address }) /** * Wraps __{@link watchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ and \`eventName\` set to \`"Approval"\` */ export const watchErc20ApprovalEvent = /*#__PURE__*/ createWatchContractEvent({ abi: erc20Abi, address: erc20Address, eventName: 'Approval' }) /** * Wraps __{@link watchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ and \`eventName\` set to \`"Transfer"\` */ export const watchErc20TransferEvent = /*#__PURE__*/ createWatchContractEvent({ abi: erc20Abi, address: erc20Address, eventName: 'Transfer' })" `) }) test('legacy hook names', async () => { const result = await actions({ getActionName: 'legacy' }).run?.({ contracts: [ { name: 'erc20', abi: erc20Abi, content: '', meta: { abiName: 'erc20Abi', addressName: 'erc20Address', }, }, ], isTypeScript: true, outputs: [], }) expect(result?.content).toMatchInlineSnapshot(` "/** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const readErc20 = /*#__PURE__*/ createReadContract({ abi: erc20Abi, address: erc20Address }) /** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"allowance"\` */ export const readErc20Allowance = /*#__PURE__*/ createReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'allowance' }) /** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"balanceOf"\` */ export const readErc20BalanceOf = /*#__PURE__*/ createReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'balanceOf' }) /** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"decimals"\` */ export const readErc20Decimals = /*#__PURE__*/ createReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'decimals' }) /** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"name"\` */ export const readErc20Name = /*#__PURE__*/ createReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'name' }) /** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"symbol"\` */ export const readErc20Symbol = /*#__PURE__*/ createReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'symbol' }) /** * Wraps __{@link readContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"totalSupply"\` */ export const readErc20TotalSupply = /*#__PURE__*/ createReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'totalSupply' }) /** * Wraps __{@link writeContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const writeErc20 = /*#__PURE__*/ createWriteContract({ abi: erc20Abi, address: erc20Address }) /** * Wraps __{@link writeContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"approve"\` */ export const writeErc20Approve = /*#__PURE__*/ createWriteContract({ abi: erc20Abi, address: erc20Address, functionName: 'approve' }) /** * Wraps __{@link writeContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transfer"\` */ export const writeErc20Transfer = /*#__PURE__*/ createWriteContract({ abi: erc20Abi, address: erc20Address, functionName: 'transfer' }) /** * Wraps __{@link writeContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transferFrom"\` */ export const writeErc20TransferFrom = /*#__PURE__*/ createWriteContract({ abi: erc20Abi, address: erc20Address, functionName: 'transferFrom' }) /** * Wraps __{@link simulateContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const prepareWriteErc20 = /*#__PURE__*/ createSimulateContract({ abi: erc20Abi, address: erc20Address }) /** * Wraps __{@link simulateContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"approve"\` */ export const prepareWriteErc20Approve = /*#__PURE__*/ createSimulateContract({ abi: erc20Abi, address: erc20Address, functionName: 'approve' }) /** * Wraps __{@link simulateContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transfer"\` */ export const prepareWriteErc20Transfer = /*#__PURE__*/ createSimulateContract({ abi: erc20Abi, address: erc20Address, functionName: 'transfer' }) /** * Wraps __{@link simulateContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transferFrom"\` */ export const prepareWriteErc20TransferFrom = /*#__PURE__*/ createSimulateContract({ abi: erc20Abi, address: erc20Address, functionName: 'transferFrom' }) /** * Wraps __{@link watchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ */ export const watchErc20Event = /*#__PURE__*/ createWatchContractEvent({ abi: erc20Abi, address: erc20Address }) /** * Wraps __{@link watchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ and \`eventName\` set to \`"Approval"\` */ export const watchErc20ApprovalEvent = /*#__PURE__*/ createWatchContractEvent({ abi: erc20Abi, address: erc20Address, eventName: 'Approval' }) /** * Wraps __{@link watchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ and \`eventName\` set to \`"Transfer"\` */ export const watchErc20TransferEvent = /*#__PURE__*/ createWatchContractEvent({ abi: erc20Abi, address: erc20Address, eventName: 'Transfer' })" `) }) test('override package name', async () => { const result = await actions({ overridePackageName: 'wagmi' }).run?.({ contracts: [ { name: 'erc20', abi: erc20Abi, content: '', meta: { abiName: 'erc20Abi', }, }, ], isTypeScript: true, outputs: [], }) expect(result?.imports).toMatchInlineSnapshot(` "import { createReadContract, createWriteContract, createSimulateContract, createWatchContractEvent } from 'wagmi/codegen' " `) }) ================================================ FILE: packages/cli/src/plugins/actions.ts ================================================ import { pascalCase } from 'change-case' import type { Contract, Plugin } from '../config.js' import type { Compute, RequiredBy } from '../types.js' import { getAddressDocString } from '../utils/getAddressDocString.js' import { getIsPackageInstalled } from '../utils/packages.js' export type ActionsConfig = { getActionName?: | 'legacy' // TODO: Deprecate `'legacy'` option | ((options: { contractName: string itemName?: string | undefined type: 'read' | 'simulate' | 'watch' | 'write' }) => string) overridePackageName?: '@wagmi/core' | 'wagmi' | undefined } type ActionsResult = Compute> export function actions(config: ActionsConfig = {}): ActionsResult { return { name: 'Action', async run({ contracts }) { const imports = new Set([]) const content: string[] = [] const pure = '/*#__PURE__*/' const actionNames = new Set() for (const contract of contracts) { let hasReadFunction = false let hasWriteFunction = false let hasEvent = false const readItems = [] const writeItems = [] const eventItems = [] for (const item of contract.abi) { if (item.type === 'function') if ( item.stateMutability === 'view' || item.stateMutability === 'pure' ) { hasReadFunction = true readItems.push(item) } else { hasWriteFunction = true writeItems.push(item) } else if (item.type === 'event') { hasEvent = true eventItems.push(item) } } let innerContent: string if (contract.meta.addressName) innerContent = `abi: ${contract.meta.abiName}, address: ${contract.meta.addressName}` else innerContent = `abi: ${contract.meta.abiName}` if (hasReadFunction) { const actionName = getActionName( config, actionNames, 'read', contract.name, ) const docString = genDocString('readContract', contract) const functionName = 'createReadContract' imports.add(functionName) content.push( `${docString} export const ${actionName} = ${pure} ${functionName}({ ${innerContent} })`, ) const names = new Set() for (const item of readItems) { if (item.type !== 'function') continue if ( item.stateMutability !== 'pure' && item.stateMutability !== 'view' ) continue // Skip overrides since they are captured by same hook if (names.has(item.name)) continue names.add(item.name) const hookName = getActionName( config, actionNames, 'read', contract.name, item.name, ) const docString = genDocString('readContract', contract, { name: 'functionName', value: item.name, }) content.push( `${docString} export const ${hookName} = ${pure} ${functionName}({ ${innerContent}, functionName: '${item.name}' })`, ) } } if (hasWriteFunction) { { const actionName = getActionName( config, actionNames, 'write', contract.name, ) const docString = genDocString('writeContract', contract) const functionName = 'createWriteContract' imports.add(functionName) content.push( `${docString} export const ${actionName} = ${pure} ${functionName}({ ${innerContent} })`, ) const names = new Set() for (const item of writeItems) { if (item.type !== 'function') continue if ( item.stateMutability !== 'nonpayable' && item.stateMutability !== 'payable' ) continue // Skip overrides since they are captured by same hook if (names.has(item.name)) continue names.add(item.name) const actionName = getActionName( config, actionNames, 'write', contract.name, item.name, ) const docString = genDocString('writeContract', contract, { name: 'functionName', value: item.name, }) content.push( `${docString} export const ${actionName} = ${pure} ${functionName}({ ${innerContent}, functionName: '${item.name}' })`, ) } } { const actionName = getActionName( config, actionNames, 'simulate', contract.name, ) const docString = genDocString('simulateContract', contract) const functionName = 'createSimulateContract' imports.add(functionName) content.push( `${docString} export const ${actionName} = ${pure} ${functionName}({ ${innerContent} })`, ) const names = new Set() for (const item of writeItems) { if (item.type !== 'function') continue if ( item.stateMutability !== 'nonpayable' && item.stateMutability !== 'payable' ) continue // Skip overrides since they are captured by same hook if (names.has(item.name)) continue names.add(item.name) const actionName = getActionName( config, actionNames, 'simulate', contract.name, item.name, ) const docString = genDocString('simulateContract', contract, { name: 'functionName', value: item.name, }) content.push( `${docString} export const ${actionName} = ${pure} ${functionName}({ ${innerContent}, functionName: '${item.name}' })`, ) } } } if (hasEvent) { const actionName = getActionName( config, actionNames, 'watch', contract.name, ) const docString = genDocString('watchContractEvent', contract) const functionName = 'createWatchContractEvent' imports.add(functionName) content.push( `${docString} export const ${actionName} = ${pure} ${functionName}({ ${innerContent} })`, ) const names = new Set() for (const item of eventItems) { if (item.type !== 'event') continue // Skip overrides since they are captured by same hook if (names.has(item.name)) continue names.add(item.name) const actionName = getActionName( config, actionNames, 'watch', contract.name, item.name, ) const docString = genDocString('watchContractEvent', contract, { name: 'eventName', value: item.name, }) content.push( `${docString} export const ${actionName} = ${pure} ${functionName}({ ${innerContent}, eventName: '${item.name}' })`, ) } } } const importValues = [...imports.values()] let packageName = '@wagmi/core/codegen' if (config.overridePackageName) { switch (config.overridePackageName) { case '@wagmi/core': packageName = '@wagmi/core/codegen' break case 'wagmi': packageName = 'wagmi/codegen' break } } else if (await getIsPackageInstalled({ packageName: 'wagmi' })) packageName = 'wagmi/codegen' else if (await getIsPackageInstalled({ packageName: '@wagmi/core' })) packageName = '@wagmi/core/codegen' return { imports: importValues.length ? `import { ${importValues.join(', ')} } from '${packageName}'\n` : '', content: content.join('\n\n'), } }, } } function genDocString( actionName: string, contract: Contract, item?: { name: string; value: string }, ) { let description = `Wraps __{@link ${actionName}}__ with \`abi\` set to __{@link ${contract.meta.abiName}}__` if (item) description += ` and \`${item.name}\` set to \`"${item.value}"\`` const docString = getAddressDocString({ address: contract.address }) if (docString) return `/** * ${description} * ${docString} */` return `/** * ${description} */` } function getActionName( config: ActionsConfig, actionNames: Set, type: 'read' | 'simulate' | 'watch' | 'write', contractName: string, itemName?: string | undefined, ) { const ContractName = pascalCase(contractName) const ItemName = itemName ? pascalCase(itemName) : undefined let actionName: string if (typeof config.getActionName === 'function') actionName = config.getActionName({ type, contractName: ContractName, itemName: ItemName, }) else if (typeof config.getActionName === 'string' && type === 'simulate') { actionName = `prepareWrite${ContractName}${ItemName ?? ''}` } else { actionName = `${type}${ContractName}${ItemName ?? ''}` if (type === 'watch') actionName = `${actionName}Event` } if (actionNames.has(actionName)) throw new Error( `Action name "${actionName}" must be unique for contract "${contractName}". Try using \`getActionName\` to create a unique name.`, ) actionNames.add(actionName) return actionName } ================================================ FILE: packages/cli/src/plugins/blockExplorer.test.ts ================================================ import { setupServer } from 'msw/node' import { afterAll, afterEach, beforeAll, expect, test } from 'vitest' import { address, apiKey, getHandlers, unverifiedContractAddress, } from '../../test/utils.js' import { blockExplorer } from './blockExplorer.js' const baseUrl = 'https://api.etherscan.io/v2/api' const server = setupServer(...getHandlers(baseUrl)) beforeAll(() => server.listen()) afterEach(() => server.resetHandlers()) afterAll(() => server.close()) test('fetches ABI', async () => { await expect( blockExplorer({ apiKey, baseUrl, contracts: [{ name: 'WagmiMintExample', address }], }).contracts!(), ).resolves.toMatchSnapshot() }) test('fetches ABI with multichain deployment', async () => { await expect( blockExplorer({ apiKey, baseUrl, contracts: [ { name: 'WagmiMintExample', address: { 1: address, 10: address } }, ], }).contracts?.(), ).resolves.toMatchSnapshot() }) test('fails to fetch for unverified contract', async () => { await expect( blockExplorer({ apiKey, baseUrl, contracts: [ { name: 'WagmiMintExample', address: unverifiedContractAddress }, ], }).contracts?.(), ).rejects.toThrowErrorMatchingInlineSnapshot( '[Error: Contract source code not verified]', ) }) ================================================ FILE: packages/cli/src/plugins/blockExplorer.ts ================================================ import { camelCase } from 'change-case' import type { Address } from 'viem' import { z } from 'zod' import type { ContractConfig } from '../config.js' import { fromZodError } from '../errors.js' import type { Compute } from '../types.js' import { fetch } from './fetch.js' export type BlockExplorerConfig = { /** * API key for block explorer. Appended to the request URL as query param `&apikey=${apiKey}`. */ apiKey?: string | undefined /** * Base URL for block explorer. */ baseUrl: string /** * Duration in milliseconds to cache ABIs. * * @default 1_800_000 // 30m in ms */ cacheDuration?: number | undefined /** * Chain ID for block explorer. Appended to the request URL as query param `&chainId=${chainId}`. */ chainId?: number | undefined /** * Contracts to fetch ABIs for. */ contracts: Compute>[] /** * Function to get address from contract config. */ getAddress?: | ((config: { address: NonNullable }) => Address) | undefined /** * Name of source. */ name?: ContractConfig['name'] | undefined } const BlockExplorerResponse = z.discriminatedUnion('status', [ z.object({ status: z.literal('1'), message: z.literal('OK'), result: z .string() .transform((val) => JSON.parse(val) as ContractConfig['abi']), }), z.object({ status: z.literal('0'), message: z.literal('NOTOK'), result: z.string(), }), ]) /** * Fetches contract ABIs from block explorers, supporting `?module=contract&action=getabi` requests. */ export function blockExplorer(config: BlockExplorerConfig) { const { apiKey, baseUrl, cacheDuration, chainId, contracts, getAddress = ({ address }) => { if (typeof address === 'string') return address return Object.values(address)[0]! }, name = 'Block Explorer', } = config return fetch({ cacheDuration, contracts, name, getCacheKey({ contract }) { if (typeof contract.address === 'string') return `${camelCase(name)}:${contract.address}` return `${camelCase(name)}:${JSON.stringify(contract.address)}` }, async parse({ response }) { const json = await response.json() const parsed = await BlockExplorerResponse.safeParseAsync(json) if (!parsed.success) throw fromZodError(parsed.error, { prefix: 'Invalid response' }) if (parsed.data.status === '0') throw new Error(parsed.data.result) return parsed.data.result }, request({ address }) { if (!address) throw new Error('address is required') return { url: `${baseUrl}?${chainId ? `chainId=${chainId}&` : ''}module=contract&action=getabi&address=${getAddress( { address, }, )}${apiKey ? `&apikey=${apiKey}` : ''}`, } }, }) } ================================================ FILE: packages/cli/src/plugins/etherscan.test.ts ================================================ import { mkdir, rm } from 'node:fs/promises' import { setupServer } from 'msw/node' import { afterAll, afterEach, beforeAll, expect, test } from 'vitest' import { address, apiKey, getHandlers, invalidApiKey, proxyAddress, timeoutAddress, unverifiedContractAddress, } from '../../test/utils.js' import { etherscan } from './etherscan.js' import { getCacheDir } from './fetch.js' const server = setupServer(...getHandlers()) beforeAll(() => server.listen()) afterEach(() => server.resetHandlers()) afterAll(() => server.close()) test('fetches ABI', async () => { await expect( etherscan({ apiKey, chainId: 1, contracts: [{ name: 'WagmiMintExample', address }], }).contracts?.(), ).resolves.toMatchSnapshot() }) test('fetches ABI with multichain deployment', async () => { await expect( etherscan({ apiKey, chainId: 1, contracts: [ { name: 'WagmiMintExample', address: { 1: address, 10: address } }, ], }).contracts?.(), ).resolves.toMatchSnapshot() }) test('fails to fetch for unverified contract', async () => { await expect( etherscan({ apiKey, chainId: 1, contracts: [ { name: 'WagmiMintExample', address: unverifiedContractAddress }, ], }).contracts?.(), ).rejects.toThrowErrorMatchingInlineSnapshot( '[Error: Contract source code not verified]', ) }) test('missing address for chainId', async () => { await expect( etherscan({ apiKey, chainId: 1, // @ts-expect-error `chainId` and `keyof typeof contracts[number].address` mismatch contracts: [{ name: 'WagmiMintExample', address: { 10: address } }], }).contracts?.(), ).rejects.toThrowErrorMatchingInlineSnapshot( `[Error: No address found for chainId "1". Make sure chainId "1" is set as an address.]`, ) }) test('invalid api key', async () => { await expect( etherscan({ apiKey: invalidApiKey, chainId: 1, contracts: [{ name: 'WagmiMintExample', address: timeoutAddress }], }).contracts?.(), ).rejects.toThrowErrorMatchingInlineSnapshot('[Error: Invalid API Key]') }) test('tryFetchProxyImplementation: fetches ABI', async () => { const cacheDir = getCacheDir() await mkdir(cacheDir, { recursive: true }) await expect( etherscan({ apiKey, chainId: 1, contracts: [{ name: 'WagmiMintExample', address }], tryFetchProxyImplementation: true, }).contracts?.(), ).resolves.toMatchSnapshot() await rm(cacheDir, { recursive: true }) }) test('tryFetchProxyImplementation: fetches implementation ABI', async () => { const cacheDir = getCacheDir() await mkdir(cacheDir, { recursive: true }) await expect( etherscan({ apiKey, chainId: 1, contracts: [{ name: 'FiatToken', address: proxyAddress }], tryFetchProxyImplementation: true, }).contracts?.(), ).resolves.toMatchSnapshot() await rm(cacheDir, { recursive: true }) }) ================================================ FILE: packages/cli/src/plugins/etherscan.ts ================================================ import { mkdir, writeFile } from 'node:fs/promises' import { Address as AddressSchema } from 'abitype/zod' import { camelCase } from 'change-case' import { join } from 'pathe' import type { Abi, Address } from 'viem' import { z } from 'zod' import type { ContractConfig } from '../config.js' import { fromZodError } from '../errors.js' import type { Compute } from '../types.js' import { fetch, getCacheDir } from './fetch.js' export type EtherscanConfig = { /** * Etherscan API key. * * Create or manage keys at https://etherscan.io/myapikey */ apiKey: string /** * Duration in milliseconds to cache ABIs. * * @default 1_800_000 // 30m in ms */ cacheDuration?: number | undefined /** * Chain ID to use for fetching ABI. * * If `address` is an object, `chainId` is used to select the address. * * View supported chains on the [Etherscan docs](https://docs.etherscan.io/etherscan-v2/getting-started/supported-chains). */ chainId: (chainId extends ChainId ? chainId : never) | (ChainId & {}) /** * Contracts to fetch ABIs for. */ contracts: Compute, 'abi'>>[] /** * Whether to try fetching proxy implementation address of the contract * * @default false */ tryFetchProxyImplementation?: boolean | undefined } /** * Fetches contract ABIs from Etherscan. */ export function etherscan( config: EtherscanConfig, ) { const { apiKey, cacheDuration = 1_800_000, chainId, tryFetchProxyImplementation = false, } = config const contracts = config.contracts.map((x) => ({ ...x, address: typeof x.address === 'string' ? { [chainId]: x.address } : x.address, })) as Omit[] const name = 'Etherscan' const getCacheKey: Parameters[0]['getCacheKey'] = ({ contract, }) => { if (typeof contract.address === 'string') return `${camelCase(name)}:${contract.address}` return `${camelCase(name)}:${JSON.stringify(contract.address)}` } return fetch({ cacheDuration, contracts, name, getCacheKey, async parse({ response }) { const json = await response.json() const parsed = await GetAbiResponse.safeParseAsync(json) if (!parsed.success) throw fromZodError(parsed.error, { prefix: 'Invalid response' }) if (parsed.data.status === '0') throw new Error(parsed.data.result) return parsed.data.result }, async request(contract) { if (!contract.address) throw new Error('address is required') const resolvedAddress = (() => { if (!contract.address) throw new Error('address is required') if (typeof contract.address === 'string') return contract.address const contractAddress = contract.address[chainId] if (!contractAddress) throw new Error( `No address found for chainId "${chainId}". Make sure chainId "${chainId}" is set as an address.`, ) return contractAddress })() const options = { address: resolvedAddress, apiKey, chainId, } let abi: Abi | undefined const implementationAddress = await (async () => { if (!tryFetchProxyImplementation) return const json = await globalThis .fetch(buildUrl({ ...options, action: 'getsourcecode' })) .then((res) => res.json()) const parsed = await GetSourceCodeResponse.safeParseAsync(json) if (!parsed.success) throw fromZodError(parsed.error, { prefix: 'Invalid response' }) if (parsed.data.status === '0') throw new Error(parsed.data.result) if (!parsed.data.result[0]) return abi = parsed.data.result[0].ABI return parsed.data.result[0].Implementation as Address })() if (abi) { const cacheDir = getCacheDir() await mkdir(cacheDir, { recursive: true }) const cacheKey = getCacheKey({ contract }) const cacheFilePath = join(cacheDir, `${cacheKey}.json`) await writeFile( cacheFilePath, `${JSON.stringify({ abi, timestamp: Date.now() + cacheDuration }, undefined, 2)}\n`, ) } return { url: buildUrl({ ...options, action: 'getabi', address: implementationAddress || resolvedAddress, }), } }, }) } function buildUrl(options: { action: 'getabi' | 'getsourcecode' address: Address apiKey: string chainId: ChainId | undefined }) { const baseUrl = 'https://api.etherscan.io/v2/api' const { action, address, apiKey, chainId } = options return `${baseUrl}?${chainId ? `chainId=${chainId}&` : ''}module=contract&action=${action}&address=${address}${apiKey ? `&apikey=${apiKey}` : ''}` } const GetAbiResponse = z.discriminatedUnion('status', [ z.object({ status: z.literal('1'), message: z.literal('OK'), result: z.string().transform((val) => JSON.parse(val) as Abi), }), z.object({ status: z.literal('0'), message: z.literal('NOTOK'), result: z.string(), }), ]) const GetSourceCodeResponse = z.discriminatedUnion('status', [ z.object({ status: z.literal('1'), message: z.literal('OK'), result: z.array( z.discriminatedUnion('Proxy', [ z.object({ ABI: z.string().transform((val) => JSON.parse(val) as Abi), Implementation: AddressSchema, Proxy: z.literal('1'), }), z.object({ ABI: z.string().transform((val) => JSON.parse(val) as Abi), Implementation: z.string(), Proxy: z.literal('0'), }), ]), ), }), z.object({ status: z.literal('0'), message: z.literal('NOTOK'), result: z.string(), }), ]) // Supported chains // https://docs.etherscan.io/etherscan-v2/getting-started/supported-chains type ChainId = | 1 // Ethereum Mainnet | 11155111 // Sepolia Testnet | 17000 // Holesky Testnet | 560048 // Hoodi Testnet | 56 // BNB Smart Chain Mainnet | 97 // BNB Smart Chain Testnet | 137 // Polygon Mainnet | 80002 // Polygon Amoy Testnet | 8453 // Base Mainnet | 84532 // Base Sepolia Testnet | 42161 // Arbitrum One Mainnet | 42170 // Arbitrum Nova Mainnet | 421614 // Arbitrum Sepolia Testnet | 59144 // Linea Mainnet | 59141 // Linea Sepolia Testnet | 81457 // Blast Mainnet | 168587773 // Blast Sepolia Testnet | 10 // OP Mainnet | 11155420 // OP Sepolia Testnet | 43114 // Avalanche C-Chain | 43113 // Avalanche Fuji Testnet | 199 // BitTorrent Chain Mainnet | 1029 // BitTorrent Chain Testnet | 42220 // Celo Mainnet | 11142220 // Celo Sepolia Testnet | 25 // Cronos Mainnet | 252 // Fraxtal Mainnet | 2522 // Fraxtal Testnet | 100 // Gnosis | 5000 // Mantle Mainnet | 5003 // Mantle Sepolia Testnet | 43521 // Memecore Testnet | 1284 // Moonbeam Mainnet | 1285 // Moonriver Mainnet | 1287 // Moonbase Alpha Testnet | 204 // opBNB Mainnet | 5611 // opBNB Testnet | 534352 // Scroll Mainnet | 534351 // Scroll Sepolia Testnet | 167000 // Taiko Mainnet | 167012 // Taiko Hoodi | 324 // zkSync Mainnet | 300 // zkSync Sepolia Testnet | 50 // XDC Mainnet | 51 // XDC Apothem Testnet | 33139 // ApeChain Mainnet | 33111 // ApeChain Curtis Testnet | 480 // World Mainnet | 4801 // World Sepolia Testnet | 50104 // Sophon Mainnet | 531050104 // Sophon Sepolia Testnet | 146 // Sonic Mainnet | 14601 // Sonic Testnet | 130 // Unichain Mainnet | 1301 // Unichain Sepolia Testnet | 2741 // Abstract Mainnet | 11124 // Abstract Sepolia Testnet | 80094 // Berachain Mainnet | 80069 // Berachain Bepolia Testnet | 1923 // Swellchain Mainnet | 1924 // Swellchain Testnet | 10143 // Monad Testnet | 999 // HyperEVM Mainnet | 747474 // Katana Mainnet | 737373 // Katana Bokuto | 1329 // Sei Mainnet | 1328 // Sei Testnet ================================================ FILE: packages/cli/src/plugins/fetch.test.ts ================================================ import { mkdir, rm, writeFile } from 'node:fs/promises' import { homedir } from 'node:os' import { setupServer } from 'msw/node' import { afterAll, afterEach, beforeAll, expect, test } from 'vitest' import { address, apiKey, getHandlers, timeoutAddress, unverifiedContractAddress, } from '../../test/utils.js' import { fetch, getCacheDir } from './fetch.js' const baseUrl = 'https://api.etherscan.io/v2/api' const server = setupServer(...getHandlers(baseUrl)) beforeAll(() => server.listen()) afterEach(() => server.resetHandlers()) afterAll(() => server.close()) type Fetch = Parameters[0] const request: Fetch['request'] = ({ address }) => { return { url: `${baseUrl}?module=contract&action=getabi&address=${address}&apikey=${apiKey}`, } } const parse: Fetch['parse'] = async ({ response }) => { const data = (await response.json()) as | { status: '1'; message: 'OK'; result: string } | { status: '0'; message: 'NOTOK'; result: string } if (data.status === '0') throw new Error(data.result) return JSON.parse(data.result) } test('fetches ABI', async () => { await expect( fetch({ contracts: [{ name: 'WagmiMintExample', address }], request, parse, }).contracts?.(), ).resolves.toMatchSnapshot() }) test('fails to fetch for unverified contract', async () => { await expect( fetch({ contracts: [ { name: 'WagmiMintExample', address: unverifiedContractAddress }, ], request, parse, }).contracts?.(), ).rejects.toThrowErrorMatchingInlineSnapshot( '[Error: Contract source code not verified]', ) }) test('aborts request', async () => { await expect( fetch({ contracts: [{ name: 'WagmiMintExample', address: timeoutAddress }], request, parse, timeoutDuration: 1_000, }).contracts?.(), ).rejects.toThrowErrorMatchingInlineSnapshot( '[AbortError: This operation was aborted]', ) }) test('reads from cache', async () => { const cacheDir = `${homedir}/.wagmi-cli/plugins/fetch/cache` await mkdir(cacheDir, { recursive: true }) const contract = { name: 'WagmiMintExample', address: timeoutAddress, } as const const cacheKey = JSON.stringify(contract) const cacheFilePath = `${cacheDir}/${cacheKey}.json` await writeFile( cacheFilePath, JSON.stringify( { abi: [ { inputs: [], name: 'mint', outputs: [], stateMutability: 'nonpayable', type: 'function', }, ], timestamp: Date.now() + 30_000, }, null, 2, ), ) await expect( fetch({ contracts: [contract], request, parse, }).contracts?.(), ).resolves.toMatchInlineSnapshot(` [ { "abi": [ { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "address": "0xecb504d39723b0be0e3a9aa33d646642d1051ee1", "name": "WagmiMintExample", }, ] `) await rm(cacheDir, { recursive: true }) }) test('fails and reads from cache', async () => { const cacheDir = getCacheDir() await mkdir(cacheDir, { recursive: true }) const contract = { name: 'WagmiMintExample', address: timeoutAddress, } as const const cacheKey = JSON.stringify(contract) const cacheFilePath = `${cacheDir}/${cacheKey}.json` await writeFile( cacheFilePath, JSON.stringify( { abi: [ { inputs: [], name: 'mint', outputs: [], stateMutability: 'nonpayable', type: 'function', }, ], timestamp: Date.now() - 30_000, }, null, 2, ), ) await expect( fetch({ contracts: [contract], request, parse, timeoutDuration: 1, }).contracts?.(), ).resolves.toMatchInlineSnapshot(` [ { "abi": [ { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "address": "0xecb504d39723b0be0e3a9aa33d646642d1051ee1", "name": "WagmiMintExample", }, ] `) await rm(cacheDir, { recursive: true }) }) ================================================ FILE: packages/cli/src/plugins/fetch.ts ================================================ import { mkdir, readFile, writeFile } from 'node:fs/promises' import { homedir } from 'node:os' import { join } from 'pathe' import type { Abi } from 'viem' import type { ContractConfig, Plugin } from '../config.js' import type { Compute, RequiredBy } from '../types.js' export type FetchConfig = { /** * Duration in milliseconds to cache ABIs from request. * * @default 1_800_000 // 30m in ms */ cacheDuration?: number | undefined /** * Contracts to fetch ABIs for. */ contracts: Compute>[] /** * Function for creating a cache key for contract. */ getCacheKey?: | ((config: { contract: Compute> }) => string) | undefined /** * Name of source. */ name?: ContractConfig['name'] | undefined /** * Function for parsing ABI from fetch response. * * @default ({ response }) => response.json() */ parse?: | ((config: { response: Response }) => ContractConfig['abi'] | Promise) | undefined /** * Function for returning a request to fetch ABI from. */ request: (config: { address?: ContractConfig['address'] | undefined name: ContractConfig['name'] }) => | { url: RequestInfo; init?: RequestInit | undefined } | Promise<{ url: RequestInfo; init?: RequestInit | undefined }> /** * Duration in milliseconds before request times out. * * @default 5_000 // 5s in ms */ timeoutDuration?: number | undefined } type FetchResult = Compute> /** Fetches and parses contract ABIs from network resource with `fetch`. */ export function fetch(config: FetchConfig): FetchResult { const { cacheDuration = 1_800_000, contracts: contractConfigs, getCacheKey = ({ contract }) => JSON.stringify(contract), name = 'Fetch', parse = ({ response }) => response.json(), request, timeoutDuration = 5_000, } = config return { async contracts() { const cacheDir = getCacheDir() await mkdir(cacheDir, { recursive: true }) const timestamp = Date.now() + cacheDuration const contracts = [] for (const contract of contractConfigs) { const cacheKey = getCacheKey({ contract }) const cacheFilePath = join(cacheDir, `${cacheKey}.json`) const cachedFile = JSON.parse( await readFile(cacheFilePath, 'utf8').catch(() => 'null'), ) let abi: Abi | undefined if (cachedFile?.timestamp > Date.now()) abi = cachedFile.abi else { const controller = new globalThis.AbortController() const timeout = setTimeout(() => controller.abort(), timeoutDuration) try { const { url, init } = await request(contract) const response = await globalThis.fetch(url, { ...init, signal: controller.signal, }) clearTimeout(timeout) abi = await parse({ response }) await writeFile( cacheFilePath, `${JSON.stringify({ abi, timestamp }, undefined, 2)}\n`, ) } catch (error) { clearTimeout(timeout) try { // Attempt to read from cache if fetch fails. abi = JSON.parse(await readFile(cacheFilePath, 'utf8')).abi } catch {} if (!abi) throw error } } if (!abi) throw Error('Failed to fetch ABI for contract.') contracts.push({ abi, address: contract.address, name: contract.name }) } return contracts }, name, } } export function getCacheDir() { return join(homedir(), '.wagmi-cli/plugins/fetch/cache') } ================================================ FILE: packages/cli/src/plugins/foundry.test.ts ================================================ import fs from 'node:fs/promises' import fixtures from 'fixturez' import { dirname, resolve } from 'pathe' import { afterEach, expect, test, vi } from 'vitest' import { foundry } from './foundry.js' const f = fixtures(__dirname) afterEach(() => { vi.restoreAllMocks() }) test('forge not installed', async () => { const dir = f.temp() await expect( foundry({ project: dir, forge: { path: '/path/to/forge', }, }).validate?.(), ).rejects.toThrowErrorMatchingInlineSnapshot(` [Error: forge must be installed to use Foundry plugin. To install, follow the instructions at https://book.getfoundry.sh/getting-started/installation] `) }) test('project does not exist', async () => { const dir = f.temp() const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) try { await foundry({ project: '../path/to/project' }).validate?.() } catch (error) { expect( (error as Error).message.replace(dirname(dir), '..'), ).toMatchInlineSnapshot('"Foundry project ../path/to/project not found."') } }) test('validates without project', async () => { const dir = resolve(__dirname, '__fixtures__/foundry/') const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await expect(foundry().validate?.()).resolves.toBeUndefined() }) test('contracts', async () => { await expect( foundry({ project: resolve(__dirname, '__fixtures__/foundry/'), exclude: ['Foo.sol/**'], }).contracts?.(), ).resolves.toMatchInlineSnapshot(` [ { "abi": [ { "inputs": [], "name": "increment", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "number", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "newNumber", "type": "uint256", }, ], "name": "setNumber", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "address": undefined, "name": "Counter", }, ] `) }) test('contracts without project', async () => { const dir = resolve(__dirname, '__fixtures__/foundry/') const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await expect( foundry({ exclude: ['Foo.sol/**'], }).contracts?.(), ).resolves.toMatchInlineSnapshot(` [ { "abi": [ { "inputs": [], "name": "increment", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "number", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "newNumber", "type": "uint256", }, ], "name": "setNumber", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "address": undefined, "name": "Counter", }, ] `) }) test('broadcast deployments', async () => { const dir = f.temp() const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) const broadcastDir = resolve(dir, 'broadcast') const scriptDir = resolve(broadcastDir, 'Deploy.s.sol') const chainDir = resolve(scriptDir, '1') await fs.mkdir(chainDir, { recursive: true }) const broadcastContent = { transactions: [ { transactionType: 'CREATE', contractName: 'Counter', contractAddress: '0x1234567890123456789012345678901234567890', additionalContracts: [ { contractName: 'Library', contractAddress: '0x0987654321098765432109876543210987654321', }, ], }, ], } await fs.writeFile( resolve(chainDir, 'run-latest.json'), JSON.stringify(broadcastContent, null, 2), ) const artifactsDir = resolve(dir, 'out') await fs.mkdir(artifactsDir, { recursive: true }) const counterArtifact = { abi: [ { inputs: [], name: 'increment', outputs: [], stateMutability: 'nonpayable', type: 'function', }, ], } const libraryArtifact = { abi: [ { inputs: [], name: 'helper', outputs: [], stateMutability: 'pure', type: 'function', }, ], } await fs.writeFile( resolve(artifactsDir, 'Counter.json'), JSON.stringify(counterArtifact, null, 2), ) await fs.writeFile( resolve(artifactsDir, 'Library.json'), JSON.stringify(libraryArtifact, null, 2), ) await expect( foundry({ includeBroadcasts: true, }).contracts?.(), ).resolves.toMatchInlineSnapshot(` [ { "abi": [ { "inputs": [], "name": "increment", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "address": { "1": "0x1234567890123456789012345678901234567890", }, "name": "Counter", }, { "abi": [ { "inputs": [], "name": "helper", "outputs": [], "stateMutability": "pure", "type": "function", }, ], "address": { "1": "0x0987654321098765432109876543210987654321", }, "name": "Library", }, ] `) }) test('broadcast deployments filters CALL transactions', async () => { const dir = f.temp() const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) const broadcastDir = resolve(dir, 'broadcast') const scriptDir = resolve(broadcastDir, 'Deploy.s.sol') const chainDir = resolve(scriptDir, '1') await fs.mkdir(chainDir, { recursive: true }) const broadcastContent = { transactions: [ { transactionType: 'CREATE', contractName: 'Counter', contractAddress: '0x1234567890123456789012345678901234567890', additionalContracts: [], }, { transactionType: 'CALL', contractName: 'CalledContract', contractAddress: '0xCCCC000000000000000000000000000000000000', additionalContracts: [], }, { transactionType: 'CREATE2', contractName: 'Factory', contractAddress: '0xFFFF000000000000000000000000000000000000', additionalContracts: [], }, ], } await fs.writeFile( resolve(chainDir, 'run-latest.json'), JSON.stringify(broadcastContent, null, 2), ) const artifactsDir = resolve(dir, 'out') await fs.mkdir(artifactsDir, { recursive: true }) const counterArtifact = { abi: [ { inputs: [], name: 'increment', outputs: [], stateMutability: 'nonpayable', type: 'function', }, ], } const factoryArtifact = { abi: [ { inputs: [], name: 'deploy', outputs: [], stateMutability: 'nonpayable', type: 'function', }, ], } await fs.writeFile( resolve(artifactsDir, 'Counter.json'), JSON.stringify(counterArtifact, null, 2), ) await fs.writeFile( resolve(artifactsDir, 'Factory.json'), JSON.stringify(factoryArtifact, null, 2), ) const result = await foundry({ includeBroadcasts: true, }).contracts?.() const counter = result?.find((c) => c.name === 'Counter') expect(counter?.address).toEqual({ '1': '0x1234567890123456789012345678901234567890', }) const calledContract = result?.find((c) => c.name === 'CalledContract') expect(calledContract).toBeUndefined() const factory = result?.find((c) => c.name === 'Factory') expect(factory?.address).toEqual({ '1': '0xFFFF000000000000000000000000000000000000', }) }) test('watch callbacks use broadcast deployments', async () => { const dir = f.temp() const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) const broadcastDir = resolve(dir, 'broadcast') const scriptDir = resolve(broadcastDir, 'Deploy.s.sol') const chainDir = resolve(scriptDir, '1') await fs.mkdir(chainDir, { recursive: true }) const broadcastContent = { transactions: [ { transactionType: 'CREATE', contractName: 'Counter', contractAddress: '0x1234567890123456789012345678901234567890', additionalContracts: [], }, ], } await fs.writeFile( resolve(chainDir, 'run-latest.json'), JSON.stringify(broadcastContent, null, 2), ) const artifactsDir = resolve(dir, 'out') await fs.mkdir(artifactsDir, { recursive: true }) const counterArtifact = { abi: [ { inputs: [], name: 'increment', outputs: [], stateMutability: 'nonpayable', type: 'function', }, ], } await fs.writeFile( resolve(artifactsDir, 'Counter.json'), JSON.stringify(counterArtifact, null, 2), ) const plugin = foundry({ includeBroadcasts: true, }) await plugin.contracts?.() const artifactPath = resolve(artifactsDir, 'Counter.json') const contract = await plugin.watch.onChange?.(artifactPath) expect(contract).toMatchObject({ name: 'Counter', address: { '1': '0x1234567890123456789012345678901234567890', }, }) }) ================================================ FILE: packages/cli/src/plugins/foundry.ts ================================================ import { execSync, spawn, spawnSync } from 'node:child_process' import { existsSync } from 'node:fs' import { readFile } from 'node:fs/promises' import dedent from 'dedent' import { fdir } from 'fdir' import { basename, extname, join, resolve } from 'pathe' import pc from 'picocolors' import { z } from 'zod' import type { ContractConfig, Plugin } from '../config.js' import * as logger from '../logger.js' import type { Compute, RequiredBy } from '../types.js' export const foundryDefaultExcludes = [ 'Base.sol/**', 'Common.sol/**', 'Components.sol/**', 'IERC165.sol/**', 'IERC20.sol/**', 'IERC721.sol/**', 'IMulticall2.sol/**', 'MockERC20.sol/**', 'MockERC721.sol/**', 'Script.sol/**', 'StdAssertions.sol/**', 'StdChains.sol/**', 'StdCheats.sol/**', 'StdError.sol/**', 'StdInvariant.sol/**', 'StdJson.sol/**', 'StdMath.sol/**', 'StdStorage.sol/**', 'StdStyle.sol/**', 'StdToml.sol/**', 'StdUtils.sol/**', 'Test.sol/**', 'Vm.sol/**', 'build-info/**', 'console.sol/**', 'console2.sol/**', 'safeconsole.sol/**', '**.s.sol/*.json', '**.t.sol/*.json', ] export type FoundryConfig = { /** * Project's artifacts directory. * * Same as your project's `--out` (`-o`) option. * * @default foundry.config#out | 'out' */ artifacts?: string | undefined /** * Set contracts in `run-latest.json` files in the `broadcast/` directory as deployments. * * @dev broadcast deployments can be overridden by including the contract in the deployments mapping. * * @default false */ includeBroadcasts?: boolean | undefined /** Mapping of addresses to attach to artifacts. */ deployments?: { [key: string]: ContractConfig['address'] } | undefined /** Artifact files to exclude. */ exclude?: string[] | undefined /** [Forge](https://book.getfoundry.sh/forge) configuration */ forge?: | { /** * Remove build artifacts and cache directories on start up. * * @default false */ clean?: boolean | undefined /** * Build Foundry project before fetching artifacts. * * @default true */ build?: boolean | undefined /** * Path to `forge` executable command * * @default "forge" */ path?: string | undefined /** * Rebuild every time a watched file or directory is changed. * * @default true */ rebuild?: boolean | undefined } | undefined /** Artifact files to include. */ include?: string[] | undefined /** Optional prefix to prepend to artifact names. */ namePrefix?: string | undefined /** Path to foundry project. */ project?: string | undefined } type FoundryResult = Compute< RequiredBy > const FoundryConfigSchema = z.object({ out: z.string().default('out'), src: z.string().default('src'), }) /** Resolves ABIs from [Foundry](https://github.com/foundry-rs/foundry) project. */ export function foundry(config: FoundryConfig = {}): FoundryResult { const { artifacts, includeBroadcasts = false, deployments = {}, exclude = foundryDefaultExcludes, forge: { clean = false, build = true, path: forgeExecutable = 'forge', rebuild = true, } = {}, include = ['*.json'], namePrefix = '', } = config let allDeployments: { [key: string]: ContractConfig['address'] } = deployments function getContractName(artifactPath: string, usePrefix = true) { const filename = basename(artifactPath) const extension = extname(artifactPath) return `${usePrefix ? namePrefix : ''}${filename.replace(extension, '')}` } async function getContract( artifactPath: string, contractDeployments: { [key: string]: ContractConfig['address'] } = allDeployments, ) { const artifact = await JSON.parse(await readFile(artifactPath, 'utf8')) return { abi: artifact.abi, address: contractDeployments[getContractName(artifactPath, false)], name: getContractName(artifactPath), } } function getArtifactPaths(artifactsDirectory: string) { const crawler = new fdir().withBasePath().globWithOptions( include.map((x) => `${artifactsDirectory}/**/${x}`), { dot: true, ignore: exclude.map((x) => `${artifactsDirectory}/**/${x}`), }, ) return crawler.crawl(artifactsDirectory).withPromise() } async function getBroadcastDeployments(broadcastDirectory: string) { const deployments: { [key: string]: Record } = {} const crawler = new fdir() .withBasePath() .glob('**/run-latest.json') .filter((path) => path.includes('/broadcast/')) const broadcastFiles = await crawler.crawl(broadcastDirectory).withPromise() for (const broadcastFile of broadcastFiles) { try { const broadcast = JSON.parse(await readFile(broadcastFile, 'utf8')) // Extract chainId from path: broadcast/.../[chainId]/run-latest.json const pathParts = broadcastFile.split('/') const chainIdPart = pathParts[pathParts.length - 2] if (!chainIdPart) continue const chainId = Number.parseInt(chainIdPart, 10) if (Number.isNaN(chainId)) continue const transactions = broadcast.transactions || [] for (const tx of transactions) { if ( tx.transactionType !== 'CREATE' && tx.transactionType !== 'CREATE2' ) continue if (tx.contractName && tx.contractAddress) { const contractName = tx.contractName const contractAddress = tx.contractAddress if (!deployments[contractName]) { deployments[contractName] = {} } deployments[contractName][chainId] = contractAddress } const additionalContracts = tx.additionalContracts || [] for (const additional of additionalContracts) { if (additional.contractName && additional.contractAddress) { const contractName = additional.contractName const contractAddress = additional.contractAddress if (!deployments[contractName]) { deployments[contractName] = {} } deployments[contractName][chainId] = contractAddress } } } } catch (error) { logger.warn( `Failed to parse broadcast file ${broadcastFile}: ${(error as Error).message}`, ) } } return deployments } const project = resolve(process.cwd(), config.project ?? '') let foundryConfig: z.infer = { out: 'out', src: 'src', } try { const result = spawnSync( forgeExecutable, ['config', '--json', '--root', project], { encoding: 'utf-8', shell: true, }, ) if (result.error) throw result.error if (result.status !== 0) throw new Error(`Failed with code ${result.status}`) if (result.signal) throw new Error('Process terminated by signal') foundryConfig = FoundryConfigSchema.parse(JSON.parse(result.stdout)) } catch { } finally { foundryConfig = { ...foundryConfig, out: artifacts ?? foundryConfig.out, } } const artifactsDirectory = join(project, foundryConfig.out) return { async contracts() { if (clean) execSync(`${forgeExecutable} clean --root ${project}`, { encoding: 'utf-8', stdio: 'pipe', }) if (build) execSync(`${forgeExecutable} build --root ${project}`, { encoding: 'utf-8', stdio: 'pipe', }) if (!existsSync(artifactsDirectory)) throw new Error('Artifacts not found.') if (includeBroadcasts) { const broadcastDeployments = Object.fromEntries( Object.entries(await getBroadcastDeployments(project)).map( ([contractName, chainAddresses]) => [ contractName, chainAddresses as ContractConfig['address'], ], ), ) allDeployments = { ...broadcastDeployments, ...deployments } } const artifactPaths = await getArtifactPaths(artifactsDirectory) const contracts = [] for (const artifactPath of artifactPaths) { const contract = await getContract(artifactPath, allDeployments) if (!contract.abi?.length) continue contracts.push(contract) } return contracts }, name: 'Foundry', async validate() { // Check that project directory exists if (!existsSync(project)) throw new Error(`Foundry project ${pc.gray(config.project)} not found.`) // Ensure forge is installed if (clean || build || rebuild) try { execSync(`${forgeExecutable} --version`, { encoding: 'utf-8', stdio: 'pipe', }) } catch (_error) { throw new Error(dedent` forge must be installed to use Foundry plugin. To install, follow the instructions at https://book.getfoundry.sh/getting-started/installation `) } }, watch: { command: rebuild ? async () => { logger.log( `${pc.magenta('Foundry')} Watching project at ${pc.gray( project, )}`, ) const subprocess = spawn(forgeExecutable, [ 'build', '--watch', '--root', project, ]) subprocess.stdout?.on('data', (data) => { process.stdout.write(`${pc.magenta('Foundry')} ${data}`) }) process.once('SIGINT', shutdown) process.once('SIGTERM', shutdown) function shutdown() { subprocess?.kill() } } : undefined, paths: [ ...include.map((x) => `${artifactsDirectory}/**/${x}`), ...exclude.map((x) => `!${artifactsDirectory}/**/${x}`), ], async onAdd(path) { return getContract(path) }, async onChange(path) { return getContract(path) }, async onRemove(path) { return getContractName(path) }, }, } } ================================================ FILE: packages/cli/src/plugins/hardhat.test.ts ================================================ import fixtures from 'fixturez' import { dirname, resolve } from 'pathe' import { afterEach, expect, test, vi } from 'vitest' import { hardhat } from './hardhat.js' const f = fixtures(__dirname) afterEach(() => { vi.restoreAllMocks() }) test('validate', async () => { const temp = f.temp() await expect( hardhat({ project: temp }).validate?.(), ).rejects.toThrowErrorMatchingInlineSnapshot( '[Error: hardhat must be installed to use Hardhat plugin.]', ) }) test('project does not exist', async () => { const dir = f.temp() const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) try { await hardhat({ project: '../path/to/project' }).validate?.() } catch (error) { expect( (error as Error).message.replace(dirname(dir), '..'), ).toMatchInlineSnapshot('"Hardhat project ../path/to/project not found."') } }) test('contracts', async () => { await expect( hardhat({ project: resolve(__dirname, '__fixtures__/hardhat/'), exclude: ['Foo.sol/**'], }).contracts?.(), ).resolves.toMatchInlineSnapshot(` [ { "abi": [ { "inputs": [], "name": "increment", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, { "inputs": [], "name": "number", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256", }, ], "stateMutability": "view", "type": "function", }, { "inputs": [ { "internalType": "uint256", "name": "newNumber", "type": "uint256", }, ], "name": "setNumber", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "address": undefined, "name": "Counter", }, ] `) }, 10_000) ================================================ FILE: packages/cli/src/plugins/hardhat.ts ================================================ import { execSync, spawn } from 'node:child_process' import { existsSync } from 'node:fs' import { readFile } from 'node:fs/promises' import { fdir } from 'fdir' import { basename, extname, join, resolve } from 'pathe' import pc from 'picocolors' import type { ContractConfig, Plugin } from '../config.js' import * as logger from '../logger.js' import type { Compute, RequiredBy } from '../types.js' import { getIsPackageInstalled, getPackageManager } from '../utils/packages.js' export const hardhatDefaultExcludes = ['build-info/**', '*.dbg.json'] export type HardhatConfig = { /** * Project's artifacts directory. * * Same as your project's `artifacts` [path configuration](https://hardhat.org/hardhat-runner/docs/config#path-configuration) option. * * @default 'artifacts/' */ artifacts?: string | undefined /** Mapping of addresses to attach to artifacts. */ deployments?: { [key: string]: ContractConfig['address'] } | undefined /** Artifact files to exclude. */ exclude?: string[] | undefined /** Commands to run */ commands?: | { /** * Remove build artifacts and cache directories on start up. * * @default `${packageManger} hardhat clean` */ clean?: string | boolean | undefined /** * Build Hardhat project before fetching artifacts. * * @default `${packageManger} hardhat compile` */ build?: string | boolean | undefined /** * Command to run when watched file or directory is changed. * * @default `${packageManger} hardhat compile` */ rebuild?: string | boolean | undefined } | undefined /** Artifact files to include. */ include?: string[] | undefined /** Optional prefix to prepend to artifact names. */ namePrefix?: string | undefined /** Path to Hardhat project. */ project: string /** * Project's artifacts directory. * * Same as your project's `sources` [path configuration](https://hardhat.org/hardhat-runner/docs/config#path-configuration) option. * * @default 'contracts/' */ sources?: string | undefined } type HardhatResult = Compute< RequiredBy > /** Resolves ABIs from [Hardhat](https://github.com/NomicFoundation/hardhat) project. */ export function hardhat(config: HardhatConfig): HardhatResult { const { artifacts = 'artifacts', deployments = {}, exclude = hardhatDefaultExcludes, commands = {}, include = ['*.json'], namePrefix = '', sources = 'contracts', } = config function getContractName(artifact: { contractName: string }) { return `${namePrefix}${artifact.contractName}` } async function getContract(artifactPath: string) { const artifact = await JSON.parse(await readFile(artifactPath, 'utf8')) return { abi: artifact.abi, address: deployments[artifact.contractName], name: getContractName(artifact), } } function getArtifactPaths(artifactsDirectory: string) { const crawler = new fdir().withBasePath().globWithOptions( include.map((x) => `${artifactsDirectory}/**/${x}`), { dot: true, ignore: exclude.map((x) => `${artifactsDirectory}/**/${x}`), }, ) return crawler.crawl(artifactsDirectory).withPromise() } const project = resolve(process.cwd(), config.project) const artifactsDirectory = join(project, artifacts) const sourcesDirectory = join(project, sources) const { build = true, clean = false, rebuild = true } = commands return { async contracts() { if (clean) { const packageManager = await getPackageManager(true) const [command, ...options] = ( typeof clean === 'boolean' ? `${packageManager} hardhat clean` : clean ).split(' ') execSync(`${command!} ${options.join(' ')}`, { cwd: project, encoding: 'utf-8', stdio: 'pipe', }) } if (build) { const packageManager = await getPackageManager(true) const [command, ...options] = ( typeof build === 'boolean' ? `${packageManager} hardhat compile` : build ).split(' ') execSync(`${command!} ${options.join(' ')}`, { cwd: project, encoding: 'utf-8', stdio: 'pipe', }) } if (!existsSync(artifactsDirectory)) throw new Error('Artifacts not found.') const artifactPaths = await getArtifactPaths(artifactsDirectory) const contracts = [] for (const artifactPath of artifactPaths) { const contract = await getContract(artifactPath) if (!contract.abi?.length) continue contracts.push(contract) } return contracts }, name: 'Hardhat', async validate() { // Check that project directory exists if (!existsSync(project)) throw new Error(`Hardhat project ${pc.gray(project)} not found.`) // Check that `hardhat` is installed const packageName = 'hardhat' const isPackageInstalled = await getIsPackageInstalled({ packageName, cwd: project, }) if (isPackageInstalled) return throw new Error(`${packageName} must be installed to use Hardhat plugin.`) }, watch: { command: rebuild ? async () => { logger.log( `${pc.blue('Hardhat')} Watching project at ${pc.gray(project)}`, ) const [command, ...options] = ( typeof rebuild === 'boolean' ? `${await getPackageManager(true)} hardhat compile` : rebuild ).split(' ') const { watch } = await import('chokidar') const watcher = watch(sourcesDirectory, { atomic: true, awaitWriteFinish: true, ignoreInitial: true, persistent: true, }) watcher.on('all', async (event, path) => { if (event !== 'change' && event !== 'add' && event !== 'unlink') return logger.log( `${pc.blue('Hardhat')} Detected ${event} at ${basename(path)}`, ) const subprocess = spawn(command!, options, { cwd: project, }) subprocess.stdout?.on('data', (data) => { process.stdout.write(`${pc.blue('Hardhat')} ${data}`) }) }) process.once('SIGINT', shutdown) process.once('SIGTERM', shutdown) async function shutdown() { await watcher.close() } } : undefined, paths: [ artifactsDirectory, ...include.map((x) => `${artifactsDirectory}/**/${x}`), ...exclude.map((x) => `!${artifactsDirectory}/**/${x}`), ], async onAdd(path) { return getContract(path) }, async onChange(path) { return getContract(path) }, async onRemove(path) { const filename = basename(path) const extension = extname(path) // Since we can't use `getContractName`, guess from path const removedContractName = `${namePrefix}${filename.replace( extension, '', )}` const artifactPaths = await getArtifactPaths(artifactsDirectory) for (const artifactPath of artifactPaths) { const contract = await getContract(artifactPath) // If contract with same name exists, don't remove if (contract.name === removedContractName) return } return removedContractName }, }, } } ================================================ FILE: packages/cli/src/plugins/react.test.ts ================================================ import { erc20Abi } from 'viem' import { expect, test } from 'vitest' import { react } from './react.js' test('default', async () => { const result = await react().run?.({ contracts: [ { name: 'erc20', abi: erc20Abi, content: '', meta: { abiName: 'erc20Abi', }, }, ], isTypeScript: true, outputs: [], }) expect(result?.imports).toMatchInlineSnapshot(` "import { createUseReadContract, createUseWriteContract, createUseSimulateContract, createUseWatchContractEvent } from 'wagmi/codegen' " `) expect(result?.content).toMatchInlineSnapshot(` "/** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const useReadErc20 = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi }) /** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"allowance"\` */ export const useReadErc20Allowance = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, functionName: 'allowance' }) /** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"balanceOf"\` */ export const useReadErc20BalanceOf = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, functionName: 'balanceOf' }) /** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"decimals"\` */ export const useReadErc20Decimals = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, functionName: 'decimals' }) /** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"name"\` */ export const useReadErc20Name = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, functionName: 'name' }) /** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"symbol"\` */ export const useReadErc20Symbol = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, functionName: 'symbol' }) /** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"totalSupply"\` */ export const useReadErc20TotalSupply = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, functionName: 'totalSupply' }) /** * Wraps __{@link useWriteContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const useWriteErc20 = /*#__PURE__*/ createUseWriteContract({ abi: erc20Abi }) /** * Wraps __{@link useWriteContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"approve"\` */ export const useWriteErc20Approve = /*#__PURE__*/ createUseWriteContract({ abi: erc20Abi, functionName: 'approve' }) /** * Wraps __{@link useWriteContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transfer"\` */ export const useWriteErc20Transfer = /*#__PURE__*/ createUseWriteContract({ abi: erc20Abi, functionName: 'transfer' }) /** * Wraps __{@link useWriteContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transferFrom"\` */ export const useWriteErc20TransferFrom = /*#__PURE__*/ createUseWriteContract({ abi: erc20Abi, functionName: 'transferFrom' }) /** * Wraps __{@link useSimulateContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const useSimulateErc20 = /*#__PURE__*/ createUseSimulateContract({ abi: erc20Abi }) /** * Wraps __{@link useSimulateContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"approve"\` */ export const useSimulateErc20Approve = /*#__PURE__*/ createUseSimulateContract({ abi: erc20Abi, functionName: 'approve' }) /** * Wraps __{@link useSimulateContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transfer"\` */ export const useSimulateErc20Transfer = /*#__PURE__*/ createUseSimulateContract({ abi: erc20Abi, functionName: 'transfer' }) /** * Wraps __{@link useSimulateContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transferFrom"\` */ export const useSimulateErc20TransferFrom = /*#__PURE__*/ createUseSimulateContract({ abi: erc20Abi, functionName: 'transferFrom' }) /** * Wraps __{@link useWatchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ */ export const useWatchErc20Event = /*#__PURE__*/ createUseWatchContractEvent({ abi: erc20Abi }) /** * Wraps __{@link useWatchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ and \`eventName\` set to \`"Approval"\` */ export const useWatchErc20ApprovalEvent = /*#__PURE__*/ createUseWatchContractEvent({ abi: erc20Abi, eventName: 'Approval' }) /** * Wraps __{@link useWatchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ and \`eventName\` set to \`"Transfer"\` */ export const useWatchErc20TransferEvent = /*#__PURE__*/ createUseWatchContractEvent({ abi: erc20Abi, eventName: 'Transfer' })" `) }) test('address', async () => { const result = await react().run?.({ contracts: [ { name: 'erc20', abi: erc20Abi, content: '', meta: { abiName: 'erc20Abi', addressName: 'erc20Address', }, }, ], isTypeScript: true, outputs: [], }) expect(result?.content).toMatchInlineSnapshot(` "/** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const useReadErc20 = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, address: erc20Address }) /** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"allowance"\` */ export const useReadErc20Allowance = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'allowance' }) /** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"balanceOf"\` */ export const useReadErc20BalanceOf = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'balanceOf' }) /** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"decimals"\` */ export const useReadErc20Decimals = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'decimals' }) /** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"name"\` */ export const useReadErc20Name = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'name' }) /** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"symbol"\` */ export const useReadErc20Symbol = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'symbol' }) /** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"totalSupply"\` */ export const useReadErc20TotalSupply = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'totalSupply' }) /** * Wraps __{@link useWriteContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const useWriteErc20 = /*#__PURE__*/ createUseWriteContract({ abi: erc20Abi, address: erc20Address }) /** * Wraps __{@link useWriteContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"approve"\` */ export const useWriteErc20Approve = /*#__PURE__*/ createUseWriteContract({ abi: erc20Abi, address: erc20Address, functionName: 'approve' }) /** * Wraps __{@link useWriteContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transfer"\` */ export const useWriteErc20Transfer = /*#__PURE__*/ createUseWriteContract({ abi: erc20Abi, address: erc20Address, functionName: 'transfer' }) /** * Wraps __{@link useWriteContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transferFrom"\` */ export const useWriteErc20TransferFrom = /*#__PURE__*/ createUseWriteContract({ abi: erc20Abi, address: erc20Address, functionName: 'transferFrom' }) /** * Wraps __{@link useSimulateContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const useSimulateErc20 = /*#__PURE__*/ createUseSimulateContract({ abi: erc20Abi, address: erc20Address }) /** * Wraps __{@link useSimulateContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"approve"\` */ export const useSimulateErc20Approve = /*#__PURE__*/ createUseSimulateContract({ abi: erc20Abi, address: erc20Address, functionName: 'approve' }) /** * Wraps __{@link useSimulateContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transfer"\` */ export const useSimulateErc20Transfer = /*#__PURE__*/ createUseSimulateContract({ abi: erc20Abi, address: erc20Address, functionName: 'transfer' }) /** * Wraps __{@link useSimulateContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transferFrom"\` */ export const useSimulateErc20TransferFrom = /*#__PURE__*/ createUseSimulateContract({ abi: erc20Abi, address: erc20Address, functionName: 'transferFrom' }) /** * Wraps __{@link useWatchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ */ export const useWatchErc20Event = /*#__PURE__*/ createUseWatchContractEvent({ abi: erc20Abi, address: erc20Address }) /** * Wraps __{@link useWatchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ and \`eventName\` set to \`"Approval"\` */ export const useWatchErc20ApprovalEvent = /*#__PURE__*/ createUseWatchContractEvent({ abi: erc20Abi, address: erc20Address, eventName: 'Approval' }) /** * Wraps __{@link useWatchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ and \`eventName\` set to \`"Transfer"\` */ export const useWatchErc20TransferEvent = /*#__PURE__*/ createUseWatchContractEvent({ abi: erc20Abi, address: erc20Address, eventName: 'Transfer' })" `) }) test('legacy hook names', async () => { const result = await react({ getHookName: 'legacy' }).run?.({ contracts: [ { name: 'erc20', abi: erc20Abi, content: '', meta: { abiName: 'erc20Abi', addressName: 'erc20Address', }, }, ], isTypeScript: true, outputs: [], }) expect(result?.content).toMatchInlineSnapshot(` "/** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const useErc20Read = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, address: erc20Address }) /** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"allowance"\` */ export const useErc20Allowance = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'allowance' }) /** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"balanceOf"\` */ export const useErc20BalanceOf = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'balanceOf' }) /** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"decimals"\` */ export const useErc20Decimals = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'decimals' }) /** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"name"\` */ export const useErc20Name = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'name' }) /** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"symbol"\` */ export const useErc20Symbol = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'symbol' }) /** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"totalSupply"\` */ export const useErc20TotalSupply = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi, address: erc20Address, functionName: 'totalSupply' }) /** * Wraps __{@link useWriteContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const useErc20Write = /*#__PURE__*/ createUseWriteContract({ abi: erc20Abi, address: erc20Address }) /** * Wraps __{@link useWriteContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"approve"\` */ export const useErc20Approve = /*#__PURE__*/ createUseWriteContract({ abi: erc20Abi, address: erc20Address, functionName: 'approve' }) /** * Wraps __{@link useWriteContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transfer"\` */ export const useErc20Transfer = /*#__PURE__*/ createUseWriteContract({ abi: erc20Abi, address: erc20Address, functionName: 'transfer' }) /** * Wraps __{@link useWriteContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transferFrom"\` */ export const useErc20TransferFrom = /*#__PURE__*/ createUseWriteContract({ abi: erc20Abi, address: erc20Address, functionName: 'transferFrom' }) /** * Wraps __{@link useSimulateContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const usePrepareErc20Write = /*#__PURE__*/ createUseSimulateContract({ abi: erc20Abi, address: erc20Address }) /** * Wraps __{@link useSimulateContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"approve"\` */ export const usePrepareErc20Approve = /*#__PURE__*/ createUseSimulateContract({ abi: erc20Abi, address: erc20Address, functionName: 'approve' }) /** * Wraps __{@link useSimulateContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transfer"\` */ export const usePrepareErc20Transfer = /*#__PURE__*/ createUseSimulateContract({ abi: erc20Abi, address: erc20Address, functionName: 'transfer' }) /** * Wraps __{@link useSimulateContract}__ with \`abi\` set to __{@link erc20Abi}__ and \`functionName\` set to \`"transferFrom"\` */ export const usePrepareErc20TransferFrom = /*#__PURE__*/ createUseSimulateContract({ abi: erc20Abi, address: erc20Address, functionName: 'transferFrom' }) /** * Wraps __{@link useWatchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ */ export const useErc20Event = /*#__PURE__*/ createUseWatchContractEvent({ abi: erc20Abi, address: erc20Address }) /** * Wraps __{@link useWatchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ and \`eventName\` set to \`"Approval"\` */ export const useErc20ApprovalEvent = /*#__PURE__*/ createUseWatchContractEvent({ abi: erc20Abi, address: erc20Address, eventName: 'Approval' }) /** * Wraps __{@link useWatchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ and \`eventName\` set to \`"Transfer"\` */ export const useErc20TransferEvent = /*#__PURE__*/ createUseWatchContractEvent({ abi: erc20Abi, address: erc20Address, eventName: 'Transfer' })" `) }) test('abi item hooks disabled', async () => { const result = await react({ abiItemHooks: false }).run?.({ contracts: [ { name: 'erc20', abi: erc20Abi, content: '', meta: { abiName: 'erc20Abi', }, }, ], isTypeScript: true, outputs: [], }) expect(result?.imports).toMatchInlineSnapshot(` "import { createUseReadContract, createUseWriteContract, createUseSimulateContract, createUseWatchContractEvent } from 'wagmi/codegen' " `) expect(result?.content).toMatchInlineSnapshot(` "/** * Wraps __{@link useReadContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const useReadErc20 = /*#__PURE__*/ createUseReadContract({ abi: erc20Abi }) /** * Wraps __{@link useWriteContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const useWriteErc20 = /*#__PURE__*/ createUseWriteContract({ abi: erc20Abi }) /** * Wraps __{@link useSimulateContract}__ with \`abi\` set to __{@link erc20Abi}__ */ export const useSimulateErc20 = /*#__PURE__*/ createUseSimulateContract({ abi: erc20Abi }) /** * Wraps __{@link useWatchContractEvent}__ with \`abi\` set to __{@link erc20Abi}__ */ export const useWatchErc20Event = /*#__PURE__*/ createUseWatchContractEvent({ abi: erc20Abi })" `) }) ================================================ FILE: packages/cli/src/plugins/react.ts ================================================ import { pascalCase } from 'change-case' import type { Contract, Plugin } from '../config.js' import type { Compute, RequiredBy } from '../types.js' import { getAddressDocString } from '../utils/getAddressDocString.js' export type ReactConfig = Compute< { abiItemHooks?: boolean | undefined } & ( | { /** @deprecated */ getHookName: 'legacy' } | { getHookName?: (options: { contractName: string itemName?: string | undefined type: 'read' | 'simulate' | 'watch' | 'write' }) => `use${string}` } ) > type ReactResult = Compute> export function react(config: ReactConfig = {}): ReactResult { return { name: 'React', async run({ contracts }) { const imports = new Set([]) const content: string[] = [] const pure = '/*#__PURE__*/' const hookNames = new Set() const isAbiItemHooksEnabled = config.abiItemHooks ?? true for (const contract of contracts) { let hasReadFunction = false let hasWriteFunction = false let hasEvent = false const readItems = [] const writeItems = [] const eventItems = [] for (const item of contract.abi) { if (item.type === 'function') if ( item.stateMutability === 'view' || item.stateMutability === 'pure' ) { hasReadFunction = true readItems.push(item) } else { hasWriteFunction = true writeItems.push(item) } else if (item.type === 'event') { hasEvent = true eventItems.push(item) } } let innerContent: string if (contract.meta.addressName) innerContent = `abi: ${contract.meta.abiName}, address: ${contract.meta.addressName}` else innerContent = `abi: ${contract.meta.abiName}` if (hasReadFunction) { const hookName = getHookName(config, hookNames, 'read', contract.name) const docString = genDocString('useReadContract', contract) const functionName = 'createUseReadContract' imports.add(functionName) content.push( `${docString} export const ${hookName} = ${pure} ${functionName}({ ${innerContent} })`, ) if (isAbiItemHooksEnabled) { const names = new Set() for (const item of readItems) { if (item.type !== 'function') continue if ( item.stateMutability !== 'pure' && item.stateMutability !== 'view' ) continue // Skip overrides since they are captured by same hook if (names.has(item.name)) continue names.add(item.name) const hookName = getHookName( config, hookNames, 'read', contract.name, item.name, ) const docString = genDocString('useReadContract', contract, { name: 'functionName', value: item.name, }) content.push( `${docString} export const ${hookName} = ${pure} ${functionName}({ ${innerContent}, functionName: '${item.name}' })`, ) } } } if (hasWriteFunction) { { const hookName = getHookName( config, hookNames, 'write', contract.name, ) const docString = genDocString('useWriteContract', contract) const functionName = 'createUseWriteContract' imports.add(functionName) content.push( `${docString} export const ${hookName} = ${pure} ${functionName}({ ${innerContent} })`, ) if (isAbiItemHooksEnabled) { const names = new Set() for (const item of writeItems) { if (item.type !== 'function') continue if ( item.stateMutability !== 'nonpayable' && item.stateMutability !== 'payable' ) continue // Skip overrides since they are captured by same hook if (names.has(item.name)) continue names.add(item.name) const hookName = getHookName( config, hookNames, 'write', contract.name, item.name, ) const docString = genDocString('useWriteContract', contract, { name: 'functionName', value: item.name, }) content.push( `${docString} export const ${hookName} = ${pure} ${functionName}({ ${innerContent}, functionName: '${item.name}' })`, ) } } } { const hookName = getHookName( config, hookNames, 'simulate', contract.name, ) const docString = genDocString('useSimulateContract', contract) const functionName = 'createUseSimulateContract' imports.add(functionName) content.push( `${docString} export const ${hookName} = ${pure} ${functionName}({ ${innerContent} })`, ) if (isAbiItemHooksEnabled) { const names = new Set() for (const item of writeItems) { if (item.type !== 'function') continue if ( item.stateMutability !== 'nonpayable' && item.stateMutability !== 'payable' ) continue // Skip overrides since they are captured by same hook if (names.has(item.name)) continue names.add(item.name) const hookName = getHookName( config, hookNames, 'simulate', contract.name, item.name, ) const docString = genDocString( 'useSimulateContract', contract, { name: 'functionName', value: item.name, }, ) content.push( `${docString} export const ${hookName} = ${pure} ${functionName}({ ${innerContent}, functionName: '${item.name}' })`, ) } } } } if (hasEvent) { const hookName = getHookName( config, hookNames, 'watch', contract.name, ) const docString = genDocString('useWatchContractEvent', contract) const functionName = 'createUseWatchContractEvent' imports.add(functionName) content.push( `${docString} export const ${hookName} = ${pure} ${functionName}({ ${innerContent} })`, ) if (isAbiItemHooksEnabled) { const names = new Set() for (const item of eventItems) { if (item.type !== 'event') continue // Skip overrides since they are captured by same hook if (names.has(item.name)) continue names.add(item.name) const hookName = getHookName( config, hookNames, 'watch', contract.name, item.name, ) const docString = genDocString( 'useWatchContractEvent', contract, { name: 'eventName', value: item.name, }, ) content.push( `${docString} export const ${hookName} = ${pure} ${functionName}({ ${innerContent}, eventName: '${item.name}' })`, ) } } } } const importValues = [...imports.values()] return { imports: importValues.length ? `import { ${importValues.join(', ')} } from 'wagmi/codegen'\n` : '', content: content.join('\n\n'), } }, } } function genDocString( hookName: string, contract: Contract, item?: { name: string; value: string }, ) { let description = `Wraps __{@link ${hookName}}__ with \`abi\` set to __{@link ${contract.meta.abiName}}__` if (item) description += ` and \`${item.name}\` set to \`"${item.value}"\`` const docString = getAddressDocString({ address: contract.address }) if (docString) return `/** * ${description} * ${docString} */` return `/** * ${description} */` } function getHookName( config: ReactConfig, hookNames: Set, type: 'read' | 'simulate' | 'watch' | 'write', contractName: string, itemName?: string | undefined, ) { const ContractName = pascalCase(contractName) const ItemName = itemName ? pascalCase(itemName) : undefined let hookName: string if (typeof config.getHookName === 'function') hookName = config.getHookName({ type, contractName: ContractName, itemName: ItemName, }) else if (typeof config.getHookName === 'string') { switch (type) { case 'read': hookName = `use${ContractName}${ItemName ?? 'Read'}` break case 'simulate': hookName = `usePrepare${ContractName}${ItemName ?? 'Write'}` break case 'watch': hookName = `use${ContractName}${ItemName ?? ''}Event` break case 'write': hookName = `use${ContractName}${ItemName ?? 'Write'}` break } } else { hookName = `use${pascalCase(type)}${ContractName}${ItemName ?? ''}` if (type === 'watch') hookName = `${hookName}Event` } if (hookNames.has(hookName)) throw new Error( `Hook name "${hookName}" must be unique for contract "${contractName}". Try using \`getHookName\` to create a unique name.`, ) hookNames.add(hookName) return hookName } ================================================ FILE: packages/cli/src/plugins/sourcify.test.ts ================================================ import { HttpResponse, http } from 'msw' import { setupServer } from 'msw/node' import { afterAll, afterEach, beforeAll, expect, test } from 'vitest' import { depositAbi } from '../../test/constants.js' import { sourcify } from './sourcify.js' const baseUrl = 'https://sourcify.dev/server/v2/contract' const address = '0x00000000219ab540356cbb839cbe05303d7705fa' const chainId = 1 const multichainAddress = '0xC4c622862a8F548997699bE24EA4bc504e5cA865' const multichainIdGnosis = 100 const multichainIdPolygon = 137 const successJson = { abi: depositAbi, } const handlers = [ http.get(`${baseUrl}/${chainId}/${address}`, () => HttpResponse.json(successJson), ), http.get(`${baseUrl}/${multichainIdGnosis}/${address}`, () => HttpResponse.json({}, { status: 404 }), ), http.get(`${baseUrl}/${multichainIdGnosis}/${multichainAddress}`, () => HttpResponse.json(successJson), ), http.get(`${baseUrl}/${multichainIdPolygon}/${multichainAddress}`, () => HttpResponse.json(successJson), ), ] const server = setupServer(...handlers) beforeAll(() => server.listen()) afterEach(() => server.resetHandlers()) afterAll(() => server.close()) test('fetches ABI', async () => { await expect( sourcify({ chainId: chainId, contracts: [{ name: 'DepositContract', address }], }).contracts?.(), ).resolves.toMatchSnapshot() }) test('fetches ABI with multichain deployment', async () => { await expect( sourcify({ chainId: 100, contracts: [ { name: 'Community', address: { 100: multichainAddress, 137: multichainAddress }, }, ], }).contracts?.(), ).resolves.toMatchSnapshot() }) test('fails to fetch for unverified contract', async () => { await expect( sourcify({ chainId: 100, contracts: [{ name: 'DepositContract', address }], }).contracts?.(), ).rejects.toThrowErrorMatchingInlineSnapshot( '[Error: Contract not found in Sourcify repository.]', ) }) test('missing address for chainId', async () => { await expect( sourcify({ chainId: 1, // @ts-expect-error `chainId` and `keyof typeof contracts[number].address` mismatch contracts: [{ name: 'DepositContract', address: { 10: address } }], }).contracts?.(), ).rejects.toThrowErrorMatchingInlineSnapshot( `[Error: No address found for chainId "1". Make sure chainId "1" is set as an address.]`, ) }) ================================================ FILE: packages/cli/src/plugins/sourcify.ts ================================================ import { Abi as AbiSchema } from 'abitype/zod' import type { Address } from 'viem' import { z } from 'zod' import type { ContractConfig } from '../config.js' import { fromZodError } from '../errors.js' import type { Compute } from '../types.js' import { fetch } from './fetch.js' export type SourcifyConfig = { /** * Duration in milliseconds to cache ABIs. * * @default 1_800_000 // 30m in ms */ cacheDuration?: number | undefined /** * Chain id to use for fetching ABI. * * If `address` is an object, `chainId` is used to select the address. * * See https://docs.sourcify.dev/docs/chains for supported chains. */ chainId: (chainId extends ChainId ? chainId : never) | (ChainId & {}) /** * Contracts to fetch ABIs for. */ contracts: Compute, 'abi'>>[] } const SourcifyResponse = z.object({ abi: AbiSchema, }) /** Fetches contract ABIs from Sourcify. */ export function sourcify( config: SourcifyConfig, ) { const { cacheDuration, chainId, contracts: contracts_ } = config const contracts = contracts_.map((x) => ({ ...x, address: typeof x.address === 'string' ? { [chainId]: x.address } : x.address, })) as Omit[] return fetch({ cacheDuration, contracts, async parse({ response }) { if (response.status === 404) throw new Error('Contract not found in Sourcify repository.') const json = await response.json() const parsed = await SourcifyResponse.safeParseAsync(json) if (!parsed.success) throw fromZodError(parsed.error, { prefix: 'Invalid response' }) if (parsed.data.abi) return parsed.data.abi as ContractConfig['abi'] throw new Error('contract not found') }, request({ address }) { if (!address) throw new Error('address is required') let contractAddress: Address | undefined if (typeof address === 'string') contractAddress = address else if (typeof address === 'object') contractAddress = address[chainId] if (!contractAddress) throw new Error( `No address found for chainId "${chainId}". Make sure chainId "${chainId}" is set as an address.`, ) return { url: `https://sourcify.dev/server/v2/contract/${chainId}/${contractAddress}?fields=abi`, } }, }) } // Supported chains // https://docs.sourcify.dev/docs/chains type ChainId = | 1 // Ethereum Mainnet | 560048 // Ethereum Testnet Hoodi | 11155111 // Ethereum Testnet Sepolia | 17000 // Ethereum Testnet Holesky | 5 // Ethereum Testnet Goerli | 3 // Ethereum Testnet Ropsten | 4 // Ethereum Testnet Rinkeby | 96969696 // Privix Chain Testnet | 180 // AME Chain Mainnet | 78430 // Amplify Subnet | 1339 // Elysium Mainnet | 421613 // Arbitrum Goerli | 42170 // Arbitrum Nova | 42161 // Arbitrum One | 421614 // Arbitrum Sepolia | 421611 // Arbitrum Rinkeby | 10242 // Arthera Mainnet | 10243 // Arthera Testnet | 592 // Astar | 6321 // Aura Euphoria Testnet | 6322 // Aura Mainnet | 1313161554 // Aurora Mainnet | 1313161555 // Aurora Testnet | 43114 // Avalanche C-Chain | 43113 // Avalanche Fuji Testnet | 223 // B2 Mainnet | 56 // BNB Smart Chain Mainnet | 97 // BNB Smart Chain Testnet | 8453 // Base | 84531 // Base Goerli Testnet | 84532 // Base Sepolia Testnet | 4337 // Beam | 13337 // Beam Testnet | 641230 // Bear Network Chain Mainnet | 200901 // Bitlayer Mainnet | 200810 // Bitlayer Testnet | 7171 // Bitrock Mainnet | 7771 // Bitrock Testnet | 81457 // Blast | 288 // Boba Network | 28 // Boba Network Rinkeby Testnet | 78431 // Bulletin Subnet | 534 // Candle | 7700 // Canto | 7701 // Canto Tesnet | 44787 // Celo Alfajores Testnet | 62320 // Celo Baklava Testnet | 42220 // Celo Mainnet | 11142220 // Celo Sepolia Testnet | 5115 // Citrea Testnet | 78432 // Conduit Subnet | 1030 // Conflux eSpace | 1116 // Core Blockchain Mainnet | 1115 // Core Blockchain Testnet | 1114 // Core Blockchain Testnet2 | 21000000 // Corn | 44 // Crab Network | 25 // Cronos Mainnet | 4157 // CrossFi Testnet | 3737 // Crossbell | 103090 // Crystaleum | 33111 // Curtis | 53935 // DFK Chain | 335 // DFK Chain Test | 46 // Darwinia Network | 43 // Darwinia Pangolin Testnet | 666666666 // Degen Chain | 432204 // Dexalot Subnet | 432201 // Dexalot Subnet Testnet | 2000 // Dogechain Mainnet | 2021 // Edgeware EdgeEVM Mainnet | 648 // Endurance Smart Chain Mainnet | 39797 // Energi Mainnet | 49797 // Energi Testnet | 246 // Energy Web Chain | 73799 // Energy Web Volta Testnet | 61 // Ethereum Classic | 42793 // Etherlink Mainnet | 128123 // Etherlink Testnet | 9001 // Evmos | 9000 // Evmos Testnet | 250 // Fantom Opera | 26100 // Ferrum Quantum Portal Network | 314159 // Filecoin - Calibration testnet | 314 // Filecoin - Mainnet | 14 // Flare Mainnet | 252 // Fraxtal | 2522 // Fraxtal Testnet | 122 // Fuse Mainnet | 17069 // Garnet Holesky | 486217935 // Gather Devnet Network | 192837465 // Gather Mainnet Network | 356256156 // Gather Testnet Network | 100 // Gnosis | 10200 // Gnosis Chiado Testnet | 71402 // Godwoken Mainnet | 71401 // Godwoken Testnet v1 | 19011 // HOME Verse Mainnet | 216 // Happychain Testnet | 54211 // Haqq Chain Testnet | 11235 // Haqq Network | 295 // Hedera Mainnet | 16350 // Incentiv Devnet | 96 // KUB Mainnet | 25925 // KUB Testnet | 1001 // Kaia Kairos Testnet | 8217 // Kaia Mainnet | 2222 // Kava | 2221 // Kava Testnet | 420420 // Kekchain | 420666 // Kekchain (kektest) | 2037 // Kiwi Subnet | 255 // Kroma | 2358 // Kroma Sepolia | 10849 // Lamina1 | 10850 // Lamina1 Identity | 767368 // Lamina1 Identity Testnet | 764984 // Lamina1 Testnet | 1891 // Lightlink Pegasus Testnet | 1890 // Lightlink Phoenix Mainnet | 59144 // Linea | 59141 // Linea Sepolia | 1135 // Lisk | 957 // Lyra Chain | 22776 // MAP Protocol | 212 // MAPO Makalu | 5000 // Mantle | 5003 // Mantle Sepolia Testnet | 7078815900 // Mekong | 333000333 // Meld | 222000222 // Kanazawa | 4200 // Merlin Mainnet | 82 // Meter Mainnet | 83 // Meter Testnet | 1088 // Metis Andromeda Mainnet | 59902 // Metis Sepolia Testnet | 31612 // Mezo | 9996 // Mind Smart Chain Mainnet | 9977 // Mind Smart Chain Testnet | 34443 // Mode | 919 // Mode Testnet | 1287 // Moonbase Alpha | 1284 // Moonbeam | 1285 // Moonriver | 62621 // MultiVAC Mainnet | 10 // OP Mainnet | 11155420 // OP Sepolia Testnet | 42262 // Oasis Emerald | 42261 // Oasis Emerald Testnet | 23294 // Oasis Sapphire | 23295 // Oasis Sapphire Testnet | 311752642 // OneLedger Mainnet | 4216137055 // OneLedger Testnet Frankenstein | 970 // Oort Mainnet | 28528 // Optimism Bedrock (Goerli Alpha Testnet) | 420 // Optimism Goerli Testnet | 69 // Optimism Kovan | 4000 // Ozone Chain Mainnet | 16180 // PLYR PHI | 62831 // PLYR TAU Testnet | 99 // POA Network Core | 77 // POA Network Sokol | 11297108109 // Palm | 11297108099 // Palm Testnet | 13381 // Phoenix Mainnet | 2206132 // PlatON Dev Testnet2 | 210425 // PlatON Mainnet | 12898 // PlayFair Testnet Subnet | 80002 // Amoy | 137 // Polygon Mainnet | 80001 // Mumbai | 1101 // Polygon zkEVM | 2442 // Polygon zkEVM Cardona Testnet | 16969696 // Privix Chain Mainnet | 369 // PulseChain | 35441 // Q Mainnet | 35443 // Q Testnet | 690 // Redstone | 1433 // Rikeza Network Mainnet | 570 // Rollux Mainnet | 57000 // Rollux Testnet | 2020 // Ronin Mainnet | 30 // Rootstock Mainnet | 534352 // Scroll | 534351 // Scroll Sepolia Testnet | 336 // Shiden | 2044 // Shrapnel Subnet | 2038 // Shrapnel Testnet | 111000 // Siberium Test Network | 19 // Songbird Canary-Network | 1516 // Story Odyssey Testnet | 105105 // Stratis Mainnet | 205205 // Auroria Testnet | 2048 // Stratos | 2047 // Stratos Testnet | 5330 // Superseed | 1291 // Swisstronik Testnet | 1149 // Symplexia Smart Chain | 57 // Syscoin Mainnet | 5700 // Syscoin Tanenbaum Testnet | 167000 // Taiko Alethia | 167006 // Taiko Eldfell L3 | 167005 // Taiko Grimsvotn L2 | 5845 // Tangle | 841 // Taraxa Mainnet | 842 // Taraxa Testnet | 2017 // Adiri | 40 // Telos EVM Mainnet | 41 // Telos EVM Testnet | 7668 // The Root Network - Mainnet | 7672 // The Root Network - Porcini Testnet | 710420 // Tiltyard Mainnet Subnet | 1127469 // Tiltyard Subnet | 723107 // TixChain Testnet | 6119 // UPTN | 8 // Ubiq | 130 // Unichain | 100009 // VeChain | 100010 // VeChain Testnet | 106 // Velas EVM Mainnet | 11111 // WAGMI | 888 // Wanchain | 999 // Wanchain Testnet | 51 // XDC Apothem Network | 50 // XDC Network | 660279 // Xai Mainnet | 37714555429 // Xai Testnet v2 | 202401 // YMTECH-BESU Testnet | 42766 // ZKFair Mainnet | 383414847825 // Zeniq | 7000 // ZetaChain Mainnet | 7001 // ZetaChain Testnet | 32769 // Zilliqa 2 | 32770 // Zilliqa 2 EVM proto-mainnet | 33103 // Zilliqa 2 EVM proto-testnet | 33101 // Zilliqa 2 Testnet | 48898 // Zircuit Garfield Testnet | 48900 // Zircuit Mainnet | 48899 // Zircuit Testnet | 7777777 // Zora | 999999999 // Zora Sepolia Testnet | 7200 // exSat Mainnet | 839999 // exSat Testnet | 3338 // peaq | 300 // zkSync Sepolia Testnet ================================================ FILE: packages/cli/src/types.ts ================================================ export type Compute = { [key in keyof type]: type[key] } & unknown export type MaybeArray = T | T[] export type MaybePromise = T | Promise export type RequiredBy = Required< Pick > & Omit ================================================ FILE: packages/cli/src/utils/findConfig.test.ts ================================================ import { afterEach, expect, test, vi } from 'vitest' import { createFixture } from '../../test/utils.js' import { findConfig } from './findConfig.js' afterEach(() => { vi.restoreAllMocks() }) test('finds config file', async () => { const { dir, paths } = await createFixture({ files: { 'wagmi.config.ts': '' }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await expect(findConfig()).resolves.toBe(paths['wagmi.config.ts']) }) test('finds config file at location', async () => { const { dir, paths } = await createFixture({ files: { 'wagmi.config.ts': '' }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await expect(findConfig({ config: paths['wagmi.config.ts'] })).resolves.toBe( paths['wagmi.config.ts'], ) }) test('finds config file at root', async () => { const { dir, paths } = await createFixture({ files: { 'wagmi.config.ts': '' }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await expect(findConfig({ root: dir })).resolves.toBe( paths['wagmi.config.ts'], ) }) ================================================ FILE: packages/cli/src/utils/findConfig.ts ================================================ import { existsSync } from 'node:fs' import escalade from 'escalade' import { resolve } from 'pathe' // Do not reorder // In order of preference files are checked const configFiles = [ 'wagmi.config.ts', 'wagmi.config.js', 'wagmi.config.mjs', 'wagmi.config.mts', ] type FindConfigParameters = { /** Config file name */ config?: string | undefined /** Config file directory */ root?: string | undefined } /** * Resolves path to wagmi CLI config file. */ export async function findConfig(parameters: FindConfigParameters = {}) { const { config, root } = parameters const rootDir = resolve(root || process.cwd()) if (config) { const path = resolve(rootDir, config) if (existsSync(path)) return path return } const configPath = await escalade(rootDir, (_dir, names) => { for (const name of names) { if (configFiles.includes(name)) return name } return undefined }) return configPath } ================================================ FILE: packages/cli/src/utils/format.test.ts ================================================ import { expect, test } from 'vitest' import { format } from './format.js' test('formats code', async () => { await expect( format(`const foo = "bar"`), ).resolves.toMatchInlineSnapshot(` "const foo = 'bar' " `) }) ================================================ FILE: packages/cli/src/utils/format.ts ================================================ import prettier from 'prettier' export async function format(content: string) { const config = await prettier.resolveConfig(process.cwd()) return prettier.format(content, { arrowParens: 'always', endOfLine: 'lf', parser: 'typescript', printWidth: 80, semi: false, singleQuote: true, tabWidth: 2, trailingComma: 'all', ...config, plugins: [], }) } ================================================ FILE: packages/cli/src/utils/getAddressDocString.test.ts ================================================ import { expect, test } from 'vitest' import { getAddressDocString } from './getAddressDocString.js' test('address', async () => { expect( getAddressDocString({ address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', }), ).toMatchInlineSnapshot('""') }) test('multichain address with known chain ids', async () => { expect( getAddressDocString({ address: { 1: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', 5: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', 10: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', }, }), ).toMatchInlineSnapshot(` "* - [__View Contract on Ethereum Etherscan__](https://etherscan.io/address/0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e) * - [__View Contract on Goerli Etherscan__](https://goerli.etherscan.io/address/0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e) * - [__View Contract on Op Mainnet Optimism Explorer__](https://optimistic.etherscan.io/address/0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e)" `) }) test('multichain address with unknown chain id', async () => { expect( getAddressDocString({ address: { 1: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', 2: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', }, }), ).toMatchInlineSnapshot( ` "* - [__View Contract on Ethereum Etherscan__](https://etherscan.io/address/0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e) * - [__View Contract on Expanse Network Expanse Explorer__](https://explorer.expanse.tech/address/0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e)" `, ) }) ================================================ FILE: packages/cli/src/utils/getAddressDocString.ts ================================================ import { capitalCase } from 'change-case' import dedent from 'dedent' import * as allChains from 'viem/chains' import type { Contract } from '../config.js' const chainMap: Record = {} for (const chain of Object.values(allChains)) { if (typeof chain !== 'object') continue if (!('id' in chain)) continue chainMap[chain.id] = chain } export function getAddressDocString(parameters: { address: Contract['address'] }) { const { address } = parameters if (!address || typeof address === 'string') return '' if (Object.keys(address).length === 1) return `* ${getLink({ address: address[Number.parseInt(Object.keys(address)[0]!, 10)]!, chainId: Number.parseInt(Object.keys(address)[0]!, 10), })}` const addresses = Object.entries(address).filter( (x) => chainMap[Number.parseInt(x[0], 10)], ) if (addresses.length === 0) return '' if (addresses.length === 1 && addresses[0]) return `* ${getLink({ address: addresses[0][1], chainId: Number.parseInt(addresses[0][0], 10)!, })}` return dedent` ${addresses.reduce((prev, curr) => { const chainId = Number.parseInt(curr[0], 10) const address = curr[1] return `${prev}\n* - ${getLink({ address, chainId })}` }, '')} ` } function getLink({ address, chainId }: { address: string; chainId: number }) { const chain = chainMap[chainId] if (!chain) return '' const blockExplorer = chain.blockExplorers?.default if (!blockExplorer) return '' return `[__View Contract on ${capitalCase(chain.name)} ${capitalCase( blockExplorer.name, )}__](${blockExplorer.url}/address/${address})` } ================================================ FILE: packages/cli/src/utils/getIsUsingTypeScript.test.ts ================================================ import { afterEach, expect, test, vi } from 'vitest' import { createFixture } from '../../test/utils.js' import { getIsUsingTypeScript } from './getIsUsingTypeScript.js' afterEach(() => { vi.restoreAllMocks() }) test('true if has tsconfig', async () => { const { dir } = await createFixture({ files: { 'tsconfig.json': '', }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await expect(getIsUsingTypeScript()).resolves.toBe(true) }) test('true if has wagmi.config', async () => { const { dir } = await createFixture({ files: { 'wagmi.config.ts': '', }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await expect(getIsUsingTypeScript()).resolves.toBe(true) }) test('false', async () => { const { dir } = await createFixture() const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) await expect(getIsUsingTypeScript()).resolves.toBe(false) }) ================================================ FILE: packages/cli/src/utils/getIsUsingTypeScript.ts ================================================ import escalade from 'escalade' export async function getIsUsingTypeScript() { try { const cwd = process.cwd() const tsconfig = await escalade(cwd, (_dir, names) => { const files = [ 'tsconfig.json', 'tsconfig.base.json', 'tsconfig.lib.json', 'tsconfig.node.json', ] for (const name of names) { if (files.includes(name)) return name } return undefined }) if (tsconfig) return true const wagmiConfig = await escalade(cwd, (_dir, names) => { const files = ['wagmi.config.ts', 'wagmi.config.mts'] for (const name of names) { if (files.includes(name)) return name } return undefined }) if (wagmiConfig) return true return false } catch { return false } } ================================================ FILE: packages/cli/src/utils/loadEnv.test.ts ================================================ import { afterEach, expect, test, vi } from 'vitest' import { createFixture } from '../../test/utils.js' import { loadEnv } from './loadEnv.js' afterEach(() => { vi.restoreAllMocks() }) test('loads env', async () => { const { dir } = await createFixture({ files: { '.env': ` FOO=bar SOME_ENV_VAR=1 `, }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) expect(loadEnv()).toMatchInlineSnapshot(` { "FOO": "bar", "SOME_ENV_VAR": "1", } `) }) test('loads env from envDir', async () => { const { dir } = await createFixture({ files: { '.env': ` FOO=bar SOME_ENV_VAR=1 `, }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) expect(loadEnv({ envDir: dir })).toMatchInlineSnapshot(` { "FOO": "bar", "SOME_ENV_VAR": "1", } `) }) test('loads env with mode', async () => { const mode = 'dev' const { dir } = await createFixture({ files: { [`.env.${mode}`]: ` FOO=bar SOME_ENV_VAR=1 `, }, }) const spy = vi.spyOn(process, 'cwd') spy.mockImplementation(() => dir) expect(loadEnv({ mode })).toMatchInlineSnapshot(` { "FOO": "bar", "SOME_ENV_VAR": "1", } `) }) test('throws error when mode is "local"', async () => { expect(() => { loadEnv({ mode: 'local' }) }).toThrowErrorMatchingInlineSnapshot( `[Error: "local" cannot be used as a mode name because it conflicts with the .local postfix for .env files.]`, ) }) ================================================ FILE: packages/cli/src/utils/loadEnv.ts ================================================ import { existsSync, readFileSync, statSync } from 'node:fs' import { dirname, join } from 'node:path' import { parse } from 'dotenv' import { expand } from 'dotenv-expand' // https://github.com/vitejs/vite/blob/main/packages/vite/src/node/env.ts#L7 export function loadEnv( config: { mode?: string; envDir?: string } = {}, ): Record { const mode = config.mode if (mode === 'local') { throw new Error( `"local" cannot be used as a mode name because it conflicts with the .local postfix for .env files.`, ) } const envFiles = [ /** default file */ '.env', /** local file */ '.env.local', ...(mode ? [ /** mode file */ `.env.${mode}`, /** mode local file */ `.env.${mode}.local`, ] : []), ] const envDir = config.envDir ?? process.cwd() const parsed = Object.fromEntries( envFiles.flatMap((file) => { const path = lookupFile(envDir, [file], { pathOnly: true, rootDir: envDir, }) if (!path) return [] return Object.entries(parse(readFileSync(path))) }), ) try { // let environment variables use each other expand({ parsed }) } catch (error) { // custom error handling until https://github.com/motdotla/dotenv-expand/issues/65 is fixed upstream // check for message "TypeError: Cannot read properties of undefined (reading 'split')" if ((error as Error).message.includes('split')) { throw new Error( 'dotenv-expand failed to expand env vars. Maybe you need to escape `$`?', ) } throw error } return parsed } function lookupFile( dir: string, formats: string[], options?: { pathOnly?: boolean rootDir?: string predicate?: (file: string) => boolean }, ): string | undefined { for (const format of formats) { const fullPath = join(dir, format) if (existsSync(fullPath) && statSync(fullPath).isFile()) { const result = options?.pathOnly ? fullPath : readFileSync(fullPath, 'utf-8') if (!options?.predicate || options.predicate(result)) { return result } } } const parentDir = dirname(dir) if ( parentDir !== dir && (!options?.rootDir || parentDir.startsWith(options?.rootDir)) ) return lookupFile(parentDir, formats, options) return undefined } ================================================ FILE: packages/cli/src/utils/packages.test.ts ================================================ import { expect, test } from 'vitest' import { getIsPackageInstalled, getPackageManager } from './packages.js' test('getIsPackageInstalled: true', async () => { await expect(getIsPackageInstalled({ packageName: 'vitest' })).resolves.toBe( true, ) }) test('getIsPackageInstalled: false', async () => { await expect( getIsPackageInstalled({ packageName: 'vitest-unknown' }), ).resolves.toBe(false) }) test('getPackageManager', async () => { await expect(getPackageManager()).resolves.toMatchInlineSnapshot('"pnpm"') }) ================================================ FILE: packages/cli/src/utils/packages.ts ================================================ import { execSync } from 'node:child_process' import { promises as fs } from 'node:fs' import { resolve } from 'node:path' export async function getIsPackageInstalled(parameters: { packageName: string cwd?: string }) { const { packageName, cwd = process.cwd() } = parameters try { const packageManager = await getPackageManager() const command = (() => { switch (packageManager) { case 'yarn': return ['why', packageName] case 'bun': return ['pm', 'ls', '--all'] default: return ['ls', packageName] } })() const result = execSync(`${packageManager} ${command.join(' ')}`, { cwd, encoding: 'utf-8', stdio: 'pipe', }) // For Bun, we need to check if the package name is in the output if (packageManager === 'bun') return result.includes(packageName) return result !== '' } catch (_error) { return false } } export async function getPackageManager(executable?: boolean | undefined) { const userAgent = process.env.npm_config_user_agent if (userAgent) { if (userAgent.includes('pnpm')) return 'pnpm' // The yarn@^3 user agent includes npm, so yarn must be checked first. if (userAgent.includes('yarn')) return 'yarn' if (userAgent.includes('npm')) return executable ? 'npx' : 'npm' if (userAgent.includes('bun')) return executable ? 'bunx' : 'bun' } const packageManager = await detect() if (packageManager === 'npm' && executable) return 'npx' return packageManager } type PackageManager = 'npm' | 'yarn' | 'pnpm' | 'bun' async function detect( parameters: { cwd?: string; includeGlobalBun?: boolean } = {}, ) { const { cwd, includeGlobalBun } = parameters const type = await getTypeofLockFile(cwd) if (type) { return type } const [hasYarn, hasPnpm, hasBun] = await Promise.all([ hasGlobalInstallation('yarn'), hasGlobalInstallation('pnpm'), includeGlobalBun && hasGlobalInstallation('bun'), ]) if (hasYarn) return 'yarn' if (hasPnpm) return 'pnpm' if (hasBun) return 'bun' return 'npm' } const cache = new Map() function hasGlobalInstallation(pm: PackageManager): boolean { const key = `has_global_${pm}` if (cache.has(key)) return cache.get(key) try { const result = execSync(`${pm} --version`, { encoding: 'utf-8', stdio: 'pipe', }) const isGlobal = /^\d+.\d+.\d+$/.test(result) cache.set(key, isGlobal) return isGlobal } catch { return false } } function getTypeofLockFile(cwd = '.'): Promise { const key = `lockfile_${cwd}` if (cache.has(key)) { return Promise.resolve(cache.get(key)) } return Promise.all([ pathExists(resolve(cwd, 'yarn.lock')), pathExists(resolve(cwd, 'package-lock.json')), pathExists(resolve(cwd, 'pnpm-lock.yaml')), pathExists(resolve(cwd, 'bun.lockb')), ]).then(([isYarn, isNpm, isPnpm, isBun]) => { let value: PackageManager | null = null if (isYarn) value = 'yarn' else if (isPnpm) value = 'pnpm' else if (isBun) value = 'bun' else if (isNpm) value = 'npm' cache.set(key, value) return value }) } async function pathExists(p: string) { try { await fs.access(p) return true } catch { return false } } ================================================ FILE: packages/cli/src/utils/resolveConfig.test.ts ================================================ import { expect, test } from 'vitest' import { createFixture } from '../../test/utils.js' import { defaultConfig } from '../config.js' import { findConfig } from './findConfig.js' import { resolveConfig } from './resolveConfig.js' test.skip('resolves config', async () => { const { paths } = await createFixture({ files: { 'wagmi.config.ts': ` import { defineConfig } from '@wagmi/cli' export default defineConfig(${JSON.stringify(defaultConfig)}) `, }, }) const configPath = await findConfig({ config: paths['wagmi.config.ts'], }) await expect( resolveConfig({ configPath: configPath! }), ).resolves.toMatchInlineSnapshot(` { "contracts": [], "out": "src/generated.ts", "plugins": [], } `) }) test.skip('resolves function config', async () => { const { paths } = await createFixture({ files: { 'wagmi.config.ts': ` import { defineConfig } from '@wagmi/cli' export default defineConfig(() => (${JSON.stringify(defaultConfig)})) `, }, }) const configPath = await findConfig({ config: paths['wagmi.config.ts'], }) await expect( resolveConfig({ configPath: configPath! }), ).resolves.toMatchInlineSnapshot(` { "contracts": [], "out": "src/generated.ts", "plugins": [], } `) }) test.skip('resolves array config', async () => { const { paths } = await createFixture({ files: { 'wagmi.config.ts': ` import { defineConfig } from '@wagmi/cli' export default defineConfig([${JSON.stringify(defaultConfig)}]) `, }, }) const configPath = await findConfig({ config: paths['wagmi.config.ts'], }) await expect( resolveConfig({ configPath: configPath! }), ).resolves.toMatchInlineSnapshot(` [ { "contracts": [], "out": "src/generated.ts", "plugins": [], }, ] `) }) ================================================ FILE: packages/cli/src/utils/resolveConfig.ts ================================================ import { bundleRequire } from 'bundle-require' import type { Config } from '../config.js' import type { MaybeArray } from '../types.js' type ResolveConfigParameters = { /** Path to config file */ configPath: string } /** Bundles and returns wagmi config object from path. */ export async function resolveConfig( parameters: ResolveConfigParameters, ): Promise> { const { configPath } = parameters const res = await bundleRequire({ filepath: configPath }) let config = res.mod.default if (config.default) config = config.default if (typeof config !== 'function') return config return await config() } ================================================ FILE: packages/cli/src/version.ts ================================================ export const version = '2.10.0' ================================================ FILE: packages/cli/test/constants.ts ================================================ import { parseAbi } from 'viem' export const wagmiAbi = parseAbi([ 'constructor()', 'event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId)', 'event ApprovalForAll(address indexed owner, address indexed operator, bool approved)', 'event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)', 'function approve(address to, uint256 tokenId)', 'function balanceOf(address owner) view returns (uint256)', 'function getApproved(uint256 tokenId) view returns (address)', 'function isApprovedForAll(address owner, address operator) view returns (bool)', 'function mint()', 'function name() view returns (string)', 'function ownerOf(uint256 tokenId) view returns (address)', 'function safeTransferFrom(address from, address to, uint256 tokenId)', 'function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data)', 'function setApprovalForAll(address operator, bool approved)', 'function supportsInterface(bytes4 interfaceId) view returns (bool)', 'function symbol() view returns (string)', 'function tokenURI(uint256 tokenId) pure returns (string)', 'function totalSupply() view returns (uint256)', 'function transferFrom(address from, address to, uint256 tokenId)', ]) export const depositAbi = parseAbi([ 'constructor()', 'event DepositEvent(bytes pubkey, bytes withdrawal_credentials, bytes amount, bytes signature, bytes index)', 'function deposit(bytes pubkey, bytes withdrawal_credentials, bytes signature, bytes32 deposit_data_root) payable', 'function get_deposit_count() view returns (bytes)', 'function get_deposit_root() view returns (bytes32)', 'function supportsInterface(bytes4 interfaceId) pure returns (bool)', ]) ================================================ FILE: packages/cli/test/setup.ts ================================================ import { mkdir } from 'node:fs/promises' import { homedir } from 'node:os' import type { createSpinner as nanospinner_createSpinner } from 'nanospinner' import { join } from 'pathe' import { vi } from 'vitest' const cacheDir = join(homedir(), '.wagmi-cli/plugins/fetch/cache') await mkdir(cacheDir, { recursive: true }) vi.mock('nanospinner', async (importOriginal) => { const mod = await importOriginal<{ createSpinner: typeof nanospinner_createSpinner }>() function createSpinner( initialText: string, opts: Parameters[1], ) { let currentText = '' const spinner = mod.createSpinner(initialText, opts) return { ...spinner, start(text = initialText) { console.log(`- ${text}`) spinner.start(text) currentText = text }, success(text = currentText) { console.log(`√ ${text}`) spinner.success(text) }, error(text = currentText) { // biome-ignore lint/suspicious/noConsole: logging error console.error(`× ${text}`) spinner.error(text) }, } } return { createSpinner } }) vi.mock('picocolors', async () => { function pass(input: string | number | null | undefined) { return input } return { default: { blue: pass, gray: pass, green: pass, red: pass, white: pass, yellow: pass, }, } }) ================================================ FILE: packages/cli/test/utils.ts ================================================ import { spawnSync } from 'node:child_process' import { cp, mkdir, symlink, writeFile } from 'node:fs/promises' import fixtures from 'fixturez' import { HttpResponse, http } from 'msw' import * as path from 'pathe' import { vi } from 'vitest' const f = fixtures(__dirname) type Json = | string | number | boolean | null | { [property: string]: Json } | Json[] export async function createFixture< TFiles extends { [filename: string]: string | Json } & { tsconfig?: true }, >(config: { copyNodeModules?: boolean; dir?: string; files?: TFiles } = {}) { const dir = config.dir ?? f.temp() await mkdir(dir, { recursive: true }) // Create test files const paths: { [_ in keyof TFiles]: string } = {} as any await Promise.all( (Object.keys(config.files ?? {}) as (keyof TFiles)[]).map( async (filename_) => { let file: Json | true | undefined let filename = filename_ if (filename === 'tsconfig') { filename = 'tsconfig.json' file = getTsConfig(dir) } else file = config.files![filename] const filePath = path.join(dir, filename.toString()) await mkdir(path.dirname(filePath), { recursive: true }) await writeFile( filePath, typeof file === 'string' ? file : JSON.stringify(file, null, 2), ) paths[filename === 'tsconfig.json' ? 'tsconfig' : filename] = filePath }, ), ) if (config.copyNodeModules) { await symlink( path.join(__dirname, '../node_modules'), path.join(dir, 'node_modules'), 'dir', ) await cp( path.join(__dirname, '../package.json'), path.join(dir, 'package.json'), ) } return { dir, paths: paths, } } type TsConfig = { compilerOptions: { [property: string]: any } exclude: string[] include: string[] } function getTsConfig(baseUrl: string) { return { compilerOptions: { allowJs: true, baseUrl: '.', esModuleInterop: true, forceConsistentCasingInFileNames: true, incremental: true, isolatedModules: true, jsx: 'preserve', lib: ['dom', 'dom.iterable', 'esnext'], module: 'esnext', moduleResolution: 'node', noEmit: true, paths: { '@wagmi/cli': [path.relative(baseUrl, 'packages/cli/src')], '@wagmi/cli/*': [path.relative(baseUrl, 'packages/cli/src/*')], '@wagmi/connectors': [ path.relative(baseUrl, 'packages/connectors/src'), ], '@wagmi/connectors/*': [ path.relative(baseUrl, 'packages/connectors/src/*'), ], '@wagmi/core': [path.relative(baseUrl, 'packages/core/src')], '@wagmi/core/*': [path.relative(baseUrl, 'packages/core/src/*')], wagmi: [path.relative(baseUrl, 'packages/react/src')], 'wagmi/*': [path.relative(baseUrl, 'packages/react/src/*')], }, resolveJsonModule: true, skipLibCheck: true, strict: true, target: 'es6', }, include: [`${baseUrl}/**/*.ts`, `${baseUrl}/**/*.tsx`], exclude: ['node_modules'], } as TsConfig } export function watchConsole() { type Console = 'info' | 'log' | 'warn' | 'error' const output: { [_ in Console | 'all']: string[] } = { info: [], log: [], warn: [], error: [], all: [], } function handleOutput(method: Console) { return (message: string) => { output[method].push(message) output.all.push(message) } } return { // biome-ignore lint/suspicious/noConsole: logging debug: console.debug, info: vi.spyOn(console, 'info').mockImplementation(handleOutput('info')), log: vi.spyOn(console, 'log').mockImplementation(handleOutput('log')), warn: vi.spyOn(console, 'warn').mockImplementation(handleOutput('warn')), error: vi.spyOn(console, 'error').mockImplementation(handleOutput('error')), output, get formatted() { return output.all.join('\n') }, } } export async function typecheck(project: string) { try { const result = spawnSync( 'tsc', ['--noEmit', '--target', 'es2021', '--pretty', 'false', '-p', project], { encoding: 'utf-8', stdio: 'pipe', }, ) if (result.error) throw result.error if (result.status !== 0) throw new Error(`Failed with code ${result.status}`) if (result.signal) throw new Error('Process terminated by signal') return result.stdout } catch (error) { throw new Error( (error as Error).message.replaceAll( path.dirname(project), '/path/to/project', ), ) } } export const apiKey = 'abc' export const invalidApiKey = 'xyz' export const address = '0xaf0326d92b97df1221759476b072abfd8084f9be' export const proxyAddress = '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48' export const implementationAddress = '0x43506849d7c04f9138d1a2050bbf3a0c054402dd' export const unverifiedContractAddress = '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e' export const timeoutAddress = '0xecb504d39723b0be0e3a9aa33d646642d1051ee1' export function getHandlers(baseUrl = 'https://api.etherscan.io/v2/api') { return [ http.get(baseUrl, async ({ request }) => { const url = new URL(request.url) const search = url.search.replace(/^\?chainId=\d&/, '?') if ( search === `?module=contract&action=getabi&address=${unverifiedContractAddress}&apikey=${apiKey}` ) return HttpResponse.json({ status: '0', message: 'NOTOK', result: 'Contract source code not verified', }) if ( search === `?module=contract&action=getabi&address=${timeoutAddress}&apikey=${invalidApiKey}` ) return HttpResponse.json({ status: '0', message: 'NOTOK', result: 'Invalid API Key', }) if ( search === `?module=contract&action=getabi&address=${address}&apikey=${apiKey}` ) return HttpResponse.json({ status: '1', message: 'OK', result: '[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"}]', }) if ( search === `?module=contract&action=getabi&address=${timeoutAddress}&apikey=${apiKey}` ) { await new Promise((resolve) => setTimeout(resolve, 10_000)) return HttpResponse.json({}) } if ( search === `?module=contract&action=getabi&address=${implementationAddress}&apikey=${apiKey}` ) return HttpResponse.json({ status: '1', message: 'OK', result: '[{"constant":false,"inputs":[{"name":"newImplementation","type":"address"}],"name":"upgradeTo","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newImplementation","type":"address"},{"name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"implementation","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newAdmin","type":"address"}],"name":"changeAdmin","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"admin","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"_implementation","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"previousAdmin","type":"address"},{"indexed":false,"name":"newAdmin","type":"address"}],"name":"AdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"implementation","type":"address"}],"name":"Upgraded","type":"event"}]', }) if ( search === `?module=contract&action=getsourcecode&address=${proxyAddress}&apikey=${apiKey}` ) return HttpResponse.json({ status: '1', message: 'OK', result: [ { SourceCode: '...', ABI: '[{"constant":false,"inputs":[{"name":"newImplementation","type":"address"}],"name":"upgradeTo","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newImplementation","type":"address"},{"name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"implementation","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newAdmin","type":"address"}],"name":"changeAdmin","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"admin","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"_implementation","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"previousAdmin","type":"address"},{"indexed":false,"name":"newAdmin","type":"address"}],"name":"AdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"implementation","type":"address"}],"name":"Upgraded","type":"event"}]', ContractName: 'FiatTokenProxy', CompilerVersion: 'v0.4.24+commit.e67f0147', OptimizationUsed: '0', Runs: '200', ConstructorArguments: '0000000000000000000000000882477e7895bdc5cea7cb1552ed914ab157fe56', EVMVersion: 'Default', Library: '', LicenseType: '', Proxy: '1', Implementation: '0x43506849d7c04f9138d1a2050bbf3a0c054402dd', SwarmSource: 'bzzr://a4a547cfc7202c5acaaae74d428e988bc62ad5024eb0165532d3a8f91db4ed24', }, ], }) if ( search === `?module=contract&action=getsourcecode&address=${address}&apikey=${apiKey}` ) return HttpResponse.json({ status: '1', message: 'OK', result: [ { SourceCode: '...', ABI: '[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"}]', ContractName: 'WagmiMintExample', CompilerVersion: 'v0.8.11+commit.d7f03943', OptimizationUsed: '1', Runs: '10000', ConstructorArguments: '', EVMVersion: 'Default', Library: '', LicenseType: '', Proxy: '0', Implementation: '', SwarmSource: '', }, ], }) throw new Error(`Unhandled request: ${search}`) }), ] } ================================================ FILE: packages/cli/tsconfig.build.json ================================================ { "extends": "../../tsconfig.base.json", "include": ["src/**/*.ts"], "exclude": ["src/**/*.test.ts"], "compilerOptions": { "sourceMap": true, "types": ["@types/node"] } } ================================================ FILE: packages/cli/tsconfig.json ================================================ { "extends": "./tsconfig.build.json", "include": ["src/**/*.ts", "test/**/*.ts", "types/**/*.d.ts"], "exclude": [] } ================================================ FILE: packages/cli/types/fixturez.d.ts ================================================ declare module 'fixturez' { interface FixturezOpts { glob?: string cleanup?: boolean root?: string } interface Fixturez { find(basename: string): string copy(basename: string): string temp(): string cleanup(): void } function fixturez(dirname: string, opts?: FixturezOpts): Fixturez export = fixturez } ================================================ FILE: packages/connectors/CHANGELOG.md ================================================ # @wagmi/connectors ## 7.2.1 ### Patch Changes - Updated dependencies [[`8b96e2f`](https://github.com/wevm/wagmi/commit/8b96e2f46d9b3441d3b499b03924700ac0629be6)]: - @wagmi/core@3.4.0 ## 7.2.0 ### Minor Changes - **Breaking:** Removed `gemini` connector (former sponsor). If you still need this connector, vendor the [source code](https://github.com/wevm/wagmi/blob/9bbf13eac895669e70b233de767c8731d221f16e/packages/connectors/src/gemini.ts) into your project directly. ([`9dbdd82`](https://github.com/wevm/wagmi/commit/9dbdd8277808eb361fe7fe01ea34e4c6bb85c7a5)) ### Patch Changes - Updated dependencies [[`c1dedd9`](https://github.com/wevm/wagmi/commit/c1dedd99c0a1878d7cd48476946868636ac81dd8)]: - @wagmi/core@3.3.4 ## 7.1.7 ### Patch Changes - Updated dependencies [[`4b3f5a3`](https://github.com/wevm/wagmi/commit/4b3f5a3f7b3f242e8fbc1f08ae2f81ae13c5e09f)]: - @wagmi/core@3.3.3 ## 7.1.6 ### Patch Changes - Updated dependencies [[`68e17db`](https://github.com/wevm/wagmi/commit/68e17db7ff84982db8f52f54e6f047c5efab62ab)]: - @wagmi/core@3.3.2 ## 7.1.5 ### Patch Changes - Updated dependencies [[`7f756bd`](https://github.com/wevm/wagmi/commit/7f756bda12cd332016f0bb3a2f20307c37499309)]: - @wagmi/core@3.3.1 ## 7.1.4 ### Patch Changes - Updated dependencies [[`dfe7904`](https://github.com/wevm/wagmi/commit/dfe790426d5ac24d55eacdf8d0193292de801911), [`d503a2c`](https://github.com/wevm/wagmi/commit/d503a2cb6ef96018669a66d03f72a2b2b06dc0fb), [`5399840`](https://github.com/wevm/wagmi/commit/53998407645edd95d85e50a931acaed87c05e256), [`5978cc5`](https://github.com/wevm/wagmi/commit/5978cc508ac837be88ed84c15ea5aa805f59005a), [`67612ed`](https://github.com/wevm/wagmi/commit/67612edfbcb971b71c86964aae72ff3ef80bbe10), [`dbe9484`](https://github.com/wevm/wagmi/commit/dbe9484c1a635c3fc9b658a7d8e34ccc0a82ed1d)]: - @wagmi/core@3.3.0 ## 7.1.3 ### Patch Changes - Updated dependencies [[`979fe26`](https://github.com/wevm/wagmi/commit/979fe265e5273a8b49a4469ffab88b1a18b1aeaa), [`979fe26`](https://github.com/wevm/wagmi/commit/979fe265e5273a8b49a4469ffab88b1a18b1aeaa), [`e4541de`](https://github.com/wevm/wagmi/commit/e4541def76a1744dc36c188453265cc6e9d83722)]: - @wagmi/core@3.2.3 ## 7.1.2 ### Patch Changes - Updated dependencies [[`4fefa57`](https://github.com/wevm/wagmi/commit/4fefa576014820b454344b579282ddecde5c7994)]: - @wagmi/core@3.2.2 ## 7.1.1 ### Patch Changes - Updated dependencies [[`a373b50`](https://github.com/wevm/wagmi/commit/a373b504f2ba199ca63ec0da6138ad1aa12a3a8f)]: - @wagmi/core@3.2.1 ## 7.1.0 ### Patch Changes - Updated dependencies [[`2ee3f55`](https://github.com/wevm/wagmi/commit/2ee3f559a2637c7aab3fca6c7d196cf238ecd63d)]: - @wagmi/core@3.2.0 ## 7.0.7 ### Patch Changes - Updated dependencies [[`14989e4`](https://github.com/wevm/wagmi/commit/14989e425a36b765a6a24e5abf1782c2a26c70db)]: - @wagmi/core@3.1.0 ## 7.0.6 ### Patch Changes - Updated dependencies [[`a5c4381`](https://github.com/wevm/wagmi/commit/a5c4381563374018dca0074017b21181ac027e9a)]: - @wagmi/core@3.0.2 ## 7.0.5 ### Patch Changes - Fixed published exports. ([`ed86500`](https://github.com/wevm/wagmi/commit/ed86500fbd56e5f543cb04e990b2dadc08d8b3b5)) ## 7.0.4 ### Patch Changes - Fixed internal dynamic imports when using Webpack ([#4911](https://github.com/wevm/wagmi/pull/4911)) ## 7.0.3 ### Patch Changes - Updated dependencies [[`058c8c1`](https://github.com/wevm/wagmi/commit/058c8c18459a69a4aa2141e34640273a06a819f4)]: - @wagmi/core@3.0.1 ## 7.0.2 ### Patch Changes - Fixed account ordering in `baseAccount` connection response ([#4882](https://github.com/wevm/wagmi/pull/4882)) ## 7.0.1 ### Patch Changes - Fixed `baseAccount` reconnect behavior ([#4884](https://github.com/wevm/wagmi/pull/4884)) ## 7.0.0 ### Major Changes - All connector dependencies are now optional peer dependencies. This means that if you want to use a specific connector, you need to install its required dependencies. ([#4857](https://github.com/wevm/wagmi/pull/4857)) #### baseAccount [`baseAccount`](https://wagmi.sh/core/api/connectors/baseAccount) requires `@base-org/account` ``` pnpm add @base-org/account@~2.4.0 ``` #### coinbaseWallet [`coinbaseWallet`](https://wagmi.sh/core/api/connectors/coinbaseWallet) requires `@coinbase/wallet-sdk` ``` pnpm add @coinbase/wallet-sdk@~4.3.6 ``` #### gemini [`gemini`](https://wagmi.sh/core/api/connectors/gemini) requires `@gemini-wallet/core` ``` pnpm add @gemini-wallet/core@~0.3.1 ``` #### metaMask [`metaMask`](https://wagmi.sh/core/api/connectors/metaMask) requires `@metamask/sdk` ``` pnpm add @metamask/sdk@~0.33.1 ``` #### porto [`porto`](https://wagmi.sh/core/api/connectors/porto) requires `porto` ``` pnpm add porto@~0.2.35 ``` #### safe [`safe`](https://wagmi.sh/core/api/connectors/safe) requires `@safe-global/safe-apps-provider` and `@safe-global/safe-apps-sdk` ``` pnpm add @safe-global/safe-apps-provider@~0.18.6 @safe-global/safe-apps-sdk@~9.1.0 ``` #### walletConnect [`walletConnect`](https://wagmi.sh/core/api/connectors/walletConnect) requires `walletconnect/ethereum-provider` ``` pnpm add @walletconnect/ethereum-provider@~2.21.1 ``` ### Patch Changes - Updated dependencies [[`73e7326`](https://github.com/wevm/wagmi/commit/73e7326ac21303d7790765c78a7076b319b2ad26)]: - @wagmi/core@3.0.0 ## 6.2.0 ### Minor Changes - Added support for `'wallet_connect'` capabilities to `baseAccount` connector ([#4877](https://github.com/wevm/wagmi/pull/4877)) ## 6.1.4 ### Patch Changes - Bumped Gemini package version ([`2ddb506`](https://github.com/wevm/wagmi/commit/2ddb506b67fcb2abb464765d2af88df2eb58de60)) ## 6.1.3 ### Patch Changes - Added warning to `walletConnect` about vulnerability and relicensing. ([`65cf154`](https://github.com/wevm/wagmi/commit/65cf1544d65bfb1fb830c405a371e8cd3c3fb73e)) ## 6.1.2 ### Patch Changes - Bumped connector deps ([#4843](https://github.com/wevm/wagmi/pull/4843)) ## 6.1.1 ### Patch Changes - Bumped Porto version ([`990dd23`](https://github.com/wevm/wagmi/commit/990dd2339e96b302931056e0fb898bd2dd42a04d)) ## 6.1.0 ### Minor Changes - Added `getPortoInstance` method to `porto`. ([#4837](https://github.com/wevm/wagmi/pull/4837)) ## 6.0.1 ### Patch Changes - Updated dependencies [[`74100b0`](https://github.com/wevm/wagmi/commit/74100b0dea2dfe7b057fdbe1660596554c70642e)]: - @wagmi/core@2.22.1 ## 6.0.0 ### Patch Changes - Updated dependencies [[`ebb2352`](https://github.com/wevm/wagmi/commit/ebb2352375e05e52d0bcf6ae1a60ac4e798bf29f)]: - @wagmi/core@2.22.0 ## 5.11.2 ### Patch Changes - Added `chainId` parameter on `walletConnect#getProvider` ([#4806](https://github.com/wevm/wagmi/pull/4806)) - Updated dependencies [[`866aeb0`](https://github.com/wevm/wagmi/commit/866aeb0e6361ef9114246e50149c1077bc05bf10)]: - @wagmi/core@2.21.2 ## 5.11.1 ### Patch Changes - Updated `porto`. ([`41eb70e`](https://github.com/wevm/wagmi/commit/41eb70e072774b282053a5e98669a7d01c0e2438)) - Pulled `porto` connector implementation. ([#4801](https://github.com/wevm/wagmi/pull/4801)) ## 5.11.0 ### Minor Changes - Added `porto` connector. ([#4794](https://github.com/wevm/wagmi/pull/4794)) ## 5.10.2 ### Patch Changes - Updated dependencies [[`72b703a`](https://github.com/wevm/wagmi/commit/72b703ab379c74ecf88f637cf47f31786c823a48)]: - @wagmi/core@2.21.1 ## 5.10.1 ### Patch Changes - Bumped MetaMask SDK version in accordance with [security advisory](https://github.com/advisories/GHSA-qj3p-xc97-xw74). ([`5937456`](https://github.com/wevm/wagmi/commit/59374562f2c3a41245687eb1c29ee8023737c7cc)) ## 5.10.0 ### Minor Changes - [#4784](https://github.com/wevm/wagmi/pull/4784) [`8736133a13eb82099e20468b735525a266fdfd6c`](https://github.com/wevm/wagmi/commit/8736133a13eb82099e20468b735525a266fdfd6c) Thanks [@tmm](https://github.com/tmm)! - Added `withCapabilities` option to `connect` for exposing response capabilities. ### Patch Changes - Updated dependencies [[`8736133a13eb82099e20468b735525a266fdfd6c`](https://github.com/wevm/wagmi/commit/8736133a13eb82099e20468b735525a266fdfd6c)]: - @wagmi/core@2.21.0 ## 5.9.9 ### Patch Changes - Updated dependencies [[`ce06e137e7bfaf000464b1cecd6c86e19a66ebcf`](https://github.com/wevm/wagmi/commit/ce06e137e7bfaf000464b1cecd6c86e19a66ebcf)]: - @wagmi/core@2.20.3 ## 5.9.8 ### Patch Changes - [#4691](https://github.com/wevm/wagmi/pull/4691) [`a03da817a388646c9b4885792101a67eef3616e7`](https://github.com/wevm/wagmi/commit/a03da817a388646c9b4885792101a67eef3616e7) Thanks [@frolic](https://github.com/frolic)! - Fixed `walletConnect#connect` by moving chain switch directly inside instead of relying on `getProvider`. ## 5.9.7 ### Patch Changes - Updated dependencies [[`986b96427a4bb743d2673dfbc7e8cb5041316db3`](https://github.com/wevm/wagmi/commit/986b96427a4bb743d2673dfbc7e8cb5041316db3)]: - @wagmi/core@2.20.2 ## 5.9.6 ### Patch Changes - Updated dependencies [[`d4c367ca46c508598c997cf229a31593a1e2b8b8`](https://github.com/wevm/wagmi/commit/d4c367ca46c508598c997cf229a31593a1e2b8b8)]: - @wagmi/core@2.20.1 ## 5.9.5 ### Patch Changes - Updated dependencies [[`a13aa2b68890f180f6ac3f741cbb9817494cb66c`](https://github.com/wevm/wagmi/commit/a13aa2b68890f180f6ac3f741cbb9817494cb66c)]: - @wagmi/core@2.20.0 ## 5.9.4 ### Patch Changes - [#4764](https://github.com/wevm/wagmi/pull/4764) [`f4039419b83b52b2984de149db85c11f503ffe39`](https://github.com/wevm/wagmi/commit/f4039419b83b52b2984de149db85c11f503ffe39) Thanks [@mikelxc](https://github.com/mikelxc)! - Updated gemini connector ## 5.9.3 ### Patch Changes - [#4759](https://github.com/wevm/wagmi/pull/4759) [`909324d28c81e15c9df312b277dcff1983fbae4d`](https://github.com/wevm/wagmi/commit/909324d28c81e15c9df312b277dcff1983fbae4d) Thanks [@mikelxc](https://github.com/mikelxc)! - Added Gemini ## 5.9.2 ### Patch Changes - Updated dependencies [[`b5f017dbc707729eb0b36d617352be224d1139d4`](https://github.com/wevm/wagmi/commit/b5f017dbc707729eb0b36d617352be224d1139d4)]: - @wagmi/core@2.19.0 ## 5.9.1 ### Patch Changes - [`6fbafd425e488dbeee8404162dbeb3c737eeb8cf`](https://github.com/wevm/wagmi/commit/6fbafd425e488dbeee8404162dbeb3c737eeb8cf) Thanks [@jxom](https://github.com/jxom)! - Updated `@base-org/account` - Updated dependencies [[`6514ba29a5acb918773235fed0238d7d679d06d5`](https://github.com/wevm/wagmi/commit/6514ba29a5acb918773235fed0238d7d679d06d5)]: - @wagmi/core@2.18.1 ## 5.9.0 ### Minor Changes - [#4734](https://github.com/wevm/wagmi/pull/4734) [`eac550ae5b49f96a7e3404a6d88adc62d3889013`](https://github.com/wevm/wagmi/commit/eac550ae5b49f96a7e3404a6d88adc62d3889013) Thanks [@jxom](https://github.com/jxom)! - Added `baseAccount` connector. ### Patch Changes - Updated dependencies [[`eac550ae5b49f96a7e3404a6d88adc62d3889013`](https://github.com/wevm/wagmi/commit/eac550ae5b49f96a7e3404a6d88adc62d3889013)]: - @wagmi/core@2.18.0 ## 5.8.6 ### Patch Changes - [#4731](https://github.com/wevm/wagmi/pull/4731) [`e75bd89406e9b6ff5b7d3a7148ab34140fe6352a`](https://github.com/wevm/wagmi/commit/e75bd89406e9b6ff5b7d3a7148ab34140fe6352a) Thanks [@tomiir](https://github.com/tomiir)! - Updated `@coinbase/wallet-sdk` to version 4.3.6 ## 5.8.5 ### Patch Changes - Updated dependencies [[`7ce242b549d8cc78e6c319d9ee419693da36704c`](https://github.com/wevm/wagmi/commit/7ce242b549d8cc78e6c319d9ee419693da36704c)]: - @wagmi/core@2.17.3 ## 5.8.4 ### Patch Changes - [#4696](https://github.com/wevm/wagmi/pull/4696) [`3a90f358820444a85bb727742b0a16eb943fc361`](https://github.com/wevm/wagmi/commit/3a90f358820444a85bb727742b0a16eb943fc361) Thanks [@tomiir](https://github.com/tomiir)! - Updated @walletconnect/etereum-provider to version 2.21.1 ## 5.8.3 ### Patch Changes - [#4660](https://github.com/wevm/wagmi/pull/4660) [`42b1fed58e9ac09da0f8ebf3e9271f98a707aaac`](https://github.com/wevm/wagmi/commit/42b1fed58e9ac09da0f8ebf3e9271f98a707aaac) Thanks [@ganchoradkov](https://github.com/ganchoradkov)! - Updated `@walletconnect/ethereum-provider` version to `2.20.2` ## 5.8.2 ### Patch Changes - Updated dependencies [[`29297a48af72b537173d948ccd2fe37d39914c66`](https://github.com/wevm/wagmi/commit/29297a48af72b537173d948ccd2fe37d39914c66), [`07370106d5fb6b8fe300992d93abf25b3d0eaf57`](https://github.com/wevm/wagmi/commit/07370106d5fb6b8fe300992d93abf25b3d0eaf57)]: - @wagmi/core@2.17.2 ## 5.8.1 ### Patch Changes - Updated dependencies [[`01f64e64fa4f85cdd30023903f972f4f9023681f`](https://github.com/wevm/wagmi/commit/01f64e64fa4f85cdd30023903f972f4f9023681f)]: - @wagmi/core@2.17.1 ## 5.8.0 ### Minor Changes - [#4644](https://github.com/wevm/wagmi/pull/4644) [`cc5517ff6880bb630f1b201930acc20dd1a0b451`](https://github.com/wevm/wagmi/commit/cc5517ff6880bb630f1b201930acc20dd1a0b451) Thanks [@lukaisailovic](https://github.com/lukaisailovic)! - Updated `@walletconnect/etherereum-provider` to `2.20.0`. ## 5.7.13 ### Patch Changes - [#4622](https://github.com/wevm/wagmi/pull/4622) [`88427b2bcd13ec375ef519e9ad1ccffef9f02a7b`](https://github.com/wevm/wagmi/commit/88427b2bcd13ec375ef519e9ad1ccffef9f02a7b) Thanks [@dan1kov](https://github.com/dan1kov)! - Added `rdns` property to Coinbase Wallet v3 connector - [#4605](https://github.com/wevm/wagmi/pull/4605) [`3f8b2edc4f237cccff1009bcef03d51ca27a7324`](https://github.com/wevm/wagmi/commit/3f8b2edc4f237cccff1009bcef03d51ca27a7324) Thanks [@chybisov](https://github.com/chybisov)! - Bumped `@safe-global/safe-apps-provider` version to `0.18.6`. - Updated dependencies [[`799ee4d4b23c2ecd64e3f3668e67634e81939719`](https://github.com/wevm/wagmi/commit/799ee4d4b23c2ecd64e3f3668e67634e81939719)]: - @wagmi/core@2.17.0 ## 5.7.12 ### Patch Changes - [#4608](https://github.com/wevm/wagmi/pull/4608) [`b59c024b23c69f5459b17390531207cfdf126ce4`](https://github.com/wevm/wagmi/commit/b59c024b23c69f5459b17390531207cfdf126ce4) Thanks [@jxom](https://github.com/jxom)! - Updated `@walletconnect/ethereum-provider`. ## 5.7.11 ### Patch Changes - Updated dependencies [[`a4bd0623eed28e3761a27295831a60ad835f0ee0`](https://github.com/wevm/wagmi/commit/a4bd0623eed28e3761a27295831a60ad835f0ee0)]: - @wagmi/core@2.16.7 ## 5.7.10 ### Patch Changes - [#4573](https://github.com/wevm/wagmi/pull/4573) [`e944812ebc234a72c1417b77cff341166f5e0fef`](https://github.com/wevm/wagmi/commit/e944812ebc234a72c1417b77cff341166f5e0fef) Thanks [@ganchoradkov](https://github.com/ganchoradkov)! - updated `@walletconnect/ethereum-provider` to `2.19.1` - Updated dependencies [[`edf47477b2f6385a1c3ae01d36a8498c47f30a0b`](https://github.com/wevm/wagmi/commit/edf47477b2f6385a1c3ae01d36a8498c47f30a0b)]: - @wagmi/core@2.16.6 ## 5.7.9 ### Patch Changes - [#4571](https://github.com/wevm/wagmi/pull/4571) [`5b7101fddb61df56e34b2e02b46bc409e496eaf9`](https://github.com/wevm/wagmi/commit/5b7101fddb61df56e34b2e02b46bc409e496eaf9) Thanks [@ganchoradkov](https://github.com/ganchoradkov)! - Updated `@walletconnect/ethereum-provider` to `2.19.0` ## 5.7.8 ### Patch Changes - Updated dependencies [[`d0c9a86921a4e939373cc6e763284e53f2a2e93c`](https://github.com/wevm/wagmi/commit/d0c9a86921a4e939373cc6e763284e53f2a2e93c)]: - @wagmi/core@2.16.5 ## 5.7.7 ### Patch Changes - [`507f864d91238bfd423d0e36d3619eb9f6e52eec`](https://github.com/wevm/wagmi/commit/507f864d91238bfd423d0e36d3619eb9f6e52eec) Thanks [@jxom](https://github.com/jxom)! - Updated `@coinbase/wallet-sdk`. - Updated dependencies [[`507f864d91238bfd423d0e36d3619eb9f6e52eec`](https://github.com/wevm/wagmi/commit/507f864d91238bfd423d0e36d3619eb9f6e52eec)]: - @wagmi/core@2.16.4 ## 5.7.6 ### Patch Changes - [#4524](https://github.com/wevm/wagmi/pull/4524) [`639952c97f0fe3927106f42d3c9f7f366cdf7f7a`](https://github.com/wevm/wagmi/commit/639952c97f0fe3927106f42d3c9f7f366cdf7f7a) Thanks [@chakra-guy](https://github.com/chakra-guy)! - Updated MetaMask SDK. - [#4525](https://github.com/wevm/wagmi/pull/4525) [`5aa2c095f7bfb6dfcf91c6945c3e1f9c9dd05766`](https://github.com/wevm/wagmi/commit/5aa2c095f7bfb6dfcf91c6945c3e1f9c9dd05766) Thanks [@EdouardBougon](https://github.com/EdouardBougon)! - Added Phantom flag to Injected Connector. ## 5.7.5 ### Patch Changes - [#4512](https://github.com/wevm/wagmi/pull/4512) [`a257e8d4f97431a4af872cda1817b4ae17c7bbed`](https://github.com/wevm/wagmi/commit/a257e8d4f97431a4af872cda1817b4ae17c7bbed) Thanks [@EdouardBougon](https://github.com/EdouardBougon)! - Fixed MetaMask switchChain/addChain handling. ## 5.7.4 ### Patch Changes - [#4505](https://github.com/wevm/wagmi/pull/4505) [`c8a257e0f6d2ece013b873895c35769a8a804fdc`](https://github.com/wevm/wagmi/commit/c8a257e0f6d2ece013b873895c35769a8a804fdc) Thanks [@chakra-guy](https://github.com/chakra-guy)! - Bumped Metamask SDK Version (changes include [bug fixes and minor changes](https://github.com/MetaMask/metamask-sdk/pull/1194)). ## 5.7.3 ### Patch Changes - [#4480](https://github.com/wevm/wagmi/pull/4480) [`384a1d91597622eb59e1c05dc13ce25017c5b6d8`](https://github.com/wevm/wagmi/commit/384a1d91597622eb59e1c05dc13ce25017c5b6d8) Thanks [@RodeRickIsWatching](https://github.com/RodeRickIsWatching)! - Fixed invocation of default storage. - Updated dependencies [[`384a1d91597622eb59e1c05dc13ce25017c5b6d8`](https://github.com/wevm/wagmi/commit/384a1d91597622eb59e1c05dc13ce25017c5b6d8)]: - @wagmi/core@2.16.3 ## 5.7.2 ### Patch Changes - [`012907032b532a438fce48f407470250cbc8f0c6`](https://github.com/wevm/wagmi/commit/012907032b532a438fce48f407470250cbc8f0c6) Thanks [@jxom](https://github.com/jxom)! - Fixed assignment in `getDefaultStorage`. - Updated dependencies [[`012907032b532a438fce48f407470250cbc8f0c6`](https://github.com/wevm/wagmi/commit/012907032b532a438fce48f407470250cbc8f0c6)]: - @wagmi/core@2.16.2 ## 5.7.1 ### Patch Changes - [#4471](https://github.com/wevm/wagmi/pull/4471) [`9c8c35a3b829f2c58edcd3a29e2dcd99974d7470`](https://github.com/wevm/wagmi/commit/9c8c35a3b829f2c58edcd3a29e2dcd99974d7470) Thanks [@EdouardBougon](https://github.com/EdouardBougon)! - Improved MetaMask chain switching behavior. - Updated dependencies [[`3892ebd21c06beef4b28ece4e70d2a38807bce6f`](https://github.com/wevm/wagmi/commit/3892ebd21c06beef4b28ece4e70d2a38807bce6f)]: - @wagmi/core@2.16.1 ## 5.7.0 ### Minor Changes - [#4440](https://github.com/wevm/wagmi/pull/4440) [`e3f63a02c1f7d80481804584f262bc98dab0400d`](https://github.com/wevm/wagmi/commit/e3f63a02c1f7d80481804584f262bc98dab0400d) Thanks [@johanneskares](https://github.com/johanneskares)! - Added Coinbase Smart Wallet "Instant Onboarding" mode to `coinbaseWallet`. ## 5.6.2 ### Patch Changes - [#4437](https://github.com/wevm/wagmi/pull/4437) [`adf2253b10c6d4fc583e4bc9f01a8ef5ca267c85`](https://github.com/wevm/wagmi/commit/adf2253b10c6d4fc583e4bc9f01a8ef5ca267c85) Thanks [@chybisov](https://github.com/chybisov)! - Bumped `@safe-global/safe-apps-provider` version to `0.18.5`. ## 5.6.1 ### Patch Changes - [#4458](https://github.com/wevm/wagmi/pull/4458) [`987404f590c1d29ebb3cb68928f5e54aa032793d`](https://github.com/wevm/wagmi/commit/987404f590c1d29ebb3cb68928f5e54aa032793d) Thanks [@EdouardBougon](https://github.com/EdouardBougon)! - Fixed MetaMask internal metadata handling. ## 5.6.0 ### Minor Changes - [#4453](https://github.com/wevm/wagmi/pull/4453) [`070e48480194c8d7f45bda1d7dd1346e6f5d7227`](https://github.com/wevm/wagmi/commit/070e48480194c8d7f45bda1d7dd1346e6f5d7227) Thanks [@tmm](https://github.com/tmm)! - Added narrowing to `config.connectors`. ### Patch Changes - [#4456](https://github.com/wevm/wagmi/pull/4456) [`8b0726c1106fce88b782e676498eabf0718b2619`](https://github.com/wevm/wagmi/commit/8b0726c1106fce88b782e676498eabf0718b2619) Thanks [@EdouardBougon](https://github.com/EdouardBougon)! - Bumped MetaMask SDK and fixed internal metadata handling. - Updated dependencies [[`afea6b67822a7a2b96901ec851441d27ee0f7a52`](https://github.com/wevm/wagmi/commit/afea6b67822a7a2b96901ec851441d27ee0f7a52), [`070e48480194c8d7f45bda1d7dd1346e6f5d7227`](https://github.com/wevm/wagmi/commit/070e48480194c8d7f45bda1d7dd1346e6f5d7227)]: - @wagmi/core@2.16.0 ## 5.5.3 ### Patch Changes - [#4433](https://github.com/wevm/wagmi/pull/4433) [`06e186cd679b27fe195309110e766fcf46d4efbc`](https://github.com/wevm/wagmi/commit/06e186cd679b27fe195309110e766fcf46d4efbc) Thanks [@Aerilym](https://github.com/Aerilym)! - Bumped Metamask SDK version to `0.31.1`. - Updated dependencies [[`06e186cd679b27fe195309110e766fcf46d4efbc`](https://github.com/wevm/wagmi/commit/06e186cd679b27fe195309110e766fcf46d4efbc)]: - @wagmi/core@2.15.2 ## 5.5.2 ### Patch Changes - [#4422](https://github.com/wevm/wagmi/pull/4422) [`e563ef69130a511fd6f3f72ed4cd4fbe1390541f`](https://github.com/wevm/wagmi/commit/e563ef69130a511fd6f3f72ed4cd4fbe1390541f) Thanks [@abretonc7s](https://github.com/abretonc7s)! - Bumped MetaMask SDK. ## 5.5.1 ### Patch Changes - Updated dependencies [[`b8bbb409f4934538e3dd6cac5aaf7346292d0693`](https://github.com/wevm/wagmi/commit/b8bbb409f4934538e3dd6cac5aaf7346292d0693)]: - @wagmi/core@2.15.1 ## 5.5.0 ### Minor Changes - [#4417](https://github.com/wevm/wagmi/pull/4417) [`42e65ea4fea99c639817088bba915e0933d17141`](https://github.com/wevm/wagmi/commit/42e65ea4fea99c639817088bba915e0933d17141) Thanks [@jxom](https://github.com/jxom)! - Removed simulation in `writeContract` & `sendTransaction`. ### Patch Changes - Updated dependencies [[`42e65ea4fea99c639817088bba915e0933d17141`](https://github.com/wevm/wagmi/commit/42e65ea4fea99c639817088bba915e0933d17141)]: - @wagmi/core@2.15.0 ## 5.4.0 ### Minor Changes - [#4409](https://github.com/wevm/wagmi/pull/4409) [`7ca62b44cd997d48f92c2b81343726a5908aa00b`](https://github.com/wevm/wagmi/commit/7ca62b44cd997d48f92c2b81343726a5908aa00b) Thanks [@fan-zhang-sv](https://github.com/fan-zhang-sv)! - Added `preference` object for Coinbase Wallet connector. ## 5.3.10 ### Patch Changes - [#4406](https://github.com/wevm/wagmi/pull/4406) [`a13aa8d7c38eb3cc8171a02d6302e6d12cf6bcb3`](https://github.com/wevm/wagmi/commit/a13aa8d7c38eb3cc8171a02d6302e6d12cf6bcb3) Thanks [@tmm](https://github.com/tmm)! - Added additional RDNS to MetaMask Connector. - Updated dependencies [[`a13aa8d7c38eb3cc8171a02d6302e6d12cf6bcb3`](https://github.com/wevm/wagmi/commit/a13aa8d7c38eb3cc8171a02d6302e6d12cf6bcb3)]: - @wagmi/core@2.14.6 ## 5.3.9 ### Patch Changes - [`b12a04eeec985c48d2feac94b011d41fb29ca23e`](https://github.com/wevm/wagmi/commit/b12a04eeec985c48d2feac94b011d41fb29ca23e) Thanks [@tmm](https://github.com/tmm)! - Bumped Coinbase Wallet SDK version. ## 5.3.8 ### Patch Changes - [#4390](https://github.com/wevm/wagmi/pull/4390) [`dac62dc99a0679fa632a0fae49873d6053d06b35`](https://github.com/wevm/wagmi/commit/dac62dc99a0679fa632a0fae49873d6053d06b35) Thanks [@chybisov](https://github.com/chybisov)! - Bumped Safe Apps Provider version. - Updated dependencies [[`6b9bbacdc7bffd44fc2165362a5e65fd434e7646`](https://github.com/wevm/wagmi/commit/6b9bbacdc7bffd44fc2165362a5e65fd434e7646)]: - @wagmi/core@2.14.5 ## 5.3.7 ### Patch Changes - Updated dependencies [[`e08681c81fbdf475213e2d0f4c5517d0abf4e743`](https://github.com/wevm/wagmi/commit/e08681c81fbdf475213e2d0f4c5517d0abf4e743)]: - @wagmi/core@2.14.4 ## 5.3.6 ### Patch Changes - [#4385](https://github.com/wevm/wagmi/pull/4385) [`7558ff3133c11bc4c49473d08ee9a47eaa12df5b`](https://github.com/wevm/wagmi/commit/7558ff3133c11bc4c49473d08ee9a47eaa12df5b) Thanks [@cb-jake](https://github.com/cb-jake)! - Bumped Coinbase Wallet SDK version. ## 5.3.5 ### Patch Changes - [`7fe78f2d09778fc01fd0cffe85ba198e64999275`](https://github.com/wevm/wagmi/commit/7fe78f2d09778fc01fd0cffe85ba198e64999275) Thanks [@tmm](https://github.com/tmm)! - Fixed MetaMask connector not returning provider in some cases. - Updated dependencies [[`cb7dd2ebb871d0be8f1a11a8cd8ce592cd74b7c7`](https://github.com/wevm/wagmi/commit/cb7dd2ebb871d0be8f1a11a8cd8ce592cd74b7c7)]: - @wagmi/core@2.14.3 ## 5.3.4 ### Patch Changes - [#4371](https://github.com/wevm/wagmi/pull/4371) [`b6861a4c378dab78d8751ae0ac2aa425f3c24b8f`](https://github.com/wevm/wagmi/commit/b6861a4c378dab78d8751ae0ac2aa425f3c24b8f) Thanks [@iceanddust](https://github.com/iceanddust)! - Fixed Safe connector not working in some Vite apps - Updated dependencies [[`d0d0963bb5904a15cf0355862d62dd141ce0c31c`](https://github.com/wevm/wagmi/commit/d0d0963bb5904a15cf0355862d62dd141ce0c31c), [`ecac0ba36243d94c9199d0bd21937104c835d9a0`](https://github.com/wevm/wagmi/commit/ecac0ba36243d94c9199d0bd21937104c835d9a0)]: - @wagmi/core@2.14.2 ## 5.3.3 ### Patch Changes - [#4362](https://github.com/wevm/wagmi/pull/4362) [`83c6d16b7d6dddfa6bda036e04f00ec313c6248c`](https://github.com/wevm/wagmi/commit/83c6d16b7d6dddfa6bda036e04f00ec313c6248c) Thanks [@EdouardBougon](https://github.com/EdouardBougon)! - Fixed MetaMask connector internal logic. ## 5.3.2 ### Patch Changes - [#4357](https://github.com/wevm/wagmi/pull/4357) [`8970cc51398e1ac713435533096215c6d31ffdf9`](https://github.com/wevm/wagmi/commit/8970cc51398e1ac713435533096215c6d31ffdf9) Thanks [@tmm](https://github.com/tmm)! - Bumped dependencies. ## 5.3.1 ### Patch Changes - Updated dependencies [[`052e72e1f8c1c14fcbdce04a9f8fa7ec28d83702`](https://github.com/wevm/wagmi/commit/052e72e1f8c1c14fcbdce04a9f8fa7ec28d83702), [`b250fc21ee577b2a75c5a34ff684f62fb4ad771a`](https://github.com/wevm/wagmi/commit/b250fc21ee577b2a75c5a34ff684f62fb4ad771a)]: - @wagmi/core@2.14.1 ## 5.3.0 ### Minor Changes - [#4343](https://github.com/wevm/wagmi/pull/4343) [`f43e074f473820b208a6295d7c97f847332f1a1d`](https://github.com/wevm/wagmi/commit/f43e074f473820b208a6295d7c97f847332f1a1d) Thanks [@tmm](https://github.com/tmm)! - Added `rdns` property to connector interface. This is used to filter out duplicate [EIP-6963](https://eips.ethereum.org/EIPS/eip-6963) injected providers when [`createConfig#multiInjectedProviderDiscovery`](https://wagmi.sh/core/api/createConfig#multiinjectedproviderdiscovery) is enabled and `createConfig#connectors` already matches EIP-6963 providers' `rdns` property. ### Patch Changes - Updated dependencies [[`f43e074f473820b208a6295d7c97f847332f1a1d`](https://github.com/wevm/wagmi/commit/f43e074f473820b208a6295d7c97f847332f1a1d)]: - @wagmi/core@2.14.0 ## 5.2.2 ### Patch Changes - [#4347](https://github.com/wevm/wagmi/pull/4347) [`5ae49af590ff168426c9c283d54c34ae5148fcd9`](https://github.com/wevm/wagmi/commit/5ae49af590ff168426c9c283d54c34ae5148fcd9) Thanks [@EdouardBougon](https://github.com/EdouardBougon)! - Added workaround for MetaMask mobile sometimes disconnecting. - [#4350](https://github.com/wevm/wagmi/pull/4350) [`f3182b22e6e454d9bd74f1b940ef34431fd9555d`](https://github.com/wevm/wagmi/commit/f3182b22e6e454d9bd74f1b940ef34431fd9555d) Thanks [@abretonc7s](https://github.com/abretonc7s)! - Updated MetaMask SDK. - Updated dependencies [[`c05caabc20c3ced9682cfc7ba1f3f7dcfece0703`](https://github.com/wevm/wagmi/commit/c05caabc20c3ced9682cfc7ba1f3f7dcfece0703)]: - @wagmi/core@2.13.9 ## 5.2.1 ### Patch Changes - [#4345](https://github.com/wevm/wagmi/pull/4345) [`91a40f2db08e3a91db421b8732a5511a1e6c88fd`](https://github.com/wevm/wagmi/commit/91a40f2db08e3a91db421b8732a5511a1e6c88fd) Thanks [@tmm](https://github.com/tmm)! - Bumped MetaMask SDK. ## 5.2.0 ### Minor Changes - [#4337](https://github.com/wevm/wagmi/pull/4337) [`34a0c3b7eea778aee7c27f7ace5e4b2be4e8a0a4`](https://github.com/wevm/wagmi/commit/34a0c3b7eea778aee7c27f7ace5e4b2be4e8a0a4) Thanks [@tmm](https://github.com/tmm)! - Added "Connect and Sign" behavior to MetaMask Connector. ## 5.1.15 ### Patch Changes - [`3b2123664b7ac66848390739e855c3b9702ab60c`](https://github.com/wevm/wagmi/commit/3b2123664b7ac66848390739e855c3b9702ab60c) Thanks [@tmm](https://github.com/tmm)! - Bumped WalletConnect Provider. ## 5.1.14 ### Patch Changes - [#4207](https://github.com/wevm/wagmi/pull/4207) [`56f2482508f2ba71bd6b0295c70c6abca7101e57`](https://github.com/wevm/wagmi/commit/56f2482508f2ba71bd6b0295c70c6abca7101e57) Thanks [@Smert](https://github.com/Smert)! - Updated chain switch listener for `injected` and `metaMask` to be more robust. - Updated dependencies [[`56f2482508f2ba71bd6b0295c70c6abca7101e57`](https://github.com/wevm/wagmi/commit/56f2482508f2ba71bd6b0295c70c6abca7101e57)]: - @wagmi/core@2.13.8 ## 5.1.13 ### Patch Changes - Updated dependencies [[`be75c2d4ef636d7362420ab0a106bfdf63f5d1e6`](https://github.com/wevm/wagmi/commit/be75c2d4ef636d7362420ab0a106bfdf63f5d1e6)]: - @wagmi/core@2.13.7 ## 5.1.12 ### Patch Changes - Updated dependencies [[`edcbf5d6fbe92f639bead800502edda9e0aa39f1`](https://github.com/wevm/wagmi/commit/edcbf5d6fbe92f639bead800502edda9e0aa39f1)]: - @wagmi/core@2.13.6 ## 5.1.11 ### Patch Changes - [#4271](https://github.com/wevm/wagmi/pull/4271) [`82404c960e04c83e0bae6e1e12459ef9debf9554`](https://github.com/wevm/wagmi/commit/82404c960e04c83e0bae6e1e12459ef9debf9554) Thanks [@omridan159](https://github.com/omridan159)! - Bumped MetaMask SDK. - [#4227](https://github.com/wevm/wagmi/pull/4227) [`d07ad7f63a018256908a673d078aaf79e47ac703`](https://github.com/wevm/wagmi/commit/d07ad7f63a018256908a673d078aaf79e47ac703) Thanks [@xianchenxc](https://github.com/xianchenxc)! - Fixed MetaMask Connector throwing error after switching to a chain that was just added via `'wallet_addEthereumChain'`. ## 5.1.10 ### Patch Changes - [#4255](https://github.com/wevm/wagmi/pull/4255) [`81de006e66121a18c61945c1f9b8426c83a5713c`](https://github.com/wevm/wagmi/commit/81de006e66121a18c61945c1f9b8426c83a5713c) Thanks [@tomiir](https://github.com/tomiir)! - Bumped `@walletconnect/ethereum-provider` from version `2.15.3` to version `2.16.1`. - Updated dependencies [[`f47ce8f6d263e49fdff90b8edb3190142d2657bb`](https://github.com/wevm/wagmi/commit/f47ce8f6d263e49fdff90b8edb3190142d2657bb)]: - @wagmi/core@2.13.5 ## 5.1.9 ### Patch Changes - [#4243](https://github.com/wevm/wagmi/pull/4243) [`21bd0e473d374cbbd7a01bececa6022d529026ba`](https://github.com/wevm/wagmi/commit/21bd0e473d374cbbd7a01bececa6022d529026ba) Thanks [@tomiir](https://github.com/tomiir)! - Bumped `@walletconnect/ethereum-provider` from version `2.15.2` to version `2.15.3` - [#4251](https://github.com/wevm/wagmi/pull/4251) [`5c89c6853e616437a3be2b019db895451fecfb3c`](https://github.com/wevm/wagmi/commit/5c89c6853e616437a3be2b019db895451fecfb3c) Thanks [@tmm](https://github.com/tmm)! - Bumped MM SDK. ## 5.1.8 ### Patch Changes - [`b580ad4edff1721e0b9d138cf5ae2ec74d2374c7`](https://github.com/wevm/wagmi/commit/b580ad4edff1721e0b9d138cf5ae2ec74d2374c7) Thanks [@tmm](https://github.com/tmm)! - Bumped WalletConnect Provider. ## 5.1.7 ### Patch Changes - [#4213](https://github.com/wevm/wagmi/pull/4213) [`91fd81a068789c5020e891f539bcad8f54a7a52f`](https://github.com/wevm/wagmi/commit/91fd81a068789c5020e891f539bcad8f54a7a52f) Thanks [@tomiir](https://github.com/tomiir)! - Updated `@walletconnect/ethereum-provider` from version `2.15.0` to version `2.15.1`. ## 5.1.6 ### Patch Changes - [#4208](https://github.com/wevm/wagmi/pull/4208) [`3168616298cbb6135d0ffda771cba4126e83eba8`](https://github.com/wevm/wagmi/commit/3168616298cbb6135d0ffda771cba4126e83eba8) Thanks [@tomiir](https://github.com/tomiir)! - Updated WalletConnect Ethereum Provider version from `2.14.0` to `2.15.0`. - [#4211](https://github.com/wevm/wagmi/pull/4211) [`d7608ef9a79459465dc8c06a2ab740465c881907`](https://github.com/wevm/wagmi/commit/d7608ef9a79459465dc8c06a2ab740465c881907) Thanks [@tmm](https://github.com/tmm)! - Added default name for MetaMask Connector. ## 5.1.5 ### Patch Changes - Updated dependencies [[`b4c8971788c70b09479946ecfa998cff2f1b3953`](https://github.com/wevm/wagmi/commit/b4c8971788c70b09479946ecfa998cff2f1b3953)]: - @wagmi/core@2.13.4 ## 5.1.4 ### Patch Changes - Updated dependencies [[`871dbdbfe59ac8ad01d1ec6150ea7b091b7b7de4`](https://github.com/wevm/wagmi/commit/871dbdbfe59ac8ad01d1ec6150ea7b091b7b7de4)]: - @wagmi/core@2.13.3 ## 5.1.3 ### Patch Changes - Updated dependencies [[`1b9b523fa9b9dfe839aecdf4b40caa9547d7e594`](https://github.com/wevm/wagmi/commit/1b9b523fa9b9dfe839aecdf4b40caa9547d7e594)]: - @wagmi/core@2.13.2 ## 5.1.2 ### Patch Changes - [`abb490dac4f0f02f46cb0878e7ca9a0db6aada56`](https://github.com/wevm/wagmi/commit/abb490dac4f0f02f46cb0878e7ca9a0db6aada56) Thanks [@tmm](https://github.com/tmm)! - Bumped MetaMask SDK version. - [`28e0e5c9a4f856583f9d36a807502bd51a0c6ec2`](https://github.com/wevm/wagmi/commit/28e0e5c9a4f856583f9d36a807502bd51a0c6ec2) Thanks [@tmm](https://github.com/tmm)! - Bumped WalletConnect Ethereum Provider version. ## 5.1.1 ### Patch Changes - Updated dependencies [[`07c1227f306d0efb9421d4bb77a774f92f5fcf45`](https://github.com/wevm/wagmi/commit/07c1227f306d0efb9421d4bb77a774f92f5fcf45)]: - @wagmi/core@2.13.1 ## 5.1.0 ### Minor Changes - [#4162](https://github.com/wevm/wagmi/pull/4162) [`a73a7737b756886b388f120ae423e72cca53e8a0`](https://github.com/wevm/wagmi/commit/a73a7737b756886b388f120ae423e72cca53e8a0) Thanks [@jxom](https://github.com/jxom)! - Added functionality for consumer-defined RPC URLs (`config.transports`) to be propagated to the WalletConnect & MetaMask Connectors. ### Patch Changes - Updated dependencies [[`a73a7737b756886b388f120ae423e72cca53e8a0`](https://github.com/wevm/wagmi/commit/a73a7737b756886b388f120ae423e72cca53e8a0)]: - @wagmi/core@2.13.0 ## 5.0.26 ### Patch Changes - [`8d81df5cc884d0a210dedd3c1ea0e2e9e52b83c5`](https://github.com/wevm/wagmi/commit/8d81df5cc884d0a210dedd3c1ea0e2e9e52b83c5) Thanks [@tmm](https://github.com/tmm)! - Fixed `metaMask` connector switch chain issue. - Updated dependencies [[`5bc8c8877810b2eec24a829df87dce40a51e6f20`](https://github.com/wevm/wagmi/commit/5bc8c8877810b2eec24a829df87dce40a51e6f20)]: - @wagmi/core@2.12.2 ## 5.0.25 ### Patch Changes - [#4146](https://github.com/wevm/wagmi/pull/4146) [`cc996e08e930c9e88cf753a1e874652059e81a3b`](https://github.com/wevm/wagmi/commit/cc996e08e930c9e88cf753a1e874652059e81a3b) Thanks [@jxom](https://github.com/jxom)! - Updated `@safe-global/safe-apps-sdk` + `@safe-global/safe-apps-provider` dependencies. - Updated dependencies [[`cc996e08e930c9e88cf753a1e874652059e81a3b`](https://github.com/wevm/wagmi/commit/cc996e08e930c9e88cf753a1e874652059e81a3b)]: - @wagmi/core@2.12.1 ## 5.0.24 ### Patch Changes - Updated dependencies [[`5581a810ef70308e99c6f8b630cd4bca59f64afc`](https://github.com/wevm/wagmi/commit/5581a810ef70308e99c6f8b630cd4bca59f64afc)]: - @wagmi/core@2.12.0 ## 5.0.23 ### Patch Changes - [`d3814ab4b88f9f0e052b53bc3d458df87b43f01d`](https://github.com/wevm/wagmi/commit/d3814ab4b88f9f0e052b53bc3d458df87b43f01d) Thanks [@jxom](https://github.com/jxom)! - Updated `mipd` dependency. - Updated dependencies [[`b08013eaa9ce97c02f8a7128ea400e3da7ef74bb`](https://github.com/wevm/wagmi/commit/b08013eaa9ce97c02f8a7128ea400e3da7ef74bb), [`d3814ab4b88f9f0e052b53bc3d458df87b43f01d`](https://github.com/wevm/wagmi/commit/d3814ab4b88f9f0e052b53bc3d458df87b43f01d)]: - @wagmi/core@2.11.8 ## 5.0.22 ### Patch Changes - [`0bb8b562ae04ecfeb2d6b2f1b980ebae31dc127e`](https://github.com/wevm/wagmi/commit/0bb8b562ae04ecfeb2d6b2f1b980ebae31dc127e) Thanks [@tmm](https://github.com/tmm)! - Improved TypeScript `'exactOptionalPropertyTypes'` support. - Updated dependencies [[`0bb8b562ae04ecfeb2d6b2f1b980ebae31dc127e`](https://github.com/wevm/wagmi/commit/0bb8b562ae04ecfeb2d6b2f1b980ebae31dc127e)]: - @wagmi/core@2.11.7 ## 5.0.21 ### Patch Changes - [#4094](https://github.com/wevm/wagmi/pull/4094) [`ff0760b5900114bcfdf420a9fba3cc278ac95afe`](https://github.com/wevm/wagmi/commit/ff0760b5900114bcfdf420a9fba3cc278ac95afe) Thanks [@omridan159](https://github.com/omridan159)! - Bumped MetaMask SDK to fix `metaMask` connector error bubbling. - Updated dependencies [[`95965c1f19d480b97f2b297a077a9e607dee32ad`](https://github.com/wevm/wagmi/commit/95965c1f19d480b97f2b297a077a9e607dee32ad)]: - @wagmi/core@2.11.6 ## 5.0.20 ### Patch Changes - [`43fa971d34cac57fa5a2898ad4d839b95d7af37c`](https://github.com/wevm/wagmi/commit/43fa971d34cac57fa5a2898ad4d839b95d7af37c) Thanks [@tmm](https://github.com/tmm)! - Bumped Coinbase Wallet SDK and fixed `metaMask` connector hang on mobile. ## 5.0.19 ### Patch Changes - [#4083](https://github.com/wevm/wagmi/pull/4083) [`b7ad208030d9f2e3f89912ff76b16cdbd848feda`](https://github.com/wevm/wagmi/commit/b7ad208030d9f2e3f89912ff76b16cdbd848feda) Thanks [@omridan159](https://github.com/omridan159)! - Bumped MetaMask SDK ## 5.0.18 ### Patch Changes - [#4081](https://github.com/wevm/wagmi/pull/4081) [`44d24620c9e3957f3245d14d6a042736371df70b`](https://github.com/wevm/wagmi/commit/44d24620c9e3957f3245d14d6a042736371df70b) Thanks [@tmm](https://github.com/tmm)! - Bumped MetaMask SDK ## 5.0.17 ### Patch Changes - Updated dependencies [[`04f2b846b113f3d300d82c9fa75212f1805817c5`](https://github.com/wevm/wagmi/commit/04f2b846b113f3d300d82c9fa75212f1805817c5)]: - @wagmi/core@2.11.5 ## 5.0.16 ### Patch Changes - [#4071](https://github.com/wevm/wagmi/pull/4071) [`02c38c28d1aa0ad7a61c33775de603ed974c5c1b`](https://github.com/wevm/wagmi/commit/02c38c28d1aa0ad7a61c33775de603ed974c5c1b) Thanks [@omridan159](https://github.com/omridan159)! - Bumped MetaMask SDK - Updated dependencies [[`9e8345cd56186b997b5e56deaa2cfc69b30d15f6`](https://github.com/wevm/wagmi/commit/9e8345cd56186b997b5e56deaa2cfc69b30d15f6)]: - @wagmi/core@2.11.4 ## 5.0.15 ### Patch Changes - Updated dependencies [[`8974e6269bb5d7bfaa90db0246bc7d13e8bff798`](https://github.com/wevm/wagmi/commit/8974e6269bb5d7bfaa90db0246bc7d13e8bff798)]: - @wagmi/core@2.11.3 ## 5.0.14 ### Patch Changes - Updated dependencies [[`b4d9ef79deb554ee20fed6666a474be5e7cdd522`](https://github.com/wevm/wagmi/commit/b4d9ef79deb554ee20fed6666a474be5e7cdd522)]: - @wagmi/core@2.11.2 ## 5.0.13 ### Patch Changes - [`9c862d8d63e3d692a22cef2a90782b74a9103f17`](https://github.com/wevm/wagmi/commit/9c862d8d63e3d692a22cef2a90782b74a9103f17) Thanks [@tmm](https://github.com/tmm)! - Reverted internal module loading utility. - Updated dependencies [[`9c862d8d63e3d692a22cef2a90782b74a9103f17`](https://github.com/wevm/wagmi/commit/9c862d8d63e3d692a22cef2a90782b74a9103f17)]: - @wagmi/core@2.11.1 ## 5.0.12 ### Patch Changes - Updated dependencies [[`06bb598a7f04c7b167f5b7ff6d46bd15886a6a14`](https://github.com/wevm/wagmi/commit/06bb598a7f04c7b167f5b7ff6d46bd15886a6a14), [`24a45b269bd0214a29d6f82a84ac66ef8c3f3822`](https://github.com/wevm/wagmi/commit/24a45b269bd0214a29d6f82a84ac66ef8c3f3822)]: - @wagmi/core@2.11.0 ## 5.0.11 ### Patch Changes - [#4020](https://github.com/wevm/wagmi/pull/4020) [`e3b124ce414b8fd1b2214e2c5a28dc72158a13d1`](https://github.com/wevm/wagmi/commit/e3b124ce414b8fd1b2214e2c5a28dc72158a13d1) Thanks [@tmm](https://github.com/tmm)! - Added reconnection support to `metaMask` on mobile and use deeplinks by default. - Updated dependencies [[`f2a7cefab96691ebed8b8e45ffde071c47b58dbe`](https://github.com/wevm/wagmi/commit/f2a7cefab96691ebed8b8e45ffde071c47b58dbe), [`f0ea0b2a7fe193dadfeb49a4c8031ee451c638b5`](https://github.com/wevm/wagmi/commit/f0ea0b2a7fe193dadfeb49a4c8031ee451c638b5)]: - @wagmi/core@2.10.6 ## 5.0.10 ### Patch Changes - [`560952acd4bfe33db6c7c07b35c613cef278677c`](https://github.com/wevm/wagmi/commit/560952acd4bfe33db6c7c07b35c613cef278677c) Thanks [@tmm](https://github.com/tmm)! - Captured Coinbase Smart Wallet error when closing window as EIP-1193 `4001` error. ## 5.0.9 ### Patch Changes - [`32cdd7b7dc5aff916c040628519562c3a99d418d`](https://github.com/wevm/wagmi/commit/32cdd7b7dc5aff916c040628519562c3a99d418d) Thanks [@tmm](https://github.com/tmm)! - Bumped `@metamask/sdk` to remove peer dependency install warning. ## 5.0.8 ### Patch Changes - [#3997](https://github.com/wevm/wagmi/pull/3997) [`c1952d1ff7f0a491dc88595a49159451b07b5621`](https://github.com/wevm/wagmi/commit/c1952d1ff7f0a491dc88595a49159451b07b5621) Thanks [@nateReiners](https://github.com/nateReiners)! - Bumped Coinbase Wallet SDK. ## 5.0.7 ### Patch Changes - Updated dependencies [[`030c7c2cb380dfd67a2182f62e2aa7a6e1601898`](https://github.com/wevm/wagmi/commit/030c7c2cb380dfd67a2182f62e2aa7a6e1601898)]: - @wagmi/core@2.10.5 ## 5.0.6 ### Patch Changes - Updated dependencies [[`51fde8a0433b4fff357c1a8d7e08b41b4c86c968`](https://github.com/wevm/wagmi/commit/51fde8a0433b4fff357c1a8d7e08b41b4c86c968)]: - @wagmi/core@2.10.4 ## 5.0.5 ### Patch Changes - [#3979](https://github.com/wevm/wagmi/pull/3979) [`70dd28669dd8d2ce08217cd02e29a8fbba7a08d4`](https://github.com/wevm/wagmi/commit/70dd28669dd8d2ce08217cd02e29a8fbba7a08d4) Thanks [@tmm](https://github.com/tmm)! - Fixed `walletConnect` connector. ## 5.0.4 ### Patch Changes - [#3972](https://github.com/wevm/wagmi/pull/3972) [`be9e1b8a9818b92eb0654a20d9471e9e39329e7e`](https://github.com/wevm/wagmi/commit/be9e1b8a9818b92eb0654a20d9471e9e39329e7e) Thanks [@nateReiners](https://github.com/nateReiners)! - Bumped Coinbase Wallet SDK. ## 5.0.3 ### Patch Changes - [#3962](https://github.com/wevm/wagmi/pull/3962) [`2804a8a583b1874271154898b4bae38756ef581c`](https://github.com/wevm/wagmi/commit/2804a8a583b1874271154898b4bae38756ef581c) Thanks [@tmm](https://github.com/tmm)! - Added timeout to `getInfo` called in `safe` connector since [non-Safe App iFrames cause it to not resolve](https://github.com/safe-global/safe-apps-sdk/issues/263#issuecomment-1029835840). - Updated dependencies [[`2804a8a583b1874271154898b4bae38756ef581c`](https://github.com/wevm/wagmi/commit/2804a8a583b1874271154898b4bae38756ef581c)]: - @wagmi/core@2.10.3 ## 5.0.2 ### Patch Changes - [#3940](https://github.com/wevm/wagmi/pull/3940) [`a5071f581dfdfb961718873643a2fc629101c72a`](https://github.com/wevm/wagmi/commit/a5071f581dfdfb961718873643a2fc629101c72a) Thanks [@jxom](https://github.com/jxom)! - Fixed usage of `metaMask` connector in Vite environments. - Updated dependencies [[`a5071f581dfdfb961718873643a2fc629101c72a`](https://github.com/wevm/wagmi/commit/a5071f581dfdfb961718873643a2fc629101c72a)]: - @wagmi/core@2.10.2 ## 5.0.1 ### Patch Changes - Bumped versions. - Updated dependencies []: - @wagmi/core@2.10.1 ## 5.0.0 ### Major Changes - [#3928](https://github.com/wevm/wagmi/pull/3928) [`3117e71825f9c58a0d718f3d1686f1a191fa9cb1`](https://github.com/wevm/wagmi/commit/3117e71825f9c58a0d718f3d1686f1a191fa9cb1) Thanks [@tmm](https://github.com/tmm)! - **Breaking:** Updated default Coinbase SDK in `coinbaseWallet` Connector to v4.x. Added a `version` property (defaults to `'4'`) to the `coinbaseWallet` Connector to target a version of the Coinbase SDK: ```diff coinbaseWallet({ + version: '3' | '4', }) ``` If `headlessMode` property is set to `true`, then the Connector will target v3 of the Coinbase SDK. The following properties are removed in v4 of the `coinbaseWallet` Connector: - `chainId` - `darkMode` - `diagnosticLogger` - `enableMobileDeepLink` - `jsonRpcUrl` - `linkApiUrl` - `overrideIsCoinbaseBrowser` - `overrideIsCoinbaseWallet` - `overrideIsMetaMask` - `reloadOnDisconnect` - `uiConstructor` Consumers can still use the above properties in v3 by passing `version: '3'` to the Connector. However, please note that v3 of the Coinbase SDK is deprecated and will be removed in a future release. ### Patch Changes - Updated dependencies [[`3117e71825f9c58a0d718f3d1686f1a191fa9cb1`](https://github.com/wevm/wagmi/commit/3117e71825f9c58a0d718f3d1686f1a191fa9cb1)]: - @wagmi/core@2.10.0 ## 4.3.10 ### Patch Changes - [#3906](https://github.com/wevm/wagmi/pull/3906) [`32fcb4a31dde6b0206961d8ffe9c651f8a459c67`](https://github.com/wevm/wagmi/commit/32fcb4a31dde6b0206961d8ffe9c651f8a459c67) Thanks [@tmm](https://github.com/tmm)! - Added support for Vue. - Updated dependencies [[`32fcb4a31dde6b0206961d8ffe9c651f8a459c67`](https://github.com/wevm/wagmi/commit/32fcb4a31dde6b0206961d8ffe9c651f8a459c67)]: - @wagmi/core@2.9.8 ## 4.3.9 ### Patch Changes - [#3924](https://github.com/wevm/wagmi/pull/3924) [`1f58734f88458e0f6adb05c99f0c90f36ab286b8`](https://github.com/wevm/wagmi/commit/1f58734f88458e0f6adb05c99f0c90f36ab286b8) Thanks [@jxom](https://github.com/jxom)! - Refactored `isChainsStale` logic in `walletConnect` connector. - Updated dependencies [[`1f58734f88458e0f6adb05c99f0c90f36ab286b8`](https://github.com/wevm/wagmi/commit/1f58734f88458e0f6adb05c99f0c90f36ab286b8)]: - @wagmi/core@2.9.7 ## 4.3.8 ### Patch Changes - [#3917](https://github.com/wevm/wagmi/pull/3917) [`05948fdad5bb4a56b08916d45b3dec2cb1e5f55b`](https://github.com/wevm/wagmi/commit/05948fdad5bb4a56b08916d45b3dec2cb1e5f55b) Thanks [@jxom](https://github.com/jxom)! - Updated `@metamask/sdk`. - Updated dependencies [[`05948fdad5bb4a56b08916d45b3dec2cb1e5f55b`](https://github.com/wevm/wagmi/commit/05948fdad5bb4a56b08916d45b3dec2cb1e5f55b)]: - @wagmi/core@2.9.6 ## 4.3.7 ### Patch Changes - Updated dependencies [[`4fecbbb66d0aacd03b8c62a6455d11a33cde8f85`](https://github.com/wevm/wagmi/commit/4fecbbb66d0aacd03b8c62a6455d11a33cde8f85)]: - @wagmi/core@2.9.5 ## 4.3.6 ### Patch Changes - Updated dependencies [[`e6139a97c4b8804d734b1547b5e3921ce01fbe24`](https://github.com/wevm/wagmi/commit/e6139a97c4b8804d734b1547b5e3921ce01fbe24)]: - @wagmi/core@2.9.4 ## 4.3.5 ### Patch Changes - [#3904](https://github.com/wevm/wagmi/pull/3904) [`addca28ebc20f1a4367c35fe9ef786decff9c87e`](https://github.com/wevm/wagmi/commit/addca28ebc20f1a4367c35fe9ef786decff9c87e) Thanks [@jxom](https://github.com/jxom)! - Updated `@walletconnect/ethereum-provider`. - Updated dependencies [[`addca28ebc20f1a4367c35fe9ef786decff9c87e`](https://github.com/wevm/wagmi/commit/addca28ebc20f1a4367c35fe9ef786decff9c87e)]: - @wagmi/core@2.9.3 ## 4.3.4 ### Patch Changes - [#3902](https://github.com/wevm/wagmi/pull/3902) [`204b7b624612405500ec098fb9e35facd3f74ca4`](https://github.com/wevm/wagmi/commit/204b7b624612405500ec098fb9e35facd3f74ca4) Thanks [@jxom](https://github.com/jxom)! - Made third-party SDK imports type-only. - Updated dependencies [[`204b7b624612405500ec098fb9e35facd3f74ca4`](https://github.com/wevm/wagmi/commit/204b7b624612405500ec098fb9e35facd3f74ca4)]: - @wagmi/core@2.9.2 ## 4.3.3 ### Patch Changes - Updated dependencies [[`cda6a5d5`](https://github.com/wevm/wagmi/commit/cda6a5d56328330fbde050b4ef40b01c58d2519a)]: - @wagmi/core@2.9.1 ## 4.3.2 ### Patch Changes - Updated dependencies [[`017828fc`](https://github.com/wevm/wagmi/commit/017828fc027c7a84b54ea9d627e9389f4d60d6c2)]: - @wagmi/core@2.9.0 ## 4.3.1 ### Patch Changes - Updated dependencies [[`d4a78eb0`](https://github.com/wevm/wagmi/commit/d4a78eb07119d2e5617e52481ac7d6c6d1583ddc)]: - @wagmi/core@2.8.1 ## 4.3.0 ### Minor Changes - [#3868](https://github.com/wevm/wagmi/pull/3868) [`c2af20b8`](https://github.com/wevm/wagmi/commit/c2af20b88cf16970d087faaec10b463357a5836e) Thanks [@jxom](https://github.com/jxom)! - Added `supportsSimulation` property to connectors that indicates if the connector's wallet supports contract simulation. ### Patch Changes - Updated dependencies [[`0d141f17`](https://github.com/wevm/wagmi/commit/0d141f171d6ec44bcbfc9c876565b5e2fb8af6de), [`c2af20b8`](https://github.com/wevm/wagmi/commit/c2af20b88cf16970d087faaec10b463357a5836e)]: - @wagmi/core@2.8.0 ## 4.2.0 ### Minor Changes - [#3857](https://github.com/wevm/wagmi/pull/3857) [`d4274c03`](https://github.com/wevm/wagmi/commit/d4274c03a6af5f2d26d31432016ebc14950a330e) Thanks [@tmm](https://github.com/tmm)! - Added `addEthereumChainParameter` to `switchChain`-related methods. ### Patch Changes - Updated dependencies [[`d4274c03`](https://github.com/wevm/wagmi/commit/d4274c03a6af5f2d26d31432016ebc14950a330e), [`4781a405`](https://github.com/wevm/wagmi/commit/4781a4056d4ffc2c74f96a75429e9b2cd2417ad8), [`400c960b`](https://github.com/wevm/wagmi/commit/400c960b30d701c134850c695ae903a382c29b5b)]: - @wagmi/core@2.7.0 ## 4.1.28 ### Patch Changes - [`e3c832a1`](https://github.com/wevm/wagmi/commit/e3c832a12c301f9b0ee129d877b3101d220ba8b2) Thanks [@jxom](https://github.com/jxom)! - Fixed undefined `navigator` issue in MetaMask connector. - Updated dependencies [[`e3c832a1`](https://github.com/wevm/wagmi/commit/e3c832a12c301f9b0ee129d877b3101d220ba8b2)]: - @wagmi/core@2.6.19 ## 4.1.27 ### Patch Changes - [#3848](https://github.com/wevm/wagmi/pull/3848) [`dd40a41c`](https://github.com/wevm/wagmi/commit/dd40a41c526ab60a288aff2250ed8dba92a27b16) Thanks [@jxom](https://github.com/jxom)! - Updated MetaMask SDK. - Updated dependencies [[`dd40a41c`](https://github.com/wevm/wagmi/commit/dd40a41c526ab60a288aff2250ed8dba92a27b16)]: - @wagmi/core@2.6.18 ## 4.1.26 ### Patch Changes - Updated dependencies [[`a97bfbae`](https://github.com/wevm/wagmi/commit/a97bfbaeb615cfef04665e5e7348d85d17f960f0)]: - @wagmi/core@2.6.17 ## 4.1.25 ### Patch Changes - [#3788](https://github.com/wevm/wagmi/pull/3788) [`42ad380d`](https://github.com/wevm/wagmi/commit/42ad380d9a5d8bc0f61d73612142dea9d098de5e) Thanks [@tmm](https://github.com/tmm)! - Refactored connectors to remove unnecessarily event listeners. - Updated dependencies [[`42ad380d`](https://github.com/wevm/wagmi/commit/42ad380d9a5d8bc0f61d73612142dea9d098de5e)]: - @wagmi/core@2.6.16 ## 4.1.24 ### Patch Changes - Updated dependencies [[`b907d5ac`](https://github.com/wevm/wagmi/commit/b907d5ac3a746bcbccc06d1fe78c5bd8f9a7d685)]: - @wagmi/core@2.6.15 ## 4.1.23 ### Patch Changes - Updated dependencies [[`b3b54ef1`](https://github.com/wevm/wagmi/commit/b3b54ef179c5fa0d1694d38d4b808549a0550409), [`3da20bb8`](https://github.com/wevm/wagmi/commit/3da20bb80e7c3efeef8227ced66ad615370fc242), [`a3d1858f`](https://github.com/wevm/wagmi/commit/a3d1858fce448d2b70e36ee692ef1589b74e9d3f)]: - @wagmi/core@2.6.14 ## 4.1.22 ### Patch Changes - Updated dependencies [[`b80236dc`](https://github.com/wevm/wagmi/commit/b80236dc623095fe8f1e1d10957d7776fb6ab48b)]: - @wagmi/core@2.6.13 ## 4.1.21 ### Patch Changes - Updated dependencies [[`a59069e9`](https://github.com/wevm/wagmi/commit/a59069e9fab45dd606bb89a7f829fe94c51a5494), [`0acd3132`](https://github.com/wevm/wagmi/commit/0acd31320f534993af566be5490c2978b6184f66)]: - @wagmi/core@2.6.12 ## 4.1.20 ### Patch Changes - [`e1ca4e63`](https://github.com/wevm/wagmi/commit/e1ca4e637ae6cec7f5902b0a2c0e0efc3b751a1d) Thanks [@tmm](https://github.com/tmm)! - Deprecated `normalizeChainId`. Use `Number` instead. - Updated dependencies [[`e1ca4e63`](https://github.com/wevm/wagmi/commit/e1ca4e637ae6cec7f5902b0a2c0e0efc3b751a1d)]: - @wagmi/core@2.6.11 ## 4.1.19 ### Patch Changes - Updated dependencies [[`dbdca8fd`](https://github.com/wevm/wagmi/commit/dbdca8fd14b90c166222a66a373c1b33c06ce019)]: - @wagmi/core@2.6.10 ## 4.1.18 ### Patch Changes - Updated dependencies [[`d56edf4f`](https://github.com/wevm/wagmi/commit/d56edf4f27c52acc7a0f57114454b0d3e22cacd6)]: - @wagmi/core@2.6.9 ## 4.1.17 ### Patch Changes - Updated dependencies [[`e46bcd47`](https://github.com/wevm/wagmi/commit/e46bcd4738a18da15b53f6612b614379c1985374)]: - @wagmi/core@2.6.8 ## 4.1.16 ### Patch Changes - [`1c1fee6a`](https://github.com/wevm/wagmi/commit/1c1fee6ab8f01f7734ac6ce05093fa8e388beb3e) Thanks [@jxom](https://github.com/jxom)! - Updated `@walletconnect/ethereum-provider`. - [#3653](https://github.com/wevm/wagmi/pull/3653) [`88a2d744`](https://github.com/wevm/wagmi/commit/88a2d744a1315908c9e54156026df3ad2435ad44) Thanks [@tash-2s](https://github.com/tash-2s)! - Fixed error occurring when adding chains without explorers to MetaMask. - Updated dependencies [[`b479b5e8`](https://github.com/wevm/wagmi/commit/b479b5e8a5866cba792862f22e6352c4fb566137), [`f5648dd2`](https://github.com/wevm/wagmi/commit/f5648dd28b3576b628f57732b89287f55acbb1c1), [`1c1fee6a`](https://github.com/wevm/wagmi/commit/1c1fee6ab8f01f7734ac6ce05093fa8e388beb3e), [`88a2d744`](https://github.com/wevm/wagmi/commit/88a2d744a1315908c9e54156026df3ad2435ad44)]: - @wagmi/core@2.6.7 ## 4.1.15 ### Patch Changes - Updated dependencies [[`a91c0b64`](https://github.com/wevm/wagmi/commit/a91c0b64ba8b3e6537a560e69724eb601f26af27)]: - @wagmi/core@2.6.6 ## 4.1.14 ### Patch Changes - [#3591](https://github.com/wevm/wagmi/pull/3591) [`ca5decdb`](https://github.com/wevm/wagmi/commit/ca5decdb712f81e3f5dab933a94b967bca5b6af4) Thanks [@tmm](https://github.com/tmm)! - Fixed Coinbase Wallet import. - Updated dependencies [[`c677dcd2`](https://github.com/wevm/wagmi/commit/c677dcd245dccdf69289a3d66dded237b09570a2)]: - @wagmi/core@2.6.5 ## 4.1.13 ### Patch Changes - [#3569](https://github.com/wevm/wagmi/pull/3569) [`fa25b448`](https://github.com/wevm/wagmi/commit/fa25b4482504b4d9729a5687ea6d6dc959265bc0) Thanks [@svenvoskamp](https://github.com/svenvoskamp)! - Updated dependencies. - [#3558](https://github.com/wevm/wagmi/pull/3558) [`895f28e8`](https://github.com/wevm/wagmi/commit/895f28e873af7c8eda5ca85734ff67c8979fd950) Thanks [@tmm](https://github.com/tmm)! - Fixed connector warnings. - Updated dependencies [[`7c6618e6`](https://github.com/wevm/wagmi/commit/7c6618e6a0eb1ff39cf8f66b34d3ddc14be538fe), [`895f28e8`](https://github.com/wevm/wagmi/commit/895f28e873af7c8eda5ca85734ff67c8979fd950)]: - @wagmi/core@2.6.4 ## 4.1.12 ### Patch Changes - Updated dependencies [[`9c3b85dd`](https://github.com/wevm/wagmi/commit/9c3b85dd0a9a4a593e1d7e029345275735330e32), [`2a72214a`](https://github.com/wevm/wagmi/commit/2a72214a2901d6b6ddd39f80238aa0bd4db670a7)]: - @wagmi/core@2.6.3 ## 4.1.11 ### Patch Changes - [#3518](https://github.com/wevm/wagmi/pull/3518) [`338e857d`](https://github.com/wevm/wagmi/commit/338e857d8cb2fe85e13d9207bef14cada1c1962d) Thanks [@tmm](https://github.com/tmm)! - Bumped dependencies. - Updated dependencies [[`414eb048`](https://github.com/wevm/wagmi/commit/414eb048af492caac70c0e874dfc87c30702804a), [`338e857d`](https://github.com/wevm/wagmi/commit/338e857d8cb2fe85e13d9207bef14cada1c1962d)]: - @wagmi/core@2.6.2 ## 4.1.10 ### Patch Changes - [#3510](https://github.com/wevm/wagmi/pull/3510) [`660ff80d`](https://github.com/wevm/wagmi/commit/660ff80d5b046967a446eba43ee54b8359a37d0d) Thanks [@tmm](https://github.com/tmm)! - Fixed issue where connectors returning multiple addresses didn't checksum correctly. - Updated dependencies [[`660ff80d`](https://github.com/wevm/wagmi/commit/660ff80d5b046967a446eba43ee54b8359a37d0d), [`101a7dd1`](https://github.com/wevm/wagmi/commit/101a7dd131b0cae2dc25579ecab9044290efd37b)]: - @wagmi/core@2.6.1 ## 4.1.9 ### Patch Changes - [#3496](https://github.com/wevm/wagmi/pull/3496) [`ba7f8a75`](https://github.com/wevm/wagmi/commit/ba7f8a758efb07664c6e401b5e7e325e7c62341b) Thanks [@tmm](https://github.com/tmm)! - Bumped dependencies. - Updated dependencies [[`ba7f8a75`](https://github.com/wevm/wagmi/commit/ba7f8a758efb07664c6e401b5e7e325e7c62341b)]: - @wagmi/core@2.6.0 ## 4.1.8 ### Patch Changes - Updated dependencies [[`ca98041d`](https://github.com/wevm/wagmi/commit/ca98041d1b39893d90246929485f4db0d1c6f9f7)]: - @wagmi/core@2.5.0 ## 4.1.7 ### Patch Changes - [#3427](https://github.com/wevm/wagmi/pull/3427) [`370f1b4a`](https://github.com/wevm/wagmi/commit/370f1b4a3f154d181acf381c31c2e7862e22c0e4) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Bumped dependencies. - Updated dependencies [[`370f1b4a`](https://github.com/wevm/wagmi/commit/370f1b4a3f154d181acf381c31c2e7862e22c0e4)]: - @wagmi/core@2.4.0 ## 4.1.6 ### Patch Changes - Updated dependencies [[`3be5bb7b`](https://github.com/wevm/wagmi/commit/3be5bb7b0b38646e12e6da5c762ef74dff66bcc2)]: - @wagmi/core@2.3.1 ## 4.1.5 ### Patch Changes - [#3459](https://github.com/wevm/wagmi/pull/3459) [`d950b666`](https://github.com/wevm/wagmi/commit/d950b666b56700ca039ce16cdfdf34564991e7f5) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Bumped dependencies - [`1cfb6e5a`](https://github.com/wevm/wagmi/commit/1cfb6e5a875e707abcee00dd5739e87da05e8c90) Thanks [@jxom](https://github.com/jxom)! - Bumped listener limit on WalletConnect connector. - Updated dependencies [[`d950b666`](https://github.com/wevm/wagmi/commit/d950b666b56700ca039ce16cdfdf34564991e7f5), [`90ef39bb`](https://github.com/wevm/wagmi/commit/90ef39bb0f4ecb3c914d317875348e35ba0f4524), [`1cfb6e5a`](https://github.com/wevm/wagmi/commit/1cfb6e5a875e707abcee00dd5739e87da05e8c90)]: - @wagmi/core@2.3.0 ## 4.1.4 ### Patch Changes - [#3443](https://github.com/wevm/wagmi/pull/3443) [`007024a6`](https://github.com/wevm/wagmi/commit/007024a684ddbecf924cdc06dd6a8854fc3d5eeb) Thanks [@jmrossy](https://github.com/jmrossy)! - Bumped dependencies. - [#3447](https://github.com/wevm/wagmi/pull/3447) [`a02a26ad`](https://github.com/wevm/wagmi/commit/a02a26ad030d3afb78f744377d61b5c60b65d97a) Thanks [@tmm](https://github.com/tmm)! - Bumped dependencies. - Updated dependencies [[`a02a26ad`](https://github.com/wevm/wagmi/commit/a02a26ad030d3afb78f744377d61b5c60b65d97a), [`007024a6`](https://github.com/wevm/wagmi/commit/007024a684ddbecf924cdc06dd6a8854fc3d5eeb)]: - @wagmi/core@2.2.1 ## 4.1.3 ### Patch Changes - Updated dependencies [[`00bf10a4`](https://github.com/wevm/wagmi/commit/00bf10a428b0d1c5dac35ebf25b19571e033ac26), [`64c073f6`](https://github.com/wevm/wagmi/commit/64c073f6c2720961e2d6aff986670b73dbfab9c3), [`fb6c4148`](https://github.com/wevm/wagmi/commit/fb6c4148d9e9e2fccfbe74c8f343b444dc68dec5)]: - @wagmi/core@2.2.0 ## 4.1.2 ### Patch Changes - Updated dependencies [[`e00b8205`](https://github.com/wevm/wagmi/commit/e00b82058685751637edfa9a6b2d196a12549fe7)]: - @wagmi/core@2.1.2 ## 4.1.1 ### Patch Changes - [`ec0d8b41`](https://github.com/wevm/wagmi/commit/ec0d8b4112181fefb11025e436a94a6114761d37) Thanks [@tmm](https://github.com/tmm)! - Added note to `metaMask` connector. - Updated dependencies [[`64b82282`](https://github.com/wevm/wagmi/commit/64b82282c1e57e77c25aa0814673780e4d11edd4), [`ec0d8b41`](https://github.com/wevm/wagmi/commit/ec0d8b4112181fefb11025e436a94a6114761d37)]: - @wagmi/core@2.1.1 ## 4.1.0 ### Minor Changes - Updated dependencies [[`c9cd302e`](https://github.com/wevm/wagmi/commit/c9cd302e1c65c980deaee2e12567c2a8ec08b399)]: - @wagmi/core@2.1.0 ## 4.0.2 ### Patch Changes - [#3384](https://github.com/wevm/wagmi/pull/3384) [`ee868c33`](https://github.com/wevm/wagmi/commit/ee868c3385dae511230b6ddcb5627c1293cc1844) Thanks [@tmm](https://github.com/tmm)! - Fixed connectors not bubbling error when connecting with `chainId` and subsequent user rejection. - Updated dependencies [[`ee868c33`](https://github.com/wevm/wagmi/commit/ee868c3385dae511230b6ddcb5627c1293cc1844)]: - @wagmi/core@2.0.2 ## 4.0.1 ### Major Changes - [#3333](https://github.com/wevm/wagmi/pull/3333) [`b3a0baaa`](https://github.com/wevm/wagmi/commit/b3a0baaaee7decf750d376aab2502cd33ca4825a) Thanks [@tmm](https://github.com/tmm)! - Added support for Wagmi 2.0. ### Patch Changes - Updated dependencies [[`b3a0baaa`](https://github.com/wevm/wagmi/commit/b3a0baaaee7decf750d376aab2502cd33ca4825a)]: - @wagmi/core@2.0.0 ## 3.1.11 ### Patch Changes - [#3361](https://github.com/wevm/wagmi/pull/3361) [`bbbbf587`](https://github.com/wevm/wagmi/commit/bbbbf587e41bae12b072b7a7c897d580fc07cd2b) Thanks [@0xAsimetriq](https://github.com/0xAsimetriq)! - Updated WalletConnect connector dependencies ## 3.1.10 ### Patch Changes - [`53ca1f7e`](https://github.com/wevm/wagmi/commit/53ca1f7eb411d912e11fcce7e03bd61ed067959c) Thanks [@tmm](https://github.com/tmm)! - Removed LedgerConnector due to security vulnerability ## 3.1.9 ### Patch Changes - [#3114](https://github.com/wevm/wagmi/pull/3114) [`51eca0fb`](https://github.com/wevm/wagmi/commit/51eca0fbaea6932f31a5b8b4213f0252280053e2) Thanks [@akathecoder](https://github.com/akathecoder)! - Added Okto Wallet to Injected Wallets Connector - [#3299](https://github.com/wevm/wagmi/pull/3299) [`b02020b3`](https://github.com/wevm/wagmi/commit/b02020b3724e0228198f35817611bb063295906e) Thanks [@dasanra](https://github.com/dasanra)! - Fixed issue with [Safe SDK](https://github.com/wevm/viem/issues/579) by bumping `@safe-global/safe-apps-provider@0.18.1` ## 3.1.8 ### Patch Changes - [#3197](https://github.com/wevm/wagmi/pull/3197) [`e8f7bcbc`](https://github.com/wevm/wagmi/commit/e8f7bcbcd9c038a901c29e71769682c088efe2ac) Thanks [@ByteZhang1024](https://github.com/ByteZhang1024)! - Added OneKey Wallet to injected connector flags. ## 3.1.7 ### Patch Changes - [#3276](https://github.com/wevm/wagmi/pull/3276) [`83223a06`](https://github.com/wevm/wagmi/commit/83223a0659e2f675d897a1d3374c7af752c16abf) Thanks [@glitch-txs](https://github.com/glitch-txs)! - Removed required namespaces from WalletConnect connector ## 3.1.6 ### Patch Changes - [#3236](https://github.com/wevm/wagmi/pull/3236) [`cc7e18f2`](https://github.com/wevm/wagmi/commit/cc7e18f2e7f6b8b989f60f0b05aee70e996a9975) Thanks [@0xAsimetriq](https://github.com/0xAsimetriq)! - Updated @walletconnect/ethereum-provider - [#3236](https://github.com/wevm/wagmi/pull/3236) [`cc7e18f2`](https://github.com/wevm/wagmi/commit/cc7e18f2e7f6b8b989f60f0b05aee70e996a9975) Thanks [@0xAsimetriq](https://github.com/0xAsimetriq)! - Updated @walletconnect/ethereum-provider ## 3.1.5 ### Patch Changes - [#3220](https://github.com/wagmi-dev/wagmi/pull/3220) [`a1950449`](https://github.com/wagmi-dev/wagmi/commit/a1950449127ddf72fff8ecd1fc34c3690befbb05) Thanks [@rkalis](https://github.com/rkalis)! - Fixed a bug where injected walets with an empty providers array could not connect ## 3.1.4 ### Patch Changes - [#3115](https://github.com/wagmi-dev/wagmi/pull/3115) [`4e6ec415`](https://github.com/wagmi-dev/wagmi/commit/4e6ec4151baece94e940e227e0e3711c7f8534d9) Thanks [@bifot](https://github.com/bifot)! - Added SafePal injected name mapping. ## 3.1.3 ### Patch Changes - [#3141](https://github.com/wagmi-dev/wagmi/pull/3141) [`e78aa337`](https://github.com/wagmi-dev/wagmi/commit/e78aa337c454f04b41a3cbd381d25270dd4a0afd) Thanks [@einaralex](https://github.com/einaralex)! - Updated WalletConnect libraries. ## 3.1.2 ### Patch Changes - [#3009](https://github.com/wagmi-dev/wagmi/pull/3009) [`3aaba328`](https://github.com/wagmi-dev/wagmi/commit/3aaba32808ddb4035ec885f96992c91078056715) Thanks [@0xAsimetriq](https://github.com/0xAsimetriq)! - Update WalletConnect dependencies ## 3.1.1 ### Patch Changes - [#2973](https://github.com/wevm/wagmi/pull/2973) [`bf831bb3`](https://github.com/wevm/wagmi/commit/bf831bb30df8037cc4312342d0fe3c045408c2fe) Thanks [@masm](https://github.com/masm)! - Added Zeal wallet ## 3.1.0 ### Minor Changes - [#2956](https://github.com/wevm/wagmi/pull/2956) [`2abeb285`](https://github.com/wevm/wagmi/commit/2abeb285674af3e539cc2550b1f5027b1eb0c895) Thanks [@tmm](https://github.com/tmm)! - Replaced `@wagmi/chains` with `viem/chains`. ## 3.0.0 ### Patch Changes - 0306383: Updated WalletConnect dependencies - Updated dependencies [d1ef9b4] - Updated dependencies [484c846] - @wagmi/chains@1.8.0 ## 2.7.0 ### Minor Changes - a270cb9: Updated WalletConnect dependencies. ### Patch Changes - 06cc1b4: Add SubWallet injected flags - 131a337: Added Desig Wallet name mapping. - e089d7d: Added Fordefi Wallet name mapping. - ce84d0a: Added Coin98 Wallet injected flags. - Updated dependencies [8fdacd8] - Updated dependencies [2e9283a] - Updated dependencies [a432a2b] - Updated dependencies [408740a] - Updated dependencies [6794a61] - Updated dependencies [0c5a32b] - Updated dependencies [ebc85ec] - Updated dependencies [5683df2] - Updated dependencies [414ff36] - Updated dependencies [4f514c6] - Updated dependencies [1cf72bc] - Updated dependencies [cd68471] - Updated dependencies [baf3143] - Updated dependencies [9737f24] - Updated dependencies [7797238] - Updated dependencies [3846811] - Updated dependencies [0ea344c] - @wagmi/chains@1.7.0 ## 2.6.6 ### Patch Changes - 56c127d: Updated WalletConnect dependencies. - Updated dependencies [4b411d2] - Updated dependencies [df697ac] - Updated dependencies [186f5a7] - Updated dependencies [a96b514] - Updated dependencies [0a6e6da] - @wagmi/chains@1.5.0 ## 2.6.5 ### Patch Changes - 51e346e: Updated WalletConnectConnector logic to handle individual namespaces like eip155:\* ## 2.6.4 ### Patch Changes - 0a57de2: Added conditional for WalletConnectConnector optionalChains ## 2.6.3 ### Patch Changes - f2d532d: Updated WalletConnect dependencies, exposed `relayUrl` option for `WalletConnectConnector` - ff53857: Fixed issue importing `EthereumProvider` in Vite environments. - Updated dependencies [d642e1d] - Updated dependencies [3027d7b] - Updated dependencies [97dbd44] - @wagmi/chains@1.4.0 ## 2.6.2 ### Patch Changes - 27bb1b3: Added explicit type annotations for the `getWalletClient()` method. ## 2.6.1 ### Patch Changes - a3507a9: Updated @walletconnect/ethereum-provider dependency ## 2.6.0 ### Minor Changes - 32dc317: Updated @walletconnect/ethereum-provider and @walletconnect/modal dependencies ## 2.5.0 ### Minor Changes - 57e674e: Updated `@safe-global/safe-apps-sdk` & `@safe-global/safe-apps-provider` ## 2.4.0 ### Patch Changes - f21c8e0: Added WalletConnect v2 support to Ledger connector. - 27482bb: Add HAQQ Wallet detection - 7d6aa43: Exported `normalizeChainId`. - Updated dependencies [62b8209] - Updated dependencies [106ac13] - Updated dependencies [8b3f5e5] - @wagmi/chains@1.3.0 ## 2.3.0 ### Minor Changes - 28219ae: Added metadata property to WalletConnect init function - 6fef949: Updated @walletconnect/modal and @walletconnect/ethereum-provider deps ### Patch Changes - 72f6465: Added `TTWallet` to `getInjectedName` list - Updated dependencies [a7cbd04] - Updated dependencies [f6ee133] - @wagmi/chains@1.2.0 ## 2.2.0 ### Minor Changes - 6c841d4: Changed `Address` type import from ABIType to viem. ### Patch Changes - 09c83f8: Update @walletconnect/ethereum-provider, Replace @web3modal/standalone with @walletconnect/modal, Fix issue with wallet_addEthereumChain method in WalletConnectConnector ## 2.1.1 ### Patch Changes - c24de75: Updated `@walletconnect/ethereum-provider` and `@web3modal/standalone` dependencies. - 605c422: Bumped `viem` peer dependency. - dc1c546: Throw ResourceUnavailableError on -30002 errors. ## 2.1.0 ### Minor Changes - b001569: Bumped minimum TypeScript version to v5.0.4. ### Patch Changes - 0f05b2b: Updated `abitype` to `0.8.7`. - 6aea7ee: Fixed internal types. - b187cb0: Added `isNovaWallet` injected flag. - 5e44429: Added Edgeware mainnet and testnet - b18b314: Updated @walletconnect/ethereum-provider and @web3modal/standalone dependencies - Updated dependencies [b62a199] - Updated dependencies [b001569] - Updated dependencies [260ab59] - Updated dependencies [6aea7ee] - Updated dependencies [5e44429] - @wagmi/chains@1.0.0 ## 2.0.0 ### Patch Changes - Updated dependencies [36c14b2] - @wagmi/chains@0.3.0 ## 1.0.5 ### Patch Changes - fa61dfe: Updated viem. - Updated dependencies [577d2a0] - @wagmi/chains@0.2.25 ## 1.0.4 ### Patch Changes - bbbd11b: Corrected Rabby Wallet name - Updated dependencies [0639a1f] - @wagmi/chains@0.2.24 ## 1.0.3 ### Patch Changes - 64dfe61: Update @web3modal/standalone to v2.4.1, Update @walletconnect/ethereum-provider to 2.7.4 - bab7ad8: Added Defiant to injected connector flags - 44cde07: Added Talisman wallet flag ## 1.0.2 ### Patch Changes - bce5a0c: Removed chain fallback when instantiating a Wallet Client. ## 1.0.1 ### Patch Changes - [`ea651cd7`](https://github.com/wevm/wagmi/commit/ea651cd7fc75b7866272605467db11fd6e1d81af) Thanks [@jxom](https://github.com/jxom)! - Downgraded abitype. ## 1.0.0 ### Major Changes - 7e274f5: Released v1. ### Patch Changes - 0966bf7: Changed Kucoin Wallet name mapping to Halo Wallet ## 1.0.0-next.5 ### Major Changes - Updated references. ## 1.0.0-next.4 ### Major Changes - Updated references. ## 1.0.0-next.3 ### Patch Changes - Updated dependencies []: - @wagmi/chains@1.0.0-next.0 ## 1.0.0-next.2 ### Major Changes - updated viem ## 1.0.0-next.1 ### Major Changes - [`a7dda00c`](https://github.com/wevm/wagmi/commit/a7dda00c5b546f8b2c42b527e4d9ac1b9e9ab1fb) Thanks [@jxom](https://github.com/jxom)! - Released v1. ## 1.0.0-next.0 ### Major Changes - 33488cf: Released v1. ## 0.3.19 ### Patch Changes - 274eef3: - Updated @web3modal/standalone to 2.3.7 - Updated @walletconnect/ethereum-provider to 2.7.1 - 41697df: Updated @walletconnect/ethereum-provider version to 2.7.2 - 82dcb72: Added Enkrypt extension detection ## 0.3.18 ### Patch Changes - f66e065: Added BlockWallet to injected connector flags. ## 0.3.17 ### Patch Changes - 12ab5d1: Updated @coinbase/wallet-sdk to 3.6.6 ## 0.3.16 ### Patch Changes - c1e3ddf: Reverted ABIType version change. ## 0.3.15 ### Patch Changes - d4825e6: Fixed ABIType version to match downstream packages. ## 0.3.14 ### Patch Changes - c25ac82: Added more flags to `MetaMaskConnector` `getProvider` check. - b19a932: Updated @web3modal/standalone to 2.3.0, @walletconnect/ethereum-provider to 2.7.0 - cdc387e: Added `ImToken` to `getInjectedName` list ## 0.3.13 ### Patch Changes - 2a21d27: Updated `@coinbase/wallet-sdk` to `3.6.4` ## 0.3.12 ### Patch Changes - 9bb22b6: Updated `@walletconnect/ethereum-provider` to `2.6.2`, relaxed `@web3modal/standalone` version requirement - 0d7625b: Added Rabby to injected connector flags - f63d7fd: Added correct error to switch network cause. ## 0.3.11 ### Patch Changes - 0778abc: Renamed `isTally` injected provider to `Taho` ## 0.3.10 ### Patch Changes - 4267020: Added `qrModalOptions` option to `WalletConnectConnector` - e78fb0a: Pinned WalletConnect dependencies ## 0.3.9 ### Patch Changes - 5cd0afc: Added `isZerion` to `InjectedProviderFlags` and `getInjectedName` - be4825e: Added GameStop Wallet to injected connector flags ## 0.3.8 ### Patch Changes - 11f3fe2: Fixed issue where `UNSTABLE_shimOnConnectSelectAccount` would not bubble up error for MetaMask if request to connect was already active. ## 0.3.7 ### Patch Changes - 04c0e47: Fixed issue switching chain after adding to MetaMask. ## 0.3.6 ### Patch Changes - 85330c1: Removed `InjectedConnector` `shimChainChangedDisconnect` shim (no longer necessary). ## 0.3.5 ### Patch Changes - 8b1a526: Added Dawn wallet flag ## 0.3.4 ### Patch Changes - 6b15d6f: Updated `@walletconnect/ethereum-provider` to `2.5.1`. - 1f452e7: Added OKX Wallet to injected connector flags. - a4d9083: Added Backpack wallet to injected connector flags. - 6a4af48: Enabled support for programmatic chain switching on `LedgerConnector` & added `"ledger"` to the switch chain regex on `WalletConnectLegacyConnector`. ## 0.3.3 ### Patch Changes - f24ce0c: Updated @walletconnect/ethereum-provider to 2.4.8 - e3a3fee: Added "uniswap wallet" to the regex that determines wallets allowed to switch chains in the WalletConnect legacy connector - 641af48: Added name mapping for Bifrost Wallet - 4d2c90a: Added name mapping for Phantom - 3d276d0: Added Status as the name of the injected connector for the Status App ## 0.3.2 ### Patch Changes - 13a6a07: Updated `@walletconnect/ethereum-provider` to `2.4.7`. ## 0.3.1 ### Patch Changes - a23c40f: Added name mapping for [Frontier](https://frontier.xyz) Wallet - d779fb3: Added name mapping for HyperPay. ## 0.3.0 ### Minor Changes - c4d5bb5: **Breaking:** Removed the `version` config option for `WalletConnectConnector`. `WalletConnectConnector` now uses WalletConnect v2 by default. WalletConnect v1 is now `WalletConnectLegacyConnector`. ### WalletConnect v2 ```diff import { WalletConnectConnector } from '@wagmi/connectors/walletConnect' const connector = new WalletConnectConnector({ options: { - version: '2', projectId: 'abc', }, }) ``` ### WalletConnect v1 ```diff -import { WalletConnectConnector } from '@wagmi/connectors/walletConnect' +import { WalletConnectLegacyConnector } from '@wagmi/connectors/walletConnectLegacy' -const connector = new WalletConnectConnector({ +const connector = new WalletConnectLegacyConnector({ options: { qrcode: true, }, }) ``` ## 0.2.7 ### Patch Changes - 57f1226: Added name mapping for XDEFI ## 0.2.6 ### Patch Changes - bb1b88c: Added name mapping for Bitski injected wallet - fcb5595: Fixed shim disconnect key to read from defined Connector ID. - 49f8853: Fixed `SafeConnector` import type error that existed for specific build environments. ## 0.2.5 ### Patch Changes - 5d121f2: Added `isApexWallet` to injected `window.ethereum` flags. - e3566eb: Updated `@web3modal/standalone` to `2.1.1` for WalletConnectConnector. ## 0.2.4 ### Patch Changes - a4f31bc: Added Connector for [Safe](https://safe.global) wallet - d5e25d9: Locked ethers peer dependency version to >=5.5.1 <6 ## 0.2.3 ### Patch Changes - 6fa74dd: Updated `@walletconnect/universal-provider` Added more signable methods to WC v2. ## 0.2.2 ### Patch Changes - 6b0725b: Fixed race condition between `switchNetwork` and mutation Hooks that use `chainId` (e.g. `sendTransaction`). ## 0.2.1 ### Patch Changes - 942fcde: Updated `@walletconnect/universal-provider` and `@web3modal/standalone` packages for WalletConnectConnector (v2). Improved initialization flow for `@walletconnect/universal-provider` for WalletConnectConnector (v2). ## 0.2.0 ### Minor Changes - be33c7d: Chains are now narrowed to their most specific type using the TypeScript [`satisfies`](https://devblogs.microsoft.com/typescript/announcing-typescript-4-9/#the-satisfies-operator) operator. ## 0.1.10 ### Patch Changes - d75e8d2: Fixed ABIType version mismatch between packages. ## 0.1.9 ### Patch Changes - 8c3fc00: Added public RPC URL to Connector fallback chains ## 0.1.8 ### Patch Changes - 5e6dc30: Replaced legacy qrcodemodal with web3modal for WalletConnect v2. ## 0.1.7 ### Patch Changes - be4add2: Added `isRainbow` flag to `InjectedConnector`. ## 0.1.6 ### Patch Changes - 3dfc558: Add `switchSigner` method to `MockProvider`. ## 0.1.5 ### Patch Changes - 7dce4b5: Bumped WalletConnect Universal Provider version. ## 0.1.4 ### Patch Changes - 4cec598: Added CJS escape hatch bundle under the "cjs" tag. ## 0.1.3 ### Patch Changes - 822bc88: The `WalletConnectConnector` now supports WalletConnect v2. It can be enabled by setting `version` to `'2'` and supplying a [WalletConnect Cloud `projectId`](https://cloud.walletconnect.com/sign-in). ## 0.1.2 ### Patch Changes - 5e5f37f: Fixed issue where connecting to MetaMask may return with a stale address ## 0.1.1 ### Patch Changes - 919790c: Updated `@ledgerhq/connect-kit-loader` to `1.0.1` ## 0.1.0 ### Minor Changes - 5db7cba: Added `LedgerConnector` - 55a0ca2: Initial release of the `@wagmi/connectors` package – a collection of Connectors for wagmi. ================================================ FILE: packages/connectors/README.md ================================================ # @wagmi/connectors Collection of connectors for Wagmi ## Installation ```bash pnpm add @wagmi/connectors @wagmi/core viem ``` ## Documentation For documentation and guides, visit [wagmi.sh](https://wagmi.sh). ================================================ FILE: packages/connectors/package.json ================================================ { "name": "@wagmi/connectors", "description": "Collection of connectors for Wagmi", "version": "7.2.1", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/wevm/wagmi.git", "directory": "packages/connectors" }, "scripts": { "build": "pnpm run build:esm+types", "build:esm+types": "tsc --project tsconfig.build.json --outDir ./dist/esm --declaration --declarationMap --declarationDir ./dist/types", "check:types": "tsc --noEmit", "clean": "rm -rf dist tsconfig.tsbuildinfo", "test:build": "publint --strict && attw --pack --ignore-rules cjs-resolves-to-esm" }, "files": [ "dist/**", "!dist/**/*.tsbuildinfo", "src/**/*.ts", "!src/**/*.test.ts", "!src/**/*.test-d.ts" ], "sideEffects": false, "type": "module", "main": "./dist/esm/exports/index.js", "types": "./dist/types/exports/index.d.ts", "typings": "./dist/types/exports/index.d.ts", "exports": { ".": { "types": "./dist/types/exports/index.d.ts", "default": "./dist/esm/exports/index.js" }, "./package.json": "./package.json" }, "peerDependencies": { "@base-org/account": "^2.5.1", "@coinbase/wallet-sdk": "^4.3.6", "@metamask/connect-evm": "~0.9.0", "@safe-global/safe-apps-provider": "~0.18.6", "@safe-global/safe-apps-sdk": "^9.1.0", "@wagmi/core": "workspace:*", "@walletconnect/ethereum-provider": "^2.21.1", "porto": "~0.2.35", "typescript": ">=5.7.3", "viem": "2.x" }, "peerDependenciesMeta": { "@base-org/account": { "optional": true }, "@coinbase/wallet-sdk": { "optional": true }, "@metamask/connect-evm": { "optional": true }, "@safe-global/safe-apps-provider": { "optional": true }, "@safe-global/safe-apps-sdk": { "optional": true }, "@walletconnect/ethereum-provider": { "optional": true }, "porto": { "optional": true }, "typescript": { "optional": true } }, "devDependencies": { "@base-org/account": "catalog:", "@coinbase/wallet-sdk": "catalog:", "@metamask/connect-evm": "catalog:", "@safe-global/safe-apps-provider": "catalog:", "@safe-global/safe-apps-sdk": "catalog:", "@wagmi/core": "workspace:*", "@walletconnect/ethereum-provider": "catalog:", "msw": "^2.4.9", "porto": "catalog:" }, "contributors": [ "awkweb.eth ", "jxom.eth " ], "funding": "https://github.com/sponsors/wevm", "keywords": [ "react", "hooks", "eth", "ethereum", "dapps", "wallet", "web3", "abi" ] } ================================================ FILE: packages/connectors/src/baseAccount.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { baseAccount } from './baseAccount.js' test('setup', () => { const connectorFn = baseAccount({ appName: 'wagmi' }) const connector = config._internal.connectors.setup(connectorFn) expect(connector.name).toEqual('Base Account') }) ================================================ FILE: packages/connectors/src/baseAccount.ts ================================================ import type { createBaseAccountSDK, ProviderInterface } from '@base-org/account' import { ChainNotConfiguredError, type Connector, createConnector, } from '@wagmi/core' import type { Mutable, Omit } from '@wagmi/core/internal' import { type AddEthereumChainParameter, type Address, getAddress, type Hex, numberToHex, type ProviderRpcError, SwitchChainError, UserRejectedRequestError, } from 'viem' export type BaseAccountParameters = Mutable< Omit< Parameters[0], 'appChainIds' // set via wagmi config > > export function baseAccount(parameters: BaseAccountParameters = {}) { type Provider = ProviderInterface type Properties = { connect(parameters?: { chainId?: number | undefined capabilities?: | { signInWithEthereum?: { chainId?: string | undefined domain?: string | undefined expirationTime?: string | undefined issuedAt?: string | undefined nonce: string notBefore?: string | undefined requestId?: string | undefined resources?: string[] | undefined scheme?: string | undefined statement?: string | undefined uri?: string | undefined version?: string | undefined } [capability: string]: any } | undefined isReconnecting?: boolean | undefined withCapabilities?: withCapabilities | boolean | undefined }): Promise<{ accounts: withCapabilities extends true ? readonly { address: Address capabilities: WalletConnectResponseCapabilities }[] : readonly Address[] chainId: number }> } type WalletConnectResponseCapabilities = { signInWithEthereum?: { message: string; signature: Hex } | undefined [capability: string]: any } let walletProvider: Provider | undefined let accountsChanged: Connector['onAccountsChanged'] | undefined let chainChanged: Connector['onChainChanged'] | undefined let disconnect: Connector['onDisconnect'] | undefined return createConnector((config) => ({ id: 'baseAccount', name: 'Base Account', rdns: 'app.base.account', type: 'baseAccount', async connect({ chainId, withCapabilities, ...rest } = {}) { try { const provider = await this.getProvider() const targetChainId = chainId ?? config.chains[0]?.id if (!targetChainId) throw new ChainNotConfiguredError() let { accounts, currentChainId } = await (async () => { if (rest.isReconnecting) return { accounts: ( (await provider.request({ method: 'eth_accounts', params: [], })) as string[] ).map((x) => ({ address: getAddress(x) })), currentChainId: await this.getChainId(), } const response = (await provider.request({ method: 'wallet_connect', params: [ { capabilities: 'capabilities' in rest && rest.capabilities ? rest.capabilities : {}, chainIds: [ numberToHex(targetChainId), ...config.chains .filter((x) => x.id !== targetChainId) .map((x) => numberToHex(x.id)), ], }, ], })) as { accounts: { address: Address capabilities?: WalletConnectResponseCapabilities | undefined }[] chainIds: Hex[] } const orderedAccounts = (await provider.request({ method: 'eth_accounts', })) as Address[] const accounts = orderedAccounts.map( (account1) => response.accounts.find( (account2) => account2.address === account1, ) ?? { address: account1 }, ) return { accounts: accounts.map((account) => ({ address: getAddress(account.address), capabilities: account.capabilities ?? {}, })), currentChainId: Number(response.chainIds[0]), } })() if (!accountsChanged) { accountsChanged = this.onAccountsChanged.bind(this) provider.on('accountsChanged', accountsChanged) } if (!chainChanged) { chainChanged = this.onChainChanged.bind(this) provider.on('chainChanged', chainChanged) } if (!disconnect) { disconnect = this.onDisconnect.bind(this) provider.on('disconnect', disconnect) } // Switch to chain if provided if (chainId && currentChainId !== chainId) { const chain = await this.switchChain!({ chainId }).catch((error) => { if (error.code === UserRejectedRequestError.code) throw error return { id: currentChainId } }) currentChainId = chain?.id ?? currentChainId } return { // TODO(v3): Make `withCapabilities: true` default behavior accounts: (withCapabilities ? accounts : accounts.map((account) => account.address)) as never, chainId: currentChainId, } } catch (error) { if ( /(user closed modal|accounts received is empty|user denied account|request rejected)/i.test( (error as Error).message, ) ) throw new UserRejectedRequestError(error as Error) throw error } }, async disconnect() { const provider = await this.getProvider() if (accountsChanged) { provider.removeListener('accountsChanged', accountsChanged) accountsChanged = undefined } if (chainChanged) { provider.removeListener('chainChanged', chainChanged) chainChanged = undefined } if (disconnect) { provider.removeListener('disconnect', disconnect) disconnect = undefined } provider.disconnect() }, async getAccounts() { const provider = await this.getProvider() return ( (await provider.request({ method: 'eth_accounts', })) as string[] ).map((x) => getAddress(x)) }, async getChainId() { const provider = await this.getProvider() const chainId = (await provider.request({ method: 'eth_chainId', })) as Hex return Number(chainId) }, async getProvider() { if (!walletProvider) { const preference = (() => { if (typeof parameters.preference === 'string') return { options: parameters.preference } return { ...parameters.preference, options: parameters.preference?.options ?? 'all', } })() const { createBaseAccountSDK } = await (() => { // safe webpack optional peer dependency dynamic import try { return import('@base-org/account') } catch { throw new Error('dependency "@base-org/account" not found') } })() const sdk = createBaseAccountSDK({ ...parameters, appChainIds: config.chains.map((x) => x.id), preference, }) walletProvider = sdk.getProvider() } return walletProvider }, async isAuthorized() { try { const accounts = await this.getAccounts() return !!accounts.length } catch { return false } }, async switchChain({ addEthereumChainParameter, chainId }) { const chain = config.chains.find((chain) => chain.id === chainId) if (!chain) throw new SwitchChainError(new ChainNotConfiguredError()) const provider = await this.getProvider() try { await provider.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: numberToHex(chain.id) }], }) return chain } catch (error) { // Indicates chain is not added to provider if ((error as ProviderRpcError).code === 4902) { try { let blockExplorerUrls: string[] | undefined if (addEthereumChainParameter?.blockExplorerUrls) blockExplorerUrls = addEthereumChainParameter.blockExplorerUrls else blockExplorerUrls = chain.blockExplorers?.default.url ? [chain.blockExplorers?.default.url] : [] let rpcUrls: readonly string[] if (addEthereumChainParameter?.rpcUrls?.length) rpcUrls = addEthereumChainParameter.rpcUrls else rpcUrls = [chain.rpcUrls.default?.http[0] ?? ''] const addEthereumChain = { blockExplorerUrls, chainId: numberToHex(chainId), chainName: addEthereumChainParameter?.chainName ?? chain.name, iconUrls: addEthereumChainParameter?.iconUrls, nativeCurrency: addEthereumChainParameter?.nativeCurrency ?? chain.nativeCurrency, rpcUrls, } satisfies AddEthereumChainParameter await provider.request({ method: 'wallet_addEthereumChain', params: [addEthereumChain], }) return chain } catch (error) { throw new UserRejectedRequestError(error as Error) } } throw new SwitchChainError(error as Error) } }, onAccountsChanged(accounts) { if (accounts.length === 0) this.onDisconnect() else config.emitter.emit('change', { accounts: accounts.map((x) => getAddress(x)), }) }, onChainChanged(chain) { const chainId = Number(chain) config.emitter.emit('change', { chainId }) }, async onDisconnect(_error) { config.emitter.emit('disconnect') const provider = await this.getProvider() if (accountsChanged) { provider.removeListener('accountsChanged', accountsChanged) accountsChanged = undefined } if (chainChanged) { provider.removeListener('chainChanged', chainChanged) chainChanged = undefined } if (disconnect) { provider.removeListener('disconnect', disconnect) disconnect = undefined } }, })) } ================================================ FILE: packages/connectors/src/coinbaseWallet.test.ts ================================================ import { config } from '@wagmi/test' import { expect, expectTypeOf, test } from 'vitest' import { coinbaseWallet } from './coinbaseWallet.js' test('setup', () => { const connectorFn = coinbaseWallet({ appName: 'wagmi' }) const connector = config._internal.connectors.setup(connectorFn) expect(connector.name).toEqual('Coinbase Wallet') type ConnectFnParameters = NonNullable< Parameters<(typeof connector)['connect']>[0] > expectTypeOf().toMatchTypeOf< boolean | undefined >() }) ================================================ FILE: packages/connectors/src/coinbaseWallet.ts ================================================ import type { createCoinbaseWalletSDK, ProviderInterface, } from '@coinbase/wallet-sdk' import { ChainNotConfiguredError, type Connector, createConnector, } from '@wagmi/core' import type { Mutable, Omit } from '@wagmi/core/internal' import { type AddEthereumChainParameter, type Address, getAddress, type Hex, numberToHex, type ProviderRpcError, SwitchChainError, UserRejectedRequestError, } from 'viem' export type CoinbaseWalletParameters< /** @deprecated remove */ _ = unknown, > = Mutable< Omit< Parameters[0], 'appChainIds' // set via wagmi config > > coinbaseWallet.type = 'coinbaseWallet' as const export function coinbaseWallet( parameters: CoinbaseWalletParameters = {} as any, ) { type Provider = ProviderInterface & { // for backwards compatibility close?(): void } type Properties = { // TODO(v3): Make `withCapabilities: true` default behavior connect(parameters?: { chainId?: number | undefined instantOnboarding?: boolean | undefined isReconnecting?: boolean | undefined withCapabilities?: withCapabilities | boolean | undefined }): Promise<{ accounts: withCapabilities extends true ? readonly { address: Address }[] : readonly Address[] chainId: number }> } let walletProvider: Provider | undefined let accountsChanged: Connector['onAccountsChanged'] | undefined let chainChanged: Connector['onChainChanged'] | undefined let disconnect: Connector['onDisconnect'] | undefined return createConnector((config) => ({ id: 'coinbaseWalletSDK', name: 'Coinbase Wallet', rdns: 'com.coinbase.wallet', type: coinbaseWallet.type, async connect({ chainId, withCapabilities, ...rest } = {}) { try { const provider = await this.getProvider() const accounts = ( (await provider.request({ method: 'eth_requestAccounts', params: 'instantOnboarding' in rest && rest.instantOnboarding ? [{ onboarding: 'instant' }] : [], })) as string[] ).map((x) => getAddress(x)) if (!accountsChanged) { accountsChanged = this.onAccountsChanged.bind(this) provider.on('accountsChanged', accountsChanged) } if (!chainChanged) { chainChanged = this.onChainChanged.bind(this) provider.on('chainChanged', chainChanged) } if (!disconnect) { disconnect = this.onDisconnect.bind(this) provider.on('disconnect', disconnect) } // Switch to chain if provided let currentChainId = await this.getChainId() if (chainId && currentChainId !== chainId) { const chain = await this.switchChain!({ chainId }).catch((error) => { if (error.code === UserRejectedRequestError.code) throw error return { id: currentChainId } }) currentChainId = chain?.id ?? currentChainId } return { accounts: (withCapabilities ? accounts.map((address) => ({ address, capabilities: {} })) : accounts) as never, chainId: currentChainId, } } catch (error) { if ( /(user closed modal|accounts received is empty|user denied account|request rejected)/i.test( (error as Error).message, ) ) throw new UserRejectedRequestError(error as Error) throw error } }, async disconnect() { const provider = await this.getProvider() if (accountsChanged) { provider.removeListener('accountsChanged', accountsChanged) accountsChanged = undefined } if (chainChanged) { provider.removeListener('chainChanged', chainChanged) chainChanged = undefined } if (disconnect) { provider.removeListener('disconnect', disconnect) disconnect = undefined } provider.disconnect() provider.close?.() }, async getAccounts() { const provider = await this.getProvider() return ( (await provider.request({ method: 'eth_accounts', })) as string[] ).map((x) => getAddress(x)) }, async getChainId() { const provider = await this.getProvider() const chainId = (await provider.request({ method: 'eth_chainId', })) as Hex return Number(chainId) }, async getProvider() { if (!walletProvider) { const { createCoinbaseWalletSDK } = await (() => { // safe webpack optional peer dependency dynamic import try { return import('@coinbase/wallet-sdk') } catch { throw new Error('dependency "@coinbase/wallet-sdk" not found') } })() const sdk = createCoinbaseWalletSDK({ ...parameters, appChainIds: config.chains.map((x) => x.id), preference: { options: 'all', ...(parameters.preference ?? {}), }, }) walletProvider = sdk.getProvider() } return walletProvider }, async isAuthorized() { try { const accounts = await this.getAccounts() return !!accounts.length } catch { return false } }, async switchChain({ addEthereumChainParameter, chainId }) { const chain = config.chains.find((chain) => chain.id === chainId) if (!chain) throw new SwitchChainError(new ChainNotConfiguredError()) const provider = await this.getProvider() try { await provider.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: numberToHex(chain.id) }], }) return chain } catch (error) { // Indicates chain is not added to provider if ((error as ProviderRpcError).code === 4902) { try { let blockExplorerUrls: string[] | undefined if (addEthereumChainParameter?.blockExplorerUrls) blockExplorerUrls = addEthereumChainParameter.blockExplorerUrls else blockExplorerUrls = chain.blockExplorers?.default.url ? [chain.blockExplorers?.default.url] : [] let rpcUrls: readonly string[] if (addEthereumChainParameter?.rpcUrls?.length) rpcUrls = addEthereumChainParameter.rpcUrls else rpcUrls = [chain.rpcUrls.default?.http[0] ?? ''] const addEthereumChain = { blockExplorerUrls, chainId: numberToHex(chainId), chainName: addEthereumChainParameter?.chainName ?? chain.name, iconUrls: addEthereumChainParameter?.iconUrls, nativeCurrency: addEthereumChainParameter?.nativeCurrency ?? chain.nativeCurrency, rpcUrls, } satisfies AddEthereumChainParameter await provider.request({ method: 'wallet_addEthereumChain', params: [addEthereumChain], }) return chain } catch (error) { throw new UserRejectedRequestError(error as Error) } } throw new SwitchChainError(error as Error) } }, onAccountsChanged(accounts) { if (accounts.length === 0) this.onDisconnect() else config.emitter.emit('change', { accounts: accounts.map((x) => getAddress(x)), }) }, onChainChanged(chain) { const chainId = Number(chain) config.emitter.emit('change', { chainId }) }, async onDisconnect(_error) { config.emitter.emit('disconnect') const provider = await this.getProvider() if (accountsChanged) { provider.removeListener('accountsChanged', accountsChanged) accountsChanged = undefined } if (chainChanged) { provider.removeListener('chainChanged', chainChanged) chainChanged = undefined } if (disconnect) { provider.removeListener('disconnect', disconnect) disconnect = undefined } }, })) } ================================================ FILE: packages/connectors/src/exports/index.test.ts ================================================ import { expect, test } from 'vitest' import * as connectors from './index.js' test('exports', () => { expect(Object.keys(connectors)).toMatchInlineSnapshot(` [ "injected", "mock", "baseAccount", "coinbaseWallet", "metaMask", "porto", "safe", "version", "walletConnect", ] `) }) ================================================ FILE: packages/connectors/src/exports/index.ts ================================================ // biome-ignore lint/performance/noBarrelFile: entrypoint module export { type InjectedParameters, injected, type MockParameters, mock, } from '@wagmi/core' export { type BaseAccountParameters, baseAccount } from '../baseAccount.js' export { type CoinbaseWalletParameters, coinbaseWallet, } from '../coinbaseWallet.js' export { type MetaMaskParameters, metaMask } from '../metaMask.js' export { type PortoParameters, porto } from '../porto.js' export { type SafeParameters, safe } from '../safe.js' export { version } from '../version.js' export { type WalletConnectParameters, walletConnect, } from '../walletConnect.js' ================================================ FILE: packages/connectors/src/metaMask.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { metaMask } from './metaMask.js' test('setup', () => { const connectorFn = metaMask() const connector = config._internal.connectors.setup(connectorFn) expect(connector.name).toEqual('MetaMask') }) ================================================ FILE: packages/connectors/src/metaMask.ts ================================================ import type { createEVMClient, EIP1193Provider, MetamaskConnectEVM, } from '@metamask/connect-evm' import { ChainNotConfiguredError, createConnector } from '@wagmi/core' import type { ExactPartial, OneOf, UnionCompute } from '@wagmi/core/internal' import { type Address, getAddress, numberToHex, type ProviderConnectInfo, ResourceUnavailableRpcError, type RpcError, SwitchChainError, UserRejectedRequestError, withRetry, withTimeout, } from 'viem' export type MetaMaskParameters = UnionCompute< ExactPartial> & { /** * @deprecated Use `dapp` instead. * * Metadata is used to fill details for the UX on confirmation screens in MetaMask. */ dappMetadata?: { name?: string; url?: string; iconUrl?: string } | undefined /** * @deprecated Use `debug` instead. */ logging?: { sdk?: boolean } | undefined /** * @deprecated Use `ui.headless` instead. */ headless?: boolean | undefined } & OneOf< | { /* Shortcut to connect and sign a message */ connectAndSign?: string | undefined } | { // TODO: Strongly type `method` and `params` /* Allow `connectWith` any rpc method */ connectWith?: { method: string; params: unknown[] } | undefined } > > type CreateEVMClientParameters = Parameters[0] metaMask.type = 'metaMask' as const export function metaMask(parameters: MetaMaskParameters = {}) { type Provider = EIP1193Provider type Properties = { onConnect(connectInfo: ProviderConnectInfo): void onDisplayUri(uri: string): void getInstance(): Promise } let metamask: MetamaskConnectEVM | undefined let metamaskPromise: Promise | undefined return createConnector((config) => ({ id: 'metaMaskSDK', name: 'MetaMask', rdns: ['io.metamask', 'io.metamask.mobile'], type: metaMask.type, async connect({ chainId, isReconnecting, withCapabilities } = {}) { const instance = await this.getInstance() const provider = instance.getProvider() let accounts: readonly Address[] = [] if (isReconnecting) accounts = await this.getAccounts().catch(() => []) try { let signResponse: string | undefined let connectWithResponse: unknown | undefined if (!accounts?.length) { const chainIds = config.chains.map((chain) => numberToHex(chain.id)) if (parameters.connectAndSign || parameters.connectWith) { if (parameters.connectAndSign) signResponse = await instance.connectAndSign({ chainIds, message: parameters.connectAndSign, }) else if (parameters.connectWith) connectWithResponse = await instance.connectWith({ chainIds, method: parameters.connectWith.method, params: parameters.connectWith.params, }) accounts = await this.getAccounts() } else { const result = await instance.connect({ chainIds }) accounts = result.accounts.map((x) => getAddress(x)) } } // Switch to chain if provided let currentChainId = await this.getChainId() if (chainId && currentChainId !== chainId) { const chain = await this.switchChain!({ chainId }).catch((error) => { if (error.code === UserRejectedRequestError.code) throw error return { id: currentChainId } }) currentChainId = chain?.id ?? currentChainId } if (signResponse) provider.emit('connectAndSign', { accounts, chainId: numberToHex(currentChainId), signResponse, }) else if (connectWithResponse) provider.emit('connectWith', { accounts, chainId: numberToHex(currentChainId), connectWithResponse, }) return { // TODO(v3): Make `withCapabilities: true` default behavior accounts: (withCapabilities ? accounts.map((address) => ({ address, capabilities: {} })) : accounts) as never, chainId: currentChainId, } } catch (err) { const error = err as RpcError if (error.code === UserRejectedRequestError.code) throw new UserRejectedRequestError(error) if (error.code === ResourceUnavailableRpcError.code) throw new ResourceUnavailableRpcError(error) throw error } }, async disconnect() { const instance = await this.getInstance() return instance.disconnect() }, async getAccounts() { const instance = await this.getInstance() if (instance.accounts.length) return instance.accounts.map((x) => getAddress(x)) // Fallback to provider if SDK doesn't return accounts const provider = instance.getProvider() const accounts = (await provider.request({ method: 'eth_accounts', })) as string[] return accounts.map((x) => getAddress(x)) }, async getChainId() { const instance = await this.getInstance() if (instance.getChainId()) return Number(instance.getChainId()) // Fallback to provider if SDK doesn't return chainId const provider = instance.getProvider() const chainId = await provider.request({ method: 'eth_chainId' }) return Number(chainId) }, async getProvider() { const instance = await this.getInstance() return instance.getProvider() }, async isAuthorized() { try { // MetaMask mobile provider sometimes fails to immediately resolve // JSON-RPC requests on page load const timeout = 10 const accounts = await withRetry( async () => withTimeout( async () => { const accounts = await this.getAccounts() if (!accounts.length) throw new Error('try again') return accounts }, { timeout }, ), { delay: timeout + 1, retryCount: 3 }, ) return Boolean(accounts.length) } catch { return false } }, async switchChain({ addEthereumChainParameter, chainId }) { const chain = config.chains.find(({ id }) => id === Number(chainId)) if (!chain) throw new SwitchChainError(new ChainNotConfiguredError()) const hexChainId = numberToHex(chainId) try { const instance = await this.getInstance() await instance.switchChain({ chainId: hexChainId, chainConfiguration: { blockExplorerUrls: addEthereumChainParameter?.blockExplorerUrls ? [...addEthereumChainParameter.blockExplorerUrls] : chain.blockExplorers?.default.url ? [chain.blockExplorers.default.url] : undefined, chainId: hexChainId, chainName: addEthereumChainParameter?.chainName ?? chain.name, iconUrls: addEthereumChainParameter?.iconUrls, nativeCurrency: addEthereumChainParameter?.nativeCurrency ?? chain.nativeCurrency, rpcUrls: addEthereumChainParameter?.rpcUrls ? [...addEthereumChainParameter.rpcUrls] : chain.rpcUrls.default?.http ? [...chain.rpcUrls.default.http] : undefined, }, }) return chain } catch (err) { const error = err as RpcError if (error.code === UserRejectedRequestError.code) throw new UserRejectedRequestError(error) throw new SwitchChainError(error) } }, async onAccountsChanged(accounts) { config.emitter.emit('change', { accounts: accounts.map((x) => getAddress(x)), }) }, onChainChanged(chain) { const chainId = Number(chain) config.emitter.emit('change', { chainId }) }, async onConnect(connectInfo) { const accounts = await this.getAccounts() if (accounts.length === 0) return const chainId = Number(connectInfo.chainId) config.emitter.emit('connect', { accounts, chainId }) }, async onDisconnect(error) { // If MetaMask emits a `code: 1013` error, wait for reconnection before disconnecting // https://github.com/MetaMask/providers/pull/120 if (error && (error as RpcError<1013>).code === 1013) { const provider = await this.getProvider() if (provider && Boolean((await this.getAccounts()).length)) return } config.emitter.emit('disconnect') }, onDisplayUri(uri) { config.emitter.emit('message', { type: 'display_uri', data: uri }) }, async getInstance() { if (!metamask) { if (!metamaskPromise) { const { createEVMClient } = await (async () => { try { return import('@metamask/connect-evm') } catch { throw new Error('dependency "@metamask/connect-evm" not found') } })() const defaultDappParams = typeof window === 'undefined' ? { name: 'wagmi' } : { name: window.location.hostname, url: window.location.href } metamaskPromise = createEVMClient({ ...parameters, api: { supportedNetworks: Object.fromEntries( config.chains.map((chain) => [ numberToHex(chain.id), chain.rpcUrls.default?.http[0] ?? '', ]), ), }, dapp: parameters.dapp ?? { ...defaultDappParams, ...parameters.dappMetadata, }, debug: parameters.debug ?? parameters.logging?.sdk, eventHandlers: { accountsChanged: this.onAccountsChanged.bind(this), chainChanged: this.onChainChanged.bind(this), connect: this.onConnect.bind(this), disconnect: this.onDisconnect.bind(this), displayUri: this.onDisplayUri.bind(this), }, analytics: { integrationType: 'wagmi', }, ui: { ...parameters.ui, ...(parameters.headless != null && { headless: parameters.headless, }), }, ...(parameters.mobile && { mobile: parameters.mobile }), }) } metamask = await metamaskPromise } return metamask }, })) } ================================================ FILE: packages/connectors/src/porto.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { porto } from './porto.js' test('setup', () => { const connectorFn = porto() const connector = config._internal.connectors.setup(connectorFn) expect(connector.name).toEqual('Porto') }) ================================================ FILE: packages/connectors/src/porto.ts ================================================ import { ChainNotConfiguredError, type Connector, createConnector, } from '@wagmi/core' import type { ExactPartial } from '@wagmi/core/internal' import type { Porto, RpcSchema } from 'porto' import { type Address, getAddress, numberToHex, type ProviderConnectInfo, type RpcError, SwitchChainError, UserRejectedRequestError, withRetry, } from 'viem' export type PortoParameters = ExactPartial export function porto(parameters: PortoParameters = {}) { type Provider = ReturnType['provider'] type Properties = { connect(parameters?: { chainId?: number | undefined capabilities?: | (RpcSchema.wallet_connect.Capabilities & { force?: boolean | undefined }) | undefined isReconnecting?: boolean | undefined withCapabilities?: withCapabilities | boolean | undefined }): Promise<{ accounts: withCapabilities extends true ? readonly { address: Address capabilities: RpcSchema.wallet_connect.ResponseCapabilities }[] : readonly Address[] chainId: number }> getPortoInstance(): Promise onConnect(connectInfo: ProviderConnectInfo): void } return createConnector((wagmiConfig) => { const chains = wagmiConfig.chains ?? parameters.chains ?? [] const transports = (() => { if (wagmiConfig.transports) return wagmiConfig.transports return parameters.transports })() let porto_promise: Promise | undefined let accountsChanged: Connector['onAccountsChanged'] | undefined let chainChanged: Connector['onChainChanged'] | undefined let connect: Connector['onConnect'] | undefined let disconnect: Connector['onDisconnect'] | undefined return { async connect({ chainId = chains[0].id, ...rest } = {}) { const isReconnecting = ('isReconnecting' in rest && rest.isReconnecting) || false const withCapabilities = ('withCapabilities' in rest && rest.withCapabilities) || false let accounts: readonly (Address | { address: Address })[] = [] let currentChainId: number | undefined if (isReconnecting) { ;[accounts, currentChainId] = await Promise.all([ this.getAccounts().catch(() => []), this.getChainId().catch(() => undefined), ]) if (chainId && currentChainId !== chainId) { const chain = await this.switchChain!({ chainId }).catch( (error) => { if (error.code === UserRejectedRequestError.code) throw error return { id: currentChainId } }, ) currentChainId = chain?.id ?? currentChainId } } const provider = (await this.getProvider()) as Provider try { if (!accounts?.length && !isReconnecting) { const { RpcSchema } = await (() => { // safe webpack optional peer dependency dynamic import try { return import('porto') } catch { throw new Error('dependency "porto" not found') } })() const { z } = await (() => { // safe webpack optional peer dependency dynamic import try { return import('porto/internal') } catch { throw new Error('dependency "porto/internal" not found') } })() const res = await provider.request({ method: 'wallet_connect', params: [ { ...('capabilities' in rest ? { capabilities: z.encode( RpcSchema.wallet_connect.Capabilities, rest.capabilities ?? {}, ), } : {}), chainIds: [ numberToHex(chainId), ...chains .filter((x) => x.id !== chainId) .map((x) => numberToHex(x.id)), ], }, ], }) accounts = res.accounts currentChainId = Number(res.chainIds[0]) } if (!currentChainId) throw new ChainNotConfiguredError() // Manage EIP-1193 event listeners // https://eips.ethereum.org/EIPS/eip-1193#events if (connect) { provider.removeListener('connect', connect) connect = undefined } if (!accountsChanged) { accountsChanged = this.onAccountsChanged.bind(this) // Porto Provider uses Ox, which uses `readonly Address.Address[]` for `accountsChanged`, // while Connector `accountsChanged` is `string[]` provider.on('accountsChanged', accountsChanged as never) } if (!chainChanged) { chainChanged = this.onChainChanged.bind(this) provider.on('chainChanged', chainChanged) } if (!disconnect) { disconnect = this.onDisconnect.bind(this) provider.on('disconnect', disconnect) } return { accounts: accounts.map((account) => { if (typeof account === 'object') return withCapabilities ? account : account.address return withCapabilities ? { address: account, capabilities: {} } : account }) as never, chainId: currentChainId, } } catch (err) { const error = err as RpcError if (error.code === UserRejectedRequestError.code) throw new UserRejectedRequestError(error) throw error } }, async disconnect() { const provider = await this.getProvider() if (chainChanged) { provider.removeListener('chainChanged', chainChanged) chainChanged = undefined } if (disconnect) { provider.removeListener('disconnect', disconnect) disconnect = undefined } if (!connect) { connect = this.onConnect.bind(this) provider.on('connect', connect) } await provider.request({ method: 'wallet_disconnect' }) }, async getAccounts() { const provider = await this.getProvider() const accounts = await provider.request({ method: 'eth_accounts', }) return accounts.map((x) => getAddress(x)) }, async getChainId() { const provider = await this.getProvider() const hexChainId = await provider.request({ method: 'eth_chainId', }) return Number(hexChainId) }, async getPortoInstance() { porto_promise ??= (async () => { const { Porto } = await (() => { // safe webpack optional peer dependency dynamic import try { return import('porto') } catch { throw new Error('dependency "porto" not found') } })() // @ts-ignore return Porto.create({ ...parameters, announceProvider: false, // @ts-ignore chains, // @ts-ignore transports, }) })() return await porto_promise }, async getProvider() { return (await this.getPortoInstance()).provider }, icon: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDIyIiBoZWlnaHQ9IjQyMiIgdmlld0JveD0iMCAwIDQyMiA0MjIiIGZpbGw9Im5vbmUiI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DYxQzMyOS43NDggMjc2LjQ1NyAzMjkuNjI5IDI3Ni40NTUgMzI5LjUxMSAyNzYuNDU1SDkwLjk0MDRDODUuNDUwNSAyNzYuNDU1IDgxIDI4MC44OTMgODEgMjg2LjM2NlYzMDYuMTg4QzgxIDMxMS42NjIgODUuNDUwNSAzMTYuMTAxIDkwLjk0MDQgMzE2LjEwMUgzMjkuNTExQzMzNS4wMDEgMzE2LjEwMSAzMzkuNDUyIDMxMS42NjIgMzM5LjQ1MiAzMDYuMTg4VjI4Ni4zNjZaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBkPSJNMjY5Ljg2OCAxMzEuNzUyQzI2OS44NjggMTI2LjI3OCAyNzQuMzE4IDEyMS44NCAyNzkuODA4IDEyMS44NEgzMTEuNjE4QzMxNy4xMDggMTIxLjg0IDMyMS41NTggMTI2LjI3OCAzMjEuNTU4IDEzMS43NTJWMTYxLjQ4NUMzMjEuNTU4IDE2Ni45NTkgMzE3LjEwOCAxNzEuMzk2IDMxMS42MTggMTcxLjM5NkgyNzkuODA4QzI3NC4zMTggMTcxLjM5NiAyNjkuODY4IDE2Ni45NTkgMjY5Ljg2OCAxNjEuNDg1VjEzMS43NTJaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjxkZWZzPgo8Y2xpcFBhdGggaWQ9ImNsaXAwXzFfMTUiPgo8cmVjdCB3aWR0aD0iMjU5IiBoZWlnaHQ9IjIxMyIgZmlsbD0id2hpdGUiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDgxIDEwNCkiLz4KPC9jbGlwUGF0aD4KPC9kZWZzPgo8L3N2Zz4K', id: 'xyz.ithaca.porto', async isAuthorized() { try { // Use retry strategy as some injected wallets (e.g. MetaMask) fail to // immediately resolve JSON-RPC requests on page load. const accounts = await withRetry(() => this.getAccounts()) return !!accounts.length } catch { return false } }, name: 'Porto', async onAccountsChanged(accounts) { wagmiConfig.emitter.emit('change', { accounts: accounts.map((x) => getAddress(x)), }) }, onChainChanged(chain) { const chainId = Number(chain) wagmiConfig.emitter.emit('change', { chainId }) }, async onConnect(connectInfo) { const accounts = await this.getAccounts() if (accounts.length === 0) return const chainId = Number(connectInfo.chainId) wagmiConfig.emitter.emit('connect', { accounts, chainId }) // Manage EIP-1193 event listeners const provider = await this.getProvider() if (provider) { if (connect) { provider.removeListener('connect', connect) connect = undefined } if (!accountsChanged) { accountsChanged = this.onAccountsChanged.bind(this) // Porto Provider uses Ox, which uses `readonly Address.Address[]` for `accountsChanged`, // while Connector `accountsChanged` is `string[]` provider.on('accountsChanged', accountsChanged as never) } if (!chainChanged) { chainChanged = this.onChainChanged.bind(this) provider.on('chainChanged', chainChanged) } if (!disconnect) { disconnect = this.onDisconnect.bind(this) provider.on('disconnect', disconnect) } } }, async onDisconnect(_error) { const provider = await this.getProvider() wagmiConfig.emitter.emit('disconnect') // Manage EIP-1193 event listeners if (provider) { if (chainChanged) { provider.removeListener('chainChanged', chainChanged) chainChanged = undefined } if (disconnect) { provider.removeListener('disconnect', disconnect) disconnect = undefined } if (!connect) { connect = this.onConnect.bind(this) provider.on('connect', connect) } } }, async setup() { if (!connect) { const provider = await this.getProvider() connect = this.onConnect.bind(this) provider.on('connect', connect) } }, async switchChain({ chainId }) { const chain = chains.find((x) => x.id === chainId) if (!chain) throw new SwitchChainError(new ChainNotConfiguredError()) const provider = await this.getProvider() await provider.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: numberToHex(chainId) }], }) return chain }, type: 'injected', } }) } ================================================ FILE: packages/connectors/src/safe.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { safe } from './safe.js' /* * To manually test the Safe connector: * * 1. Run the wagmi playground app (`pnpm dev`) * 2. Add a custom Safe App with App URL set to `http://localhost:5173` (make sure there is a `manifest.json` file served by the playground) * 3. Open the playground app at `https://app.safe.global/eth:0x4557B18E779944BFE9d78A672452331C186a9f48/apps?appUrl=http%3A%2F%2Flocalhost%3A5173` * * See https://docs.gnosis-safe.io/learn/safe-tools/sdks/safe-apps/releasing-your-safe-app for more info. */ test('setup', () => { const connectorFn = safe({ allowedDomains: [/gnosis-safe.io$/, /app.safe.global$/], debug: false, }) const connector = config._internal.connectors.setup(connectorFn) expect(connector.name).toEqual('Safe') }) ================================================ FILE: packages/connectors/src/safe.ts ================================================ import type { SafeAppProvider } from '@safe-global/safe-apps-provider' import type { Opts } from '@safe-global/safe-apps-sdk' import { type Connector, createConnector, ProviderNotFoundError, } from '@wagmi/core' import type { Compute } from '@wagmi/core/internal' import { getAddress, withTimeout } from 'viem' export type SafeParameters = Compute< Opts & { /** * Connector automatically connects when used as Safe App. * * This flag simulates the disconnect behavior by keeping track of connection status in storage * and only autoconnecting when previously connected by user action (e.g. explicitly choosing to connect). * * @default false */ shimDisconnect?: boolean | undefined /** * Timeout in milliseconds for `getInfo` (from the Safe SDK) to resolve. * * `getInfo` does not resolve when not used in Safe App iFrame. This allows the connector to force a timeout. * @default 10 */ unstable_getInfoTimeout?: number | undefined } > safe.type = 'safe' as const export function safe(parameters: SafeParameters = {}) { const { shimDisconnect = false } = parameters type Provider = SafeAppProvider | undefined type Properties = Record type StorageItem = { 'safe.disconnected': true } let provider_: Provider | undefined let disconnect: Connector['onDisconnect'] | undefined return createConnector((config) => ({ id: 'safe', name: 'Safe', type: safe.type, async connect({ withCapabilities } = {}) { const provider = await this.getProvider() if (!provider) throw new ProviderNotFoundError() const accounts = await this.getAccounts() const chainId = await this.getChainId() if (!disconnect) { disconnect = this.onDisconnect.bind(this) provider.on('disconnect', disconnect) } // Remove disconnected shim if it exists if (shimDisconnect) await config.storage?.removeItem('safe.disconnected') return { // TODO(v3): Make `withCapabilities: true` default behavior accounts: (withCapabilities ? accounts.map((address) => ({ address, capabilities: {} })) : accounts) as never, chainId, } }, async disconnect() { const provider = await this.getProvider() if (!provider) throw new ProviderNotFoundError() if (disconnect) { provider.removeListener('disconnect', disconnect) disconnect = undefined } // Add shim signalling connector is disconnected if (shimDisconnect) await config.storage?.setItem('safe.disconnected', true) }, async getAccounts() { const provider = await this.getProvider() if (!provider) throw new ProviderNotFoundError() return (await provider.request({ method: 'eth_accounts' })).map( getAddress, ) }, async getProvider() { // Only allowed in iframe context const isIframe = typeof window !== 'undefined' && window?.parent !== window if (!isIframe) return if (!provider_) { const { default: SDK } = await (() => { // safe webpack optional peer dependency dynamic import try { return import('@safe-global/safe-apps-sdk') } catch { throw new Error('dependency "@safe-global/safe-apps-sdk" not found') } })() const sdk = new SDK(parameters) // `getInfo` hangs when not used in Safe App iFrame // https://github.com/safe-global/safe-apps-sdk/issues/263#issuecomment-1029835840 const safe = await withTimeout(() => sdk.safe.getInfo(), { timeout: parameters.unstable_getInfoTimeout ?? 10, }) if (!safe) throw new Error('Could not load Safe information') // Unwrapping import for Vite compatibility. // See: https://github.com/vitejs/vite/issues/9703 const SafeAppProvider = await (async () => { const Provider = await (() => { // safe webpack optional peer dependency dynamic import try { return import('@safe-global/safe-apps-provider') } catch { throw new Error( 'dependency "@safe-global/safe-apps-provider" not found', ) } })() if ( typeof Provider.SafeAppProvider !== 'function' && typeof Provider.default.SafeAppProvider === 'function' ) return Provider.default.SafeAppProvider return Provider.SafeAppProvider })() provider_ = new SafeAppProvider(safe, sdk) } return provider_ }, async getChainId() { const provider = await this.getProvider() if (!provider) throw new ProviderNotFoundError() return Number(provider.chainId) }, async isAuthorized() { try { const isDisconnected = shimDisconnect && // If shim exists in storage, connector is disconnected (await config.storage?.getItem('safe.disconnected')) if (isDisconnected) return false const accounts = await this.getAccounts() return !!accounts.length } catch { return false } }, onAccountsChanged() { // Not relevant for Safe because changing account requires app reload. }, onChainChanged() { // Not relevant for Safe because Safe smart contract wallets only exist on single chain. }, onDisconnect() { config.emitter.emit('disconnect') }, })) } ================================================ FILE: packages/connectors/src/version.ts ================================================ export const version = '7.2.1' ================================================ FILE: packages/connectors/src/walletConnect.test.ts ================================================ import { config, walletConnectProjectId } from '@wagmi/test' import { HttpResponse, http } from 'msw' import { setupServer } from 'msw/node' import { afterAll, afterEach, beforeAll, expect, expectTypeOf, test, vi, } from 'vitest' import { walletConnect } from './walletConnect.js' const handlers = [ http.get('https://relay.walletconnect.com', async () => HttpResponse.json( { topic: '222781e3-3fad-4184-acde-077796bf0d3d', type: 'sub', payload: '', silent: true, }, { status: 200 }, ), ), ] const server = setupServer(...handlers) beforeAll(() => { server.listen({ onUnhandledRequest: 'warn', }) const matchMedia = vi.fn().mockImplementation((query) => { return { matches: false, media: query, onchange: null, addListener: vi.fn(), // deprecated removeListener: vi.fn(), // deprecated addEventListener: vi.fn(), removeEventListener: vi.fn(), dispatchEvent: vi.fn(), } }) vi.stubGlobal('matchMedia', matchMedia) }) afterEach(() => server.resetHandlers()) afterAll(() => server.close()) test('setup', () => { const connectorFn = walletConnect({ projectId: walletConnectProjectId }) const connector = config._internal.connectors.setup(connectorFn) expect(connector.name).toEqual('WalletConnect') type ConnectFnParameters = NonNullable< Parameters<(typeof connector)['connect']>[0] > expectTypeOf().toMatchTypeOf< string | undefined >() }) ================================================ FILE: packages/connectors/src/walletConnect.ts ================================================ import { ChainNotConfiguredError, type Connector, createConnector, extractRpcUrls, ProviderNotFoundError, } from '@wagmi/core' import type { Compute, ExactPartial, Omit } from '@wagmi/core/internal' import type { EthereumProvider } from '@walletconnect/ethereum-provider' import { type AddEthereumChainParameter, type Address, getAddress, numberToHex, type ProviderConnectInfo, type ProviderRpcError, type RpcError, SwitchChainError, UserRejectedRequestError, } from 'viem' type WalletConnectConnector = Connector & { onDisplayUri(uri: string): void onSessionDelete(data: { topic: string }): void } type EthereumProviderOptions = Parameters<(typeof EthereumProvider)['init']>[0] export type WalletConnectParameters = Compute< { /** * If a new chain is added to a previously existing configured connector `chains`, this flag * will determine if that chain should be considered as stale. A stale chain is a chain that * WalletConnect has yet to establish a relationship with (e.g. the user has not approved or * rejected the chain). * * This flag mainly affects the behavior when a wallet does not support dynamic chain authorization * with WalletConnect v2. * * If `true` (default), the new chain will be treated as a stale chain. If the user * has yet to establish a relationship (approved/rejected) with this chain in their WalletConnect * session, the connector will disconnect upon the dapp auto-connecting, and the user will have to * reconnect to the dapp (revalidate the chain) in order to approve the newly added chain. * This is the default behavior to avoid an unexpected error upon switching chains which may * be a confusing user experience (e.g. the user will not know they have to reconnect * unless the dapp handles these types of errors). * * If `false`, the new chain will be treated as a potentially valid chain. This means that if the user * has yet to establish a relationship with the chain in their WalletConnect session, wagmi will successfully * auto-connect the user. This comes with the trade-off that the connector will throw an error * when attempting to switch to the unapproved chain if the wallet does not support dynamic session updates. * This may be useful in cases where a dapp constantly * modifies their configured chains, and they do not want to disconnect the user upon * auto-connecting. If the user decides to switch to the unapproved chain, it is important that the * dapp handles this error and prompts the user to reconnect to the dapp in order to approve * the newly added chain. * * @default true */ isNewChainsStale?: boolean } & Omit< EthereumProviderOptions, | 'chains' | 'events' | 'optionalChains' | 'optionalEvents' | 'optionalMethods' | 'methods' | 'rpcMap' | 'showQrModal' > & ExactPartial> > walletConnect.type = 'walletConnect' as const export function walletConnect(parameters: WalletConnectParameters) { const isNewChainsStale = parameters.isNewChainsStale ?? true type Provider = Awaited> type Properties = { // TODO(v3): Make `withCapabilities: true` default behavior connect(parameters?: { chainId?: number | undefined isReconnecting?: boolean | undefined pairingTopic?: string | undefined withCapabilities?: withCapabilities | boolean | undefined }): Promise<{ accounts: withCapabilities extends true ? readonly { address: Address }[] : readonly Address[] chainId: number }> getNamespaceChainsIds(): number[] getRequestedChainsIds(): Promise isChainsStale(): Promise onConnect(connectInfo: ProviderConnectInfo): void onDisplayUri(uri: string): void onSessionDelete(data: { topic: string }): void setRequestedChainsIds(chains: number[]): void requestedChainsStorageKey: `${string}.requestedChains` } type StorageItem = { [_ in Properties['requestedChainsStorageKey']]: number[] } let provider_: Provider | undefined let providerPromise: Promise const NAMESPACE = 'eip155' let accountsChanged: WalletConnectConnector['onAccountsChanged'] | undefined let chainChanged: WalletConnectConnector['onChainChanged'] | undefined let connect: WalletConnectConnector['onConnect'] | undefined let displayUri: WalletConnectConnector['onDisplayUri'] | undefined let sessionDelete: WalletConnectConnector['onSessionDelete'] | undefined let disconnect: WalletConnectConnector['onDisconnect'] | undefined return createConnector((config) => ({ id: 'walletConnect', name: 'WalletConnect', type: walletConnect.type, async setup() { const provider = await this.getProvider().catch(() => null) if (!provider) return if (!connect) { connect = this.onConnect.bind(this) provider.on('connect', connect) } if (!sessionDelete) { sessionDelete = this.onSessionDelete.bind(this) provider.on('session_delete', sessionDelete) } }, async connect({ chainId, withCapabilities, ...rest } = {}) { try { const provider = await this.getProvider() if (!provider) throw new ProviderNotFoundError() if (!displayUri) { displayUri = this.onDisplayUri provider.on('display_uri', displayUri) } let targetChainId = chainId if (!targetChainId) { const state = (await config.storage?.getItem('state')) ?? {} const isChainSupported = config.chains.some( (x) => x.id === state.chainId, ) if (isChainSupported) targetChainId = state.chainId else targetChainId = config.chains[0]?.id } if (!targetChainId) throw new Error('No chains found on connector.') const isChainsStale = await this.isChainsStale() // If there is an active session with stale chains, disconnect current session. if (provider.session && isChainsStale) await provider.disconnect() // If there isn't an active session or chains are stale, connect. if (!provider.session || isChainsStale) { const optionalChains = config.chains .filter((chain) => chain.id !== targetChainId) .map((optionalChain) => optionalChain.id) await provider.connect({ optionalChains: [targetChainId, ...optionalChains], ...('pairingTopic' in rest ? { pairingTopic: rest.pairingTopic } : {}), }) this.setRequestedChainsIds(config.chains.map((x) => x.id)) } // If session exists and chains are authorized, enable provider for required chain const accounts = (await provider.enable()).map((x) => getAddress(x)) // Switch to chain if provided let currentChainId = await this.getChainId() if (chainId && currentChainId !== chainId) { const chain = await this.switchChain!({ chainId }).catch( (error: RpcError) => { if ( error.code === UserRejectedRequestError.code && (error.cause as RpcError | undefined)?.message !== 'Missing or invalid. request() method: wallet_addEthereumChain' ) throw error return { id: currentChainId } }, ) currentChainId = chain?.id ?? currentChainId } if (displayUri) { provider.removeListener('display_uri', displayUri) displayUri = undefined } if (connect) { provider.removeListener('connect', connect) connect = undefined } if (!accountsChanged) { accountsChanged = this.onAccountsChanged.bind(this) provider.on('accountsChanged', accountsChanged) } if (!chainChanged) { chainChanged = this.onChainChanged.bind(this) provider.on('chainChanged', chainChanged) } if (!disconnect) { disconnect = this.onDisconnect.bind(this) provider.on('disconnect', disconnect) } if (!sessionDelete) { sessionDelete = this.onSessionDelete.bind(this) provider.on('session_delete', sessionDelete) } return { accounts: (withCapabilities ? accounts.map((address) => ({ address, capabilities: {} })) : accounts) as never, chainId: currentChainId, } } catch (error) { if ( /(user rejected|connection request reset)/i.test( (error as ProviderRpcError)?.message, ) ) { throw new UserRejectedRequestError(error as Error) } throw error } }, async disconnect() { const provider = await this.getProvider() try { await provider?.disconnect() } catch (error) { if (!/No matching key/i.test((error as Error).message)) throw error } finally { if (chainChanged) { provider?.removeListener('chainChanged', chainChanged) chainChanged = undefined } if (disconnect) { provider?.removeListener('disconnect', disconnect) disconnect = undefined } if (!connect) { connect = this.onConnect.bind(this) provider?.on('connect', connect) } if (accountsChanged) { provider?.removeListener('accountsChanged', accountsChanged) accountsChanged = undefined } if (sessionDelete) { provider?.removeListener('session_delete', sessionDelete) sessionDelete = undefined } this.setRequestedChainsIds([]) } }, async getAccounts() { const provider = await this.getProvider() return provider.accounts.map((x) => getAddress(x)) }, async getProvider({ chainId } = {}) { async function initProvider() { const optionalChains = config.chains.map((x) => x.id) as [number] if (!optionalChains.length) return const { EthereumProvider } = await (() => { // safe webpack optional peer dependency dynamic import try { return import('@walletconnect/ethereum-provider') } catch { throw new Error( 'dependency "@walletconnect/ethereum-provider" not found', ) } })() return await EthereumProvider.init({ ...parameters, disableProviderPing: true, optionalChains, projectId: parameters.projectId, rpcMap: Object.fromEntries( config.chains.map((chain) => { const [url] = extractRpcUrls({ chain, transports: config.transports, }) return [chain.id, url] }), ), showQrModal: parameters.showQrModal ?? true, }) } if (!provider_) { if (!providerPromise) providerPromise = initProvider() provider_ = await providerPromise provider_?.events.setMaxListeners(Number.POSITIVE_INFINITY) } if (chainId) await this.switchChain?.({ chainId }) return provider_! }, async getChainId() { const provider = await this.getProvider() return provider.chainId }, async isAuthorized() { try { const [accounts, provider] = await Promise.all([ this.getAccounts(), this.getProvider(), ]) // If an account does not exist on the session, then the connector is unauthorized. if (!accounts.length) return false // If the chains are stale on the session, then the connector is unauthorized. const isChainsStale = await this.isChainsStale() if (isChainsStale && provider.session) { await provider.disconnect().catch(() => {}) return false } return true } catch { return false } }, async switchChain({ addEthereumChainParameter, chainId }) { const provider = await this.getProvider() if (!provider) throw new ProviderNotFoundError() const chain = config.chains.find((x) => x.id === chainId) if (!chain) throw new SwitchChainError(new ChainNotConfiguredError()) try { await Promise.all([ new Promise((resolve) => { const listener = ({ chainId: currentChainId, }: { chainId?: number | undefined }) => { if (currentChainId === chainId) { config.emitter.off('change', listener) resolve() } } config.emitter.on('change', listener) }), provider.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: numberToHex(chainId) }], }), ]) const requestedChains = await this.getRequestedChainsIds() this.setRequestedChainsIds([...requestedChains, chainId]) return chain } catch (err) { const error = err as RpcError if (/(user rejected)/i.test(error.message)) throw new UserRejectedRequestError(error) // Indicates chain is not added to provider try { let blockExplorerUrls: string[] | undefined if (addEthereumChainParameter?.blockExplorerUrls) blockExplorerUrls = addEthereumChainParameter.blockExplorerUrls else blockExplorerUrls = chain.blockExplorers?.default.url ? [chain.blockExplorers?.default.url] : [] let rpcUrls: readonly string[] if (addEthereumChainParameter?.rpcUrls?.length) rpcUrls = addEthereumChainParameter.rpcUrls else rpcUrls = [...chain.rpcUrls.default.http] const addEthereumChain = { blockExplorerUrls, chainId: numberToHex(chainId), chainName: addEthereumChainParameter?.chainName ?? chain.name, iconUrls: addEthereumChainParameter?.iconUrls, nativeCurrency: addEthereumChainParameter?.nativeCurrency ?? chain.nativeCurrency, rpcUrls, } satisfies AddEthereumChainParameter await provider.request({ method: 'wallet_addEthereumChain', params: [addEthereumChain], }) const requestedChains = await this.getRequestedChainsIds() this.setRequestedChainsIds([...requestedChains, chainId]) return chain } catch (error) { throw new UserRejectedRequestError(error as Error) } } }, onAccountsChanged(accounts) { if (accounts.length === 0) this.onDisconnect() else config.emitter.emit('change', { accounts: accounts.map((x) => getAddress(x)), }) }, onChainChanged(chain) { const chainId = Number(chain) config.emitter.emit('change', { chainId }) }, async onConnect(connectInfo) { const chainId = Number(connectInfo.chainId) const accounts = await this.getAccounts() config.emitter.emit('connect', { accounts, chainId }) }, async onDisconnect(_error) { this.setRequestedChainsIds([]) config.emitter.emit('disconnect') const provider = await this.getProvider() if (accountsChanged) { provider.removeListener('accountsChanged', accountsChanged) accountsChanged = undefined } if (chainChanged) { provider.removeListener('chainChanged', chainChanged) chainChanged = undefined } if (disconnect) { provider.removeListener('disconnect', disconnect) disconnect = undefined } if (sessionDelete) { provider.removeListener('session_delete', sessionDelete) sessionDelete = undefined } if (!connect) { connect = this.onConnect.bind(this) provider.on('connect', connect) } }, onDisplayUri(uri) { config.emitter.emit('message', { type: 'display_uri', data: uri }) }, onSessionDelete() { this.onDisconnect() }, getNamespaceChainsIds() { if (!provider_) return [] const chainIds = provider_.session?.namespaces[NAMESPACE]?.accounts?.map( (account) => Number.parseInt(account.split(':')[1] || '', 10), ) return chainIds ?? [] }, async getRequestedChainsIds() { return ( (await config.storage?.getItem(this.requestedChainsStorageKey)) ?? [] ) }, /** * Checks if the target chains match the chains that were * initially requested by the connector for the WalletConnect session. * If there is a mismatch, this means that the chains on the connector * are considered stale, and need to be revalidated at a later point (via * connection). * * There may be a scenario where a dapp adds a chain to the * connector later on, however, this chain will not have been approved or rejected * by the wallet. In this case, the chain is considered stale. */ async isChainsStale() { if (!isNewChainsStale) return false const connectorChains = config.chains.map((x) => x.id) const namespaceChains = this.getNamespaceChainsIds() if ( namespaceChains.length && !namespaceChains.some((id) => connectorChains.includes(id)) ) return false const requestedChains = await this.getRequestedChainsIds() return !connectorChains.every((id) => requestedChains.includes(id)) }, async setRequestedChainsIds(chains) { await config.storage?.setItem(this.requestedChainsStorageKey, chains) }, get requestedChainsStorageKey() { return `${this.id}.requestedChains` as Properties['requestedChainsStorageKey'] }, })) } ================================================ FILE: packages/connectors/tsconfig.build.json ================================================ { "extends": "../../tsconfig.base.json", "include": ["src/**/*.ts"], "exclude": ["src/**/*.test.ts", "src/**/*.test-d.ts"], "compilerOptions": { "sourceMap": true } } ================================================ FILE: packages/connectors/tsconfig.json ================================================ { "extends": "./tsconfig.build.json", "include": ["src/**/*.ts"], "exclude": [] } ================================================ FILE: packages/core/CHANGELOG.md ================================================ # @wagmi/core ## 3.4.0 ### Minor Changes - Added `signTransaction` action ([#4995](https://github.com/wevm/wagmi/pull/4995)) ## 3.3.4 ### Patch Changes - Added credential fast path to `webAuthn` connector — pass `capabilities.credential` directly to skip the WebAuthn ceremony when the credential is already known. ([#5005](https://github.com/wevm/wagmi/pull/5005)) ## 3.3.3 ### Patch Changes - Added ability to sign arbitrary `hash` on `webAuthn#connect`. ([#4994](https://github.com/wevm/wagmi/pull/4994)) ## 3.3.2 ### Patch Changes - Updated internal exports ([`68e17db`](https://github.com/wevm/wagmi/commit/68e17db7ff84982db8f52f54e6f047c5efab62ab)) ## 3.3.1 ### Patch Changes - Fixed "illegal invocation" error when signing up with passkeys while using password manager browser extensions ([#4968](https://github.com/wevm/wagmi/pull/4968)) ## 3.3.0 ### Minor Changes - Added `getBlobBaseFee` and `writeContractSync` actions. ([`dfe7904`](https://github.com/wevm/wagmi/commit/dfe790426d5ac24d55eacdf8d0193292de801911)) - Added `getContractEvents` action. ([#4905](https://github.com/wevm/wagmi/pull/4905)) ### Patch Changes - Fixed `eth_accounts` to return `mock#accounts` parameter when provided. ([#4920](https://github.com/wevm/wagmi/pull/4920)) - Added explicit return type to mutation options. ([#4964](https://github.com/wevm/wagmi/pull/4964)) - Fixed `readContractsQueryKey` using passed `chainId` when all contracts specifiy `chainId` ([`5978cc5`](https://github.com/wevm/wagmi/commit/5978cc508ac837be88ed84c15ea5aa805f59005a)) - **`wagmi/tempo`:** Propagated `rpId` to `Account.fromWebAuthnP256` in webAuthn connector. ([#4963](https://github.com/wevm/wagmi/pull/4963)) ## 3.2.3 ### Patch Changes - **wagmi/tempo:** Fixed access key lookup to use `account` address instead of `accessKey` address in `webAuthn` connector. ([#4953](https://github.com/wevm/wagmi/pull/4953)) - Propagated `chain` to Viem's `sendTransactiion` to preserve chain-specific configuration. ([#4953](https://github.com/wevm/wagmi/pull/4953)) - Fixed serialization of credentials in `KeyManager.http`. ([#4951](https://github.com/wevm/wagmi/pull/4951)) ## 3.2.2 ### Patch Changes - Updated query internals. ([`4fefa57`](https://github.com/wevm/wagmi/commit/4fefa576014820b454344b579282ddecde5c7994)) ## 3.2.1 ### Patch Changes - `wagmi/tempo`: Fixed issue where `webAuthn` connector was not adhering to chain-specific `prepareTransactionRequest` phases. ([#4939](https://github.com/wevm/wagmi/pull/4939)) ## 3.2.0 ### Minor Changes - Updated to `viem@2.44.0` with Tempo Moderato support. ([#4940](https://github.com/wevm/wagmi/pull/4940)) **Breaking Changes (Tempo)** - Renamed `reward.start` → `reward.distribute` (no longer supports streaming) - Renamed `reward.startSync` → `reward.distributeSync` - Renamed `reward.getTotalPerSecond` → `reward.getGlobalRewardPerToken` - Renamed `reward.watchRewardScheduled` → `reward.watchRewardDistributed` - Removed `nonce.getNonceKeyCount` - Removed `nonce.watchActiveKeyCountChanged` - Removed `amm.watchFeeSwap` (FeeSwap event no longer emitted by protocol) **New Features (Tempo)** - Added `dex.cancelStale` action to cancel stale orders from restricted makers - Added `dex.cancelStaleSync` action - Added `salt` parameter to `token.create` ## 3.1.0 ### Minor Changes - Added first-class support and extension for [Tempo](https://docs.tempo.xyz) via `/tempo` entrypoint. ([#4922](https://github.com/wevm/wagmi/pull/4922)) ## 3.0.2 ### Patch Changes - Fixed `config.connectors` type inference ([#4923](https://github.com/wevm/wagmi/pull/4923)) ## 3.0.1 ### Patch Changes - Fixed `readContract` return type inference for ABI function overloads. ([`058c8c1`](https://github.com/wevm/wagmi/commit/058c8c18459a69a4aa2141e34640273a06a819f4)) ## 3.0.0 ### Major Changes - All connector dependencies are now optional peer dependencies. This means that if you want to use a specific connector, you need to install its required dependencies. ([#4857](https://github.com/wevm/wagmi/pull/4857)) #### baseAccount [`baseAccount`](https://wagmi.sh/core/api/connectors/baseAccount) requires `@base-org/account` ``` pnpm add @base-org/account@~2.4.0 ``` #### coinbaseWallet [`coinbaseWallet`](https://wagmi.sh/core/api/connectors/coinbaseWallet) requires `@coinbase/wallet-sdk` ``` pnpm add @coinbase/wallet-sdk@~4.3.6 ``` #### gemini [`gemini`](https://wagmi.sh/core/api/connectors/gemini) requires `@gemini-wallet/core` ``` pnpm add @gemini-wallet/core@~0.3.1 ``` #### metaMask [`metaMask`](https://wagmi.sh/core/api/connectors/metaMask) requires `@metamask/sdk` ``` pnpm add @metamask/sdk@~0.33.1 ``` #### porto [`porto`](https://wagmi.sh/core/api/connectors/porto) requires `porto` ``` pnpm add porto@~0.2.35 ``` #### safe [`safe`](https://wagmi.sh/core/api/connectors/safe) requires `@safe-global/safe-apps-provider` and `@safe-global/safe-apps-sdk` ``` pnpm add @safe-global/safe-apps-provider@~0.18.6 @safe-global/safe-apps-sdk@~9.1.0 ``` #### walletConnect [`walletConnect`](https://wagmi.sh/core/api/connectors/walletConnect) requires `walletconnect/ethereum-provider` ``` pnpm add @walletconnect/ethereum-provider@~2.21.1 ``` ## 2.22.1 ### Patch Changes - Fixed passing `account` in `waitForTransactionReceipt` for reverted transaction. ([#4832](https://github.com/wevm/wagmi/pull/4832)) ## 2.22.0 ### Minor Changes - Added `sendTransactionSync` and `sendCallsSync` Actions. ([#4823](https://github.com/wevm/wagmi/pull/4823)) ## 2.21.2 ### Patch Changes - Added `assertChainId` parameter to `getConnectorClient`. ([`866aeb0`](https://github.com/wevm/wagmi/commit/866aeb0e6361ef9114246e50149c1077bc05bf10)) ## 2.21.1 ### Patch Changes - Fixed `getConnectors` comparison ([#4792](https://github.com/wevm/wagmi/pull/4792)) ## 2.21.0 ### Minor Changes - [#4784](https://github.com/wevm/wagmi/pull/4784) [`8736133a13eb82099e20468b735525a266fdfd6c`](https://github.com/wevm/wagmi/commit/8736133a13eb82099e20468b735525a266fdfd6c) Thanks [@tmm](https://github.com/tmm)! - Added `withCapabilities` option to `connect` for exposing response capabilities. ## 2.20.3 ### Patch Changes - [#4752](https://github.com/wevm/wagmi/pull/4752) [`ce06e137e7bfaf000464b1cecd6c86e19a66ebcf`](https://github.com/wevm/wagmi/commit/ce06e137e7bfaf000464b1cecd6c86e19a66ebcf) Thanks [@iamakulov](https://github.com/iamakulov)! - Fixed `deepEqual` crashing for objects with no prototype ## 2.20.2 ### Patch Changes - [#4733](https://github.com/wevm/wagmi/pull/4733) [`986b96427a4bb743d2673dfbc7e8cb5041316db3`](https://github.com/wevm/wagmi/commit/986b96427a4bb743d2673dfbc7e8cb5041316db3) Thanks [@effie-ms](https://github.com/effie-ms)! - Fixed `getConnectorClient` chain ID race condition. ## 2.20.1 ### Patch Changes - [#4773](https://github.com/wevm/wagmi/pull/4773) [`d4c367ca46c508598c997cf229a31593a1e2b8b8`](https://github.com/wevm/wagmi/commit/d4c367ca46c508598c997cf229a31593a1e2b8b8) Thanks [@tmm](https://github.com/tmm)! - Fixed issue with codegen actions/hooks, where `syncConnectedChain: false` did not work as intended. ## 2.20.0 ### Minor Changes - [#4770](https://github.com/wevm/wagmi/pull/4770) [`a13aa2b68890f180f6ac3f741cbb9817494cb66c`](https://github.com/wevm/wagmi/commit/a13aa2b68890f180f6ac3f741cbb9817494cb66c) Thanks [@tmm](https://github.com/tmm)! - Added internal `revalidate` function. ## 2.19.0 ### Minor Changes - [#4756](https://github.com/wevm/wagmi/pull/4756) [`b5f017dbc707729eb0b36d617352be224d1139d4`](https://github.com/wevm/wagmi/commit/b5f017dbc707729eb0b36d617352be224d1139d4) Thanks [@plusminushalf](https://github.com/plusminushalf)! - Added `getAction` to `sendCalls` and `getCallsStatus` ## 2.18.1 ### Patch Changes - [#4704](https://github.com/wevm/wagmi/pull/4704) [`6514ba29a5acb918773235fed0238d7d679d06d5`](https://github.com/wevm/wagmi/commit/6514ba29a5acb918773235fed0238d7d679d06d5) Thanks [@iceanddust](https://github.com/iceanddust)! - Added missing `from` address to the `wallet_sendCalls` handler in the `mock` connector ## 2.18.0 ### Minor Changes - [#4734](https://github.com/wevm/wagmi/pull/4734) [`eac550ae5b49f96a7e3404a6d88adc62d3889013`](https://github.com/wevm/wagmi/commit/eac550ae5b49f96a7e3404a6d88adc62d3889013) Thanks [@jxom](https://github.com/jxom)! - Added `baseAccount` connector. ## 2.17.3 ### Patch Changes - [#4700](https://github.com/wevm/wagmi/pull/4700) [`7ce242b549d8cc78e6c319d9ee419693da36704c`](https://github.com/wevm/wagmi/commit/7ce242b549d8cc78e6c319d9ee419693da36704c) Thanks [@jade-u410](https://github.com/jade-u410)! - Updated `@coinbase/wallet-sdk` to 4.3.3 ## 2.17.2 ### Patch Changes - [`29297a48af72b537173d948ccd2fe37d39914c66`](https://github.com/wevm/wagmi/commit/29297a48af72b537173d948ccd2fe37d39914c66) Thanks [@jxom](https://github.com/jxom)! - Fixed `sendCalls` generics. - [`07370106d5fb6b8fe300992d93abf25b3d0eaf57`](https://github.com/wevm/wagmi/commit/07370106d5fb6b8fe300992d93abf25b3d0eaf57) Thanks [@jxom](https://github.com/jxom)! - Fixed propagation of `waitForCallsStatus` parameters. ## 2.17.1 ### Patch Changes - [#4649](https://github.com/wevm/wagmi/pull/4649) [`01f64e64fa4f85cdd30023903f972f4f9023681f`](https://github.com/wevm/wagmi/commit/01f64e64fa4f85cdd30023903f972f4f9023681f) Thanks [@jxom](https://github.com/jxom)! - Added `chainId` parameter to `getCapabilities`/`useCapabilities`. ## 2.17.0 ### Minor Changes - [#4638](https://github.com/wevm/wagmi/pull/4638) [`799ee4d4b23c2ecd64e3f3668e67634e81939719`](https://github.com/wevm/wagmi/commit/799ee4d4b23c2ecd64e3f3668e67634e81939719) Thanks [@jxom](https://github.com/jxom)! - Stabilized EIP-5792 Actions & Hooks. ## 2.16.7 ### Patch Changes - [`a4bd0623eed28e3761a27295831a60ad835f0ee0`](https://github.com/wevm/wagmi/commit/a4bd0623eed28e3761a27295831a60ad835f0ee0) Thanks [@jxom](https://github.com/jxom)! - **Experimental (EIP-5792):** Updated `id` parameter to be optional on `useWaitForCallsStatus`. ## 2.16.6 ### Patch Changes - [#4586](https://github.com/wevm/wagmi/pull/4586) [`edf47477b2f6385a1c3ae01d36a8498c47f30a0b`](https://github.com/wevm/wagmi/commit/edf47477b2f6385a1c3ae01d36a8498c47f30a0b) Thanks [@jxom](https://github.com/jxom)! - **Experimental (EIP-5792):** Added `waitForCallsStatus` + `useWaitForCallsStatus`. ## 2.16.5 ### Patch Changes - [`d0c9a86921a4e939373cc6e763284e53f2a2e93c`](https://github.com/wevm/wagmi/commit/d0c9a86921a4e939373cc6e763284e53f2a2e93c) Thanks [@jxom](https://github.com/jxom)! - **Experimental (ERC-5792)**: Added support for `account: null` in `sendCalls` to cater for sending calls without a connected account (account will be filled by the wallet). ## 2.16.4 ### Patch Changes - [`507f864d91238bfd423d0e36d3619eb9f6e52eec`](https://github.com/wevm/wagmi/commit/507f864d91238bfd423d0e36d3619eb9f6e52eec) Thanks [@jxom](https://github.com/jxom)! - Updated `@coinbase/wallet-sdk`. ## 2.16.3 ### Patch Changes - [#4480](https://github.com/wevm/wagmi/pull/4480) [`384a1d91597622eb59e1c05dc13ce25017c5b6d8`](https://github.com/wevm/wagmi/commit/384a1d91597622eb59e1c05dc13ce25017c5b6d8) Thanks [@RodeRickIsWatching](https://github.com/RodeRickIsWatching)! - Fixed invocation of default storage. ## 2.16.2 ### Patch Changes - [`012907032b532a438fce48f407470250cbc8f0c6`](https://github.com/wevm/wagmi/commit/012907032b532a438fce48f407470250cbc8f0c6) Thanks [@jxom](https://github.com/jxom)! - Fixed assignment in `getDefaultStorage`. ## 2.16.1 ### Patch Changes - [#4472](https://github.com/wevm/wagmi/pull/4472) [`3892ebd21c06beef4b28ece4e70d2a38807bce6f`](https://github.com/wevm/wagmi/commit/3892ebd21c06beef4b28ece4e70d2a38807bce6f) Thanks [@tmm](https://github.com/tmm)! - Added handling to default storage for `setItem` errors, like `QuotaExceededError`, `SecurityError`, etc. ## 2.16.0 ### Minor Changes - [#4453](https://github.com/wevm/wagmi/pull/4453) [`070e48480194c8d7f45bda1d7dd1346e6f5d7227`](https://github.com/wevm/wagmi/commit/070e48480194c8d7f45bda1d7dd1346e6f5d7227) Thanks [@tmm](https://github.com/tmm)! - Added narrowing to `config.connectors`. ### Patch Changes - [`afea6b67822a7a2b96901ec851441d27ee0f7a52`](https://github.com/wevm/wagmi/commit/afea6b67822a7a2b96901ec851441d27ee0f7a52) Thanks [@tmm](https://github.com/tmm)! - Passed through parameters to `connector.connect` in `connect` action. ## 2.15.2 ### Patch Changes - [#4433](https://github.com/wevm/wagmi/pull/4433) [`06e186cd679b27fe195309110e766fcf46d4efbc`](https://github.com/wevm/wagmi/commit/06e186cd679b27fe195309110e766fcf46d4efbc) Thanks [@Aerilym](https://github.com/Aerilym)! - Bumped Metamask SDK version to `0.31.1`. ## 2.15.1 ### Patch Changes - [`b8bbb409f4934538e3dd6cac5aaf7346292d0693`](https://github.com/wevm/wagmi/commit/b8bbb409f4934538e3dd6cac5aaf7346292d0693) Thanks [@jxom](https://github.com/jxom)! - Fixed issue where `null` gas would accidentally pass through. ## 2.15.0 ### Minor Changes - [#4417](https://github.com/wevm/wagmi/pull/4417) [`42e65ea4fea99c639817088bba915e0933d17141`](https://github.com/wevm/wagmi/commit/42e65ea4fea99c639817088bba915e0933d17141) Thanks [@jxom](https://github.com/jxom)! - Removed simulation in `writeContract` & `sendTransaction`. ## 2.14.6 ### Patch Changes - [#4406](https://github.com/wevm/wagmi/pull/4406) [`a13aa8d7c38eb3cc8171a02d6302e6d12cf6bcb3`](https://github.com/wevm/wagmi/commit/a13aa8d7c38eb3cc8171a02d6302e6d12cf6bcb3) Thanks [@tmm](https://github.com/tmm)! - Added support for multiple connector `rdns` entries. ## 2.14.5 ### Patch Changes - [#4400](https://github.com/wevm/wagmi/pull/4400) [`6b9bbacdc7bffd44fc2165362a5e65fd434e7646`](https://github.com/wevm/wagmi/commit/6b9bbacdc7bffd44fc2165362a5e65fd434e7646) Thanks [@AzzouQ](https://github.com/AzzouQ)! - Fixed `createWatchContractEvent` internal wiring, where `eventName` was incorrectly `functionName`. ## 2.14.4 ### Patch Changes - [#4311](https://github.com/wevm/wagmi/pull/4311) [`e08681c81fbdf475213e2d0f4c5517d0abf4e743`](https://github.com/wevm/wagmi/commit/e08681c81fbdf475213e2d0f4c5517d0abf4e743) Thanks [@chybisov](https://github.com/chybisov)! - Fixed `injected` connector race condition after calling `'wallet_addEthereumChain'` in `switchChain`. ## 2.14.3 ### Patch Changes - [`cb7dd2ebb871d0be8f1a11a8cd8ce592cd74b7c7`](https://github.com/wevm/wagmi/commit/cb7dd2ebb871d0be8f1a11a8cd8ce592cd74b7c7) Thanks [@tmm](https://github.com/tmm)! - Removed unnecessary internal deep equal check in `structuralSharing`. ## 2.14.2 ### Patch Changes - [#4339](https://github.com/wevm/wagmi/pull/4339) [`d0d0963bb5904a15cf0355862d62dd141ce0c31c`](https://github.com/wevm/wagmi/commit/d0d0963bb5904a15cf0355862d62dd141ce0c31c) Thanks [@AndriyAntonenko](https://github.com/AndriyAntonenko)! - Fixed bug in `waitForTransactionReceipt`, where transaction data wasn't passed to `'eth_call'` method as part of getting the revert reason. - [`ecac0ba36243d94c9199d0bd21937104c835d9a0`](https://github.com/wevm/wagmi/commit/ecac0ba36243d94c9199d0bd21937104c835d9a0) Thanks [@tmm](https://github.com/tmm)! - Fixed `getBalance` symbol error handling. ## 2.14.1 ### Patch Changes - [`052e72e1f8c1c14fcbdce04a9f8fa7ec28d83702`](https://github.com/wevm/wagmi/commit/052e72e1f8c1c14fcbdce04a9f8fa7ec28d83702) Thanks [@tmm](https://github.com/tmm)! - Added `defaultConnected` feature to `mock` connector. - [#4349](https://github.com/wevm/wagmi/pull/4349) [`b250fc21ee577b2a75c5a34ff684f62fb4ad771a`](https://github.com/wevm/wagmi/commit/b250fc21ee577b2a75c5a34ff684f62fb4ad771a) Thanks [@tmm](https://github.com/tmm)! - Bumped internal deps. ## 2.14.0 ### Minor Changes - [#4343](https://github.com/wevm/wagmi/pull/4343) [`f43e074f473820b208a6295d7c97f847332f1a1d`](https://github.com/wevm/wagmi/commit/f43e074f473820b208a6295d7c97f847332f1a1d) Thanks [@tmm](https://github.com/tmm)! - Added `rdns` property to connector interface. This is used to filter out duplicate [EIP-6963](https://eips.ethereum.org/EIPS/eip-6963) injected providers when [`createConfig#multiInjectedProviderDiscovery`](https://wagmi.sh/core/api/createConfig#multiinjectedproviderdiscovery) is enabled and `createConfig#connectors` already matches EIP-6963 providers' `rdns` property. ## 2.13.9 ### Patch Changes - [#4336](https://github.com/wevm/wagmi/pull/4336) [`c05caabc20c3ced9682cfc7ba1f3f7dcfece0703`](https://github.com/wevm/wagmi/commit/c05caabc20c3ced9682cfc7ba1f3f7dcfece0703) Thanks [@EdouardBougon](https://github.com/EdouardBougon)! - Added deprecation notice to `injected` target flags. ## 2.13.8 ### Patch Changes - [#4207](https://github.com/wevm/wagmi/pull/4207) [`56f2482508f2ba71bd6b0295c70c6abca7101e57`](https://github.com/wevm/wagmi/commit/56f2482508f2ba71bd6b0295c70c6abca7101e57) Thanks [@Smert](https://github.com/Smert)! - Updated chain switch listener for `injected` and `metaMask` to be more robust. ## 2.13.7 ### Patch Changes - [`be75c2d4ef636d7362420ab0a106bfdf63f5d1e6`](https://github.com/wevm/wagmi/commit/be75c2d4ef636d7362420ab0a106bfdf63f5d1e6) Thanks [@tmm](https://github.com/tmm)! - Added guard for missing `provider.on` for `injected` connector. ## 2.13.6 ### Patch Changes - [#4286](https://github.com/wevm/wagmi/pull/4286) [`edcbf5d6fbe92f639bead800502edda9e0aa39f1`](https://github.com/wevm/wagmi/commit/edcbf5d6fbe92f639bead800502edda9e0aa39f1) Thanks [@holic](https://github.com/holic)! - Removed duplicate code. ## 2.13.5 ### Patch Changes - [#4259](https://github.com/wevm/wagmi/pull/4259) [`f47ce8f6d263e49fdff90b8edb3190142d2657bb`](https://github.com/wevm/wagmi/commit/f47ce8f6d263e49fdff90b8edb3190142d2657bb) Thanks [@tmm](https://github.com/tmm)! - Added guard to `getConnectorClient` when reconnecting to check if connector is fully restored. ## 2.13.4 ### Patch Changes - [`b4c8971788c70b09479946ecfa998cff2f1b3953`](https://github.com/wevm/wagmi/commit/b4c8971788c70b09479946ecfa998cff2f1b3953) Thanks [@tmm](https://github.com/tmm)! - Made `serialize` and `deserialize` types more permissive. ## 2.13.3 ### Patch Changes - [`871dbdbfe59ac8ad01d1ec6150ea7b091b7b7de4`](https://github.com/wevm/wagmi/commit/871dbdbfe59ac8ad01d1ec6150ea7b091b7b7de4) Thanks [@tmm](https://github.com/tmm)! - Added validation to internal state for persisted `chainId`. ## 2.13.2 ### Patch Changes - [`1b9b523fa9b9dfe839aecdf4b40caa9547d7e594`](https://github.com/wevm/wagmi/commit/1b9b523fa9b9dfe839aecdf4b40caa9547d7e594) Thanks [@tmm](https://github.com/tmm)! - Fixed built-in cookie storage `removeItem` working for all paths. ## 2.13.1 ### Patch Changes - [`07c1227f306d0efb9421d4bb77a774f92f5fcf45`](https://github.com/wevm/wagmi/commit/07c1227f306d0efb9421d4bb77a774f92f5fcf45) Thanks [@tmm](https://github.com/tmm)! - Fixed internal `extractRpcUrls` usage with `unstable_connector`. ## 2.13.0 ### Minor Changes - [#4162](https://github.com/wevm/wagmi/pull/4162) [`a73a7737b756886b388f120ae423e72cca53e8a0`](https://github.com/wevm/wagmi/commit/a73a7737b756886b388f120ae423e72cca53e8a0) Thanks [@jxom](https://github.com/jxom)! - Added functionality for consumer-defined RPC URLs (`config.transports`) to be propagated to the WalletConnect & MetaMask Connectors. ## 2.12.2 ### Patch Changes - [`5bc8c8877810b2eec24a829df87dce40a51e6f20`](https://github.com/wevm/wagmi/commit/5bc8c8877810b2eec24a829df87dce40a51e6f20) Thanks [@tmm](https://github.com/tmm)! - Fixed reconnection when `status` is defined. ## 2.12.1 ### Patch Changes - [#4146](https://github.com/wevm/wagmi/pull/4146) [`cc996e08e930c9e88cf753a1e874652059e81a3b`](https://github.com/wevm/wagmi/commit/cc996e08e930c9e88cf753a1e874652059e81a3b) Thanks [@jxom](https://github.com/jxom)! - Updated `@safe-global/safe-apps-sdk` + `@safe-global/safe-apps-provider` dependencies. ## 2.12.0 ### Minor Changes - [#4128](https://github.com/wevm/wagmi/pull/4128) [`5581a810ef70308e99c6f8b630cd4bca59f64afc`](https://github.com/wevm/wagmi/commit/5581a810ef70308e99c6f8b630cd4bca59f64afc) Thanks [@dalechyn](https://github.com/dalechyn)! - Added `watchAsset` action. ## 2.11.8 ### Patch Changes - [`b08013eaa9ce97c02f8a7128ea400e3da7ef74bb`](https://github.com/wevm/wagmi/commit/b08013eaa9ce97c02f8a7128ea400e3da7ef74bb) Thanks [@tmm](https://github.com/tmm)! - Fixed injected accounts ordering for `'wallet_requestPermissions'`. - [`d3814ab4b88f9f0e052b53bc3d458df87b43f01d`](https://github.com/wevm/wagmi/commit/d3814ab4b88f9f0e052b53bc3d458df87b43f01d) Thanks [@jxom](https://github.com/jxom)! - Updated `mipd` dependency. ## 2.11.7 ### Patch Changes - [`0bb8b562ae04ecfeb2d6b2f1b980ebae31dc127e`](https://github.com/wevm/wagmi/commit/0bb8b562ae04ecfeb2d6b2f1b980ebae31dc127e) Thanks [@tmm](https://github.com/tmm)! - Improved TypeScript `'exactOptionalPropertyTypes'` support. ## 2.11.6 ### Patch Changes - [#4060](https://github.com/wevm/wagmi/pull/4060) [`95965c1f19d480b97f2b297a077a9e607dee32ad`](https://github.com/wevm/wagmi/commit/95965c1f19d480b97f2b297a077a9e607dee32ad) Thanks [@dalechyn](https://github.com/dalechyn)! - Bumped Tanstack Query dependencies to fix typing issues between exported Wagmi query options and TanStack Query suspense query methods (due to [`direction` property in `QueryFunctionContext` being deprecated](https://github.com/TanStack/query/pull/7410)). ## 2.11.5 ### Patch Changes - [#4079](https://github.com/wevm/wagmi/pull/4079) [`04f2b846b113f3d300d82c9fa75212f1805817c5`](https://github.com/wevm/wagmi/commit/04f2b846b113f3d300d82c9fa75212f1805817c5) Thanks [@tmm](https://github.com/tmm)! - Added revalidation for config chain ID in SSR and migration. ## 2.11.4 ### Patch Changes - [`9e8345cd56186b997b5e56deaa2cfc69b30d15f6`](https://github.com/wevm/wagmi/commit/9e8345cd56186b997b5e56deaa2cfc69b30d15f6) Thanks [@tmm](https://github.com/tmm)! - Switched `Register` to `interface` to fix declaration merging. ## 2.11.3 ### Patch Changes - [#4065](https://github.com/wevm/wagmi/pull/4065) [`8974e6269bb5d7bfaa90db0246bc7d13e8bff798`](https://github.com/wevm/wagmi/commit/8974e6269bb5d7bfaa90db0246bc7d13e8bff798) Thanks [@alx-khramov](https://github.com/alx-khramov)! - Added timeout to internal call of `'wallet_revokePermissions'` request during `injected#disconnect` as some wallets that do not support this method hang. ## 2.11.2 ### Patch Changes - [#4042](https://github.com/wevm/wagmi/pull/4042) [`b4d9ef79deb554ee20fed6666a474be5e7cdd522`](https://github.com/wevm/wagmi/commit/b4d9ef79deb554ee20fed6666a474be5e7cdd522) Thanks [@tmm](https://github.com/tmm)! - Removed `injected` connector `isAuthorized` timeout. ## 2.11.1 ### Patch Changes - [`9c862d8d63e3d692a22cef2a90782b74a9103f17`](https://github.com/wevm/wagmi/commit/9c862d8d63e3d692a22cef2a90782b74a9103f17) Thanks [@tmm](https://github.com/tmm)! - Reverted internal module loading utility. ## 2.11.0 ### Minor Changes - [#3816](https://github.com/wevm/wagmi/pull/3816) [`06bb598a7f04c7b167f5b7ff6d46bd15886a6a14`](https://github.com/wevm/wagmi/commit/06bb598a7f04c7b167f5b7ff6d46bd15886a6a14) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Added `deployContract` action. ### Patch Changes - [`24a45b269bd0214a29d6f82a84ac66ef8c3f3822`](https://github.com/wevm/wagmi/commit/24a45b269bd0214a29d6f82a84ac66ef8c3f3822) Thanks [@tmm](https://github.com/tmm)! - Added `SameSite` default to `cookieStorage` ## 2.10.6 ### Patch Changes - [#4009](https://github.com/wevm/wagmi/pull/4009) [`f2a7cefab96691ebed8b8e45ffde071c47b58dbe`](https://github.com/wevm/wagmi/commit/f2a7cefab96691ebed8b8e45ffde071c47b58dbe) Thanks [@roninjin10](https://github.com/roninjin10)! - Marked `to` as optional for `sendTransaction`. - [#4023](https://github.com/wevm/wagmi/pull/4023) [`f0ea0b2a7fe193dadfeb49a4c8031ee451c638b5`](https://github.com/wevm/wagmi/commit/f0ea0b2a7fe193dadfeb49a4c8031ee451c638b5) Thanks [@jxom](https://github.com/jxom)! - Added chain check to `getConnectorClient` since it's possible for connection state chain ID to get out of sync with the connector (e.g. [wallet bug](https://github.com/MetaMask/metamask-extension/issues/25097)). ## 2.10.5 ### Patch Changes - [#3970](https://github.com/wevm/wagmi/pull/3970) [`030c7c2cb380dfd67a2182f62e2aa7a6e1601898`](https://github.com/wevm/wagmi/commit/030c7c2cb380dfd67a2182f62e2aa7a6e1601898) Thanks [@nanxiaobei](https://github.com/nanxiaobei)! - Fixed `cookieStorage` not working across paths. ## 2.10.4 ### Patch Changes - [#3984](https://github.com/wevm/wagmi/pull/3984) [`51fde8a0433b4fff357c1a8d7e08b41b4c86c968`](https://github.com/wevm/wagmi/commit/51fde8a0433b4fff357c1a8d7e08b41b4c86c968) Thanks [@tmm](https://github.com/tmm)! - Fixed `writeContract` query types for `value` property. ## 2.10.3 ### Patch Changes - [#3962](https://github.com/wevm/wagmi/pull/3962) [`2804a8a583b1874271154898b4bae38756ef581c`](https://github.com/wevm/wagmi/commit/2804a8a583b1874271154898b4bae38756ef581c) Thanks [@tmm](https://github.com/tmm)! - Added catch to `reconnect`. ## 2.10.2 ### Patch Changes - [#3940](https://github.com/wevm/wagmi/pull/3940) [`a5071f581dfdfb961718873643a2fc629101c72a`](https://github.com/wevm/wagmi/commit/a5071f581dfdfb961718873643a2fc629101c72a) Thanks [@jxom](https://github.com/jxom)! - Fixed usage of `metaMask` connector in Vite environments. ## 2.10.1 ### Patch Changes - Bumped versions. ## 2.10.0 ### Minor Changes - [#3928](https://github.com/wevm/wagmi/pull/3928) [`3117e71825f9c58a0d718f3d1686f1a191fa9cb1`](https://github.com/wevm/wagmi/commit/3117e71825f9c58a0d718f3d1686f1a191fa9cb1) Thanks [@tmm](https://github.com/tmm)! - Updated the default Coinbase SDK in `coinbaseWallet` Connector to v4.x. ## 2.9.8 ### Patch Changes - [#3906](https://github.com/wevm/wagmi/pull/3906) [`32fcb4a31dde6b0206961d8ffe9c651f8a459c67`](https://github.com/wevm/wagmi/commit/32fcb4a31dde6b0206961d8ffe9c651f8a459c67) Thanks [@tmm](https://github.com/tmm)! - Added support for Vue. ## 2.9.7 ### Patch Changes - [#3924](https://github.com/wevm/wagmi/pull/3924) [`1f58734f88458e0f6adb05c99f0c90f36ab286b8`](https://github.com/wevm/wagmi/commit/1f58734f88458e0f6adb05c99f0c90f36ab286b8) Thanks [@jxom](https://github.com/jxom)! - Refactored `isChainsStale` logic in `walletConnect` connector. ## 2.9.6 ### Patch Changes - [#3917](https://github.com/wevm/wagmi/pull/3917) [`05948fdad5bb4a56b08916d45b3dec2cb1e5f55b`](https://github.com/wevm/wagmi/commit/05948fdad5bb4a56b08916d45b3dec2cb1e5f55b) Thanks [@jxom](https://github.com/jxom)! - Updated `@metamask/sdk`. ## 2.9.5 ### Patch Changes - [`4fecbbb66d0aacd03b8c62a6455d11a33cde8f85`](https://github.com/wevm/wagmi/commit/4fecbbb66d0aacd03b8c62a6455d11a33cde8f85) Thanks [@jxom](https://github.com/jxom)! - Fixed address comparison in `getConnectorClient`. ## 2.9.4 ### Patch Changes - [#3910](https://github.com/wevm/wagmi/pull/3910) [`e6139a97c4b8804d734b1547b5e3921ce01fbe24`](https://github.com/wevm/wagmi/commit/e6139a97c4b8804d734b1547b5e3921ce01fbe24) Thanks [@tmm](https://github.com/tmm)! - Added experimental `wallet_revokePermissions` support to `injected`. ## 2.9.3 ### Patch Changes - [#3904](https://github.com/wevm/wagmi/pull/3904) [`addca28ebc20f1a4367c35fe9ef786decff9c87e`](https://github.com/wevm/wagmi/commit/addca28ebc20f1a4367c35fe9ef786decff9c87e) Thanks [@jxom](https://github.com/jxom)! - Updated `@walletconnect/ethereum-provider`. ## 2.9.2 ### Patch Changes - [#3902](https://github.com/wevm/wagmi/pull/3902) [`204b7b624612405500ec098fb9e35facd3f74ca4`](https://github.com/wevm/wagmi/commit/204b7b624612405500ec098fb9e35facd3f74ca4) Thanks [@jxom](https://github.com/jxom)! - Made third-party SDK imports type-only. ## 2.9.1 ### Patch Changes - [`cda6a5d5`](https://github.com/wevm/wagmi/commit/cda6a5d56328330fbde050b4ef40b01c58d2519a) Thanks [@jxom](https://github.com/jxom)! - Updated packages. ## 2.9.0 ### Minor Changes - [#3878](https://github.com/wevm/wagmi/pull/3878) [`017828fc`](https://github.com/wevm/wagmi/commit/017828fc027c7a84b54ea9d627e9389f4d60d6c2) Thanks [@jxom](https://github.com/jxom)! - Added experimental EIP-5792 Actions & Hooks. ## 2.8.1 ### Patch Changes - [#3869](https://github.com/wevm/wagmi/pull/3869) [`d4a78eb0`](https://github.com/wevm/wagmi/commit/d4a78eb07119d2e5617e52481ac7d6c6d1583ddc) Thanks [@jxom](https://github.com/jxom)! - Fixed issue where `prepareTransactionRequest` would internally call unsupported wallet RPC methods. ## 2.8.0 ### Minor Changes - [#3868](https://github.com/wevm/wagmi/pull/3868) [`c2af20b8`](https://github.com/wevm/wagmi/commit/c2af20b88cf16970d087faaec10b463357a5836e) Thanks [@jxom](https://github.com/jxom)! - Added `supportsSimulation` property to connectors that indicates if the connector's wallet supports contract simulation. ### Patch Changes - [#3858](https://github.com/wevm/wagmi/pull/3858) [`0d141f17`](https://github.com/wevm/wagmi/commit/0d141f171d6ec44bcbfc9c876565b5e2fb8af6de) Thanks [@yulafezmesi](https://github.com/yulafezmesi)! - Fixed accessing reverted reason property inside `waitForTransactionReceipt`. ## 2.7.0 ### Minor Changes - [#3857](https://github.com/wevm/wagmi/pull/3857) [`d4274c03`](https://github.com/wevm/wagmi/commit/d4274c03a6af5f2d26d31432016ebc14950a330e) Thanks [@tmm](https://github.com/tmm)! - Added `addEthereumChainParameter` to `switchChain`-related methods. ### Patch Changes - [#3849](https://github.com/wevm/wagmi/pull/3849) [`4781a405`](https://github.com/wevm/wagmi/commit/4781a4056d4ffc2c74f96a75429e9b2cd2417ad8) Thanks [@tmm](https://github.com/tmm)! - Fixed `shimDisconnect: false` behavior. - [#3859](https://github.com/wevm/wagmi/pull/3859) [`400c960b`](https://github.com/wevm/wagmi/commit/400c960b30d701c134850c695ae903a382c29b5b) Thanks [@holic](https://github.com/holic)! - Added workaround to injected connector for MetaMask bug, where chain switching does not work if target chain RPC `'net_version'` request fails. ## 2.6.19 ### Patch Changes - [`e3c832a1`](https://github.com/wevm/wagmi/commit/e3c832a12c301f9b0ee129d877b3101d220ba8b2) Thanks [@jxom](https://github.com/jxom)! - Fixed undefined `navigator` issue in MetaMask connector. ## 2.6.18 ### Patch Changes - [#3848](https://github.com/wevm/wagmi/pull/3848) [`dd40a41c`](https://github.com/wevm/wagmi/commit/dd40a41c526ab60a288aff2250ed8dba92a27b16) Thanks [@jxom](https://github.com/jxom)! - Updated MetaMask SDK. ## 2.6.17 ### Patch Changes - [#3822](https://github.com/wevm/wagmi/pull/3822) [`a97bfbae`](https://github.com/wevm/wagmi/commit/a97bfbaeb615cfef04665e5e7348d85d17f960f0) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where Wagmi would not correctly rehydrate the active chain when a persisted store was being used. ## 2.6.16 ### Patch Changes - [#3788](https://github.com/wevm/wagmi/pull/3788) [`42ad380d`](https://github.com/wevm/wagmi/commit/42ad380d9a5d8bc0f61d73612142dea9d098de5e) Thanks [@tmm](https://github.com/tmm)! - Refactored connectors to remove unnecessarily event listeners. ## 2.6.15 ### Patch Changes - [#3782](https://github.com/wevm/wagmi/pull/3782) [`b907d5ac`](https://github.com/wevm/wagmi/commit/b907d5ac3a746bcbccc06d1fe78c5bd8f9a7d685) Thanks [@jxom](https://github.com/jxom)! - Refactored injected connector connection logic. ## 2.6.14 ### Patch Changes - [#3777](https://github.com/wevm/wagmi/pull/3777) [`b3b54ef1`](https://github.com/wevm/wagmi/commit/b3b54ef179c5fa0d1694d38d4b808549a0550409) Thanks [@desfero](https://github.com/desfero)! - Fixed `writeContract` to forward `chainIn` when simulating contract call - [#3779](https://github.com/wevm/wagmi/pull/3779) [`3da20bb8`](https://github.com/wevm/wagmi/commit/3da20bb80e7c3efeef8227ced66ad615370fc242) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where `eth_requestAccounts` would be called upon reconnect instead of `eth_accounts`. - [`a3d1858f`](https://github.com/wevm/wagmi/commit/a3d1858fce448d2b70e36ee692ef1589b74e9d3f) Thanks [@jxom](https://github.com/jxom)! - Fixed hydration conditional in `createConfig`. ## 2.6.13 ### Patch Changes - [`b80236dc`](https://github.com/wevm/wagmi/commit/b80236dc623095fe8f1e1d10957d7776fb6ab48b) Thanks [@jxom](https://github.com/jxom)! - Removed unneeded `uniqueBy` check on connectors state. ## 2.6.12 ### Patch Changes - [#3763](https://github.com/wevm/wagmi/pull/3763) [`a59069e9`](https://github.com/wevm/wagmi/commit/a59069e9fab45dd606bb89a7f829fe94c51a5494) Thanks [@tmm](https://github.com/tmm)! - Fixed `getConnectorClient` internal address comparison. - [#3608](https://github.com/wevm/wagmi/pull/3608) [`0acd3132`](https://github.com/wevm/wagmi/commit/0acd31320f534993af566be5490c2978b6184f66) Thanks [@mqklin](https://github.com/mqklin)! - Disabled `wallet_requestPermissions` prompt when `shimDisconnect` is `false`. ## 2.6.11 ### Patch Changes - [`e1ca4e63`](https://github.com/wevm/wagmi/commit/e1ca4e637ae6cec7f5902b0a2c0e0efc3b751a1d) Thanks [@tmm](https://github.com/tmm)! - Deprecated `normalizeChainId`. Use `Number` instead. ## 2.6.10 ### Patch Changes - [`dbdca8fd`](https://github.com/wevm/wagmi/commit/dbdca8fd14b90c166222a66a373c1b33c06ce019) Thanks [@jxom](https://github.com/jxom)! - Fixed issue where duplicate connectors could be instantiated if injected after page mount. ## 2.6.9 ### Patch Changes - [#3715](https://github.com/wevm/wagmi/pull/3715) [`d56edf4f`](https://github.com/wevm/wagmi/commit/d56edf4f27c52acc7a0f57114454b0d3e22cacd6) Thanks [@jxom](https://github.com/jxom)! - Fixed SSR hydration issues. ## 2.6.8 ### Patch Changes - [#3643](https://github.com/wevm/wagmi/pull/3643) [`e46bcd47`](https://github.com/wevm/wagmi/commit/e46bcd4738a18da15b53f6612b614379c1985374) Thanks [@TateB](https://github.com/TateB)! - Fixed race condition arising from `reconnect`. ## 2.6.7 ### Patch Changes - [#3642](https://github.com/wevm/wagmi/pull/3642) [`b479b5e8`](https://github.com/wevm/wagmi/commit/b479b5e8a5866cba792862f22e6352c4fb566137) Thanks [@johanneskares](https://github.com/johanneskares)! - Fixed a bug where minification caused the wrong functions to be called on the client. - [`f5648dd2`](https://github.com/wevm/wagmi/commit/f5648dd28b3576b628f57732b89287f55acbb1c1) Thanks [@jxom](https://github.com/jxom)! - Updated `prepareTransactionRequest` types for `viem@2.8.0`. - [`1c1fee6a`](https://github.com/wevm/wagmi/commit/1c1fee6ab8f01f7734ac6ce05093fa8e388beb3e) Thanks [@jxom](https://github.com/jxom)! - Updated `@walletconnect/ethereum-provider`. - [#3653](https://github.com/wevm/wagmi/pull/3653) [`88a2d744`](https://github.com/wevm/wagmi/commit/88a2d744a1315908c9e54156026df3ad2435ad44) Thanks [@tash-2s](https://github.com/tash-2s)! - Fixed error occurring when adding chains without explorers to MetaMask. ## 2.6.6 ### Patch Changes - [#3644](https://github.com/wevm/wagmi/pull/3644) [`a91c0b64`](https://github.com/wevm/wagmi/commit/a91c0b64ba8b3e6537a560e69724eb601f26af27) Thanks [@nishuzumi](https://github.com/nishuzumi)! - Exported types ## 2.6.5 ### Patch Changes - [#3580](https://github.com/wevm/wagmi/pull/3580) [`c677dcd2`](https://github.com/wevm/wagmi/commit/c677dcd245dccdf69289a3d66dded237b09570a2) Thanks [@tmm](https://github.com/tmm)! - Updated internals. ## 2.6.4 ### Patch Changes - [#3571](https://github.com/wevm/wagmi/pull/3571) [`7c6618e6`](https://github.com/wevm/wagmi/commit/7c6618e6a0eb1ff39cf8f66b34d3ddc14be538fe) Thanks [@tmm](https://github.com/tmm)! - Fixed `getClient` passthrough properties from `createConfig`. - [#3558](https://github.com/wevm/wagmi/pull/3558) [`895f28e8`](https://github.com/wevm/wagmi/commit/895f28e873af7c8eda5ca85734ff67c8979fd950) Thanks [@tmm](https://github.com/tmm)! - Fixed connector warnings. ## 2.6.3 ### Patch Changes - [#3533](https://github.com/wevm/wagmi/pull/3533) [`9c3b85dd`](https://github.com/wevm/wagmi/commit/9c3b85dd0a9a4a593e1d7e029345275735330e32) Thanks [@tmm](https://github.com/tmm)! - Fixed `account` property passthrough for actions. - [`2a72214a`](https://github.com/wevm/wagmi/commit/2a72214a2901d6b6ddd39f80238aa0bd4db670a7) Thanks [@tmm](https://github.com/tmm)! - Shimmed EIP-1193 `removeListener` for injected since some wallets do not follow spec. ## 2.6.2 ### Patch Changes - [#3519](https://github.com/wevm/wagmi/pull/3519) [`414eb048`](https://github.com/wevm/wagmi/commit/414eb048af492caac70c0e874dfc87c30702804a) Thanks [@tmm](https://github.com/tmm)! - Fixed multicall passing through all properties to Viem method. - [#3518](https://github.com/wevm/wagmi/pull/3518) [`338e857d`](https://github.com/wevm/wagmi/commit/338e857d8cb2fe85e13d9207bef14cada1c1962d) Thanks [@tmm](https://github.com/tmm)! - Fixed internal store migration between versions. ## 2.6.1 ### Patch Changes - [#3510](https://github.com/wevm/wagmi/pull/3510) [`660ff80d`](https://github.com/wevm/wagmi/commit/660ff80d5b046967a446eba43ee54b8359a37d0d) Thanks [@tmm](https://github.com/tmm)! - Fixed issue where connectors returning multiple addresses didn't checksum correctly. - [#3433](https://github.com/wevm/wagmi/pull/3433) [`101a7dd1`](https://github.com/wevm/wagmi/commit/101a7dd131b0cae2dc25579ecab9044290efd37b) Thanks [@tmm](https://github.com/tmm)! - Fixed `getClient` and `getPublicClient` throwing when used with unconfigured `chainId`. ## 2.6.0 ### Minor Changes - [#3496](https://github.com/wevm/wagmi/pull/3496) [`ba7f8a75`](https://github.com/wevm/wagmi/commit/ba7f8a758efb07664c6e401b5e7e325e7c62341b) Thanks [@tmm](https://github.com/tmm)! - Updated action internals to resolve Viem Client actions. ## 2.5.0 ### Minor Changes - [#3461](https://github.com/wevm/wagmi/pull/3461) [`ca98041d`](https://github.com/wevm/wagmi/commit/ca98041d1b39893d90246929485f4db0d1c6f9f7) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Added `getTransactionConfirmations` action. ## 2.4.0 ### Minor Changes - [#3427](https://github.com/wevm/wagmi/pull/3427) [`370f1b4a`](https://github.com/wevm/wagmi/commit/370f1b4a3f154d181acf381c31c2e7862e22c0e4) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Added `prepareTransactionRequest` action. ## 2.3.1 ### Patch Changes - [#3476](https://github.com/wevm/wagmi/pull/3476) [`3be5bb7b`](https://github.com/wevm/wagmi/commit/3be5bb7b0b38646e12e6da5c762ef74dff66bcc2) Thanks [@jxom](https://github.com/jxom)! - Modified persist strategy to only store "critical" properties that are needed before hydration. ## 2.3.0 ### Minor Changes - [#3459](https://github.com/wevm/wagmi/pull/3459) [`d950b666`](https://github.com/wevm/wagmi/commit/d950b666b56700ca039ce16cdfdf34564991e7f5) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Added `getEnsText` action. ### Patch Changes - [#3467](https://github.com/wevm/wagmi/pull/3467) [`90ef39bb`](https://github.com/wevm/wagmi/commit/90ef39bb0f4ecb3c914d317875348e35ba0f4524) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where connectors that share the same provider instance could reconnect when they have never been connected before. - [`1cfb6e5a`](https://github.com/wevm/wagmi/commit/1cfb6e5a875e707abcee00dd5739e87da05e8c90) Thanks [@jxom](https://github.com/jxom)! - Bumped listener limit on WalletConnect connector. ## 2.2.1 ### Patch Changes - [#3447](https://github.com/wevm/wagmi/pull/3447) [`a02a26ad`](https://github.com/wevm/wagmi/commit/a02a26ad030d3afb78f744377d61b5c60b65d97a) Thanks [@tmm](https://github.com/tmm)! - Fixed account typing. - [#3443](https://github.com/wevm/wagmi/pull/3443) [`007024a6`](https://github.com/wevm/wagmi/commit/007024a684ddbecf924cdc06dd6a8854fc3d5eeb) Thanks [@jmrossy](https://github.com/jmrossy)! - Fixed invalid `chainId` parameter passed through actions to Viem. ## 2.2.0 ### Minor Changes - [#3434](https://github.com/wevm/wagmi/pull/3434) [`00bf10a4`](https://github.com/wevm/wagmi/commit/00bf10a428b0d1c5dac35ebf25b19571e033ac26) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Added `getBytecode` and `getStorageAt` actions. - [#3416](https://github.com/wevm/wagmi/pull/3416) [`64c073f6`](https://github.com/wevm/wagmi/commit/64c073f6c2720961e2d6aff986670b73dbfab9c3) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Added `getTransactionReceipt` action. - [#3408](https://github.com/wevm/wagmi/pull/3408) [`fb6c4148`](https://github.com/wevm/wagmi/commit/fb6c4148d9e9e2fccfbe74c8f343b444dc68dec5) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Added `getProof` action. ## 2.1.2 ### Patch Changes - [#3407](https://github.com/wevm/wagmi/pull/3407) [`e00b8205`](https://github.com/wevm/wagmi/commit/e00b82058685751637edfa9a6b2d196a12549fe7) Thanks [@jxom](https://github.com/jxom)! - Added a prelude gas estimate check to `sendTransaction`/`useSendTransaction`. ## 2.1.1 ### Patch Changes - [#3402](https://github.com/wevm/wagmi/pull/3402) [`64b82282`](https://github.com/wevm/wagmi/commit/64b82282c1e57e77c25aa0814673780e4d11edd4) Thanks [@Songkeys](https://github.com/Songkeys)! - Fixed SSR cookie support for cookies that have special characters, e.g. `=`. - [`ec0d8b41`](https://github.com/wevm/wagmi/commit/ec0d8b4112181fefb11025e436a94a6114761d37) Thanks [@tmm](https://github.com/tmm)! - Added note to `metaMask` connector. ## 2.1.0 ### Minor Changes - [#3387](https://github.com/wevm/wagmi/pull/3387) [`c9cd302e`](https://github.com/wevm/wagmi/commit/c9cd302e1c65c980deaee2e12567c2a8ec08b399) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Added `call` action. ## 2.0.2 ### Patch Changes - [#3384](https://github.com/wevm/wagmi/pull/3384) [`ee868c33`](https://github.com/wevm/wagmi/commit/ee868c3385dae511230b6ddcb5627c1293cc1844) Thanks [@tmm](https://github.com/tmm)! - Fixed connectors not bubbling error when connecting with `chainId` and subsequent user rejection. ## 2.0.1 ### Major Changes - [#3333](https://github.com/wevm/wagmi/pull/3333) [`b3a0baaa`](https://github.com/wevm/wagmi/commit/b3a0baaaee7decf750d376aab2502cd33ca4825a) Thanks [@tmm](https://github.com/tmm)! - Wagmi Core 2.0 featuring: - Full TanStack Query support + queryKeys - Connect multiple connectors - Switch chains while disconnected - EIP-6963 enabled - Strongly typed chainId and chain properties - Smaller bundle size - Miscellaneous improvements and bug fixes [Breaking Changes & Migration Guide](https://wagmi.sh/core/guides/migrate-from-v1-to-v2) ## 1.4.13 ### Patch Changes - Updated dependencies [[`bbbbf587`](https://github.com/wevm/wagmi/commit/bbbbf587e41bae12b072b7a7c897d580fc07cd2b)]: - @wagmi/connectors@3.1.11 ## 1.4.12 ### Patch Changes - [`53ca1f7e`](https://github.com/wevm/wagmi/commit/53ca1f7eb411d912e11fcce7e03bd61ed067959c) Thanks [@tmm](https://github.com/tmm)! - Removed LedgerConnector due to security vulnerability - Updated dependencies [[`53ca1f7e`](https://github.com/wevm/wagmi/commit/53ca1f7eb411d912e11fcce7e03bd61ed067959c)]: - @wagmi/connectors@3.1.10 ## 1.4.11 ### Patch Changes - [#3299](https://github.com/wevm/wagmi/pull/3299) [`b02020b3`](https://github.com/wevm/wagmi/commit/b02020b3724e0228198f35817611bb063295906e) Thanks [@dasanra](https://github.com/dasanra)! - Fixed issue with [Safe SDK](https://github.com/wevm/viem/issues/579) by bumping `@safe-global/safe-apps-provider@0.18.1` - Updated dependencies [[`51eca0fb`](https://github.com/wevm/wagmi/commit/51eca0fbaea6932f31a5b8b4213f0252280053e2), [`b02020b3`](https://github.com/wevm/wagmi/commit/b02020b3724e0228198f35817611bb063295906e)]: - @wagmi/connectors@3.1.9 ## 1.4.10 ### Patch Changes - Updated dependencies [[`e8f7bcbc`](https://github.com/wevm/wagmi/commit/e8f7bcbcd9c038a901c29e71769682c088efe2ac)]: - @wagmi/connectors@3.1.8 ## 1.4.9 ### Patch Changes - [#3276](https://github.com/wevm/wagmi/pull/3276) [`83223a06`](https://github.com/wevm/wagmi/commit/83223a0659e2f675d897a1d3374c7af752c16abf) Thanks [@glitch-txs](https://github.com/glitch-txs)! - Removed required namespaces from WalletConnect connector - Updated dependencies [[`83223a06`](https://github.com/wevm/wagmi/commit/83223a0659e2f675d897a1d3374c7af752c16abf)]: - @wagmi/connectors@3.1.7 ## 1.4.8 ### Patch Changes - Updated dependencies [[`cc7e18f2`](https://github.com/wevm/wagmi/commit/cc7e18f2e7f6b8b989f60f0b05aee70e996a9975), [`cc7e18f2`](https://github.com/wevm/wagmi/commit/cc7e18f2e7f6b8b989f60f0b05aee70e996a9975)]: - @wagmi/connectors@3.1.6 ## 1.4.7 ### Patch Changes - Updated dependencies [[`a1950449`](https://github.com/wagmi-dev/wagmi/commit/a1950449127ddf72fff8ecd1fc34c3690befbb05)]: - @wagmi/connectors@3.1.5 ## 1.4.6 ### Patch Changes - Updated dependencies [[`4e6ec415`](https://github.com/wagmi-dev/wagmi/commit/4e6ec4151baece94e940e227e0e3711c7f8534d9)]: - @wagmi/connectors@3.1.4 ## 1.4.5 ### Patch Changes - Updated dependencies [[`e78aa337`](https://github.com/wagmi-dev/wagmi/commit/e78aa337c454f04b41a3cbd381d25270dd4a0afd)]: - @wagmi/connectors@3.1.3 ## 1.4.4 ### Patch Changes - [#3125](https://github.com/wagmi-dev/wagmi/pull/3125) [`725e73fe`](https://github.com/wagmi-dev/wagmi/commit/725e73feb9143dbaa6d540bb76d2009cef29da0b) Thanks [@lukasrosario](https://github.com/lukasrosario)! - Fixed an issue where `dataSuffix` was not being passed down into viem's `simulateContract`, causing the data to be omitted from requests. ## 1.4.3 ### Patch Changes - [#3076](https://github.com/wagmi-dev/wagmi/pull/3076) [`4c36831b`](https://github.com/wagmi-dev/wagmi/commit/4c36831b7aa44d03b5c0decf64dcd20faae28a67) Thanks [@jxom](https://github.com/jxom)! - Pass `chain` to viem `sendTransaction`/`writeContract`. - [#3006](https://github.com/wagmi-dev/wagmi/pull/3006) [`f2ddce23`](https://github.com/wagmi-dev/wagmi/commit/f2ddce23324aff0a91e066100918dac552dc3b4a) Thanks [@jxom](https://github.com/jxom)! - Changed `normalize` to a dynamic import. ## 1.4.2 ### Patch Changes - Updated dependencies [[`3aaba328`](https://github.com/wagmi-dev/wagmi/commit/3aaba32808ddb4035ec885f96992c91078056715)]: - @wagmi/connectors@3.1.2 ## 1.4.1 ### Patch Changes - Updated dependencies [[`bf831bb3`](https://github.com/wagmi-dev/wagmi/commit/bf831bb30df8037cc4312342d0fe3c045408c2fe)]: - @wagmi/connectors@3.1.1 ## 1.4.0 ### Minor Changes - [#2956](https://github.com/wagmi-dev/wagmi/pull/2956) [`2abeb285`](https://github.com/wagmi-dev/wagmi/commit/2abeb285674af3e539cc2550b1f5027b1eb0c895) Thanks [@tmm](https://github.com/tmm)! - Replaced `@wagmi/chains` with `viem/chains`. ### Patch Changes - Updated dependencies [[`2abeb285`](https://github.com/wagmi-dev/wagmi/commit/2abeb285674af3e539cc2550b1f5027b1eb0c895)]: - @wagmi/connectors@3.1.0 ## 1.3.10 ### Patch Changes - [`557e6400`](https://github.com/wagmi-dev/wagmi/commit/557e6400b9cef3b2c5131739143956c37d7c934a) Thanks [@jxom](https://github.com/jxom)! - Updated references. ## 1.3.9 ### Patch Changes - [`247c5d11`](https://github.com/wagmi-dev/wagmi/commit/247c5d113e83acf3a6894264c00d4b125d455107) Thanks [@jxom](https://github.com/jxom)! - Updated references. ## 1.3.8 ### Patch Changes - [#2741](https://github.com/wagmi-dev/wagmi/pull/2741) [`5b1453d9`](https://github.com/wagmi-dev/wagmi/commit/5b1453d95973ed51f1c235a919fffb707eab9b70) Thanks [@jxom](https://github.com/jxom)! - Updated references ## 1.3.7 ### Patch Changes - [#2700](https://github.com/wagmi-dev/wagmi/pull/2700) [`30118e97`](https://github.com/wagmi-dev/wagmi/commit/30118e979b1b00302e035f31f58c15d1aed911d5) Thanks [@jxom](https://github.com/jxom)! - Updated references. ## 1.3.6 ### Patch Changes - [`7ad2fdb8`](https://github.com/wagmi-dev/wagmi/commit/7ad2fdb81c7734d0c8107670800c68390e3bad99) Thanks [@jxom](https://github.com/jxom)! - Updated references. ## 1.3.5 ### Patch Changes - [`aab63fc1`](https://github.com/wagmi-dev/wagmi/commit/aab63fc1f8949004573978ecd8574fada3360758) Thanks [@jxom](https://github.com/jxom)! - Updated references. ## 1.3.4 ### Patch Changes - [`22246d98`](https://github.com/wagmi-dev/wagmi/commit/22246d9884277d28ccad6ca2d9529b96b67d47fc) Thanks [@jxom](https://github.com/jxom)! - Updated references. ## 1.3.3 ### Patch Changes - [`1946aa43`](https://github.com/wagmi-dev/wagmi/commit/1946aa43a65b684ef41b7b4c43c67bf29c13e854) Thanks [@jxom](https://github.com/jxom)! - Updated references ## 1.3.2 ### Patch Changes - [`e86d0940`](https://github.com/wagmi-dev/wagmi/commit/e86d09409bb20b64d24e1263abcf0291314f03c7) Thanks [@jxom](https://github.com/jxom)! - Updated references ## 1.3.1 ### Patch Changes - [`964042fa`](https://github.com/wagmi-dev/wagmi/commit/964042fa94d682977923c595820c58283fb9244a) Thanks [@jxom](https://github.com/jxom)! - Updated references. ## 1.3.0 ### Minor Changes - [#2619](https://github.com/wagmi-dev/wagmi/pull/2619) [`0d79748c`](https://github.com/wagmi-dev/wagmi/commit/0d79748cec2b6ac2410ad2c9816cc662f2b70962) Thanks [@jxom](https://github.com/jxom)! - Updated references: - Updated `@safe-global/safe-apps-sdk` to `^8.0.0` (the one with `viem` support) ## 1.2.2 ### Patch Changes - [#2611](https://github.com/wagmi-dev/wagmi/pull/2611) [`6d1ed7a1`](https://github.com/wagmi-dev/wagmi/commit/6d1ed7a156729b4df5d66fef3ae9a8b5762a2d34) Thanks [@jxom](https://github.com/jxom)! - Updated references. ## 1.2.1 ### Patch Changes - [#2589](https://github.com/wagmi-dev/wagmi/pull/2589) [`9680c347`](https://github.com/wagmi-dev/wagmi/commit/9680c347476500d28ceca20d23eeaed7931cb6e0) Thanks [@jxom](https://github.com/jxom)! - Fixed `writeContract` parameters to be compatible with `prepareWriteContract`. - [#2587](https://github.com/wagmi-dev/wagmi/pull/2587) [`cfff9994`](https://github.com/wagmi-dev/wagmi/commit/cfff999459384ac644ff7e62f53a7b787cf37507) Thanks [@jxom](https://github.com/jxom)! - Updated references ## 1.2.0 ### Minor Changes - [#2536](https://github.com/wagmi-dev/wagmi/pull/2536) [`85e9760a`](https://github.com/wagmi-dev/wagmi/commit/85e9760a140cb169ac6236d9466b96e2105dd193) Thanks [@tmm](https://github.com/tmm)! - Changed `Address` type import from ABIType to viem. ### Patch Changes - [#2539](https://github.com/wagmi-dev/wagmi/pull/2539) [`96319c64`](https://github.com/wagmi-dev/wagmi/commit/96319c640b9d07b375821c08a5c213355d8c290b) Thanks [@jxom](https://github.com/jxom)! - Updated references ## 1.1.1 ### Patch Changes - [`02b98a9f`](https://github.com/wagmi-dev/wagmi/commit/02b98a9f9b2c503a47af4a8967e0202b5db21787) Thanks [@jxom](https://github.com/jxom)! - Updated `viem` peer dependency. - [`02b98a9f`](https://github.com/wagmi-dev/wagmi/commit/02b98a9f9b2c503a47af4a8967e0202b5db21787) Thanks [@jxom](https://github.com/jxom)! - Updated references. ## 1.1.0 ### Minor Changes - [#2482](https://github.com/wagmi-dev/wagmi/pull/2482) [`8764b54a`](https://github.com/wagmi-dev/wagmi/commit/8764b54aab68020063946112e8fe52aff650c99c) Thanks [@tmm](https://github.com/tmm)! - Bumped minimum TypeScript version to v5.0.4. ### Patch Changes - [#2484](https://github.com/wagmi-dev/wagmi/pull/2484) [`3adf1f4f`](https://github.com/wagmi-dev/wagmi/commit/3adf1f4feab863cb7b5d52c81ad46f7e4eb56f09) Thanks [@jxom](https://github.com/jxom)! - Updated `abitype` to 0.8.7 - [#2484](https://github.com/wagmi-dev/wagmi/pull/2484) [`3adf1f4f`](https://github.com/wagmi-dev/wagmi/commit/3adf1f4feab863cb7b5d52c81ad46f7e4eb56f09) Thanks [@jxom](https://github.com/jxom)! - Updated references. ## 1.0.8 ### Patch Changes - [#2441](https://github.com/wagmi-dev/wagmi/pull/2441) [`326edee4`](https://github.com/wagmi-dev/wagmi/commit/326edee4bc85db84a7a4e3768e33785849ab8d8e) Thanks [@tmm](https://github.com/tmm)! - Fixed internal type issue ## 1.0.7 ### Patch Changes - [#2433](https://github.com/wagmi-dev/wagmi/pull/2433) [`54fcff5f`](https://github.com/wagmi-dev/wagmi/commit/54fcff5f02f6933bbbe045ee0c83c5a78b6bba49) Thanks [@jxom](https://github.com/jxom)! - Added ability to pass an `account` to `writeContract`/`prepareWriteContract`. ## 1.0.6 ### Patch Changes - [`ca2e1e96`](https://github.com/wagmi-dev/wagmi/commit/ca2e1e96149b87a7dc42c9db07e1f1ad2bb02c4a) Thanks [@jxom](https://github.com/jxom)! - Updated references. - [#2401](https://github.com/wagmi-dev/wagmi/pull/2401) [`0f9dc875`](https://github.com/wagmi-dev/wagmi/commit/0f9dc875e90cfdd7a2028e04b7204caf9ea313b2) Thanks [@jxom](https://github.com/jxom)! - Exposed `account` on `readContract`/`useContractRead`. ## 1.0.5 ### Patch Changes - [`90e2b3b3`](https://github.com/wagmi-dev/wagmi/commit/90e2b3b39efe0585fe28645ac2264109be17362a) Thanks [@jxom](https://github.com/jxom)! - Updated references. ## 1.0.4 ### Patch Changes - [#2344](https://github.com/wagmi-dev/wagmi/pull/2344) [`8a725458`](https://github.com/wagmi-dev/wagmi/commit/8a72545853ae1024acd9efd18c06142e8c6c5750) Thanks [@jxom](https://github.com/jxom)! - Added gas estimation back into `prepareSendTransaction`. ## 1.0.3 ### Patch Changes - [#2338](https://github.com/wagmi-dev/wagmi/pull/2338) [`92bfdc2c`](https://github.com/wagmi-dev/wagmi/commit/92bfdc2c744539558ba93c95f140b46ad331cee4) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where synchronous switch chain behavior (WalletConnect v2) would encounter chain id race conditions in `watchWalletClient`. ## 1.0.2 ### Patch Changes - [#2304](https://github.com/wevm/wagmi/pull/2304) [`09a4fd38`](https://github.com/wevm/wagmi/commit/09a4fd38f44eb176797925fd85314be17b610cd4) Thanks [@jxom](https://github.com/jxom)! - Removed assert chain workaround. ## 1.0.1 ### Patch Changes - [`ea651cd7`](https://github.com/wevm/wagmi/commit/ea651cd7fc75b7866272605467db11fd6e1d81af) Thanks [@jxom](https://github.com/jxom)! - Downgraded abitype. - Updated dependencies [[`ea651cd7`](https://github.com/wevm/wagmi/commit/ea651cd7fc75b7866272605467db11fd6e1d81af)]: - @wagmi/connectors@1.0.1 ## 1.0.0 ### Major Changes - [#2235](https://github.com/wevm/wagmi/pull/2235) [`5be0655c`](https://github.com/wevm/wagmi/commit/5be0655c8e48b25d38009022461fbf611af54349) Thanks [@jxom](https://github.com/jxom)! - Released v1. Read [Migration Guide](https://next.wagmi.sh/react/migration-guide#1xx-breaking-changes). ## 1.0.0-next.7 ### Major Changes - [#2235](https://github.com/wevm/wagmi/pull/2235) [`708b2ce2`](https://github.com/wevm/wagmi/commit/708b2ce26efa8d3d910806a97cea5171dabc65de) Thanks [@jxom](https://github.com/jxom)! - Added `config.setPublicClient` & `config.setWebSocketPublicClient` - Updated references. ### Patch Changes - Updated dependencies []: - @wagmi/connectors@1.0.0-next.5 ## 1.0.0-next.6 ### Major Changes - [#2235](https://github.com/wevm/wagmi/pull/2235) [`708b2ce2`](https://github.com/wevm/wagmi/commit/708b2ce26efa8d3d910806a97cea5171dabc65de) Thanks [@jxom](https://github.com/jxom)! - Added `config.setPublicClient` & `config.setWebSocketPublicClient` - Added `config.setConnectors` ### Patch Changes - Updated dependencies []: - @wagmi/connectors@1.0.0-next.6 ## 1.0.0-next.5 ### Major Changes - [#2235](https://github.com/wevm/wagmi/pull/2235) [`708b2ce2`](https://github.com/wevm/wagmi/commit/708b2ce26efa8d3d910806a97cea5171dabc65de) Thanks [@jxom](https://github.com/jxom)! - Added `config.setPublicClient` & `config.setWebSocketPublicClient` ## 1.0.0-next.4 ### Major Changes - Updated viem. Removed `goerli` export from main entrypoint. ### Patch Changes - Updated dependencies []: - @wagmi/connectors@1.0.0-next.5 ## 1.0.0-next.3 ### Major Changes - Updated references. ### Patch Changes - Updated dependencies []: - @wagmi/connectors@1.0.0-next.4 ## 1.0.0-next.2 ### Major Changes - **Breaking:** Renamed `createClient` to `createConfig` - **Breaking:** Renamed `getClient` to `getConfig` - **Breaking:** Removed `request` as an argument to `prepareSendTransaction` & `sendTransaction`. Arguments now belong on the root level of the Action. ### Patch Changes - Updated dependencies []: - @wagmi/chains@1.0.0-next.0 - @wagmi/connectors@1.0.0-next.3 ## 1.0.0-next.1 ### Major Changes - updated viem ### Patch Changes - Updated dependencies []: - @wagmi/connectors@1.0.0-next.2 ## 1.0.0-next.0 ### Major Changes - [`a7dda00c`](https://github.com/wevm/wagmi/commit/a7dda00c5b546f8b2c42b527e4d9ac1b9e9ab1fb) Thanks [@jxom](https://github.com/jxom)! - Released v1. ### Patch Changes - Updated dependencies [[`a7dda00c`](https://github.com/wevm/wagmi/commit/a7dda00c5b546f8b2c42b527e4d9ac1b9e9ab1fb)]: - @wagmi/connectors@1.0.0-next.1 ## 0.10.11 ### Patch Changes - [#2270](https://github.com/wevm/wagmi/pull/2270) [`6d1fa9df`](https://github.com/wevm/wagmi/commit/6d1fa9df790287729c3b33d4f01fd23c2f8153f1) Thanks [@jxom](https://github.com/jxom)! - Updated references. - Updated dependencies []: - @wagmi/connectors@0.3.19 ## 0.10.10 ### Patch Changes - [#2208](https://github.com/wevm/wagmi/pull/2208) [`cfc696d8`](https://github.com/wevm/wagmi/commit/cfc696d83c6f768a2e1a29c5197efeed7f1d40a1) Thanks [@bangtoven](https://github.com/bangtoven)! - Bumped references to apply coinbase wallet sdk updates - Updated dependencies []: - @wagmi/connectors@0.3.16 ## 0.10.9 ### Patch Changes - [#2143](https://github.com/wevm/wagmi/pull/2143) [`26dc5326`](https://github.com/wevm/wagmi/commit/26dc53260fde1d3278018c0b20a6d48a093d9427) Thanks [@tmm](https://github.com/tmm)! - Exported Sepolia Chain. - [#2146](https://github.com/wevm/wagmi/pull/2146) [`21b6842e`](https://github.com/wevm/wagmi/commit/21b6842e8c296a0bbe71ebe0780d898abc4cf4a8) Thanks [@tmm](https://github.com/tmm)! - Bumped references - Updated dependencies []: - @wagmi/connectors@0.3.12 ## 0.10.8 ### Patch Changes - [#2099](https://github.com/wevm/wagmi/pull/2099) [`f1fee5b3`](https://github.com/wevm/wagmi/commit/f1fee5b30a1bd13b5e66118bf9cdc44b0dc003a1) Thanks [@jxom](https://github.com/jxom)! - Added chains: - `nexi` - `polygonZkEvm` - `xdc` - `xdcTestnet` - [#2085](https://github.com/wevm/wagmi/pull/2085) [`7d64e3f5`](https://github.com/wevm/wagmi/commit/7d64e3f538a6149777bfa84ea9435769b2a7db58) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where multicall would not throw if the target chain was not configured on the wagmi client. - Updated dependencies []: - @wagmi/connectors@0.3.10 ## 0.10.7 ### Patch Changes - [#2082](https://github.com/wevm/wagmi/pull/2082) [`2ccc8a25`](https://github.com/wevm/wagmi/commit/2ccc8a255e93f0a2bb7b22101656b3905ec59abd) Thanks [@jxom](https://github.com/jxom)! - Updated references. - Updated dependencies []: - @wagmi/connectors@0.3.10 ## 0.10.6 ### Patch Changes - [#2056](https://github.com/wevm/wagmi/pull/2056) [`944f6513`](https://github.com/wevm/wagmi/commit/944f6513adf09a6f0b3bd34f591d3bbd1f1ffd2e) Thanks [@tmm](https://github.com/tmm)! - Bumped references. - Updated dependencies []: - @wagmi/connectors@0.3.8 ## 0.10.5 ### Patch Changes - [#2053](https://github.com/wevm/wagmi/pull/2053) [`665df1bf`](https://github.com/wevm/wagmi/commit/665df1bf2afccb533102069def395e19fb7194dd) Thanks [@tmm](https://github.com/tmm)! - Fixed issue where you add a new chain to MetaMask, but the switch after is rejected. - Updated dependencies []: - @wagmi/connectors@0.3.7 ## 0.10.4 ### Patch Changes - [#2046](https://github.com/wevm/wagmi/pull/2046) [`90d8e9b8`](https://github.com/wevm/wagmi/commit/90d8e9b87962b72c54311649537e91a953660f9b) Thanks [@tmm](https://github.com/tmm)! - Exported internal type. - Updated dependencies []: - @wagmi/connectors@0.3.6 ## 0.10.3 ### Patch Changes - [#2039](https://github.com/wevm/wagmi/pull/2039) [`bac893ab`](https://github.com/wevm/wagmi/commit/bac893ab26012d4d8741c4f80e8b8813aee26f0c) Thanks [@tmm](https://github.com/tmm)! - Updated references. - [#2043](https://github.com/wevm/wagmi/pull/2043) [`49a58320`](https://github.com/wevm/wagmi/commit/49a58320ab5f1f13bc4de25abcc028c8335e98f0) Thanks [@tmm](https://github.com/tmm)! - Removed `InjectedConnector` `shimChainChangedDisconnect` shim (no longer necessary). - Updated dependencies []: - @wagmi/connectors@0.3.6 ## 0.10.2 ### Patch Changes - [#2016](https://github.com/wevm/wagmi/pull/2016) [`06bf61de`](https://github.com/wevm/wagmi/commit/06bf61dee6d2920777bd9392491e6b7aedebe7ab) Thanks [@jxom](https://github.com/jxom)! - Added chains: - `boba` - `chronos` - `crossbell` - `dfk` - `dogechain` - `flare` - `flareTestnet` - `klaytn` - `scrollTestnet` - `shardeumSphinx` - `skaleCalypso` - `skaleCalypsoTestnet` - `skaleChaosTestnet` - `skaleCryptoBlades` - `skaleCryptoColosseum` - `skaleEuropa` - `skaleEuropaTestnet` - `skaleExorde` - `skaleHumanProtocol` - `skaleNebula` - `skaleNebulaTestnet` - `skaleRazor` - `skaleTitan` - `skaleTitanTestnet` - `songbird` - `songbirdTestnet` - `titan` - `titanTestnet` - `wanchain` - `wanchainTestnet` - [#2016](https://github.com/wevm/wagmi/pull/2016) [`06bf61de`](https://github.com/wevm/wagmi/commit/06bf61dee6d2920777bd9392491e6b7aedebe7ab) Thanks [@jxom](https://github.com/jxom)! - Updated references/ submodule. - Updated dependencies []: - @wagmi/connectors@0.3.4 ## 0.10.0 ### Minor Changes - [#1902](https://github.com/wevm/wagmi/pull/1902) [`0994e896`](https://github.com/wevm/wagmi/commit/0994e8966349b8811db0a5886db3831dafc99245) Thanks [@jxom](https://github.com/jxom)! - **Breaking:** Removed the `version` config option for `WalletConnectConnector`. `WalletConnectConnector` now uses WalletConnect v2 by default. WalletConnect v1 is now `WalletConnectLegacyConnector`. ### WalletConnect v2 ```diff import { WalletConnectConnector } from 'wagmi/connectors/walletConnect' const connector = new WalletConnectConnector({ options: { - version: '2', projectId: 'abc', }, }) ``` ### WalletConnect v1 ```diff -import { WalletConnectConnector } from 'wagmi/connectors/walletConnect' +import { WalletConnectConnector } from 'wagmi/connectors/walletConnectLegacy' -const connector = new WalletConnectConnector({ +const connector = new WalletConnectLegacyConnector({ options: { qrcode: true, }, }) ``` ### Patch Changes - Updated dependencies []: - @wagmi/connectors@0.3.2 ## 0.9.7 ### Patch Changes - [#1907](https://github.com/wevm/wagmi/pull/1907) [`cc4e74ee`](https://github.com/wevm/wagmi/commit/cc4e74ee19665eccb3767052dab6ab956ff4e676) Thanks [@jxom](https://github.com/jxom)! - Added the following chains to the `wagmi/chains` entrypoint: - `baseGoerli` - `harmonyOne` - `polygonZkEvmTestnet` - Updated dependencies []: - @wagmi/connectors@0.2.7 ## 0.9.6 ### Patch Changes - [#1882](https://github.com/wevm/wagmi/pull/1882) [`282cc1b0`](https://github.com/wevm/wagmi/commit/282cc1b02003684d582cea411b11792a59c26fd0) Thanks [@tmm](https://github.com/tmm)! - Updated references. - Updated dependencies []: - @wagmi/connectors@0.2.6 ## 0.9.5 ### Patch Changes - [#1812](https://github.com/wevm/wagmi/pull/1812) [`c7fd7fbd`](https://github.com/wevm/wagmi/commit/c7fd7fbde6f6c69a3a9a4f89d948c4dfb1d22679) Thanks [@jxom](https://github.com/jxom)! - Added the following chains to the `wagmi/chains` entrypoint: - `filecoinCalibration` - `moonbaseAlpha` - `moonbeam` - `moonriver` - Updated dependencies []: - @wagmi/connectors@0.2.5 ## 0.9.4 ### Patch Changes - [#1786](https://github.com/wevm/wagmi/pull/1786) [`b173a431`](https://github.com/wevm/wagmi/commit/b173a43165c7925a4e56ce1e0327a31917e7edc5) Thanks [@tmm](https://github.com/tmm)! - Locked ethers peer dependency version to >=5.5.1 <6 - [#1787](https://github.com/wevm/wagmi/pull/1787) [`f023fd8f`](https://github.com/wevm/wagmi/commit/f023fd8f66befb78b9a4df5ca971ceaa64e37ab4) Thanks [@tmm](https://github.com/tmm)! - Added `SafeConnector` - Updated dependencies []: - @wagmi/connectors@0.2.4 ## 0.9.3 ### Patch Changes - [#1773](https://github.com/wevm/wagmi/pull/1773) [`9aaf1955`](https://github.com/wevm/wagmi/commit/9aaf195514d3b5f4d085c797fc5021d42a9efb6c) Thanks [@jxom](https://github.com/jxom)! - Updated `@walletconnect/universal-provider` on `WalletConnectConnector` v2. Added more signable methods to `WalletConnectConnector` v2. - [#1773](https://github.com/wevm/wagmi/pull/1773) [`9aaf1955`](https://github.com/wevm/wagmi/commit/9aaf195514d3b5f4d085c797fc5021d42a9efb6c) Thanks [@jxom](https://github.com/jxom)! - Added Telos to the `wagmi/chains` entrypoint. Thanks @donnyquixotic! - Updated dependencies []: - @wagmi/connectors@0.2.3 ## 0.9.2 ### Patch Changes - [#1756](https://github.com/wevm/wagmi/pull/1756) [`31d06b8c`](https://github.com/wevm/wagmi/commit/31d06b8ce1e7af5e9d1a7ba57f1743b2dff7a53d) Thanks [@jxom](https://github.com/jxom)! - Added OKC Chain. Thanks @clark-cui! - [#1756](https://github.com/wevm/wagmi/pull/1756) [`31d06b8c`](https://github.com/wevm/wagmi/commit/31d06b8ce1e7af5e9d1a7ba57f1743b2dff7a53d) Thanks [@jxom](https://github.com/jxom)! - Fixed race condition between `switchNetwork` and mutation Actions that use `chainId` (e.g. `sendTransaction`). Thanks @DanInTheD4rk! - Updated dependencies []: - @wagmi/connectors@0.2.2 ## 0.9.1 ### Patch Changes - [#1752](https://github.com/wevm/wagmi/pull/1752) [`144a0e76`](https://github.com/wevm/wagmi/commit/144a0e76ef4bb9ba0650b5ffb9c63f95329819a4) Thanks [@jxom](https://github.com/jxom)! - Improved `WalletConnectConnector` (v2) initialization & updated dependencies. - [#1752](https://github.com/wevm/wagmi/pull/1752) [`144a0e76`](https://github.com/wevm/wagmi/commit/144a0e76ef4bb9ba0650b5ffb9c63f95329819a4) Thanks [@jxom](https://github.com/jxom)! - Added the following chains to the `wagmi/chains` entrypoint: - Aurora – thanks @salil-naik - Bronos – thanks @chedetinaveen - Canto – thanks @tster - Celo – thanks @aaronmgdr - Updated dependencies []: - @wagmi/connectors@0.2.1 ## 0.9.0 ### Minor Changes - [#1732](https://github.com/wevm/wagmi/pull/1732) [`01e21897`](https://github.com/wevm/wagmi/commit/01e2189747a5c22dc758c6d719b4145adc2a643c) Thanks [@tmm](https://github.com/tmm)! - Bumped minimum TypeScript version to typescript@>=4.9.4. TypeScript 5.0 is coming soon and has some great features we are excited to bring into wagmi. To prepare for this, update your TypeScript version to 4.9.4 or higher. There are likely no [breaking changes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#correctness-fixes-and-breaking-changes) if you are coming from typescript@4.7.x || typescript@4.8.x. ## 0.8.19 ### Patch Changes - [#1718](https://github.com/wevm/wagmi/pull/1718) [`e62b5ef8`](https://github.com/wevm/wagmi/commit/e62b5ef8aaa8063abb5264790768899ea35bbd31) Thanks [@tmm](https://github.com/tmm)! - Updated references ## 0.8.18 ### Patch Changes - [#1708](https://github.com/wevm/wagmi/pull/1708) [`07fc3801`](https://github.com/wevm/wagmi/commit/07fc3801fa13c2cb5f7cf9b86ba8320b05a6a135) Thanks [@jxom](https://github.com/jxom)! - Updated `references/` submodule. ## 0.8.17 ### Patch Changes - [#1705](https://github.com/wevm/wagmi/pull/1705) [`9ff797dc`](https://github.com/wevm/wagmi/commit/9ff797dcb979dc86b798a432b74c98598165430d) Thanks [@jxom](https://github.com/jxom)! - Added the following chains to the `@wagmi/core/chains` entrypoint: - `crossbell` (thanks @Songkeys) - `filecoin` & `filecoinHyperspace` (thanks @neil0x46dc) - `gnosisChiado` (thanks @theNvN) - `metis` & `metisGoerli` (thanks @CookedCookee) ## 0.8.16 ### Patch Changes - [#1699](https://github.com/wevm/wagmi/pull/1699) [`2f1e7950`](https://github.com/wevm/wagmi/commit/2f1e7950e55550d9b50ef5ccb97cb609f4af39b1) Thanks [@tmm](https://github.com/tmm)! - Added public RPC URL property to Chain ## 0.8.15 ### Patch Changes - [#1685](https://github.com/wevm/wagmi/pull/1685) [`917f5bc1`](https://github.com/wevm/wagmi/commit/917f5bc1fad578e35a8c6ee787e339bfdc156bab) Thanks [@jxom](https://github.com/jxom)! - Replaced qrcodemodal with web3modal for the WalletConnect v2 Connector. ## 0.8.14 ### Patch Changes - [#1646](https://github.com/wevm/wagmi/pull/1646) [`fcdbe353`](https://github.com/wevm/wagmi/commit/fcdbe3531e6d05cda4a4a511bae1ad4c9e426d88) Thanks [@jxom](https://github.com/jxom)! - Upgraded `zustand` to v4.3.1. ## 0.8.13 ### Patch Changes - [#1639](https://github.com/wevm/wagmi/pull/1639) [`c6869f06`](https://github.com/wevm/wagmi/commit/c6869f0604fffb197752a08256f31db77f52e746) Thanks [@jxom](https://github.com/jxom)! - Added `isRainbow` flag to `InjectedConnector`. ## 0.8.12 ### Patch Changes - [#1636](https://github.com/wevm/wagmi/pull/1636) [`025f6771`](https://github.com/wevm/wagmi/commit/025f6771b32ff7eed22f527be81c5141ddaf9c3d) Thanks [@DanielSinclair](https://github.com/DanielSinclair)! - Added `isRainbow` flag to injected `window.ethereum` types. ## 0.8.11 ### Patch Changes - [#1621](https://github.com/wevm/wagmi/pull/1621) [`5812b590`](https://github.com/wevm/wagmi/commit/5812b5909277bf2862cb57a31d52465b47291410) Thanks [@tmm](https://github.com/tmm)! - Bumped @wagmi/connectors ## 0.8.10 ### Patch Changes - [#1598](https://github.com/wevm/wagmi/pull/1598) [`fc10ebe6`](https://github.com/wevm/wagmi/commit/fc10ebe659dd5f3b7a8e00581f094652280a779b) Thanks [@jxom](https://github.com/jxom)! - Fixed CJS dependency version range ## 0.8.9 ### Patch Changes - [#1593](https://github.com/wevm/wagmi/pull/1593) [`216d555c`](https://github.com/wevm/wagmi/commit/216d555c62bd95c3c7c8f8e20f7269f6c8504610) Thanks [@jxom](https://github.com/jxom)! - Added CJS escape hatch bundle under the "cjs" tag. ## 0.8.8 ### Patch Changes - [#1573](https://github.com/wevm/wagmi/pull/1573) [`ef380d9c`](https://github.com/wevm/wagmi/commit/ef380d9c6d51ae0495b9c35925d2843c75d97fd4) Thanks [@tmm](https://github.com/tmm)! - Updated internal types. ## 0.8.7 ### Patch Changes - [#1570](https://github.com/wevm/wagmi/pull/1570) [`216f585b`](https://github.com/wevm/wagmi/commit/216f585be8a9e3a56e3243f49ccd54d655b5a6dd) Thanks [@wslyvh](https://github.com/wslyvh)! - Added `watchPendingTransactions` - [#1470](https://github.com/wevm/wagmi/pull/1470) [`3a1a6c9f`](https://github.com/wevm/wagmi/commit/3a1a6c9fe5db5c360adfd116f9a03a1238b5720c) Thanks [@jxom](https://github.com/jxom)! - The `WalletConnectConnector` now supports WalletConnect v2. It can be enabled by setting `version` to `'2'` and supplying a [WalletConnect Cloud `projectId`](https://cloud.walletconnect.com/sign-in). ## 0.8.6 ### Patch Changes - [#1539](https://github.com/wevm/wagmi/pull/1539) [`732da004`](https://github.com/wevm/wagmi/commit/732da0042c7e28091b2e36a484ea8239971306f5) Thanks [@0xFlicker](https://github.com/0xFlicker)! - All Providers (ie. Alchemy, Infura, Public) now use the ENS Registry address on the wagmi `Chain` object (`chain.contracts.ensRegistry`). - [#1574](https://github.com/wevm/wagmi/pull/1574) [`ecde3d10`](https://github.com/wevm/wagmi/commit/ecde3d1029ccdf90e2853ba0e9ae4f5f4ebb9c4c) Thanks [@jxom](https://github.com/jxom)! - Added the following chains: - `iotex` - `iotexTestnet` - `zkSync` - `zkSyncTestnet` ## 0.8.5 ### Patch Changes - [#1542](https://github.com/wevm/wagmi/pull/1542) [`731b3b73`](https://github.com/wevm/wagmi/commit/731b3b733c6a093d1693d49de601705b7c730549) Thanks [@jxom](https://github.com/jxom)! - Added the following chains: - `evmos` - `evmosTestnet` - `gnosis` - [#1542](https://github.com/wevm/wagmi/pull/1542) [`731b3b73`](https://github.com/wevm/wagmi/commit/731b3b733c6a093d1693d49de601705b7c730549) Thanks [@jxom](https://github.com/jxom)! - Updated Goerli symbol to `"ETH"`. - [#1542](https://github.com/wevm/wagmi/pull/1542) [`731b3b73`](https://github.com/wevm/wagmi/commit/731b3b733c6a093d1693d49de601705b7c730549) Thanks [@jxom](https://github.com/jxom)! - Updated Arbitrum Goerli RPC and Block Explorer. - [#1542](https://github.com/wevm/wagmi/pull/1542) [`731b3b73`](https://github.com/wevm/wagmi/commit/731b3b733c6a093d1693d49de601705b7c730549) Thanks [@jxom](https://github.com/jxom)! - Fixed issue where connecting to MetaMask may return with a stale address. - [#1542](https://github.com/wevm/wagmi/pull/1542) [`731b3b73`](https://github.com/wevm/wagmi/commit/731b3b733c6a093d1693d49de601705b7c730549) Thanks [@jxom](https://github.com/jxom)! - Removed ENS registry for Sepolia. ## 0.8.4 ### Patch Changes - [#1508](https://github.com/wevm/wagmi/pull/1508) [`0b50b62f`](https://github.com/wevm/wagmi/commit/0b50b62f7389619e429509a3e337e451e823b059) Thanks [@jxom](https://github.com/jxom)! - Updated `@wagmi/chains` to `0.1.3`. - [#1504](https://github.com/wevm/wagmi/pull/1504) [`11b8b794`](https://github.com/wevm/wagmi/commit/11b8b794fbfd4a2b40f39962e2758e9fbf48cb54) Thanks [@tmm](https://github.com/tmm)! - Converted ethers custom "ACTION_REJECTED" error to standard RPC Error. ## 0.8.3 ### Patch Changes - [#1431](https://github.com/wevm/wagmi/pull/1431) [`af28f8f9`](https://github.com/wevm/wagmi/commit/af28f8f9cfc227e7c391927fdb934183edb5c2dc) Thanks [@jxom](https://github.com/jxom)! - Re-export connectors from `@wagmi/connectors` - [#1431](https://github.com/wevm/wagmi/pull/1431) [`af28f8f9`](https://github.com/wevm/wagmi/commit/af28f8f9cfc227e7c391927fdb934183edb5c2dc) Thanks [@jxom](https://github.com/jxom)! - Added `LedgerConnector` connector ## 0.8.2 ### Patch Changes - [#1442](https://github.com/wevm/wagmi/pull/1442) [`cde15289`](https://github.com/wevm/wagmi/commit/cde152899c758dea10787412b0aef669ed7202b2) Thanks [@0xproflupin](https://github.com/0xproflupin)! - Added Phantom wallet support to `InjectedConnector` - [#1448](https://github.com/wevm/wagmi/pull/1448) [`c6075f3a`](https://github.com/wevm/wagmi/commit/c6075f3a16885d850ad2656272351f9517c9f67b) Thanks [@tmm](https://github.com/tmm)! - Updated [ABIType](https://github.com/wevm/abitype) version. - [#1444](https://github.com/wevm/wagmi/pull/1444) [`310a8bc4`](https://github.com/wevm/wagmi/commit/310a8bc428ce4e7f68377f581b45dcdd64381cce) Thanks [@jxom](https://github.com/jxom)! - Assert that a `connector` exists before invoking the callback in `watchSigner`. - [#1434](https://github.com/wevm/wagmi/pull/1434) [`100e2a3b`](https://github.com/wevm/wagmi/commit/100e2a3b22f4602716554487b1d98738e053be76) Thanks [@tmm](https://github.com/tmm)! - Updated `MockConnector` `chainId` behavior to default to first chain from `chains` if not provided in `options`. ## 0.8.1 ### Patch Changes - [#1437](https://github.com/wevm/wagmi/pull/1437) [`c34a3dc6`](https://github.com/wevm/wagmi/commit/c34a3dc6396e6473d9f0505fad88ec910f8f5275) Thanks [@jxom](https://github.com/jxom)! - Omitted `"EIP712Domain"` type from `signTypedData` `types` arg since ethers throws an [internal error](https://github.com/ethers-io/ethers.js/blob/c80fcddf50a9023486e9f9acb1848aba4c19f7b6/packages/hash/src.ts/typed-data.ts#L466) if you include it. - [#1445](https://github.com/wevm/wagmi/pull/1445) [`51dd53cb`](https://github.com/wevm/wagmi/commit/51dd53cba3fe0f79fa1393270b738194577ddf54) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where the wagmi client wouldn't rehydrate the store in local storage when `autoConnect` is truthy. ## 0.8.0 ### Minor Changes - [#1344](https://github.com/wevm/wagmi/pull/1344) [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: the shape of the `Chain` type has been modified. #### RPC URLs The `rpcUrls` shape has changed to include an array of URLs, and also the transport method (`http` or `webSocket`): ```diff type Chain = { ... rpcUrls: { - [key: string]: string + [key: string]: { + http: string[] + webSocket: string[] + } } ... } ``` Note that you will also need to ensure that usage is migrated: ```diff - const rpcUrl = mainnet.rpcUrls.alchemy + const rpcUrl = mainnet.rpcUrls.alchemy.http[0] ``` #### Contracts The `multicall` and `ens` attributes have been moved into the `contracts` object: ```diff type Contract = { address: Address blockCreated?: number } type Chain = { ... - multicall: Contract - ens: Contract + contracts: { + multicall3: Contract + ensRegistry: Contract + } ... } ``` Note that you will also need to ensure that usage is migrated: ```diff - const multicallContract = mainnet.multicall + const multicallContract = mainnet.contracts.multicall3 ``` - [#1344](https://github.com/wevm/wagmi/pull/1344) [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: Upgraded `@coinbase/wallet-sdk` peer dependency to `3.6.0`. **Migration steps**: Update `@coinbase/wallet-sdk` to `^3.6.0`. - [#1344](https://github.com/wevm/wagmi/pull/1344) [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: Removed the `wait` argument on `waitForTransaction`. Use the transaction `hash` instead. ```diff const data = await waitForTransaction({ - wait: transaction.wait + hash: transaction.hash }) ``` - [#1344](https://github.com/wevm/wagmi/pull/1344) [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: With the introduction of the [`@wagmi/core/chains` entrypoint](/core/chains), `@wagmi/core` no longer exports the following: - `chain` - `allChains` - `defaultChains` - `defaultL2Chains` - `chainId` - `etherscanBlockExplorers` - `alchemyRpcUrls`, `infuraRpcUrls`, `publicRpcUrls` Read below for migration steps. #### Removed `chain` The `chain` export has been removed. `@wagmi/core` now only exports the `mainnet` & `goerli` chains. If you need to use an alternative chain (`polygon`, `optimism`, etc), you will need to import it from the [`@wagmi/core/chains` entrypoint](/core/chains). ```diff import { - chain configureChains } from '@wagmi/core' + import { mainnet, polygon, optimism } from '@wagmi/core/chains' const { ... } = configureChains( - [chain.mainnet, chain.polygon, chain.optimism], + [mainnet, polygon, optimism], { ... } ) ``` #### Removed `allChains` The `allChains` export has been removed. If you need a list of all chains, you can utilize [`@wagmi/core/chains` entrypoint](/core/chains). ```diff - import { allChains } from '@wagmi/core' + import * as allChains from '@wagmi/core/chains' const { ... } = configureChains(allChains, ...) ``` #### Removed `defaultChains` & `defaultL2Chains` The `defaultChains` & `defaultL2Chains` exports have been removed. If you still need the `defaultChains` or `defaultL2Chains` exports, you can build them yourself: ```diff - import { defaultChains } from '@wagmi/core' + import { mainnet, goerli } from '@wagmi/core/chains' + const defaultChains = [mainnet, goerli] ``` > The `defaultChains` export was previously populated with `mainnet` & `goerli`. ```diff - import { defaultL2Chains } from '@wagmi/core' + import { + arbitrum, + arbitrumGoerli, + polygon, + polygonMumbai, + optimism, + optimismGoerli + } from '@wagmi/core/chains' + const defaultL2Chains = [ + arbitrum, + arbitrumGoerli, + polygon, + polygonMumbai, + optimism + optimismGoerli + ] ``` > The `defaultL2Chains` export was previously populated with `arbitrum` & `optimism`. #### Removed `chainId` The `chainId` export has been removed. You can extract a chain ID from the chain itself. ```diff - import { chainId } from '@wagmi/core' + import { mainnet, polygon, optimism } from '@wagmi/core/chains' -const mainnetChainId = chainId.mainnet -const polygonChainId = chainId.polygon -const optimismChainId = chainId.optimism +const mainnetChainId = mainnet.chainId +const polygonChainId = polygon.chainId +const optimismChainId = optimism.chainId ``` #### Removed `etherscanBlockExplorers` The `etherscanBlockExplorers` export has been removed. You can extract a block explorer from the chain itself. ```diff - import { etherscanBlockExplorers } from '@wagmi/core' + import { mainnet, polygon, optimism } from '@wagmi/core/chains' -const mainnetEtherscanBlockExplorer = etherscanBlockExplorers.mainnet -const polygonEtherscanBlockExplorer = etherscanBlockExplorers.polygon -const optimismEtherscanBlockExplorer = etherscanBlockExplorers.optimism +const mainnetEtherscanBlockExplorer = mainnet.blockExplorer +const polygonEtherscanBlockExplorer = polygon.blockExplorer +const optimismEtherscanBlockExplorer = optimism.blockExplorer ``` #### Removed `alchemyRpcUrls`, `infuraRpcUrls` & `publicRpcUrls` The `alchemyRpcUrls`, `infuraRpcUrls` & `publicRpcUrls` exports have been removed. You can extract a RPC URL from the chain itself. ```diff - import { alchemyRpcUrls, infuraRpcUrls, publicRpcUrls } from '@wagmi/core' + import { mainnet } from '@wagmi/core/chains' -const mainnetAlchemyRpcUrl = alchemyRpcUrls.mainnet -const mainnetInfuraRpcUrl = infuraRpcUrls.mainnet -const mainnetOptimismRpcUrl = publicRpcUrls.mainnet +const mainnetAlchemyRpcUrl = mainnet.rpcUrls.alchemy +const mainnetInfuraRpcUrl = mainnet.rpcUrls.infura +const mainnetOptimismRpcUrl = mainnet.rpcUrls.optimism ``` - [#1344](https://github.com/wevm/wagmi/pull/1344) [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: Changed `waitForTransaction` behavior to throw an error if the transaction reverted. - [#1344](https://github.com/wevm/wagmi/pull/1344) [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652) Thanks [@jxom](https://github.com/jxom)! - Updated errors to use `cause` instead of `internal` ### Patch Changes - [#1344](https://github.com/wevm/wagmi/pull/1344) [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652) Thanks [@jxom](https://github.com/jxom)! - `waitForTransaction` now respects repriced (sped up) transactions. - [#1344](https://github.com/wevm/wagmi/pull/1344) [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652) Thanks [@jxom](https://github.com/jxom)! - Export `getClient` - [#1344](https://github.com/wevm/wagmi/pull/1344) [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652) Thanks [@jxom](https://github.com/jxom)! - `waitForTransaction` now throws an error for cancelled or replaced transactions. ## 0.7.9 ### Patch Changes - [#1411](https://github.com/wevm/wagmi/pull/1411) [`659be184`](https://github.com/wevm/wagmi/commit/659be1840c613ce9f7aca9ac96694c4f60da4a66) Thanks [@tmm](https://github.com/tmm)! - Fixed issue where block invalidation was not properly disabled when setting `enabled: false`. ## 0.7.8 ### Patch Changes - [#1406](https://github.com/wevm/wagmi/pull/1406) [`4f18c450`](https://github.com/wevm/wagmi/commit/4f18c450a4d7952bfcfa6c533348ffbe55893d3c) Thanks [@tmm](https://github.com/tmm)! - Function for selecting the [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) Ethereum Provider to target. Defaults to `() => typeof window !== 'undefined' ? window.ethereum : undefined`. ```ts import { InjectedConnector } from "@wagmi/core/connectors/injected"; const connector = new InjectedConnector({ options: { name: "My Injected Wallet", getProvider: () => typeof window !== "undefined" ? window.myInjectedWallet : undefined, }, }); ``` ## 0.7.7 ### Patch Changes - [#1386](https://github.com/wevm/wagmi/pull/1386) [`206a2adb`](https://github.com/wevm/wagmi/commit/206a2adbb4ee5149a364543b34612050ccf78c21) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where `persister` would still use `window.localStorage` instead of the wagmi `storage`. - [#1376](https://github.com/wevm/wagmi/pull/1376) [`a70a9528`](https://github.com/wevm/wagmi/commit/a70a9528f93f4d7fea28b7652751dfef2dcacf9b) Thanks [@jxom](https://github.com/jxom)! - Fixed issue where `switchChain` on `WalletConnectConnector` would not resolve. - [#1386](https://github.com/wevm/wagmi/pull/1386) [`206a2adb`](https://github.com/wevm/wagmi/commit/206a2adbb4ee5149a364543b34612050ccf78c21) Thanks [@jxom](https://github.com/jxom)! - Added `serialize`/`deserialize` as config options to `createStorage`. - [#1392](https://github.com/wevm/wagmi/pull/1392) [`88afc849`](https://github.com/wevm/wagmi/commit/88afc84978afe9689ab7364633e4422ecd7699ea) Thanks [@tmm](https://github.com/tmm)! - Added check for active connector when connecting ## 0.7.6 ### Patch Changes - [#1384](https://github.com/wevm/wagmi/pull/1384) [`027e88d6`](https://github.com/wevm/wagmi/commit/027e88d6e5f8d028d46ee78aec8500701e0173d9) Thanks [@tmm](https://github.com/tmm)! - Fixed issue reconnecting after disconnect with `MetaMaskConnector` in MetaMask mobile browser. ## 0.7.5 ### Patch Changes - [`1169914a`](https://github.com/wevm/wagmi/commit/1169914a0f0ad2810ca1c536b1f1bc6c20f2c1be) Thanks [@jxom](https://github.com/jxom)! - Use `get_accounts` for `getSigner` in InjectedConnector ## 0.7.4 ### Patch Changes - [#1309](https://github.com/wevm/wagmi/pull/1309) [`1f4a4261`](https://github.com/wevm/wagmi/commit/1f4a4261247b1d3a90e3123157bc851a35d49b9c) Thanks [@tmm](https://github.com/tmm)! - Fixed internal type ## 0.7.3 ### Patch Changes - [#1294](https://github.com/wevm/wagmi/pull/1294) [`b2f88949`](https://github.com/wevm/wagmi/commit/b2f88949f32aabaf13f318472648cd51a8b7f2e7) Thanks [@tmm](https://github.com/tmm)! - Set `abi` return type value for `prepareContractWrite` as more permissive when not inferrable as `Abi`. ## 0.7.2 ### Patch Changes - [`e9f806b6`](https://github.com/wevm/wagmi/commit/e9f806b652ba62effb3ddac464815e447fc287f6) Thanks [@tmm](https://github.com/tmm)! - Bumped abitype and zustand versions. ## 0.7.1 ### Patch Changes - [#1272](https://github.com/wevm/wagmi/pull/1272) [`1f7fc41`](https://github.com/wevm/wagmi/commit/1f7fc419f7960bbdc51dfa85c2f33b89f1ecc1bf) Thanks [@tmm](https://github.com/tmm)! - Fixed ethers import path ## 0.7.0 ### Minor Changes - [#1202](https://github.com/wevm/wagmi/pull/1202) [`9bf56af`](https://github.com/wevm/wagmi/commit/9bf56af3c30bdb80abb1e785c002e00986fadfb2) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: Removed the following deprecated chains: - `ropsten` - `rinkeby` - `kovan` - `optimismKovan` - `arbitrumRinkeby` If you feel you still need to include one of these testnets in your application, you will have to define it manually: ```diff -import { rinkeby } from 'wagmi' +import { Chain } from 'wagmi' +export const rinkeby: Chain = { + id: 4, + name: 'Rinkeby', + network: 'rinkeby', + nativeCurrency: { name: 'Rinkeby Ether', symbol: 'ETH', decimals: 18 }, + rpcUrls: { + alchemy: 'https://eth-rinkeby.alchemyapi.io/v2', + default: 'https://rpc.ankr.com/eth_rinkeby', + infura: 'https://rinkeby.infura.io/v3', + public: 'https://rpc.ankr.com/eth_rinkeby', + }, + blockExplorers: { + etherscan: 'https://rinkeby.etherscan.io', + default: 'https://rinkeby.etherscan.io', + }, + ens: { + address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', + }, + multicall: { + address: '0xca11bde05977b3631167028862be2a173976ca11', + blockCreated: 10299530, + }, + testnet: true, } ``` You can reference these removed chains [here](https://github.com/wevm/wagmi/blob/389765f7d9af063ab0df07389a2bbfbc10a41060/packages/core/src/constants/chains.ts). - [#1202](https://github.com/wevm/wagmi/pull/1202) [`9bf56af`](https://github.com/wevm/wagmi/commit/9bf56af3c30bdb80abb1e785c002e00986fadfb2) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: `addressOrName` renamed to `address` for `fetchBalance` and `fetchEnsAvatar`. ```diff const result = await fetchBalance({ - addressOrName: '0x…', + address: '0x…', }) ``` If you were using an ENS name instead of an address, you can resolve the name to an address before passing it to the action. ```diff + const { data: address } = await fetchEnsAddress({ name: 'example.eth' }) const result = await fetchBalance({ - addressOrName: 'example.eth', + address, }) ``` - [#1202](https://github.com/wevm/wagmi/pull/1202) [`9bf56af`](https://github.com/wevm/wagmi/commit/9bf56af3c30bdb80abb1e785c002e00986fadfb2) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: Made `apiKey` required on `infuraProvider` and `alchemyProvider`. ```diff import { configureChains } from 'wagmi' const config = configureChains(defaultChains, [ - alchemyProvider(), + alchemyProvider({ apiKey: process.env.ALCHEMY_API_KEY }) ]) ``` You can find your Alchemy API key from the [Alchemy Dashboard](https://dashboard.alchemyapi.io/), or your Infura API key from the [Infura Dashboard](https://infura.io/login). - [#1202](https://github.com/wevm/wagmi/pull/1202) [`9bf56af`](https://github.com/wevm/wagmi/commit/9bf56af3c30bdb80abb1e785c002e00986fadfb2) Thanks [@tmm](https://github.com/tmm)! - Removed CommonJS support ## 0.6.12 ### Patch Changes - [#1250](https://github.com/wevm/wagmi/pull/1250) [`ce2e0f4`](https://github.com/wevm/wagmi/commit/ce2e0f4a46b8fd1c509ead552012ef4c072a525b) Thanks [@tmm](https://github.com/tmm)! - Added support for Trust Wallet browser extension. ## 0.6.11 ### Patch Changes - [#1234](https://github.com/wevm/wagmi/pull/1234) [`3ff9303`](https://github.com/wevm/wagmi/commit/3ff930349250f62137cca4ca3b382522882abf8a) Thanks [@tmm](https://github.com/tmm)! - Fixed issue with adding chain to wallet without block explorer URL. ## 0.6.10 ### Patch Changes - [#1232](https://github.com/wevm/wagmi/pull/1232) [`c0ca509`](https://github.com/wevm/wagmi/commit/c0ca509506dcf6d98b058df549dc761c9a5f3d1c) Thanks [@tmm](https://github.com/tmm)! - Added validation to check that chain is configured for connector when accessing `Signer`. ## 0.6.9 ### Patch Changes - [#1207](https://github.com/wevm/wagmi/pull/1207) [`c73d463`](https://github.com/wevm/wagmi/commit/c73d463d65c9dbfcfe709187e47323a769589741) Thanks [@lvshaoping007](https://github.com/lvshaoping007)! - Added Kucoin wallet support to `InjectedConnector` ## 0.6.8 ### Patch Changes - [#1132](https://github.com/wevm/wagmi/pull/1132) [`d41c0d6`](https://github.com/wevm/wagmi/commit/d41c0d650f8c0e54145758685b7604b8909d7ae0) Thanks [@toniocodo](https://github.com/toniocodo)! - Added ERC-4626 ABI - [#1201](https://github.com/wevm/wagmi/pull/1201) [`9a07efa`](https://github.com/wevm/wagmi/commit/9a07efaa397d3ba03f2edbe527c359f21e22139a) Thanks [@jxom](https://github.com/jxom)! - Fixed issue where non-checksum addresses did not resolve with an ENS name ## 0.6.7 ### Patch Changes - [#1174](https://github.com/wevm/wagmi/pull/1174) [`196a458`](https://github.com/wevm/wagmi/commit/196a458f64141e8a9f39c1b1e1af5937f692cb39) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where `client.chains` (active connector chains) would be populated when there is no active connector (disconnected user). - [#1176](https://github.com/wevm/wagmi/pull/1176) [`389765f`](https://github.com/wevm/wagmi/commit/389765f7d9af063ab0df07389a2bbfbc10a41060) Thanks [@jxom](https://github.com/jxom)! - Migrate away from Alchemy RPC URLs in the public RPC URL list ## 0.6.6 ### Patch Changes - [`81ce9e6`](https://github.com/wevm/wagmi/commit/81ce9e64d85f7d01370324c1a529988a0919894f) Thanks [@jxom](https://github.com/jxom)! - Add `isPortal` to injected MetaMask flags. - [`c2c0109`](https://github.com/wevm/wagmi/commit/c2c01096ef4cd0ffadbb49062969c208604c6194) Thanks [@jxom](https://github.com/jxom)! - Add etherscan block explorer to Optimism Goerli ## 0.6.5 ### Patch Changes - [#1162](https://github.com/wevm/wagmi/pull/1162) [`30335b3`](https://github.com/wevm/wagmi/commit/30335b3199fb425e398e9c492b50c68d5e2ade7e) Thanks [@tmm](https://github.com/tmm)! - Fixed issue where non-indexed event parameter types were set to `null`. - [#1162](https://github.com/wevm/wagmi/pull/1162) [`30335b3`](https://github.com/wevm/wagmi/commit/30335b3199fb425e398e9c492b50c68d5e2ade7e) Thanks [@tmm](https://github.com/tmm)! - Fixed issue where `useContractReads` and `useContractInfiniteReads` types were slowing down TypeScript compiler. ## 0.6.4 ### Patch Changes - [#1103](https://github.com/wevm/wagmi/pull/1103) [`651eda0`](https://github.com/wevm/wagmi/commit/651eda06384bd0955268427f898e9337b2dc5a31) Thanks [@tmm](https://github.com/tmm)! - Bumped `abitype` dependency. ## 0.6.3 ### Patch Changes - [#1086](https://github.com/wevm/wagmi/pull/1086) [`4e28d2a`](https://github.com/wevm/wagmi/commit/4e28d2ad4c2e6b3479b728563040b9529463cbcf) Thanks [@tmm](https://github.com/tmm)! - Exposed module types. ## 0.6.2 ### Patch Changes - [#1080](https://github.com/wevm/wagmi/pull/1080) [`3be5e8b`](https://github.com/wevm/wagmi/commit/3be5e8b01e58ed40cc9dab7ef9533c0197cb74d0) Thanks [@tmm](https://github.com/tmm)! - Added `abitype` to `dependencies` so types ship correctly. ## 0.6.1 ### Patch Changes - [#1074](https://github.com/wevm/wagmi/pull/1074) [`8db807f`](https://github.com/wevm/wagmi/commit/8db807f16149aa278c2a7db9ee5245431db12173) Thanks [@IljaDaderko](https://github.com/IljaDaderko)! - Exported `EventListener` type ## 0.6.0 ### Minor Changes - [#940](https://github.com/wevm/wagmi/pull/940) [`b6cb8f4`](https://github.com/wevm/wagmi/commit/b6cb8f4cd15eb13073bc7e9ecb4bfa2c261c0663) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: `watchSigner` now requires an arguments object (that accepts an optional `chainId`) as it's first parameter. ```diff import { watchSigner } from `@wagmi/core` -watchSigner(signer => { +watchSigner({}, signer => { console.log('new signer!', signer) }) ``` - [#940](https://github.com/wevm/wagmi/pull/940) [`b6cb8f4`](https://github.com/wevm/wagmi/commit/b6cb8f4cd15eb13073bc7e9ecb4bfa2c261c0663) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: `prepareSendTransaction` now throws when a `chainId` is specified and the end-user is on a different chain id (the wrong network). - [#941](https://github.com/wevm/wagmi/pull/941) [`0c96009`](https://github.com/wevm/wagmi/commit/0c96009398647a515a57f72ef25c32724f7c978c) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: `addressOrName` and `contractInterface` renamed to `address` and `abi` respectively for contract actions: `getContract`, `multicall`, `prepareWriteContract`, `readContract`, `readContracts`, `watchContractEvent`, `watchMulticall`, `watchReadContract`, `watchReadContracts`, `writeContract`. ```diff import { readContract } from '@wagmi/core' const result = await readContract({ - addressOrName: '0x…', + address: '0x…', - contractInterface: […] as const, + abi: […] as const, functionName: 'balanceOf', args: ['0x…'], }) ``` If you were using an ENS name instead of an address, you can resolve the name to an address before passing it to the action. ```diff - import { readContract } from '@wagmi/core' + import { fetchEnsAddress, readContract } from '@wagmi/core' + const address = await fetchEnsAddress('example.eth') const result = await readContract({ - addressOrName: 'example.eth', + address, abi: […] as const, functionName: 'balanceOf', args: ['0x…'], }) ``` - [#940](https://github.com/wevm/wagmi/pull/940) [`b6cb8f4`](https://github.com/wevm/wagmi/commit/b6cb8f4cd15eb13073bc7e9ecb4bfa2c261c0663) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: `prepareWriteContract` now throws when a `chainId` is specified and the end-user is on a different chain id (the wrong network). - [#940](https://github.com/wevm/wagmi/pull/940) [`b6cb8f4`](https://github.com/wevm/wagmi/commit/b6cb8f4cd15eb13073bc7e9ecb4bfa2c261c0663) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: `prepareSendTransaction` now only accepts a `signer` instead of `signerOrProvider`. This is to reach parity with `prepareWriteContract`. If no `signer` is provided, wagmi will use the signer that is currently connected. If no user is connected, then `prepareWriteContract` will throw an error. - [#941](https://github.com/wevm/wagmi/pull/941) [`0c96009`](https://github.com/wevm/wagmi/commit/0c96009398647a515a57f72ef25c32724f7c978c) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: `args` config option must now be an array for the following actions: `readContract`, `writeContract`, `prepareWriteContract`, `multicall`, `readContracts`, `watchMulticall`, and `watchReadContracts`. ```diff import { readContract } from '@wagmi/core' const result = await readContract({ address: '0x…', abi: […], functionName: 'balanceOf', - args: '0x…', + args: ['0x…'], }) ``` - [#941](https://github.com/wevm/wagmi/pull/941) [`0c96009`](https://github.com/wevm/wagmi/commit/0c96009398647a515a57f72ef25c32724f7c978c) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: `watchContractEvent` now accepts a configuration object and callback instead of positional arguments. ```diff import { watchContractEvent } from '@wagmi/core' - const unsubscribe = watchContractEvent( - { - address: '0x…', - abi: […], - }, - 'Transfer', - (from, to, tokenId) => { - // ... - }, - { once: true }, - ) + const unsubscribe = watchContractEvent( + { + address: '0x…', + abi: […], + eventName: 'Transfer', + once: true, + }, + (from, to, tokenId) => { + // ... + }, + ) ``` - [#941](https://github.com/wevm/wagmi/pull/941) [`0c96009`](https://github.com/wevm/wagmi/commit/0c96009398647a515a57f72ef25c32724f7c978c) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: Updated TypeScript version to `typescript@>=4.7.4`. `@wagmi/core` can now infer types based on [ABI](https://docs.soliditylang.org/en/v0.8.15/abi-spec.html#json) and [EIP-712](https://eips.ethereum.org/EIPS/eip-712) Typed Data definitions, giving you full end-to-end type-safety from your contracts to your frontend and incredible developer experience (e.g. autocomplete contract function names and catch misspellings, type contract function arguments, etc.). For this to work, you must upgrade to `typescript@>=4.7.4`. Why is TypeScript v4.7.4 or greater necessary? TypeScript 4.7.4 introduced the ability to [extend constraints on inferred type variables](https://devblogs.microsoft.com/typescript/announcing-typescript-4-7/#extends-constraints-on-infer-type-variables), which is used extensively to help narrow types for ABIs. Good news! When upgrading TypeScript from 4.6 to 4.7 there are likely no [breaking changes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-7.html#breaking-changes) for your set up. - [#941](https://github.com/wevm/wagmi/pull/941) [`0c96009`](https://github.com/wevm/wagmi/commit/0c96009398647a515a57f72ef25c32724f7c978c) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: Updated TypeScript generics for contract interaction and typed data actions. Adding a [const assertion](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions) to `abi` allows TypeScript to infer `functionName`, `args`, `overrides`, and return types for functions, and `eventName` and `listener` types for events. ```diff import { readContract } from '@wagmi/core' const result = await readContract({ address: '0x…', - abi: […], + abi: […] as const, functionName: 'balanceOf', // will autocomplete and catch typos args: ['0x…'], // inferred based on `functionName` }) result // inferred based on `functionName` ``` This works for the following actions: `readContract`, `writeContract`, `prepareWriteContract`, `multicall`, `readContracts`, `watchMulticall`, `watchReadContracts`, and `watchContractEvent`. Adding a [const assertion](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions) to `signTypedData`'s config option, `types`, allows TypeScript to infer `value`. ```diff import { signTypedData } from '@wagmi/core' const result = await signTypedData({ domain: { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', }, types: { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], - }, + } as const, value: { // `value` is inferred based on `types` from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) ``` ### Patch Changes - [#1061](https://github.com/wevm/wagmi/pull/1061) [`a4ffe8b`](https://github.com/wevm/wagmi/commit/a4ffe8b25516d5504685ae94579da4cd8c409329) Thanks [@alecananian](https://github.com/alecananian)! - Added Arbitrum Goerli Arbiscan block explorer - [#940](https://github.com/wevm/wagmi/pull/940) [`b6cb8f4`](https://github.com/wevm/wagmi/commit/b6cb8f4cd15eb13073bc7e9ecb4bfa2c261c0663) Thanks [@jxom](https://github.com/jxom)! - The `fetchSigner` action now accepts an optional `chainId` to use for signer initialization as an argument. ```tsx import { fetchSigner } from "@wagmi/core"; import { optimism } from "@wagmi/core/chains"; // ... fetchSigner({ chainId: optimism.id }); ``` - [#1048](https://github.com/wevm/wagmi/pull/1048) [`ed13074`](https://github.com/wevm/wagmi/commit/ed130747c0f28c1d9980a1328883e4000a60455e) Thanks [@Max-3-7](https://github.com/Max-3-7)! - Added support for Avalanche core wallet - [#1046](https://github.com/wevm/wagmi/pull/1046) [`ab9ecaa`](https://github.com/wevm/wagmi/commit/ab9ecaa74dfa4324279e167dd7e348319ef7d35d) Thanks [@jxom](https://github.com/jxom)! - make ethers block format validator compatible with Celo - [#1050](https://github.com/wevm/wagmi/pull/1050) [`73d4d47`](https://github.com/wevm/wagmi/commit/73d4d47bc679f4f9a1cf46010fe2bf858c9d0b5c) Thanks [@jxom](https://github.com/jxom)! - update dependencies - `zustand@4.1.1` ## 0.5.8 ### Patch Changes - [`8cb07462`](https://github.com/wevm/wagmi/commit/8cb07462acc3c5637398d11d2451f8b8e330d553) Thanks [@jxom](https://github.com/jxom)! - Added `chainId` as an argument to `watchBlockNumber`. * [`53c1a474`](https://github.com/wevm/wagmi/commit/53c1a4747d03b685e8cfbf55361fc2a56777fb06) Thanks [@tmm](https://github.com/tmm)! - Added missing `decimals` option to `Connector` `watchAsset` - [`4d74dd4f`](https://github.com/wevm/wagmi/commit/4d74dd4ff827ba5c43c3546a218f38cee45ea76a) Thanks [@jxom](https://github.com/jxom)! - Support ERC20 contracts that represent strings as bytes32 ## 0.5.7 ### Patch Changes - [`aa51bc4d`](https://github.com/wevm/wagmi/commit/aa51bc4dc5683bf0178597d2fdb8f2e9d82e7970) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue in `CoinbaseWalletConnector` where the browser extension would unintendedly reset the network when the browser is refreshed. * [#955](https://github.com/wevm/wagmi/pull/955) [`e326cd80`](https://github.com/wevm/wagmi/commit/e326cd80fe65267db623eb6c80ccdd75572914cf) Thanks [@0xFlicker](https://github.com/0xFlicker)! - Added Infura RPC URL for Sepolia - [`cec14089`](https://github.com/wevm/wagmi/commit/cec14089500c86687226ab272b4c3fcb85ae3d69) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where `useProvider` & `getProvider` were not returning referentially equal providers. * [`cec14089`](https://github.com/wevm/wagmi/commit/cec14089500c86687226ab272b4c3fcb85ae3d69) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where the `watch` option was not respecting the neighboring `chainId` option in `useBlockNumber`. - [`cec14089`](https://github.com/wevm/wagmi/commit/cec14089500c86687226ab272b4c3fcb85ae3d69) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where block listeners (via `watch`) were firing excessively on L2 chains. ## 0.5.6 ### Patch Changes - [#936](https://github.com/wevm/wagmi/pull/936) [`3329d1f`](https://github.com/wevm/wagmi/commit/3329d1f5880431566e14ac1640f48d0975aec4c2) Thanks [@jxom](https://github.com/jxom)! - Added the ability to provide a custom logger to override how logs are broadcasted to the consumer in wagmi. A custom logger can be provided to the wagmi client via `logger`. ### API ```tsx logger?: { warn: typeof console.warn | null } ``` ### Examples **Passing in a custom logger** You can pass in a function to define your own custom logger. ```diff + import { logWarn } from './logger'; const client = createClient({ ... + logger: { + warn: message => logWarn(message) + } ... }) ``` **Disabling a logger** You can disable a logger by passing `null` as the value. ```diff const client = createClient({ ... + logger: { + warn: null + } ... }) ``` * [#889](https://github.com/wevm/wagmi/pull/889) [`27788ed`](https://github.com/wevm/wagmi/commit/27788ed989b5dc26849c7945fb91a92e56766018) Thanks [@jxom](https://github.com/jxom)! - Make multicall & readContracts more error robust ## 0.5.5 ### Patch Changes - [#912](https://github.com/wevm/wagmi/pull/912) [`e529e12`](https://github.com/wevm/wagmi/commit/e529e125c713ed3ef24a59c6bf226fe4deee7ac9) Thanks [@zouhangwithsweet](https://github.com/zouhangwithsweet)! - Added BitKeep to injected flags - [#912](https://github.com/wevm/wagmi/pull/910) Thanks [@mytangying](https://github.com/zouhangwithsweet)! - Added MathWallet to injected flags - [#904](https://github.com/wevm/wagmi/pull/904) [`c231058`](https://github.com/wevm/wagmi/commit/c23105850f335f8798031e14c7098b7dee8c2975) Thanks [@jxom](https://github.com/jxom)! - Minimized contract interface returned from `prepareWriteContract`. ## 0.5.4 ### Patch Changes - [#852](https://github.com/wevm/wagmi/pull/852) [`c3192d0`](https://github.com/wevm/wagmi/commit/c3192d0663aa332ae9edfd9dd49b333454013ab7) Thanks [@skeithc](https://github.com/skeithc)! - Added support for the Sepolia testnet ## 0.5.3 ### Patch Changes - [#835](https://github.com/wevm/wagmi/pull/835) [`1b85e54`](https://github.com/wevm/wagmi/commit/1b85e54ae654e2564cf5bc2dae6411fe0a25875c) Thanks [@jxom](https://github.com/jxom)! - Update `@coinbase/wallet-sdk` to `3.4.1` * [#834](https://github.com/wevm/wagmi/pull/834) [`9655879`](https://github.com/wevm/wagmi/commit/96558793b0319df47aefafa6b7b9c959068d491b) Thanks [@jxom](https://github.com/jxom)! - Update zustand to `4.0.0` ## 0.5.2 ### Patch Changes - [#823](https://github.com/wevm/wagmi/pull/823) [`10b8b78`](https://github.com/wevm/wagmi/commit/10b8b78605b7246b2c55b8d69f96663906e5cd20) Thanks [@tmm](https://github.com/tmm)! - Add Optimism Goerli to `chain` lookup. ## 0.5.1 ### Patch Changes - [#767](https://github.com/wevm/wagmi/pull/767) [`e9392f3`](https://github.com/wevm/wagmi/commit/e9392f396e48e928bd9d2522e3ad671c589f08cb) Thanks [@klyap](https://github.com/klyap)! - Add Optimism Goerli chain ahead of [Kovan deprecation](https://dev.optimism.io/kovan-to-goerli). * [#817](https://github.com/wevm/wagmi/pull/817) [`7e5cac7`](https://github.com/wevm/wagmi/commit/7e5cac75815dcd8aa563462342a4853fc5207735) Thanks [@alecananian](https://github.com/alecananian)! - Added custom name mapping for 1inch Wallet injected provider - [#806](https://github.com/wevm/wagmi/pull/806) [`0b34e56`](https://github.com/wevm/wagmi/commit/0b34e56db97e6dcdb71088e0149b2d55ebc604a5) Thanks [@vmichalik](https://github.com/vmichalik)! - Fix canonical testnet native asset symbols by changing them to ETH * [#778](https://github.com/wevm/wagmi/pull/778) [`0892908`](https://github.com/wevm/wagmi/commit/08929084eeeba1a3a55aa098fa9d92a243685ad5) Thanks [@0xcadams](https://github.com/0xcadams)! - Add Arbitrum Goerli chain. ## 0.5.0 ### Minor Changes - [#658](https://github.com/wevm/wagmi/pull/658) [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The configuration passed to the `sendTransaction` action now needs to be: - prepared with the `prepareSendTransaction` action **(new functionality)**, or - recklessly unprepared **(previous functionality)** > Why? [Read here](https://wagmi.sh/docs/prepare-hooks) ### Prepared usage ```diff import { prepareSendTransaction, sendTransaction } from '@wagmi/core' +const config = await prepareSendTransaction({ + request: { + to: 'moxey.eth', + value: parseEther('1'), + } +}) const result = await sendTransaction({ - request: { - to: 'moxey.eth', - value: parseEther('1') - } + ...config }) ``` ### Recklessly unprepared usage It is possible to use `sendTransaction` without preparing the configuration first by passing `mode: 'recklesslyUnprepared'`. ```diff import { sendTransaction } from '@wagmi/core' const result = await sendTransaction({ + mode: 'recklesslyUnprepared', request: { to: 'moxey.eth', value: parseEther('1'), } }) ``` * [#760](https://github.com/wevm/wagmi/pull/760) [`d8af6bf`](https://github.com/wevm/wagmi/commit/d8af6bf50885aec110ae4d64716642453aa27896) Thanks [@tmm](https://github.com/tmm)! - **Breaking:** `alchemyProvider` and `infuraProvider` now use a generic `apiKey` configuration option instead of `alchemyId` and `infuraId`. ```diff import { alchemyProvider } from '@wagmi/core/providers/alchemy' import { infuraProvider } from '@wagmi/core/providers/infura' alchemyProvider({ - alchemyId: 'yourAlchemyApiKey', + apiKey: 'yourAlchemyApiKey', }) infuraProvider({ - infuraId: 'yourInfuraApiKey', + apiKey: 'yourInfuraApiKey', }) ``` - [#727](https://github.com/wevm/wagmi/pull/727) [`ac3b9b8`](https://github.com/wevm/wagmi/commit/ac3b9b87f80cb45b65d003f09d916d7d1427a62e) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: Moved the `pollingInterval` config option from the chain provider config to `configureChains` config. ```diff const { chains, provider } = configureChains( [chain.mainnet, chain.polygon], [ - alchemyProvider({ apiKey, pollingInterval: 5000 }), - publicProvider({ pollingInterval: 5000 }) + alchemyProvider({ apiKey }), + publicProvider() ], + { pollingInterval: 5000 } ) ``` * [#658](https://github.com/wevm/wagmi/pull/658) [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432) Thanks [@jxom](https://github.com/jxom)! - **Breaking:** The `sendTransaction` action now returns an object only consisting of `hash` & `wait`, and not the full [`TransactionResponse`](https://docs.ethers.io/v5/api/providers/types/#providers-TransactionResponse). If you require the full `TransactionResponse`, you can use `fetchTransaction`: ```diff import { sendTransaction, fetchTransaction } from '@wagmi/core' const { hash, wait, - ...transaction } = sendTransaction(...) +const transaction = fetchTransaction({ hash }) ``` > Why? The old implementation of `sendTransaction` created a long-running async task, causing [UX pitfalls](https://wagmi.sh/docs/prepare-hooks#ux-pitfalls-without-prepare-hooks) when invoked in a click handler. - [#658](https://github.com/wevm/wagmi/pull/658) [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: If a `chainId` is passed to `writeContract` or `sendTransaction`, it will no longer attempt to switch chain before sending the transaction. Instead, it will throw an error if the user is on the wrong chain. > Why? > > - Eagerly prompting to switch chain in these actions created a long-running async task that that makes [iOS App Links](https://wagmi.sh/docs/prepare-hooks#ios-app-link-constraints) vulnerable. > - Not all wallets support programmatic chain switching. ### Patch Changes - [#658](https://github.com/wevm/wagmi/pull/658) [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The configuration passed to the `writeContract` action now needs to be: - prepared with the `prepareWriteContract` action **(new functionality)**, or - recklessly unprepared **(previous functionality)** > Why? [Read here](https://wagmi.sh/docs/prepare-hooks) ### Prepared usage ```diff import { prepareWriteContract, writeContract } from '@wagmi/core' const tokenId = 69 +const config = await prepareWriteContract({ + addressOrName: '0x...', + contractInterface: wagmiAbi, + functionName: 'mint', + args: [tokenId] +}) const result = await writeContract({ - addressOrName: '0x...', - contractInterface: wagmiAbi, - functionName: 'mint', - args: [tokenId], + ...config }) ``` ### Recklessly unprepared usage It is possible to use `writeContract` without preparing the configuration first by passing `mode: 'recklesslyUnprepared'`. ```diff import { writeContract } from '@wagmi/core' const tokenId = 69 const result = await writeContract({ + mode: 'recklesslyUnprepared', addressOrName: '0x...', contractInterface: wagmiAbi, functionName: 'mint', args: [tokenId], }) ``` * [#658](https://github.com/wevm/wagmi/pull/658) [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432) Thanks [@jxom](https://github.com/jxom)! - Added the `prepareSendTransaction` hook that prepares the parameters required for sending a transaction. It returns config to be passed through to `sendTransaction`. ```ts import { prepareSendTransaction, sendTransaction } from "@wagmi/core"; const config = await prepareSendTransaction({ request: { to: "moxey.eth", value: parseEther("1"), }, }); const result = await sendTransaction(config); ``` - [#658](https://github.com/wevm/wagmi/pull/658) [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432) Thanks [@jxom](https://github.com/jxom)! - Added the `prepareWriteContract` hook that prepares the parameters required for a contract write transaction. It returns config to be passed through to `writeContract`. Example: ```tsx import { prepareWriteContract, writeContract } from "@wagmi/core"; const config = await prepareWriteContract({ addressOrName: "0x...", contractInterface: wagmiAbi, functionName: "mint", }); const result = await writeContract(config); ``` * [#739](https://github.com/wevm/wagmi/pull/739) [`c2295a5`](https://github.com/wevm/wagmi/commit/c2295a56cc86d02cc6602e2b4557b8ab9a091a3f) Thanks [@tmm](https://github.com/tmm)! - Fix balance formatting for tokens that do not have 18 decimals. - [#759](https://github.com/wevm/wagmi/pull/759) [`959953d`](https://github.com/wevm/wagmi/commit/959953d1f5b3e8189bac56de245c62333470d18e) Thanks [@tmm](https://github.com/tmm)! - Added `fetchTransaction` action: ```ts import { fetchTransaction } from "@wagmi/core"; const transaction = await fetchTransaction({ hash: "0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060", }); ``` ## 0.4.9 ### Patch Changes - [#721](https://github.com/tmm/wagmi/pull/721) [`abea25f`](https://github.com/tmm/wagmi/commit/abea25fd15d81d1ecaec9d3fbd687042ab29b1e6) Thanks [@tmm](https://github.com/tmm)! - Stay connected to existing `client.connector` when `connect` action fails to connect to new connector. * [#721](https://github.com/tmm/wagmi/pull/721) [`abea25f`](https://github.com/tmm/wagmi/commit/abea25fd15d81d1ecaec9d3fbd687042ab29b1e6) Thanks [@tmm](https://github.com/tmm)! - Switch `fetchToken` action to multicall and add `name` output property. ## 0.4.8 ### Patch Changes - [#693](https://github.com/tmm/wagmi/pull/693) [`56e468c`](https://github.com/tmm/wagmi/commit/56e468c3617ec222527bb3c02eadec3ebeff923a) Thanks [@markdalgleish](https://github.com/markdalgleish)! - Fix import errors with Coinbase Wallet SDK in Vite ## 0.4.7 ### Patch Changes - [#677](https://github.com/tmm/wagmi/pull/677) [`35e4219`](https://github.com/tmm/wagmi/commit/35e42199af9dd346549c1718e144728f55b8d7dd) Thanks [@jxom](https://github.com/jxom)! - Move `parseContractResult` to `@wagmi/core` ## 0.4.6 ### Patch Changes - [#670](https://github.com/tmm/wagmi/pull/670) [`29a0d21`](https://github.com/tmm/wagmi/commit/29a0d21ee83995559f63542778dfa805f15e7441) Thanks [@tmm](https://github.com/tmm)! - Added ethers-compatible `deepEqual` function. ## 0.4.5 ### Patch Changes - [#654](https://github.com/tmm/wagmi/pull/654) [`e66530b`](https://github.com/tmm/wagmi/commit/e66530bf4881b3533c528f8c5a5f41be0eab0a64) Thanks [@jxom](https://github.com/jxom)! - fix `multicall` returning nullish data for all calls unexpectedly ## 0.4.4 ### Patch Changes - [#616](https://github.com/tmm/wagmi/pull/616) [`7a7a17a`](https://github.com/tmm/wagmi/commit/7a7a17a46d4c9e6465cc46a111b5fe8a56109f1b) Thanks [@tmm](https://github.com/tmm)! - Adds `UNSTABLE_shimOnConnectSelectAccount` flag. With this flag and "disconnected" with `shimDisconnect` enabled, the user is prompted to select a different MetaMask account (than the currently connected account) when trying to connect (e.g. `useConnect`/`connect` action). ## 0.4.3 ### Patch Changes - [#631](https://github.com/tmm/wagmi/pull/631) [`a780e32`](https://github.com/tmm/wagmi/commit/a780e32e91a0072c795fa0b5a6111302768e2a01) Thanks [@tmm](https://github.com/tmm)! - Fix WalletConnect stale session ## 0.4.2 ### Patch Changes - [#624](https://github.com/tmm/wagmi/pull/624) [`416fa7e`](https://github.com/tmm/wagmi/commit/416fa7ee1f8019ab86e33fb93783ffddecc02c49) Thanks [@jxom](https://github.com/jxom)! - Fix broken `WebSocketProvider` type defs ## 0.4.1 ### Patch Changes - [#622](https://github.com/tmm/wagmi/pull/622) [`d171581`](https://github.com/tmm/wagmi/commit/d171581464891dd870d97b6232205da0cb152d9b) Thanks [@tmm](https://github.com/tmm)! - Use `domain.chainId` to validate and switch chain before signing in `signTypedData`. * [#618](https://github.com/tmm/wagmi/pull/618) [`a5138e8`](https://github.com/tmm/wagmi/commit/a5138e82a00e4d9469ad78c97b2d34200d7f1fbe) Thanks [@tmm](https://github.com/tmm)! - Fix adding chains when using MetaMask mobile app, add `publicRpcUrls` constant, and default to public endpoint when adding chain. ## 0.4.0 ### Minor Changes - [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The `provider` config option is now required on `createClient`. It is recommended to pass the [`provider` given from `configureChains`](https://wagmi.sh/docs/providers/configuring-chains). ```diff import { createClient, + defaultChains, + configureChains } from 'wagmi' +import { publicProvider } from 'wagmi/providers/publicProvider' +const { provider } = configureChains(defaultChains, [ + publicProvider +]) const client = createClient({ + provider }) ``` If you previously used an ethers.js Provider, you now need to provide your `chains` on the Provider instance: ```diff import { createClient, + defaultChains } from 'wagmi' import ethers from 'ethers' const client = createClient({ - provider: getDefaultProvider() + provider: Object.assign(getDefaultProvider(), { chains: defaultChains }) }) ``` * [`4f8f3c0`](https://github.com/tmm/wagmi/commit/4f8f3c0d65383bd8bbdfc3f1033adfdb11d80ebb) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Use ethereum-lists chains symbols - [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4) Thanks [@jxom](https://github.com/jxom)! - **Breaking:** Removed the `chainId` parameter from `connectors` function on `createClient`. ```diff const client = createClient({ - connectors({ chainId }) { + connectors() { ... } }) ``` If you previously derived RPC URLs from the `chainId` on `connectors`, you can now remove that logic as `wagmi` now handles RPC URLs internally when used with `configureChains`. ```diff import { chain, + configureChains, createClient } from 'wagmi'; +import { publicProvider } from 'wagmi/providers/public' import { CoinbaseWalletConnector } from 'wagmi/connectors/coinbaseWallet' import { InjectedConnector } from 'wagmi/connectors/injected' import { MetaMaskConnector } from 'wagmi/connectors/metaMask' import { WalletConnectConnector } from 'wagmi/connectors/walletConnect' +const { chains } = configureChains( + [chain.mainnet], + [publicProvider()] +); const client = createClient({ - connectors({ chainId }) { - const chain = chains.find((x) => x.id === chainId) ?? defaultChain - const rpcUrl = chain.rpcUrls.alchemy - ? `${chain.rpcUrls.alchemy}/${alchemyId}` - : chain.rpcUrls.default - return [ + connectors: [ new MetaMaskConnector({ chains }), new CoinbaseWalletConnector({ chains, options: { appName: 'wagmi', - chainId: chain.id, - jsonRpcUrl: rpcUrl, }, }), new WalletConnectConnector({ chains, options: { qrcode: true, - rpc: { [chain.id]: rpcUrl }, }, }), new InjectedConnector({ chains, options: { name: 'Injected' }, }), ] - }, }) ``` * [#611](https://github.com/tmm/wagmi/pull/611) [`3089c34`](https://github.com/tmm/wagmi/commit/3089c34196d4034acabac031e0a2f7ee63ae30cc) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: `Connector`s `getProvider` method no longer supports the `create` config parameter. Use the `chainId` config option instead. - [#596](https://github.com/tmm/wagmi/pull/596) [`a770af7`](https://github.com/tmm/wagmi/commit/a770af7d2cb214b6620d5341115f1e938e1e77ff) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: `TypedDataDomain` and `TypedDataField` types were removed and incorporated into `SignTypedDataArgs`. * [`4f8f3c0`](https://github.com/tmm/wagmi/commit/4f8f3c0d65383bd8bbdfc3f1033adfdb11d80ebb) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Update symbols to match ethereum-lists/chains - [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The `writeContract` function parameters have been consolidated into a singular config parameter. Before: ```tsx writeContract( { addressOrName: "0xecb504d39723b0be0e3a9aa33d646642d1051ee1", contractInterface: wagmigotchiABI, }, "feed", ); ``` After: ```tsx readContract({ addressOrName: "0xecb504d39723b0be0e3a9aa33d646642d1051ee1", contractInterface: wagmigotchiABI, functionName: "feed", }); ``` ### Patch Changes - [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The `readContract` & `watchReadContract` function parameters have been consolidated into a singular config parameter. Before: ```tsx readContract( { addressOrName: "0xecb504d39723b0be0e3a9aa33d646642d1051ee1", contractInterface: wagmigotchiABI, }, "getHunger", { args: [0] }, ); watchReadContract( { addressOrName: "0xecb504d39723b0be0e3a9aa33d646642d1051ee1", contractInterface: wagmigotchiABI, }, "getHunger", { args: [0] }, (result) => {}, ); ``` After: ```tsx readContract({ addressOrName: "0xecb504d39723b0be0e3a9aa33d646642d1051ee1", contractInterface: wagmigotchiABI, functionName: "getHunger", args: [0], }); watchReadContract( { addressOrName: "0xecb504d39723b0be0e3a9aa33d646642d1051ee1", contractInterface: wagmigotchiABI, functionName: "getHunger", args: [0], }, (result) => {}, ); ``` * [#598](https://github.com/tmm/wagmi/pull/598) [`fef26bf`](https://github.com/tmm/wagmi/commit/fef26bf8aef76fc9621e3cd54d4e0ca8f69abb38) Thanks [@markdalgleish](https://github.com/markdalgleish)! - Update `@coinbase/wallet-sdk` peer dependency to `>=3.3.0` to fix errors when connecting with older versions of the Coinbase Wallet extension and mobile app. - [#611](https://github.com/tmm/wagmi/pull/611) [`3089c34`](https://github.com/tmm/wagmi/commit/3089c34196d4034acabac031e0a2f7ee63ae30cc) Thanks [@tmm](https://github.com/tmm)! - Added `chainId` config parameter for `writeContract` and `sendTransaction`. If `chainId` is provided, the connector will validate that `chainId` is the active chain before sending a transaction (and switch to `chainId` if necessary). * [#582](https://github.com/tmm/wagmi/pull/582) [`b03830a`](https://github.com/tmm/wagmi/commit/b03830a54465215c2526f9509543fe2c978bfe70) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where the wagmi client's `status` would not update from `"disconnected"` to `"connecting" -> "connected"` when the `connect` action is invoked. - [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4) Thanks [@jxom](https://github.com/jxom)! - Added a `multicall` & `watchMulticall` action that provides multicall support. Internally uses the [`multicall3` contract](https://github.com/mds1/multicall). [See example usage](https://github.com/tmm/wagmi/blob/194866032985fdd3f49bc46bf1b14181d7cb61d1/packages/core/src/actions/contracts/multicall.test.ts) * [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4) Thanks [@jxom](https://github.com/jxom)! - Added a `readContracts` & `watchReadContracts` action that provides the ability to batch up multiple ethers Contract read-only methods. ## 0.3.8 ### Patch Changes - [#570](https://github.com/tmm/wagmi/pull/570) [`0e3fe15`](https://github.com/tmm/wagmi/commit/0e3fe15445377f35d6f4142b49bf1c96bfeb62cd) Thanks [@tmm](https://github.com/tmm)! - adds chain for [Foundry](https://github.com/foundry-rs) ## 0.3.7 ### Patch Changes - [#550](https://github.com/tmm/wagmi/pull/550) [`2a5313e`](https://github.com/tmm/wagmi/commit/2a5313e8cbc9ba6335e8e4b85e43862c9b711bd3) Thanks [@tmm](https://github.com/tmm)! - fix `CoinbaseWalletConnector` possible type error * [#548](https://github.com/tmm/wagmi/pull/548) [`0c48719`](https://github.com/tmm/wagmi/commit/0c487199f2421f042abc1f1d139468ccbbc5646a) Thanks [@dohaki](https://github.com/dohaki)! - add ensAddress to Chain type - [#549](https://github.com/tmm/wagmi/pull/549) [`89b3a74`](https://github.com/tmm/wagmi/commit/89b3a74ead4234daacd0dcf8506659887ebf0553) Thanks [@tmm](https://github.com/tmm)! - Turns on [`noUncheckedIndexedAccess`](https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess=) and [`strictNullChecks`](https://www.typescriptlang.org/tsconfig#strictNullChecks=) for better runtime safety. ## 0.3.6 ### Patch Changes - [#526](https://github.com/tmm/wagmi/pull/526) [`e95c5f9`](https://github.com/tmm/wagmi/commit/e95c5f91859e57d079b962a72d06b93dce004d2f) Thanks [@jxom](https://github.com/jxom)! - Added `shimChainChangedDisconnect` option to `InjectedConnector`. Defaults to `true` for `MetaMaskConnector`. * [#526](https://github.com/tmm/wagmi/pull/526) [`e95c5f9`](https://github.com/tmm/wagmi/commit/e95c5f91859e57d079b962a72d06b93dce004d2f) Thanks [@jxom](https://github.com/jxom)! - Added `lastUsedChainId` property to the wagmi `Client`. - [#526](https://github.com/tmm/wagmi/pull/526) [`e95c5f9`](https://github.com/tmm/wagmi/commit/e95c5f91859e57d079b962a72d06b93dce004d2f) Thanks [@jxom](https://github.com/jxom)! - Added `chainId` config option to the `connect` action. Example: ```tsx import { connect } from "@wagmi/core"; await connect({ chainId: 69 }); ``` ## 0.3.5 ### Patch Changes - [#543](https://github.com/tmm/wagmi/pull/543) [`4d489fd`](https://github.com/tmm/wagmi/commit/4d489fd630dd8c00440bdaf4d646de662c41ff52) Thanks [@tmm](https://github.com/tmm)! - fix fee data formatting for null values ## 0.3.4 ### Patch Changes - [`c4deb66`](https://github.com/tmm/wagmi/commit/c4deb6655a52e4cc4e5b3fd82202db11d6106848) Thanks [@jxom](https://github.com/jxom)! - infer `options.chainId` config from `chains` on WalletConnectConnector ## 0.3.3 ### Patch Changes - [#486](https://github.com/tmm/wagmi/pull/486) [`dbfe3dd`](https://github.com/tmm/wagmi/commit/dbfe3dd320d178d6854a8096101200c1508786bb) Thanks [@tmm](https://github.com/tmm)! - add chains entrypoint ## 0.3.2 ### Patch Changes - [`17212da`](https://github.com/tmm/wagmi/commit/17212da601640110d2835300e6433d1433db212e) Thanks [@jxom](https://github.com/jxom)! - Made the `defaultChains` type generic in `configureChains`. ## 0.3.1 ### Patch Changes - [#484](https://github.com/tmm/wagmi/pull/484) [`1b9a503`](https://github.com/tmm/wagmi/commit/1b9a5033d51c6655b4f6570c490da6e0e9a29da9) Thanks [@tmm](https://github.com/tmm)! - export React Context ## 0.3.0 ### Minor Changes - [#408](https://github.com/tmm/wagmi/pull/408) [`bfcc3a5`](https://github.com/tmm/wagmi/commit/bfcc3a51bbb1551753e3ccde6af134e9fd4fec9a) Thanks [@jxom](https://github.com/jxom)! - **Breaking:** The `connectors` option on `createClient` no longer reacts to chain switching. **Passing a function to `connectors` has been deprecated.** If you previously derived an RPC URL from the `chainId` in `connectors`, you will need to migrate to use the [`configureChains` API](https://wagmi.sh/docs/providers/configuring-chains). ### Before ```tsx import { providers } from "ethers"; import { chain, createClient, defaultChains } from "wagmi"; import { CoinbaseWalletConnector } from "wagmi/connectors/coinbaseWallet"; import { InjectedConnector } from "wagmi/connectors/injected"; import { MetaMaskConnector } from "wagmi/connectors/metaMask"; import { WalletConnectConnector } from "wagmi/connectors/walletConnect"; const alchemyId = process.env.ALCHEMY_ID; const chains = defaultChains; const defaultChain = chain.mainnet; const client = createClient({ autoConnect: true, connectors({ chainId }) { const chain = chains.find((x) => x.id === chainId) ?? defaultChain; const rpcUrl = chain.rpcUrls.alchemy ? `${chain.rpcUrls.alchemy}/${alchemyId}` : chain.rpcUrls.default; return [ new MetaMaskConnector({ chains }), new CoinbaseWalletConnector({ chains, options: { appName: "wagmi", chainId: chain.id, jsonRpcUrl: rpcUrl, }, }), new WalletConnectConnector({ chains, options: { qrcode: true, rpc: { [chain.id]: rpcUrl }, }, }), new InjectedConnector({ chains, options: { name: "Injected", shimDisconnect: true, }, }), ]; }, }); ``` ### After ```tsx import { chain, createClient, defaultChains } from "wagmi"; import { alchemyProvider } from "wagmi/providers/alchemy"; import { publicProvider } from "wagmi/providers/public"; import { CoinbaseWalletConnector } from "wagmi/connectors/coinbaseWallet"; import { InjectedConnector } from "wagmi/connectors/injected"; import { MetaMaskConnector } from "wagmi/connectors/metaMask"; import { WalletConnectConnector } from "wagmi/connectors/walletConnect"; const alchemyId = process.env.ALCHEMY_ID; const { chains } = configureChains(defaultChains, [ alchemyProvider({ alchemyId }), publicProvider(), ]); const client = createClient({ autoConnect: true, connectors: [ new MetaMaskConnector({ chains }), new CoinbaseWalletConnector({ chains, options: { appName: "wagmi", }, }), new WalletConnectConnector({ chains, options: { qrcode: true, }, }), new InjectedConnector({ chains, options: { name: "Injected", shimDisconnect: true, }, }), ], }); ``` * [#468](https://github.com/tmm/wagmi/pull/468) [`44a884b`](https://github.com/tmm/wagmi/commit/44a884b84171c418f57701e80ef8de972948ef0b) Thanks [@tmm](https://github.com/tmm)! - **Breaking:** Duplicate exports with different names and the same functionality were removed to simplify the public API. In addition, confusing exports were renamed to be more descriptive. - `createWagmiClient` alias was removed. Use `createClient` instead. - `useWagmiClient` alias was removed. Use `useClient` instead. - `WagmiClient` alias was removed. Use `Client` instead. - `createWagmiStorage` alias was removed. Use `createStorage` instead. - `Provider` was renamed and `WagmiProvider` alias was removed. Use `WagmiConfig` instead. - [#408](https://github.com/tmm/wagmi/pull/408) [`bfcc3a5`](https://github.com/tmm/wagmi/commit/bfcc3a51bbb1551753e3ccde6af134e9fd4fec9a) Thanks [@jxom](https://github.com/jxom)! - Add `configureChains` API. The `configureChains` function allows you to configure your chains with a selected provider (Alchemy, Infura, JSON RPC, Public RPC URLs). This means you don't have to worry about deriving your own RPC URLs for each chain, or instantiating a Ethereum Provider. `configureChains` accepts 3 parameters: an array of chains, and an array of providers, and a config object. [Learn more about configuring chains & providers.](https://wagmi.sh/docs/providers/configuring-chains) ### Before ```tsx import { providers } from "ethers"; import { chain, createClient, defaultChains } from "wagmi"; import { CoinbaseWalletConnector } from "wagmi/connectors/coinbaseWallet"; import { InjectedConnector } from "wagmi/connectors/injected"; import { MetaMaskConnector } from "wagmi/connectors/metaMask"; import { WalletConnectConnector } from "wagmi/connectors/walletConnect"; const alchemyId = process.env.ALCHEMY_ID; const chains = defaultChains; const defaultChain = chain.mainnet; const client = createClient({ autoConnect: true, connectors({ chainId }) { const chain = chains.find((x) => x.id === chainId) ?? defaultChain; const rpcUrl = chain.rpcUrls.alchemy ? `${chain.rpcUrls.alchemy}/${alchemyId}` : chain.rpcUrls.default; return [ new MetaMaskConnector({ chains }), new CoinbaseWalletConnector({ chains, options: { appName: "wagmi", chainId: chain.id, jsonRpcUrl: rpcUrl, }, }), new WalletConnectConnector({ chains, options: { qrcode: true, rpc: { [chain.id]: rpcUrl }, }, }), new InjectedConnector({ chains, options: { name: "Injected", shimDisconnect: true, }, }), ]; }, provider: ({ chainId }) => new providers.AlchemyProvider(chainId, alchemyId), }); ``` ### After ```tsx import { chain, createClient, defaultChains } from "wagmi"; import { alchemyProvider } from "wagmi/providers/alchemy"; import { publicProvider } from "wagmi/providers/public"; import { CoinbaseWalletConnector } from "wagmi/connectors/coinbaseWallet"; import { InjectedConnector } from "wagmi/connectors/injected"; import { MetaMaskConnector } from "wagmi/connectors/metaMask"; import { WalletConnectConnector } from "wagmi/connectors/walletConnect"; const alchemyId = process.env.ALCHEMY_ID; const { chains, provider, webSocketProvider } = configureChains( defaultChains, [alchemyProvider({ alchemyId }), publicProvider()], ); const client = createClient({ autoConnect: true, connectors: [ new MetaMaskConnector({ chains }), new CoinbaseWalletConnector({ chains, options: { appName: "wagmi", }, }), new WalletConnectConnector({ chains, options: { qrcode: true, }, }), new InjectedConnector({ chains, options: { name: "Injected", shimDisconnect: true, }, }), ], provider, webSocketProvider, }); ``` ### Patch Changes - [#404](https://github.com/tmm/wagmi/pull/404) [`f81c156`](https://github.com/tmm/wagmi/commit/f81c15665e2e71534f84ada3fa705f2d78627472) Thanks [@holic](https://github.com/holic)! - Add `ProviderRpcError` and `RpcError` error classes. Certain wagmi-standardized errors may wrap `ProviderRpcError` or `RpcError`. For these cases, you can access the original provider rpc or rpc error value using the `internal` property. * [#459](https://github.com/tmm/wagmi/pull/459) [`72dcf7c`](https://github.com/tmm/wagmi/commit/72dcf7c09e814261b2e43a8fa364c57675c472de) Thanks [@tmm](https://github.com/tmm)! - update dependencies - [#473](https://github.com/tmm/wagmi/pull/473) [`a54f3e2`](https://github.com/tmm/wagmi/commit/a54f3e23ea385ed8aa4ad188128d7089ba20f83e) Thanks [@cesargdm](https://github.com/cesargdm)! - Add workaround for CoinbaseWalletSDK import on esbuild * [#447](https://github.com/tmm/wagmi/pull/447) [`b9ebf78`](https://github.com/tmm/wagmi/commit/b9ebf782e0900725bcb76483686b30f09d357ebd) Thanks [@tmm](https://github.com/tmm)! - Fix case where connector disconnected while app was closed and stale data was returned when autoconnecting. For example, [MetaMask was locked](https://github.com/tmm/wagmi/issues/444) when page was closed. ## 0.2.5 ### Patch Changes - [`4e03666`](https://github.com/tmm/wagmi/commit/4e03666428d42fc9186c617001b5eb356229677e) Thanks [@tmm](https://github.com/tmm)! - bump dependencies #429 add imToken support for WC switch chains #432 fix MetaMask and Brave Wallet collision #436 ## 0.2.4 ### Patch Changes - [#421](https://github.com/tmm/wagmi/pull/421) [`a232b3f`](https://github.com/tmm/wagmi/commit/a232b3ff5cc41e882c4d2a34c599a8cb670edd2b) Thanks [@tmm](https://github.com/tmm)! - fix erc721 abi ## 0.2.3 ### Patch Changes - [#412](https://github.com/tmm/wagmi/pull/412) [`80bef4f`](https://github.com/tmm/wagmi/commit/80bef4ff3f714b0b8f896f1b4b658acc7266299b) Thanks [@markdalgleish](https://github.com/markdalgleish)! - Import providers from `ethers` peer dependency rather than `@ethersproject/providers` to avoid multiple conflicting versions being installed ## 0.2.2 ### Patch Changes - [`018c2a1`](https://github.com/tmm/wagmi/commit/018c2a11b22ee513571cc7f83fd63f7eb169ee70) Thanks [@tmm](https://github.com/tmm)! - - warn and fallback to default client #380 - remove signerOrProvider option from read contract #390 - MetaMaskConnector #391 ## 0.2.1 ### Patch Changes - [`afc4607`](https://github.com/tmm/wagmi/commit/afc46071e91601ab8a2b465524da796cd60b6ad4) Thanks [@tmm](https://github.com/tmm)! - - Fix time scaling e9593df - Use fully-specified path for use-sync-external-store import 7b235c1 - Update serialize 236fc17 ## 0.2.0 ### Minor Changes - [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - don't persist account data when `autoConnect` is falsy * [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - - fix(@wagmi/core): persist connector chains to local storage - [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - - Favour `message` event over `connecting` event to conform to EIP-1193 - Export `useWaitForTransaction` * [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - Initial 0.3.0 release - [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - Add `cacheOnBlock` config for `useContractRead` Update `react-query` to v4 Fix `watchBlockNumber` listener leak * [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - add `connecting` event to connectors - [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - Fix issue where `getProvider` was not being awaited in `getSigner` * [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - - remove storage persistence of `connector` - add `chains` to client state ### Patch Changes - [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - add chainId to actions and hooks * [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - showtime - [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - improve type support for ethers providers * [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - update zustand - [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - update babel target * [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - update block explorers and rpc urls structure - [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - keep previous data when watching * [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - republish - [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - fix stale connectors when switching chains * [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - last beta ## 0.2.0-next.18 ### Patch Changes - showtime ## 0.2.0-next.17 ### Patch Changes - update block explorers and rpc urls structure ## 0.2.0-next.16 ### Patch Changes - last beta ## 0.2.0-next.15 ### Patch Changes - update zustand ## 0.2.0-next.14 ### Minor Changes - Add `cacheOnBlock` config for `useContractRead` - Update `react-query` to v4 - Fix `watchBlockNumber` listener leak ## 0.2.0-next.13 ### Patch Changes - keep previous data when watching ## 0.2.0-next.12 ### Patch Changes - add chainId to actions and hooks ## 0.2.0-next.11 ### Patch Changes - fix stale connectors when switching chains ## 0.2.0-next.10 ### Patch Changes - republish ## 0.2.0-next.9 ### Patch Changes - improve type support for ethers providers ## 0.2.0-next.8 ### Patch Changes - update babel target ## 0.2.0-next.7 ### Minor Changes - - Favour `message` event over `connecting` event to conform to EIP-1193 - Export `useWaitForTransaction` ## 0.2.0-next.6 ### Minor Changes - add `connecting` event to connectors ## 0.2.0-next.5 ### Minor Changes - don't persist account data when `autoConnect` is falsy ## 0.2.0-next.4 ### Minor Changes - remove storage persistence of `connector` - add `chains` to client state ## 0.2.0-next.3 ### Minor Changes - Fix issue where `getProvider` was not being awaited in `getSigner` ## 0.2.0-next.2 ### Minor Changes - fix: persist connector chains to local storage ## 0.2.0-next.1 ### Minor Changes - Initial 0.3.0 release ## 0.1.22 ### Patch Changes - [`747d895`](https://github.com/tmm/wagmi/commit/747d895a54b562958afde34b1d34e81ab5039e2c) Thanks [@tmm](https://github.com/tmm)! - add warning to WalletLinkConnector ## 0.1.21 ### Patch Changes - [`c858c51`](https://github.com/tmm/wagmi/commit/c858c51b44d9039f1d0db5bcf016639f47d1931f) Thanks [@tmm](https://github.com/tmm)! - update coinbase connector ## 0.1.20 ### Patch Changes - [#326](https://github.com/tmm/wagmi/pull/326) [`36e6989`](https://github.com/tmm/wagmi/commit/36e69894f4c27aaad7fb6d678476c8bb870244bb) Thanks [@0xGabi](https://github.com/0xGabi)! - Add Gnosis Chain ## 0.1.19 ### Patch Changes - [`d467df6`](https://github.com/tmm/wagmi/commit/d467df6374210dbc4b016788b4beb4fded54cb4d) Thanks [@tmm](https://github.com/tmm)! - fix global type leaking ## 0.1.18 ### Patch Changes - [#294](https://github.com/tmm/wagmi/pull/294) [`1d253f3`](https://github.com/tmm/wagmi/commit/1d253f3a59b61d24c88d25c99decd84a6c734e5d) Thanks [@tmm](https://github.com/tmm)! - change babel target ## 0.1.17 ### Patch Changes - [#292](https://github.com/tmm/wagmi/pull/292) [`53c9be1`](https://github.com/tmm/wagmi/commit/53c9be17ee0c2ae6b8f34f2351b8858257b3f5f2) Thanks [@tmm](https://github.com/tmm)! - fix private fields ## 0.1.16 ### Patch Changes - [`79a2499`](https://github.com/tmm/wagmi/commit/79a249989029f818c32c0e84c0dd2c75e8aa990a) Thanks [@tmm](https://github.com/tmm)! - update build target to es2021 ## 0.1.15 ### Patch Changes - [`f9790b5`](https://github.com/tmm/wagmi/commit/f9790b55600df09c77bb8ca349c5a3457df1b07c) Thanks [@tmm](https://github.com/tmm)! - fix WalletConnect issue ## 0.1.14 ### Patch Changes - [#236](https://github.com/tmm/wagmi/pull/236) [`53bad61`](https://github.com/tmm/wagmi/commit/53bad615788764e31121678083c382c1bd042fe8) Thanks [@markdalgleish](https://github.com/markdalgleish)! - Updated `@walletconnect/ethereum-provider` to [v1.7.4](https://github.com/WalletConnect/walletconnect-monorepo/releases/tag/1.7.4) ## 0.1.13 ### Patch Changes - [`8e9412a`](https://github.com/tmm/wagmi/commit/8e9412af71958301ae2f9748febb936e79900aa0) Thanks [@tmm](https://github.com/tmm)! - bump walletlink ## 0.1.12 ### Patch Changes - [#210](https://github.com/tmm/wagmi/pull/210) [`684468a`](https://github.com/tmm/wagmi/commit/684468aee3e42a1ce2b4b599f3f17d1819213de8) Thanks [@tmm](https://github.com/tmm)! - update chains to match chainslist.org ## 0.1.11 ### Patch Changes - [#195](https://github.com/tmm/wagmi/pull/195) [`25b6083`](https://github.com/tmm/wagmi/commit/25b6083a662a0236794d1765343467691421c14b) Thanks [@tmm](https://github.com/tmm)! - rename wagmi-private to wagmi-core ## 0.1.10 ### Patch Changes - [#192](https://github.com/tmm/wagmi/pull/192) [`428cedb`](https://github.com/tmm/wagmi/commit/428cedb3dec4e3e4b9f4559c8e65932e05f94e05) Thanks [@tmm](https://github.com/tmm)! - rename core and testing packages ## 0.1.9 ### Patch Changes - [#190](https://github.com/tmm/wagmi/pull/190) [`7034bb8`](https://github.com/tmm/wagmi/commit/7034bb868412b9f481b206371280e84c2d52706d) Thanks [@tmm](https://github.com/tmm)! - add shim for metamask chain changed to prevent disconnect ## 0.1.8 ### Patch Changes - [#137](https://github.com/tmm/wagmi/pull/137) [`dceeb43`](https://github.com/tmm/wagmi/commit/dceeb430d9021fbf98366859cb1cd0149e80c55c) Thanks [@tmm](https://github.com/tmm)! - add siwe guide ## 0.1.7 ### Patch Changes - [#127](https://github.com/tmm/wagmi/pull/127) [`f05b031`](https://github.com/tmm/wagmi/commit/f05b0310f7f7e6447e9b6c81cedbb27dcf2f3649) Thanks [@tmm](https://github.com/tmm)! - update switch chain return type ## 0.1.6 ### Patch Changes - [`1412eed`](https://github.com/tmm/wagmi/commit/1412eed0d1494bb4f8c6845a0e890f79e4e68e03) Thanks [@tmm](https://github.com/tmm)! - add frame to injected ## 0.1.5 ### Patch Changes - [`e338c3b`](https://github.com/tmm/wagmi/commit/e338c3b6cc255742be6a67593aa5da6c17e90fbd) Thanks [@tmm](https://github.com/tmm)! - checksum connector address on change events add shim to injected connector for simulating disconnect ## 0.1.4 ### Patch Changes - [`0176c4e`](https://github.com/tmm/wagmi/commit/0176c4e83fb0c5f159c3c802a1da3d6deb2184ae) Thanks [@tmm](https://github.com/tmm)! - added switchChain to WalletConnect and WalletLink connectors ## 0.1.3 ### Patch Changes - [`071d7fb`](https://github.com/tmm/wagmi/commit/071d7fbca35ec4832700b5343661ceb2dae20598) Thanks [@tmm](https://github.com/tmm)! - add hardhat chain ## 0.1.2 ### Patch Changes - [`78bade9`](https://github.com/tmm/wagmi/commit/78bade9d0da97ab38a7e6594c34e3841ec1c8fe6) Thanks [@tmm](https://github.com/tmm)! - add type definitions ## 0.1.1 ### Patch Changes - [#56](https://github.com/tmm/wagmi/pull/56) [`2ebfd8e`](https://github.com/tmm/wagmi/commit/2ebfd8e85b560f25cd46cff04619c84643cab297) Thanks [@tmm](https://github.com/tmm)! - add chain support status ## 0.1.0 ### Minor Changes - [#52](https://github.com/tmm/wagmi/pull/52) [`da7a3a6`](https://github.com/tmm/wagmi/commit/da7a3a615def2443f65c041999100ce35e9774cc) Thanks [@tmm](https://github.com/tmm)! - Moves connectors to their own entrypoints to reduce bundle size. ```ts // old - WalletLinkConnector unused, but still in final bundle import { InjectedConnector, WalletConnectConnector } from "wagmi"; // new - WalletLinkConnector not in final bundle import { InjectedConnector } from "wagmi/connectors/injected"; import { WalletConnectConnector } from "wagmi/connectors/walletConnect"; ``` ## 0.0.17 ### Patch Changes - [#25](https://github.com/tmm/wagmi/pull/25) [`9a7dab7`](https://github.com/tmm/wagmi/commit/9a7dab78b3518658bc7d85dc397990f0d28da175) Thanks [@tmm](https://github.com/tmm)! - update response types ## 0.0.16 ### Patch Changes - [`d1574cf`](https://github.com/tmm/wagmi/commit/d1574cf5f7a578ccd480889c2e375134145a4aba) Thanks [@tmm](https://github.com/tmm)! - add better type information for contract results ## 0.0.15 ### Patch Changes - [`3909624`](https://github.com/tmm/wagmi/commit/39096249c1fa9516beabb11735beb67c94032879) Thanks [@tmm](https://github.com/tmm)! - make contract read and write execute overrides param optional ## 0.0.14 ### Patch Changes - [`63312e2`](https://github.com/tmm/wagmi/commit/63312e2b06b8d835abc2908cba399d941ca79408) Thanks [@tmm](https://github.com/tmm)! - add once to contract event ## 0.0.13 ### Patch Changes - [`6f890b0`](https://github.com/tmm/wagmi/commit/6f890b0dabbdbea913ec91cb8bfc970c05ed0a93) Thanks [@tmm](https://github.com/tmm)! - update readme ## 0.0.12 ### Patch Changes - [#19](https://github.com/tmm/wagmi/pull/19) [`7bc1c47`](https://github.com/tmm/wagmi/commit/7bc1c47875e9ef24e9c79cfafc6b23e7a838b5bc) Thanks [@tmm](https://github.com/tmm)! - remove console log from walletlink connector ## 0.0.11 ### Patch Changes - [#17](https://github.com/tmm/wagmi/pull/17) [`571648b`](https://github.com/tmm/wagmi/commit/571648b754f7f538536bafc9387bd3104657ea49) Thanks [@tmm](https://github.com/tmm)! - standardize connector provider ## 0.0.10 ### Patch Changes - [#15](https://github.com/tmm/wagmi/pull/15) [`5f7675c`](https://github.com/tmm/wagmi/commit/5f7675c3ffd848522d4117c07c1f62b17dfc6616) Thanks [@tmm](https://github.com/tmm)! - read and write contract functions ## 0.0.9 ### Patch Changes - [#13](https://github.com/tmm/wagmi/pull/13) [`e5545f5`](https://github.com/tmm/wagmi/commit/e5545f5565cf0bbf5e62ec7ccab3051705b1d313) Thanks [@tmm](https://github.com/tmm)! - add testing package ## 0.0.8 ### Patch Changes - [`5332500`](https://github.com/tmm/wagmi/commit/5332500918ac240d29ffe4d2aed8566a8ac001e4) Thanks [@tmm](https://github.com/tmm)! - update signing ## 0.0.7 ### Patch Changes - [`0bff89a`](https://github.com/tmm/wagmi/commit/0bff89ab2ad28b2cb9b346d1ac870e859d9278bc) Thanks [@tmm](https://github.com/tmm)! - update injected connector ## 0.0.6 ### Patch Changes - [`37d39d1`](https://github.com/tmm/wagmi/commit/37d39d174ddfa122462bbe2d02141cd61eb9db4a) Thanks [@tmm](https://github.com/tmm)! - add message signing ## 0.0.5 ### Patch Changes - [`d7d94f0`](https://github.com/tmm/wagmi/commit/d7d94f06f7d30468e5e39d64db63124c6315cf82) Thanks [@tmm](https://github.com/tmm)! - fix injected connector name ## 0.0.4 ### Patch Changes - [`29fbe29`](https://github.com/tmm/wagmi/commit/29fbe2920046b9e87a34faa04500ccf3c4f83748) Thanks [@tmm](https://github.com/tmm)! - fix external deps ## 0.0.3 ### Patch Changes - [#6](https://github.com/tmm/wagmi/pull/6) [`8dc3a5d`](https://github.com/tmm/wagmi/commit/8dc3a5d5f418813b09663534fe585d9bcf94dbeb) Thanks [@tmm](https://github.com/tmm)! - clean up deps ## 0.0.2 ### Patch Changes - [#4](https://github.com/tmm/wagmi/pull/4) [`2fbd821`](https://github.com/tmm/wagmi/commit/2fbd8216379bd03c9cc5c06b10b75637e75cb7d8) Thanks [@tmm](https://github.com/tmm)! - init changesets ================================================ FILE: packages/core/README.md ================================================ # @wagmi/core VanillaJS library for Ethereum ## Installation ```bash pnpm add @wagmi/core viem ``` ## Documentation For documentation and guides, visit [wagmi.sh](https://wagmi.sh). ================================================ FILE: packages/core/package.json ================================================ { "name": "@wagmi/core", "description": "VanillaJS library for Ethereum", "version": "3.4.0", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/wevm/wagmi.git", "directory": "packages/core" }, "scripts": { "build": "pnpm run build:esm+types", "build:esm+types": "tsc --project tsconfig.build.json --outDir ./dist/esm --declaration --declarationMap --declarationDir ./dist/types", "check:types": "tsc --noEmit", "clean": "rm -rf dist tsconfig.tsbuildinfo actions chains codegen internal query tempo", "test:build": "publint --strict && attw --pack --ignore-rules cjs-resolves-to-esm" }, "files": [ "dist/**", "!dist/**/*.tsbuildinfo", "src/**/*.ts", "!src/**/*.test.ts", "!src/**/*.test-d.ts", "/actions", "/chains", "/internal", "/query", "/tempo" ], "sideEffects": false, "type": "module", "main": "./dist/esm/exports/index.js", "types": "./dist/types/exports/index.d.ts", "typings": "./dist/types/exports/index.d.ts", "exports": { ".": { "types": "./dist/types/exports/index.d.ts", "default": "./dist/esm/exports/index.js" }, "./actions": { "types": "./dist/types/exports/actions.d.ts", "default": "./dist/esm/exports/actions.js" }, "./chains": { "types": "./dist/types/exports/chains.d.ts", "default": "./dist/esm/exports/chains.js" }, "./codegen": { "types": "./dist/types/exports/codegen.d.ts", "default": "./dist/esm/exports/codegen.js" }, "./internal": { "types": "./dist/types/exports/internal.d.ts", "default": "./dist/esm/exports/internal.js" }, "./query": { "types": "./dist/types/exports/query.d.ts", "default": "./dist/esm/exports/query.js" }, "./tempo": { "types": "./dist/types/exports/tempo.d.ts", "default": "./dist/esm/exports/tempo.js" }, "./package.json": "./package.json" }, "typesVersions": { "*": { "actions": [ "./dist/types/exports/actions.d.ts" ], "chains": [ "./dist/types/exports/chains.d.ts" ], "codegen": [ "./dist/types/exports/codegen.d.ts" ], "internal": [ "./dist/types/exports/internal.d.ts" ], "query": [ "./dist/types/exports/query.d.ts" ], "tempo": [ "./dist/types/exports/tempo.d.ts" ] } }, "peerDependencies": { "@tanstack/query-core": ">=5.0.0", "ox": ">=0.11.1", "typescript": ">=5.7.3", "viem": "2.x" }, "peerDependenciesMeta": { "@tanstack/query-core": { "optional": true }, "ox": { "optional": true }, "typescript": { "optional": true } }, "dependencies": { "eventemitter3": "5.0.1", "mipd": "0.0.7", "zustand": "5.0.0" }, "devDependencies": { "@tanstack/query-core": "catalog:", "ox": "catalog:" }, "contributors": [ "awkweb.eth ", "jxom.eth " ], "funding": "https://github.com/sponsors/wevm", "keywords": [ "wagmi", "eth", "ethereum", "dapps", "wallet", "web3" ] } ================================================ FILE: packages/core/src/actions/call.test.ts ================================================ import { accounts, address, config } from '@wagmi/test' import { parseEther, parseGwei } from 'viem' import { expect, test } from 'vitest' import { call } from './call.js' const name4bytes = '0x06fdde03' const mint4bytes = '0x1249c58b' const mintWithParams4bytes = '0xa0712d68' const fourTwenty = '00000000000000000000000000000000000000000000000000000000000001a4' const account = accounts[0] test('default', async () => { await expect( call(config, { account, data: name4bytes, to: address.wagmiMintExample, }), ).resolves.toMatchInlineSnapshot(` { "data": "0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000", } `) }) test('zero data', async () => { await expect( call(config, { account, data: mint4bytes, to: address.wagmiMintExample, }), ).resolves.toMatchInlineSnapshot(` { "data": undefined, } `) }) // TODO: Re-enable test.skip('parameters: blockNumber', async () => { await expect( call(config, { account, data: name4bytes, to: address.wagmiMintExample, blockNumber: 16280770n, }), ).resolves.toMatchInlineSnapshot(` { "data": "0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000", } `) }) test('insufficient funds', async () => { await expect( call(config, { account, to: accounts[1], value: parseEther('100000'), }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [CallExecutionError: The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account. This error could arise when the account does not have enough funds to: - pay for the total gas fee, - pay for the value to send. The cost of the transaction is calculated as \`gas * gas fee + value\`, where: - \`gas\` is the amount of gas needed for transaction to execute, - \`gas fee\` is the gas fee, - \`value\` is the amount of ether to send to the recipient. Raw Call Arguments: from: 0x95132632579b073D12a6673e18Ab05777a6B86f8 to: 0x1D5D7e139A994CeE7f360be398Ef032fE5D74fce value: 100000 ETH Details: Insufficient funds for gas * price + value Version: viem@2.47.5] `) }) test('maxFeePerGas less than maxPriorityFeePerGas', async () => { await expect( call(config, { account, data: name4bytes, to: address.wagmiMintExample, maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('22'), }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [CallExecutionError: The provided tip (\`maxPriorityFeePerGas\` = 22 gwei) cannot be higher than the fee cap (\`maxFeePerGas\` = 20 gwei). Raw Call Arguments: from: 0x95132632579b073D12a6673e18Ab05777a6B86f8 to: 0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2 data: 0x06fdde03 maxFeePerGas: 20 gwei maxPriorityFeePerGas: 22 gwei Version: viem@2.47.5] `) }) test('contract revert (contract error)', async () => { await expect( call(config, { account, data: `${mintWithParams4bytes}${fourTwenty}`, to: address.wagmiMintExample, }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [CallExecutionError: Execution reverted with reason: Token ID is taken. Raw Call Arguments: from: 0x95132632579b073D12a6673e18Ab05777a6B86f8 to: 0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2 data: 0xa0712d6800000000000000000000000000000000000000000000000000000000000001a4 Details: execution reverted: Token ID is taken Version: viem@2.47.5] `) }) test('contract revert (insufficient params)', async () => { await expect( call(config, { account, data: mintWithParams4bytes, to: address.wagmiMintExample, }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [CallExecutionError: Execution reverted for an unknown reason. Raw Call Arguments: from: 0x95132632579b073D12a6673e18Ab05777a6B86f8 to: 0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2 data: 0xa0712d68 Details: execution reverted Version: viem@2.47.5] `) }) ================================================ FILE: packages/core/src/actions/call.ts ================================================ import type { CallErrorType as viem_CallErrorType, CallParameters as viem_CallParameters, CallReturnType as viem_CallReturnType, } from 'viem' import { call as viem_call } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import { getAction } from '../utils/getAction.js' export type CallParameters = viem_CallParameters & ChainIdParameter export type CallReturnType = viem_CallReturnType export type CallErrorType = viem_CallErrorType export async function call( config: config, parameters: CallParameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_call, 'call') return action(rest) } ================================================ FILE: packages/core/src/actions/codegen/createReadContract.test-d.ts ================================================ import { abi, config, mainnet, optimism } from '@wagmi/test' import { assertType, expectTypeOf, test } from 'vitest' import { createReadContract } from './createReadContract.js' test('default', async () => { const readErc20 = createReadContract({ abi: abi.erc20, address: '0x', }) const result = await readErc20(config, { functionName: 'balanceOf', args: ['0x'], chainId: 1, }) expectTypeOf(result).toEqualTypeOf() }) test('multichain address', async () => { const readErc20 = createReadContract({ abi: abi.erc20, address: { [mainnet.id]: '0x', [optimism.id]: '0x', }, }) const result = await readErc20(config, { functionName: 'balanceOf', args: ['0x'], chainId: mainnet.id, // ^? }) assertType(result) readErc20(config, { functionName: 'balanceOf', args: ['0x'], // @ts-expect-error chain id must match address keys chainId: 420, }) readErc20(config, { functionName: 'balanceOf', args: ['0x'], // @ts-expect-error address not allowed address: '0x', }) }) test('overloads', async () => { const readViewOverloads = createReadContract({ abi: abi.viewOverloads, address: '0x', }) const result1 = await readViewOverloads(config, { functionName: 'foo', }) assertType(result1) const result2 = await readViewOverloads(config, { functionName: 'foo', args: [], }) assertType(result2) const result3 = await readViewOverloads(config, { functionName: 'foo', args: ['0x'], }) // @ts-ignore – TODO: Fix https://github.com/wevm/viem/issues/1916 assertType(result3) const result4 = await readViewOverloads(config, { functionName: 'foo', args: ['0x', '0x'], }) assertType<{ foo: `0x${string}` bar: `0x${string}` // @ts-ignore – TODO: Fix https://github.com/wevm/viem/issues/1916 }>(result4) }) test('functionName', async () => { const readErc20BalanceOf = createReadContract({ abi: abi.erc20, address: '0x', functionName: 'balanceOf', }) const result = await readErc20BalanceOf(config, { args: ['0x'], chainId: 1, }) expectTypeOf(result).toEqualTypeOf() }) test('functionName with overloads', async () => { const readViewOverloads = createReadContract({ abi: abi.viewOverloads, address: '0x', functionName: 'foo', }) const result1 = await readViewOverloads(config, {}) assertType(result1) const result2 = await readViewOverloads(config, { args: [], }) assertType(result2) const result3 = await readViewOverloads(config, { args: ['0x'], }) // @ts-ignore – TODO: Fix https://github.com/wevm/viem/issues/1916 assertType(result3) const result4 = await readViewOverloads(config, { args: ['0x', '0x'], }) assertType<{ foo: `0x${string}` bar: `0x${string}` // @ts-ignore – TODO: Fix https://github.com/wevm/viem/issues/1916 }>(result4) }) ================================================ FILE: packages/core/src/actions/codegen/createReadContract.test.ts ================================================ import { abi, address, chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { createReadContract } from './createReadContract.js' test('default', async () => { const readWagmiMintExample = createReadContract({ address: address.wagmiMintExample, abi: abi.wagmiMintExample, }) await expect( readWagmiMintExample(config, { functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }), ).resolves.toMatchInlineSnapshot('10n') }) test('multichain', async () => { const readWagmiMintExample = createReadContract({ address: { [chain.mainnet.id]: address.wagmiMintExample, [chain.mainnet2.id]: address.wagmiMintExample, }, abi: abi.wagmiMintExample, }) await expect( readWagmiMintExample(config, { functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], chainId: chain.mainnet2.id, }), ).resolves.toMatchInlineSnapshot('10n') }) test('functionName', async () => { const readWagmiMintExampleBalanceOf = createReadContract({ address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'balanceOf', }) await expect( readWagmiMintExampleBalanceOf(config, { args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }), ).resolves.toMatchInlineSnapshot('10n') }) ================================================ FILE: packages/core/src/actions/codegen/createReadContract.ts ================================================ import type { Abi, Address, ContractFunctionArgs, ContractFunctionName, } from 'viem' import type { Config } from '../../createConfig.js' import type { UnionCompute, UnionStrictOmit } from '../../types/utils.js' import { getChainId } from '../getChainId.js' import { type ReadContractParameters, type ReadContractReturnType, readContract, } from '../readContract.js' type stateMutability = 'pure' | 'view' export type CreateReadContractParameters< abi extends Abi | readonly unknown[], address extends Address | Record | undefined = undefined, functionName extends | ContractFunctionName | undefined = undefined, > = { abi: abi | Abi | readonly unknown[] address?: address | Address | Record | undefined functionName?: | functionName | ContractFunctionName | undefined } export type CreateReadContractReturnType< abi extends Abi | readonly unknown[], address extends Address | Record | undefined, functionName extends ContractFunctionName | undefined, /// omittedProperties extends 'abi' | 'address' | 'chainId' | 'functionName' = | 'abi' | (address extends undefined ? never : 'address') | (address extends Record ? 'chainId' : never) | (functionName extends undefined ? never : 'functionName'), > = < config extends Config, name extends functionName extends ContractFunctionName ? functionName : ContractFunctionName, args extends ContractFunctionArgs, >( config: config, parameters: UnionCompute< UnionStrictOmit< ReadContractParameters, omittedProperties > > & (address extends Record ? { chainId?: keyof address | undefined } : unknown), ) => Promise> export function createReadContract< const abi extends Abi | readonly unknown[], const address extends | Address | Record | undefined = undefined, functionName extends | ContractFunctionName | undefined = undefined, >( c: CreateReadContractParameters, ): CreateReadContractReturnType { if (c.address !== undefined && typeof c.address === 'object') return (config, parameters) => { const configChainId = getChainId(config) const chainId = (parameters as { chainId?: number })?.chainId ?? configChainId return readContract(config, { ...(parameters as any), ...(c.functionName ? { functionName: c.functionName } : {}), address: c.address?.[chainId], abi: c.abi, }) } return (config, parameters) => { return readContract(config, { ...(parameters as any), ...(c.address ? { address: c.address } : {}), ...(c.functionName ? { functionName: c.functionName } : {}), abi: c.abi, }) } } ================================================ FILE: packages/core/src/actions/codegen/createSimulateContract.test-d.ts ================================================ import { abi, config, mainnet, optimism } from '@wagmi/test' import { type Address, http } from 'viem' import { celo } from 'viem/chains' import { assertType, expectTypeOf, test } from 'vitest' import { createConfig } from '../../createConfig.js' import { createSimulateContract } from './createSimulateContract.js' test('default', async () => { const simulateErc20 = createSimulateContract({ abi: abi.erc20, address: '0x', }) const result = await simulateErc20(config, { functionName: 'transferFrom', args: ['0x', '0x', 123n], chainId: 1, }) expectTypeOf(result).toMatchTypeOf<{ result: boolean request: { chainId: 1 abi: readonly [ { readonly name: 'transferFrom' readonly type: 'function' readonly stateMutability: 'nonpayable' readonly inputs: readonly [ { readonly type: 'address'; readonly name: 'sender' }, { readonly type: 'address'; readonly name: 'recipient' }, { readonly type: 'uint256'; readonly name: 'amount' }, ] readonly outputs: readonly [{ type: 'bool' }] }, ] functionName: 'transferFrom' args: readonly [Address, Address, bigint] } }>() }) test('multichain address', async () => { const simulateErc20 = createSimulateContract({ abi: abi.erc20, address: { [mainnet.id]: '0x', [optimism.id]: '0x', }, }) const result = await simulateErc20(config, { functionName: 'transferFrom', args: ['0x', '0x', 123n], chainId: optimism.id, }) expectTypeOf(result.result).toEqualTypeOf() simulateErc20(config, { functionName: 'transferFrom', args: ['0x', '0x', 123n], // @ts-expect-error chain id must match address keys chainId: 420, }) simulateErc20(config, { functionName: 'transferFrom', args: ['0x', '0x', 123n], // @ts-expect-error address not allowed address: '0x', }) }) test('overloads', async () => { const simulateWriteOverloads = createSimulateContract({ abi: abi.writeOverloads, address: '0x', }) const result1 = await simulateWriteOverloads(config, { functionName: 'foo', }) assertType(result1.result) const result2 = await simulateWriteOverloads(config, { functionName: 'foo', args: [], }) assertType(result2.result) const result3 = await simulateWriteOverloads(config, { functionName: 'foo', args: ['0x'], }) // @ts-ignore – TODO: Fix https://github.com/wevm/viem/issues/1916 assertType(result3.result) const result4 = await simulateWriteOverloads(config, { functionName: 'foo', args: ['0x', '0x'], }) assertType< | { foo: `0x${string}` bar: `0x${string}` } | undefined // @ts-ignore – TODO: Fix https://github.com/wevm/viem/issues/1916 >(result4.result) }) test('functionName', async () => { const simulateErc20 = createSimulateContract({ abi: abi.erc20, address: '0x', functionName: 'transferFrom', }) const result = await simulateErc20(config, { args: ['0x', '0x', 123n], chainId: 1, }) expectTypeOf(result).toMatchTypeOf<{ result: boolean request: { chainId: 1 abi: readonly [ { readonly name: 'transferFrom' readonly type: 'function' readonly stateMutability: 'nonpayable' readonly inputs: readonly [ { readonly type: 'address'; readonly name: 'sender' }, { readonly type: 'address'; readonly name: 'recipient' }, { readonly type: 'uint256'; readonly name: 'amount' }, ] readonly outputs: readonly [{ type: 'bool' }] }, ] functionName: 'transferFrom' args: readonly [Address, Address, bigint] } }>() }) test('functionName with overloads', async () => { const simulateWriteOverloads = createSimulateContract({ abi: abi.writeOverloads, address: '0x', functionName: 'foo', }) const result1 = await simulateWriteOverloads(config, {}) assertType(result1.result) const result2 = await simulateWriteOverloads(config, { args: [], }) assertType(result2.result) const result3 = await simulateWriteOverloads(config, { args: ['0x'], }) // @ts-ignore – TODO: Fix https://github.com/wevm/viem/issues/1916 assertType(result3.result) const result4 = await simulateWriteOverloads(config, { args: ['0x', '0x'], }) assertType< | { foo: `0x${string}` bar: `0x${string}` } | undefined // @ts-ignore – TODO: Fix https://github.com/wevm/viem/issues/1916 >(result4.result) }) test('chain formatters', async () => { const simulateErc20 = createSimulateContract({ abi: abi.erc20, address: '0x', }) const config = createConfig({ chains: [celo, mainnet], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) const response = await simulateErc20(config, { functionName: 'transferFrom', args: ['0x', '0x', 123n], }) if (response.chainId === celo.id) { expectTypeOf(response.request.feeCurrency).toEqualTypeOf< `0x${string}` | undefined >() } const response2 = await simulateErc20(config, { functionName: 'transferFrom', args: ['0x', '0x', 123n], chainId: celo.id, }) expectTypeOf(response2.request.feeCurrency).toEqualTypeOf< `0x${string}` | undefined >() }) ================================================ FILE: packages/core/src/actions/codegen/createSimulateContract.test.ts ================================================ import { abi, address, chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { connect } from '../connect.js' import { disconnect } from '../disconnect.js' import { switchChain } from '../switchChain.js' import { createSimulateContract } from './createSimulateContract.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const simulateWagmiMintExample = createSimulateContract({ address: address.wagmiMintExample, abi: abi.wagmiMintExample, }) await expect( simulateWagmiMintExample(config, { functionName: 'mint', }), ).resolves.toMatchInlineSnapshot(` { "chainId": 1, "request": { "abi": [ { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "account": { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "type": "json-rpc", }, "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": undefined, "chainId": undefined, "dataSuffix": undefined, "functionName": "mint", }, "result": undefined, } `) await disconnect(config, { connector }) }) test('multichain', async () => { await connect(config, { connector }) const simulateWagmiMintExample = createSimulateContract({ address: { [chain.mainnet.id]: address.wagmiMintExample, [chain.mainnet2.id]: address.wagmiMintExample, }, abi: abi.wagmiMintExample, }) await expect( simulateWagmiMintExample(config, { functionName: 'mint', }), ).resolves.toMatchObject({ chainId: 1, }) await switchChain(config, { chainId: chain.mainnet2.id }) await expect( simulateWagmiMintExample(config, { functionName: 'mint', chainId: chain.mainnet2.id, }), ).resolves.toMatchInlineSnapshot(` { "chainId": 456, "request": { "abi": [ { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "account": { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "type": "json-rpc", }, "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": undefined, "chainId": 456, "dataSuffix": undefined, "functionName": "mint", }, "result": undefined, } `) await switchChain(config, { chainId: chain.mainnet.id }) await disconnect(config, { connector }) }) test('functionName', async () => { await connect(config, { connector }) const simulateWagmiMintExample = createSimulateContract({ address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'mint', }) await expect( simulateWagmiMintExample(config, {}), ).resolves.toMatchInlineSnapshot(` { "chainId": 1, "request": { "abi": [ { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "account": { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "type": "json-rpc", }, "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": undefined, "chainId": undefined, "dataSuffix": undefined, "functionName": "mint", }, "result": undefined, } `) await disconnect(config, { connector }) }) ================================================ FILE: packages/core/src/actions/codegen/createSimulateContract.ts ================================================ import type { Abi, Account, Address, Chain, ContractFunctionArgs, ContractFunctionName, SimulateContractParameters as viem_SimulateContractParameters, } from 'viem' import type { Config } from '../../createConfig.js' import type { SelectChains } from '../../types/chain.js' import type { ChainIdParameter, ConnectorParameter, } from '../../types/properties.js' import type { UnionCompute, UnionStrictOmit } from '../../types/utils.js' import { getChainId } from '../getChainId.js' import { type SimulateContractReturnType, simulateContract, } from '../simulateContract.js' type stateMutability = 'nonpayable' | 'payable' export type CreateSimulateContractParameters< abi extends Abi | readonly unknown[], address extends Address | Record | undefined = undefined, functionName extends | ContractFunctionName | undefined = undefined, > = { abi: abi | Abi | readonly unknown[] address?: address | Address | Record | undefined functionName?: | functionName | ContractFunctionName | undefined } export type CreateSimulateContractReturnType< abi extends Abi | readonly unknown[], address extends Address | Record | undefined, functionName extends ContractFunctionName | undefined, > = < config extends Config, name extends functionName extends ContractFunctionName ? functionName : ContractFunctionName, args extends ContractFunctionArgs, chainId extends config['chains'][number]['id'] | undefined = undefined, /// chains extends readonly Chain[] = SelectChains, >( config: config, parameters: { [key in keyof chains]: UnionCompute< UnionStrictOmit< viem_SimulateContractParameters< abi, name, args, chains[key], chains[key], Account | Address >, | 'abi' | 'chain' | (address extends undefined ? never : 'address') | (functionName extends undefined ? never : 'functionName') > > & ChainIdParameter & ConnectorParameter & { chainId?: address extends Record ? | keyof address | (chainId extends keyof address ? chainId : never) | undefined : chainId | number | undefined } }[number], ) => Promise> export function createSimulateContract< const abi extends Abi | readonly unknown[], const address extends | Address | Record | undefined = undefined, functionName extends | ContractFunctionName | undefined = undefined, >( c: CreateSimulateContractParameters, ): CreateSimulateContractReturnType { if (c.address !== undefined && typeof c.address === 'object') return (config, parameters) => { const configChainId = getChainId(config) const chainId = (parameters as { chainId?: number })?.chainId ?? configChainId return simulateContract(config, { ...(parameters as any), ...(c.functionName ? { functionName: c.functionName } : {}), address: c.address?.[chainId], abi: c.abi, }) } return (config, parameters) => { return simulateContract(config, { ...(parameters as any), ...(c.address ? { address: c.address } : {}), ...(c.functionName ? { functionName: c.functionName } : {}), abi: c.abi, }) } } ================================================ FILE: packages/core/src/actions/codegen/createWatchContractEvent.test-d.ts ================================================ import { abi, config, mainnet, optimism } from '@wagmi/test' import { http, webSocket } from 'viem' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../../createConfig.js' import { createWatchContractEvent } from './createWatchContractEvent.js' test('default', () => { const watchErc20Event = createWatchContractEvent({ abi: abi.erc20, }) watchErc20Event(config, { eventName: 'Transfer', chainId: 1, onLogs(logs) { expectTypeOf(logs[0]!.eventName).toEqualTypeOf<'Transfer'>() expectTypeOf(logs[0]!.args).toEqualTypeOf<{ from?: `0x${string}` | undefined to?: `0x${string}` | undefined value?: bigint | undefined }>() }, }) }) test('multichain address', () => { const watchErc20Event = createWatchContractEvent({ abi: abi.erc20, address: { [mainnet.id]: '0x', [optimism.id]: '0x', }, }) watchErc20Event(config, { eventName: 'Transfer', chainId: mainnet.id, // ^? onLogs() {}, }) watchErc20Event(config, { eventName: 'Transfer', // @ts-expect-error chain id must match address keys chainId: 420, onLogs() {}, }) watchErc20Event(config, { eventName: 'Transfer', // @ts-expect-error chain id must match address keys address: '0x', onLogs() {}, }) }) test('differing transports', () => { const watchErc20Event = createWatchContractEvent({ abi: abi.erc20, }) const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: webSocket(), }, }) watchErc20Event(config, { poll: false, address: '0x', onLogs() {}, }) watchErc20Event(config, { chainId: mainnet.id, poll: true, address: '0x', onLogs() {}, }) watchErc20Event(config, { config, chainId: mainnet.id, // @ts-expect-error poll required since http transport poll: false, address: '0x', onLogs() {}, }) watchErc20Event(config, { chainId: optimism.id, poll: true, address: '0x', onLogs() {}, }) watchErc20Event(config, { chainId: optimism.id, poll: false, address: '0x', onLogs() {}, }) }) test('eventName', () => { const watchErc20Event = createWatchContractEvent({ abi: abi.erc20, eventName: 'Transfer', }) watchErc20Event(config, { chainId: 1, onLogs(logs) { expectTypeOf(logs[0]!.eventName).toEqualTypeOf<'Transfer'>() expectTypeOf(logs[0]!.args).toEqualTypeOf<{ from?: `0x${string}` | undefined to?: `0x${string}` | undefined value?: bigint | undefined }>() }, }) }) ================================================ FILE: packages/core/src/actions/codegen/createWatchContractEvent.test.ts ================================================ import { abi, address, chain, config, wait } from '@wagmi/test' import type { WatchEventOnLogsParameter } from 'viem' import { test } from 'vitest' import { createWatchContractEvent } from './createWatchContractEvent.js' test('default', async () => { const watchErc20Event = createWatchContractEvent({ address: address.usdc, abi: abi.wagmiMintExample, }) let logs: WatchEventOnLogsParameter = [] const unwatch = watchErc20Event(config, { eventName: 'Transfer', onLogs(next) { logs = logs.concat(next) }, }) await wait(500) unwatch() await wait(500) }) test('multichain', async () => { const watchErc20Event = createWatchContractEvent({ address: { [chain.mainnet.id]: address.usdc, [chain.mainnet2.id]: address.usdc, }, abi: abi.wagmiMintExample, }) let logs: WatchEventOnLogsParameter = [] const unwatch = watchErc20Event(config, { eventName: 'Transfer', chainId: chain.mainnet2.id, onLogs(next) { logs = logs.concat(next) }, }) await wait(500) unwatch() await wait(500) }) ================================================ FILE: packages/core/src/actions/codegen/createWatchContractEvent.ts ================================================ import type { Abi, Address, ContractEventName } from 'viem' import type { Config } from '../../createConfig.js' import type { UnionCompute, UnionStrictOmit } from '../../types/utils.js' import { getChainId } from '../getChainId.js' import { type WatchContractEventParameters, type WatchContractEventReturnType, watchContractEvent, } from '../watchContractEvent.js' export type CreateWatchContractEventParameters< abi extends Abi | readonly unknown[], address extends Address | Record | undefined = undefined, eventName extends ContractEventName | undefined = undefined, > = { abi: abi | Abi | readonly unknown[] address?: address | Address | Record | undefined eventName?: eventName | ContractEventName | undefined } export type CreateWatchContractEventReturnType< abi extends Abi | readonly unknown[], address extends Address | Record | undefined, eventName extends ContractEventName | undefined, /// omittedProperties extends 'abi' | 'address' | 'chainId' | 'eventName' = | 'abi' | (address extends undefined ? never : 'address') | (address extends Record ? 'chainId' : never) | (eventName extends undefined ? never : 'eventName'), > = < config extends Config, name extends eventName extends ContractEventName ? eventName : ContractEventName, strict extends boolean | undefined = undefined, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], >( config: config, parameters: UnionCompute< UnionStrictOmit< WatchContractEventParameters, omittedProperties > > & (address extends Record ? { chainId?: keyof address | undefined } : unknown), ) => WatchContractEventReturnType export function createWatchContractEvent< const abi extends Abi | readonly unknown[], const address extends | Address | Record | undefined = undefined, eventName extends ContractEventName | undefined = undefined, >( c: CreateWatchContractEventParameters, ): CreateWatchContractEventReturnType { if (c.address !== undefined && typeof c.address === 'object') return (config, parameters) => { const configChainId = getChainId(config) const chainId = (parameters as { chainId?: number })?.chainId ?? configChainId return watchContractEvent(config, { ...(parameters as any), ...(c.eventName ? { eventName: c.eventName } : {}), address: c.address?.[chainId], abi: c.abi, }) } return (config, parameters) => { return watchContractEvent(config, { ...(parameters as any), ...(c.address ? { address: c.address } : {}), ...(c.eventName ? { eventName: c.eventName } : {}), abi: c.abi, }) } } ================================================ FILE: packages/core/src/actions/codegen/createWriteContract.test-d.ts ================================================ import { abi, config, mainnet, optimism } from '@wagmi/test' import { test } from 'vitest' import { simulateContract } from '../simulateContract.js' import { createWriteContract } from './createWriteContract.js' test('default', () => { const writeErc20 = createWriteContract({ abi: abi.erc20, address: '0x', }) writeErc20(config, { functionName: 'transfer', args: ['0x', 123n], }) }) test('multichain address', () => { const writeErc20 = createWriteContract({ abi: abi.erc20, address: { [mainnet.id]: '0x', [optimism.id]: '0x', }, }) writeErc20(config, { functionName: 'transfer', args: ['0x', 123n], chainId: mainnet.id, // ^? }) writeErc20(config, { functionName: 'transfer', args: ['0x', 123n], // @ts-expect-error chain id must match address keys chainId: 420, }) writeErc20(config, { // @ts-expect-error address not allowed address: '0x', functionName: 'transfer', args: ['0x', 123n], }) }) test('overloads', () => { const writeOverloads = createWriteContract({ abi: abi.writeOverloads, address: { [mainnet.id]: '0x', [optimism.id]: '0x', }, }) writeOverloads(config, { functionName: 'foo', args: [], }) writeOverloads(config, { functionName: 'foo', args: ['0x'], }) writeOverloads(config, { functionName: 'foo', args: ['0x', '0x'], }) }) test('useSimulateContract', async () => { const writeErc20 = createWriteContract({ abi: abi.erc20, address: { [mainnet.id]: '0x', [optimism.id]: '0x', }, }) const { request } = await simulateContract(config, { account: '0x', address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], chainId: 1, }) writeErc20(config, request) }) test('functionName', () => { const writeErc20 = createWriteContract({ abi: abi.erc20, address: '0x', functionName: 'transfer', }) writeErc20(config, { args: ['0x', 123n], }) }) test('functionName with overloads', () => { const writeOverloads = createWriteContract({ abi: abi.writeOverloads, address: { [mainnet.id]: '0x', [optimism.id]: '0x', }, functionName: 'foo', }) writeOverloads(config, { args: [], }) writeOverloads(config, { args: ['0x'], }) writeOverloads(config, { args: ['0x', '0x'], }) }) ================================================ FILE: packages/core/src/actions/codegen/createWriteContract.test.ts ================================================ import { abi } from '@wagmi/test' import { expect, test } from 'vitest' import { createWriteContract } from './createWriteContract.js' test('default', () => { const writeErc20 = createWriteContract({ abi: abi.erc20, }) expect(writeErc20).toBeDefined() }) ================================================ FILE: packages/core/src/actions/codegen/createWriteContract.ts ================================================ import type { Abi, Account, Address, Chain, ContractFunctionArgs, ContractFunctionName, WriteContractParameters as viem_WriteContractParameters, } from 'viem' import type { Config } from '../../createConfig.js' import type { SelectChains } from '../../types/chain.js' import type { ChainIdParameter, ConnectorParameter, } from '../../types/properties.js' import type { Compute, UnionCompute, UnionStrictOmit, } from '../../types/utils.js' import { getChainId } from '../getChainId.js' import { type WriteContractReturnType, writeContract, } from '../writeContract.js' type stateMutability = 'nonpayable' | 'payable' export type CreateWriteContractParameters< abi extends Abi | readonly unknown[], address extends Address | Record | undefined = undefined, functionName extends | ContractFunctionName | undefined = undefined, > = { abi: abi | Abi | readonly unknown[] address?: address | Address | Record | undefined functionName?: | functionName | ContractFunctionName | undefined } export type CreateWriteContractReturnType< abi extends Abi | readonly unknown[], address extends Address | Record | undefined, functionName extends ContractFunctionName | undefined, > = < config extends Config, name extends functionName extends ContractFunctionName ? functionName : ContractFunctionName, args extends ContractFunctionArgs, chainId extends config['chains'][number]['id'], /// allFunctionNames = ContractFunctionName, chains extends readonly Chain[] = SelectChains, omittedProperties extends 'abi' | 'address' | 'functionName' = | 'abi' | (address extends undefined ? never : 'address') | (functionName extends undefined ? never : 'functionName'), >( config: config, parameters: UnionCompute< { [key in keyof chains]: UnionStrictOmit< viem_WriteContractParameters< abi, name, args, chains[key], Account, chains[key], allFunctionNames >, omittedProperties | 'chain' > }[number] & (address extends Record ? { chainId?: | keyof address | (chainId extends keyof address ? chainId : never) | undefined } : Compute>) & ConnectorParameter >, ) => Promise export function createWriteContract< const abi extends Abi | readonly unknown[], const address extends | Address | Record | undefined = undefined, functionName extends | ContractFunctionName | undefined = undefined, >( c: CreateWriteContractParameters, ): CreateWriteContractReturnType { if (c.address !== undefined && typeof c.address === 'object') return (config, parameters) => { const chainId = (() => { if (parameters.chainId) return parameters.chainId return getChainId(config) })() return writeContract(config, { ...(parameters as any), ...(c.functionName ? { functionName: c.functionName } : {}), address: chainId ? c.address?.[chainId] : undefined, abi: c.abi, }) } return (config, parameters) => { return writeContract(config, { ...(parameters as any), ...(c.address ? { address: c.address } : {}), ...(c.functionName ? { functionName: c.functionName } : {}), abi: c.abi, }) } } ================================================ FILE: packages/core/src/actions/connect.test-d.ts ================================================ import { accounts, config as testConfig } from '@wagmi/test' import { type Address, type Hex, http } from 'viem' import { mainnet } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import type { CreateConnectorFn } from '../connectors/createConnector.js' import { mock } from '../connectors/mock.js' import { type Connector, createConfig } from '../createConfig.js' import { connect } from './connect.js' const config = createConfig({ chains: [mainnet], transports: { [mainnet.id]: http() }, }) test('parameters: connector (ConnectorFn)', () => { const connectorFn = mock({ accounts }) connect(config, { connector: connectorFn, foo: 'bar', }) expectTypeOf< typeof connectorFn extends CreateConnectorFn ? true : false >().toEqualTypeOf() type Result = NonNullable< Parameters>[1] > expectTypeOf().toEqualTypeOf() }) test('parameters: connector (Connector)', () => { const connector = config._internal.connectors.setup(mock({ accounts })) connect(config, { connector, foo: 'bar', }) expectTypeOf< typeof connector extends Connector ? true : false >().toEqualTypeOf() type Result = NonNullable< Parameters>[1] > expectTypeOf().toEqualTypeOf() }) test('parameters: withCapabilities', async () => { const connectorFn = mock({ accounts }) const res0 = await connect(config, { connector: connectorFn }) expectTypeOf(res0.accounts).toEqualTypeOf() const res1 = await connect(config, { connector: connectorFn, withCapabilities: false, }) expectTypeOf(res1.accounts).toEqualTypeOf() const res2 = await connect(config, { connector: connectorFn, withCapabilities: true, }) expectTypeOf(res2.accounts).toEqualTypeOf< readonly [ { address: Address capabilities: { foo: { bar: Hex } } }, ...{ address: Address capabilities: { foo: { bar: Hex } } }[], ] >() }) test('behavior: with config', () => { connect(testConfig, { connector: testConfig.connectors[0]!, foo: 'bar', }) // @ts-expect-error testConfig.connectors[4] }) ================================================ FILE: packages/core/src/actions/connect.test.ts ================================================ import { accounts, chain, config } from '@wagmi/test' import { beforeEach, expect, test } from 'vitest' import { mock } from '../connectors/mock.js' import { connect } from './connect.js' import { disconnect } from './disconnect.js' const connector = config._internal.connectors.setup(mock({ accounts })) beforeEach(async () => { if (config.state.current === connector.uid) await disconnect(config, { connector }) }) test('default', async () => { await expect(connect(config, { connector })).resolves.toMatchObject( expect.objectContaining({ accounts: expect.arrayContaining([expect.any(String)]), chainId: expect.any(Number), }), ) }) test('parameters: chainId', async () => { const chainId = chain.mainnet2.id await expect(connect(config, { connector, chainId })).resolves.toMatchObject( expect.objectContaining({ accounts: expect.arrayContaining([expect.any(String)]), chainId, }), ) }) test('parameters: connector', async () => { const connector_ = config._internal.connectors.setup(mock({ accounts })) await expect( connect(config, { connector: connector_ }), ).resolves.toMatchObject( expect.objectContaining({ accounts: expect.arrayContaining([expect.any(String)]), chainId: expect.any(Number), }), ) await disconnect(config, { connector: connector_ }) }) test('parameters: withCapabilities', async () => { await expect( connect(config, { connector, withCapabilities: true }), ).resolves.toMatchObject( expect.objectContaining({ accounts: expect.arrayContaining([ expect.objectContaining({ address: expect.any(String), capabilities: expect.objectContaining({ foo: expect.objectContaining({ bar: expect.any(String) }), }), }), ]), }), ) }) test('behavior: user rejected request', async () => { const connector_ = config._internal.connectors.setup( mock({ accounts, features: { connectError: true }, }), ) await expect( connect(config, { connector: connector_ }), ).rejects.toMatchInlineSnapshot(` [UserRejectedRequestError: User rejected the request. Details: Failed to connect. Version: viem@2.47.5] `) }) test('behavior: already connected', async () => { await connect(config, { connector }) await expect(connect(config, { connector })).rejects.toMatchInlineSnapshot(` [ConnectorAlreadyConnectedError: Connector already connected. Version: @wagmi/core@x.y.z] `) }) ================================================ FILE: packages/core/src/actions/connect.ts ================================================ import type { Address, ResourceUnavailableRpcErrorType, UserRejectedRequestErrorType, } from 'viem' import type { CreateConnectorFn } from '../connectors/createConnector.js' import type { Config, Connector } from '../createConfig.js' import type { BaseErrorType, ErrorType } from '../errors/base.js' import { ConnectorAlreadyConnectedError, type ConnectorAlreadyConnectedErrorType, } from '../errors/config.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' export type ConnectParameters< config extends Config = Config, connector extends Connector | CreateConnectorFn = | Connector | CreateConnectorFn, withCapabilities extends boolean = false, /// parameters extends unknown | undefined = | (connector extends CreateConnectorFn ? Omit< NonNullable['connect']>[0]>, 'isReconnecting' > : never) | (connector extends Connector ? Omit< NonNullable[0]>, 'isReconnecting' > : never), > = Compute< ChainIdParameter & { connector: connector | CreateConnectorFn withCapabilities?: withCapabilities | boolean | undefined } > & parameters export type ConnectReturnType< config extends Config = Config, connector extends Connector | CreateConnectorFn = | Connector | CreateConnectorFn, withCapabilities extends boolean = false, /// capabilities extends unknown | undefined = | (connector extends CreateConnectorFn ? Awaited< ReturnType['connect']> >['accounts'] extends | readonly Address[] | readonly { capabilities: infer capabilities }[] ? capabilities : Record : never) | (connector extends Connector ? Awaited>['accounts'] extends | readonly Address[] | readonly { capabilities: infer capabilities }[] ? capabilities : Record : never), > = { accounts: withCapabilities extends true ? readonly [ { address: Address; capabilities: capabilities }, ...{ address: Address; capabilities: capabilities }[], ] : readonly [Address, ...Address[]] chainId: | config['chains'][number]['id'] | (number extends config['chains'][number]['id'] ? number : number & {}) } export type ConnectErrorType = | ConnectorAlreadyConnectedErrorType // connector.connect() | UserRejectedRequestErrorType | ResourceUnavailableRpcErrorType // base | BaseErrorType | ErrorType /** https://wagmi.sh/core/api/actions/connect */ export async function connect< config extends Config, connector extends Connector | CreateConnectorFn, withCapabilities extends boolean = false, >( config: config, parameters: ConnectParameters, ): Promise> { // "Register" connector if not already created let connector: Connector if (typeof parameters.connector === 'function') { connector = config._internal.connectors.setup(parameters.connector) } else connector = parameters.connector // Check if connector is already connected if (connector.uid === config.state.current) throw new ConnectorAlreadyConnectedError() try { config.setState((x) => ({ ...x, status: 'connecting' })) connector.emitter.emit('message', { type: 'connecting' }) const { connector: _, ...rest } = parameters const data = await connector.connect(rest) connector.emitter.off('connect', config._internal.events.connect) connector.emitter.on('change', config._internal.events.change) connector.emitter.on('disconnect', config._internal.events.disconnect) await config.storage?.setItem('recentConnectorId', connector.id) config.setState((x) => ({ ...x, connections: new Map(x.connections).set(connector.uid, { accounts: (rest.withCapabilities ? data.accounts.map((account) => typeof account === 'object' ? account.address : account, ) : data.accounts) as readonly [Address, ...Address[]], chainId: data.chainId, connector: connector, }), current: connector.uid, status: 'connected', })) return { // TODO(v3): Remove `withCapabilities: true` default behavior so remove compat marshalling // Workaround so downstream connectors work with `withCapabilities` without any changes required accounts: (rest.withCapabilities ? data.accounts.map((address) => typeof address === 'object' ? address : { address, capabilities: {} }, ) : data.accounts) as never, chainId: data.chainId, } as never } catch (error) { config.setState((x) => ({ ...x, // Keep existing connector connected in case of error status: x.current ? 'connected' : 'disconnected', })) throw error } } ================================================ FILE: packages/core/src/actions/deployContract.test-d.ts ================================================ import { abi, bytecode, config } from '@wagmi/test' import { http } from 'viem' import { celo, mainnet } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { type DeployContractParameters, deployContract, } from './deployContract.js' test('default', async () => { await deployContract(config, { abi: abi.bayc, bytecode: bytecode.bayc, args: ['Bored Ape Wagmi Club', 'BAYC', 69420n, 0n], chainId: mainnet.id, }) }) test('chain formatters', () => { const config = createConfig({ chains: [mainnet, celo], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) type Result = DeployContractParameters expectTypeOf().toMatchTypeOf<{ chainId?: typeof celo.id | typeof mainnet.id | undefined feeCurrency?: `0x${string}` | undefined }>() deployContract(config, { abi: abi.bayc, bytecode: bytecode.bayc, args: ['Bored Ape Wagmi Club', 'BAYC', 69420n, 0n], feeCurrency: '0x', }) type Result2 = DeployContractParameters< typeof abi.bayc, typeof config, typeof celo.id > expectTypeOf().toMatchTypeOf<{ feeCurrency?: `0x${string}` | undefined }>() deployContract(config, { chainId: celo.id, abi: abi.bayc, bytecode: bytecode.bayc, args: ['Bored Ape Wagmi Club', 'BAYC', 69420n, 0n], feeCurrency: '0x', }) type Result3 = DeployContractParameters< typeof abi.bayc, typeof config, typeof mainnet.id > expectTypeOf().not.toMatchTypeOf<{ feeCurrency?: `0x${string}` | undefined }>() deployContract(config, { chainId: mainnet.id, abi: abi.bayc, bytecode: bytecode.bayc, args: ['Bored Ape Wagmi Club', 'BAYC', 69420n, 0n], // @ts-expect-error feeCurrency: '0x', }) }) ================================================ FILE: packages/core/src/actions/deployContract.test.ts ================================================ import { abi, bytecode, config, testClient, transactionHashRegex, } from '@wagmi/test' import { parseEther } from 'viem' import { expect, test } from 'vitest' import { connect } from './connect.js' import { deployContract } from './deployContract.js' import { disconnect } from './disconnect.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) await expect( deployContract(config, { abi: abi.bayc, bytecode: bytecode.bayc, args: ['Bored Ape Wagmi Club', 'BAYC', 69420n, 0n], }), ).resolves.toMatch(transactionHashRegex) await disconnect(config, { connector }) }) test('behavior: no funds', async () => { const data = await connect(config, { connector }) const connectedAddress = data.accounts[0] await testClient.mainnet.setBalance({ address: connectedAddress, value: parseEther('0'), }) await expect( deployContract(config, { chainId: testClient.mainnet.chain.id, abi: abi.bayc, bytecode: bytecode.bayc, args: ['Bored Ape Wagmi Club', 'BAYC', 69420n, 0n], }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [TransactionExecutionError: The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account. This error could arise when the account does not have enough funds to: - pay for the total gas fee, - pay for the value to send. The cost of the transaction is calculated as \`gas * gas fee + value\`, where: - \`gas\` is the amount of gas needed for transaction to execute, - \`gas fee\` is the gas fee, - \`value\` is the amount of ether to send to the recipient. Request Arguments: chain: Ethereum (id: 1) from: 0x95132632579b073D12a6673e18Ab05777a6B86f8 data: 0x608060405260405180602001604052806000815250600b90805190602001906200002b92919062000484565b506000600f60006101000a81548160ff0219169083151502179055503480156200005457600080fd5b50604051620046d0380380620046d0833981810160405260808110156200007a57600080fd5b81019080805160405193929190846401000000008211156200009b57600080fd5b83820191506020820185811115620000b257600080fd5b8251866001820283011164010000000082111715620000d057600080fd5b8083526020830192505050908051906020019080838360005b8381101562000106578082015181840152602081019050620000e9565b50505050905090810190601f168015620001345780820380516001836020036101000a031916815260200191505b50604052602001805160405193929190846401000000008211156200015857600080fd5b838201915060208201858111156200016f57600080fd5b82518660018202830111640100000000821117156200018d57600080fd5b8083526020830192505050908051906020019080838360005b83811015620001c3578082015181840152602081019050620001a6565b50505050905090810190601f168015620001f15780820380516001836020036101000a031916815260200191505b5060405260200180519060200190929190805190602001909291905050508383620002296301ffc9a760e01b6200037360201b60201c565b81600690805190602001906200024192919062000484565b5080600790805190602001906200025a92919062000484565b50620002736380ac58cd60e01b6200037360201b60201c565b6200028b635b5e139f60e01b6200037360201b60201c565b620002a363780e9d6360e01b6200037360201b60201c565b50506000620002b76200047c60201b60201c565b905080600a60006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508073ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a35081600e81905550620bdd808101601081905550505050506200052a565b63ffffffff60e01b817bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916141562000410576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601c8152602001807f4552433136353a20696e76616c696420696e746572666163652069640000000081525060200191505060405180910390fd5b6001600080837bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916815260200190815260200160002060006101000a81548160ff02191690831515021790555050565b600033905090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10620004c757805160ff1916838001178555620004f8565b82800160010185558215620004f8579182015b82811115620004f7578251825591602001919060010190620004da565b5b5090506200050791906200050b565b5090565b5b80821115620005265760008160009055506001016200050c565b5090565b614196806200053a6000396000f3fe60806040526004361061021a5760003560e01c80636c0360eb11610123578063b0f67427116100ab578063e36d64981161006f578063e36d649814610ddf578063e985e9c514610e0a578063e986655014610e91578063eb8d244414610ea8578063f2fde38b14610ed55761021a565b8063b0f6742714610bac578063b88d4fde14610bc3578063bb8a16bd14610cd5578063c87b56dd14610d00578063cb774d4714610db45761021a565b80637d17fcbe116100f25780637d17fcbe14610a395780638da5cb5b14610a5057806395d89b4114610a91578063a22cb46514610b21578063a723533e14610b7e5761021a565b80636c0360eb1461090257806370a0823114610992578063715018a6146109f75780637a3f451e14610a0e5761021a565b80632f745c59116101a65780634f6ccce7116101755780634f6ccce7146106cb57806355f804b31461071a578063571dff3b146107e2578063607e20e31461080d5780636352211e1461089d5761021a565b80632f745c59146105b357806334918dfd146106225780633ccfd60b1461063957806342842e0e146106505761021a565b8063095ea7b3116101ed578063095ea7b3146103bf578063109695231461041a57806318160ddd146104e257806318e20a381461050d57806323b872dd146105385761021a565b8063018a2c371461021f57806301ffc9a71461025a57806306fdde03146102ca578063081812fc1461035a575b600080fd5b34801561022b57600080fd5b506102586004803603602081101561024257600080fd5b8101908080359060200190929190505050610f26565b005b34801561026657600080fd5b506102b26004803603602081101561027d57600080fd5b8101908080357bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19169060200190929190505050610fdf565b60405180821515815260200191505060405180910390f35b3480156102d657600080fd5b506102df611046565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561031f578082015181840152602081019050610304565b50505050905090810190601f16801561034c5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561036657600080fd5b506103936004803603602081101561037d57600080fd5b81019080803590602001909291905050506110e8565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b3480156103cb57600080fd5b50610418600480360360408110156103e257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050611183565b005b34801561042657600080fd5b506104e06004803603602081101561043d57600080fd5b810190808035906020019064010000000081111561045a57600080fd5b82018360208201111561046c57600080fd5b8035906020019184600183028401116401000000008311171561048e57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192905050506112c7565b005b3480156104ee57600080fd5b506104f7611390565b6040518082815260200191505060405180910390f35b34801561051957600080fd5b506105226113a1565b6040518082815260200191505060405180910390f35b34801561054457600080fd5b506105b16004803603606081101561055b57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506113a7565b005b3480156105bf57600080fd5b5061060c600480360360408110156105d657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061141d565b6040518082815260200191505060405180910390f35b34801561062e57600080fd5b50610637611478565b005b34801561064557600080fd5b5061064e611553565b005b34801561065c57600080fd5b506106c96004803603606081101561067357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050611651565b005b3480156106d757600080fd5b50610704600480360360208110156106ee57600080fd5b8101908080359060200190929190505050611671565b6040518082815260200191505060405180910390f35b34801561072657600080fd5b506107e06004803603602081101561073d57600080fd5b810190808035906020019064010000000081111561075a57600080fd5b82018360208201111561076c57600080fd5b8035906020019184600183028401116401000000008311171561078e57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f820116905080830192505050505050509192919290505050611694565b005b3480156107ee57600080fd5b506107f761174f565b6040518082815260200191505060405180910390f35b34801561081957600080fd5b50610822611754565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610862578082015181840152602081019050610847565b50505050905090810190601f16801561088f5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156108a957600080fd5b506108d6600480360360208110156108c057600080fd5b81019080803590602001909291905050506117f2565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34801561090e57600080fd5b50610917611829565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561095757808201518184015260208101905061093c565b50505050905090810190601f1680156109845780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561099e57600080fd5b506109e1600480360360208110156109b557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506118cb565b6040518082815260200191505060405180910390f35b348015610a0357600080fd5b50610a0c6119a0565b005b348015610a1a57600080fd5b50610a23611b10565b6040518082815260200191505060405180910390f35b348015610a4557600080fd5b50610a4e611b1c565b005b348015610a5c57600080fd5b50610a65611c4c565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b348015610a9d57600080fd5b50610aa6611c76565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610ae6578082015181840152602081019050610acb565b50505050905090810190601f168015610b135780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b348015610b2d57600080fd5b50610b7c60048036036040811015610b4457600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803515159060200190929190505050611d18565b005b610baa60048036036020811015610b9457600080fd5b8101908080359060200190929190505050611ece565b005b348015610bb857600080fd5b50610bc1612127565b005b348015610bcf57600080fd5b50610cd360048036036080811015610be657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919080359060200190640100000000811115610c4d57600080fd5b820183602082011115610c5f57600080fd5b80359060200191846001830284011164010000000083111715610c8157600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f82011690508083019250505050505050919291929050505061220b565b005b348015610ce157600080fd5b50610cea612283565b6040518082815260200191505060405180910390f35b348015610d0c57600080fd5b50610d3960048036036020811015610d2357600080fd5b8101908080359060200190929190505050612289565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610d79578082015181840152602081019050610d5e565b50505050905090810190601f168015610da65780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b348015610dc057600080fd5b50610dc961255a565b6040518082815260200191505060405180910390f35b348015610deb57600080fd5b50610df4612560565b6040518082815260200191505060405180910390f35b348015610e1657600080fd5b50610e7960048036036040811015610e2d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612566565b60405180821515815260200191505060405180910390f35b348015610e9d57600080fd5b50610ea66125fa565b005b348015610eb457600080fd5b50610ebd612764565b60405180821515815260200191505060405180910390f35b348015610ee157600080fd5b50610f2460048036036020811015610ef857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612777565b005b610f2e61296c565b73ffffffffffffffffffffffffffffffffffffffff16610f4c611c4c565b73ffffffffffffffffffffffffffffffffffffffff1614610fd5576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b8060108190555050565b6000806000837bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916815260200190815260200160002060009054906101000a900460ff169050919050565b606060068054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156110de5780601f106110b3576101008083540402835291602001916110de565b820191906000526020600020905b8154815290600101906020018083116110c157829003601f168201915b5050505050905090565b60006110f382612974565b611148576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602c81526020018061408b602c913960400191505060405180910390fd5b6004600083815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff169050919050565b600061118e826117f2565b90508073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415611215576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602181526020018061410f6021913960400191505060405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff1661123461296c565b73ffffffffffffffffffffffffffffffffffffffff16148061126357506112628161125d61296c565b612566565b5b6112b8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526038815260200180613f956038913960400191505060405180910390fd5b6112c28383612991565b505050565b6112cf61296c565b73ffffffffffffffffffffffffffffffffffffffff166112ed611c4c565b73ffffffffffffffffffffffffffffffffffffffff1614611376576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b80600b908051906020019061138c929190613de6565b5050565b600061139c6002612a4a565b905090565b60105481565b6113b86113b261296c565b82612a5f565b61140d576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260318152602001806141306031913960400191505060405180910390fd5b611418838383612b53565b505050565b600061147082600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020612d9690919063ffffffff16565b905092915050565b61148061296c565b73ffffffffffffffffffffffffffffffffffffffff1661149e611c4c565b73ffffffffffffffffffffffffffffffffffffffff1614611527576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b600f60009054906101000a900460ff1615600f60006101000a81548160ff021916908315150217905550565b61155b61296c565b73ffffffffffffffffffffffffffffffffffffffff16611579611c4c565b73ffffffffffffffffffffffffffffffffffffffff1614611602576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b60004790503373ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051600060405180830381858888f1935050505015801561164d573d6000803e3d6000fd5b5050565b61166c8383836040518060200160405280600081525061220b565b505050565b600080611688836002612db090919063ffffffff16565b50905080915050919050565b61169c61296c565b73ffffffffffffffffffffffffffffffffffffffff166116ba611c4c565b73ffffffffffffffffffffffffffffffffffffffff1614611743576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b61174c81612ddc565b50565b601481565b600b8054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156117ea5780601f106117bf576101008083540402835291602001916117ea565b820191906000526020600020905b8154815290600101906020018083116117cd57829003601f168201915b505050505081565b600061182282604051806060016040528060298152602001613ff7602991396002612df69092919063ffffffff16565b9050919050565b606060098054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156118c15780601f10611896576101008083540402835291602001916118c1565b820191906000526020600020905b8154815290600101906020018083116118a457829003601f168201915b5050505050905090565b60008073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415611952576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602a815260200180613fcd602a913960400191505060405180910390fd5b611999600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020612e15565b9050919050565b6119a861296c565b73ffffffffffffffffffffffffffffffffffffffff166119c6611c4c565b73ffffffffffffffffffffffffffffffffffffffff1614611a4f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff16600a60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a36000600a60006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550565b67011c37937e08000081565b611b2461296c565b73ffffffffffffffffffffffffffffffffffffffff16611b42611c4c565b73ffffffffffffffffffffffffffffffffffffffff1614611bcb576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b6000600d5414611c43576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f5374617274696e6720696e64657820697320616c72656164792073657400000081525060200191505060405180910390fd5b43600c81905550565b6000600a60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b606060078054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015611d0e5780601f10611ce357610100808354040283529160200191611d0e565b820191906000526020600020905b815481529060010190602001808311611cf157829003601f168201915b5050505050905090565b611d2061296c565b73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415611dc1576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260198152602001807f4552433732313a20617070726f766520746f2063616c6c65720000000000000081525060200191505060405180910390fd5b8060056000611dce61296c565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055508173ffffffffffffffffffffffffffffffffffffffff16611e7b61296c565b73ffffffffffffffffffffffffffffffffffffffff167f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c318360405180821515815260200191505060405180910390a35050565b600f60009054906101000a900460ff16611f50576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601f8152602001807f53616c65206d7573742062652061637469766520746f206d696e74204170650081525060200191505060405180910390fd5b6014811115611faa576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526021815260200180613f746021913960400191505060405180910390fd5b600e54611fc782611fb9611390565b612e2a90919063ffffffff16565b111561201e576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260288152602001806140426028913960400191505060405180910390fd5b3461203a8267011c37937e080000612eb290919063ffffffff16565b11156120ae576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601f8152602001807f45746865722076616c75652073656e74206973206e6f7420636f72726563740081525060200191505060405180910390fd5b60005b818110156120ef5760006120c3611390565b9050600e546120d0611390565b10156120e1576120e03382612f38565b5b5080806001019150506120b1565b506000600c541480156121175750600e54612108611390565b148061211657506010544210155b5b156121245743600c819055505b50565b61212f61296c565b73ffffffffffffffffffffffffffffffffffffffff1661214d611c4c565b73ffffffffffffffffffffffffffffffffffffffff16146121d6576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b60006121e0611390565b905060005b601e811015612207576121fa33828401612f38565b80806001019150506121e5565b5050565b61221c61221661296c565b83612a5f565b612271576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260318152602001806141306031913960400191505060405180910390fd5b61227d84848484612f56565b50505050565b600e5481565b606061229482612974565b6122e9576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602f8152602001806140e0602f913960400191505060405180910390fd5b6060600860008481526020019081526020016000208054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156123925780601f1061236757610100808354040283529160200191612392565b820191906000526020600020905b81548152906001019060200180831161237557829003601f168201915b5050505050905060606123a3611829565b90506000815114156123b9578192505050612555565b60008251111561248a5780826040516020018083805190602001908083835b602083106123fb57805182526020820191506020810190506020830392506123d8565b6001836020036101000a03801982511681845116808217855250505050505090500182805190602001908083835b6020831061244c5780518252602082019150602081019050602083039250612429565b6001836020036101000a0380198251168184511680821785525050505050509050019250505060405160208183030381529060405292505050612555565b8061249485612fc8565b6040516020018083805190602001908083835b602083106124ca57805182526020820191506020810190506020830392506124a7565b6001836020036101000a03801982511681845116808217855250505050505090500182805190602001908083835b6020831061251b57805182526020820191506020810190506020830392506124f8565b6001836020036101000a03801982511681845116808217855250505050505090500192505050604051602081830303815290604052925050505b919050565b600d5481565b600c5481565b6000600560008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16905092915050565b6000600d5414612672576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f5374617274696e6720696e64657820697320616c72656164792073657400000081525060200191505060405180910390fd5b6000600c5414156126eb576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f5374617274696e6720696e64657820626c6f636b206d7573742062652073657481525060200191505060405180910390fd5b600e54600c544060001c816126fc57fe5b06600d8190555060ff61271a600c544361310f90919063ffffffff16565b111561273a57600e54600143034060001c8161273257fe5b06600d819055505b6000600d5414156127625761275b6001600d54612e2a90919063ffffffff16565b600d819055505b565b600f60009054906101000a900460ff1681565b61277f61296c565b73ffffffffffffffffffffffffffffffffffffffff1661279d611c4c565b73ffffffffffffffffffffffffffffffffffffffff1614612826576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156128ac576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526026815260200180613ed86026913960400191505060405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff16600a60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a380600a60006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b600033905090565b600061298a82600261319290919063ffffffff16565b9050919050565b816004600083815260200190815260200160002060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550808273ffffffffffffffffffffffffffffffffffffffff16612a04836117f2565b73ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560405160405180910390a45050565b6000612a58826000016131ac565b9050919050565b6000612a6a82612974565b612abf576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602c815260200180613f48602c913960400191505060405180910390fd5b6000612aca836117f2565b90508073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff161480612b3957508373ffffffffffffffffffffffffffffffffffffffff16612b21846110e8565b73ffffffffffffffffffffffffffffffffffffffff16145b80612b4a5750612b498185612566565b5b91505092915050565b8273ffffffffffffffffffffffffffffffffffffffff16612b73826117f2565b73ffffffffffffffffffffffffffffffffffffffff1614612bdf576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260298152602001806140b76029913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415612c65576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526024815260200180613efe6024913960400191505060405180910390fd5b612c708383836131bd565b612c7b600082612991565b612ccc81600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206131c290919063ffffffff16565b50612d1e81600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206131dc90919063ffffffff16565b50612d35818360026131f69092919063ffffffff16565b50808273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60405160405180910390a4505050565b6000612da5836000018361322b565b60001c905092915050565b600080600080612dc386600001866132ae565b915091508160001c8160001c9350935050509250929050565b8060099080519060200190612df2929190613de6565b5050565b6000612e09846000018460001b84613347565b60001c90509392505050565b6000612e238260000161343d565b9050919050565b600080828401905083811015612ea8576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b600080831415612ec55760009050612f32565b6000828402905082848281612ed657fe5b0414612f2d576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602181526020018061406a6021913960400191505060405180910390fd5b809150505b92915050565b612f5282826040518060200160405280600081525061344e565b5050565b612f61848484612b53565b612f6d848484846134bf565b612fc2576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526032815260200180613ea66032913960400191505060405180910390fd5b50505050565b60606000821415613010576040518060400160405280600181526020017f3000000000000000000000000000000000000000000000000000000000000000815250905061310a565b600082905060005b6000821461303a578080600101915050600a828161303257fe5b049150613018565b60608167ffffffffffffffff8111801561305357600080fd5b506040519080825280601f01601f1916602001820160405280156130865781602001600182028036833780820191505090505b50905060006001830390508593505b6000841461310257600a84816130a757fe5b0660300160f81b828280600190039350815181106130c157fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600a84816130fa57fe5b049350613095565b819450505050505b919050565b600082821115613187576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601e8152602001807f536166654d6174683a207375627472616374696f6e206f766572666c6f77000081525060200191505060405180910390fd5b818303905092915050565b60006131a4836000018360001b6136d8565b905092915050565b600081600001805490509050919050565b505050565b60006131d4836000018360001b6136fb565b905092915050565b60006131ee836000018360001b6137e3565b905092915050565b6000613222846000018460001b8473ffffffffffffffffffffffffffffffffffffffff1660001b613853565b90509392505050565b60008183600001805490501161328c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180613e846022913960400191505060405180910390fd5b82600001828154811061329b57fe5b9060005260206000200154905092915050565b60008082846000018054905011613310576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806140206022913960400191505060405180910390fd5b600084600001848154811061332157fe5b906000526020600020906002020190508060000154816001015492509250509250929050565b6000808460010160008581526020019081526020016000205490506000811415839061340e576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b838110156133d35780820151818401526020810190506133b8565b50505050905090810190601f1680156134005780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5084600001600182038154811061342157fe5b9060005260206000209060020201600101549150509392505050565b600081600001805490509050919050565b613458838361392f565b61346560008484846134bf565b6134ba576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526032815260200180613ea66032913960400191505060405180910390fd5b505050565b60006134e08473ffffffffffffffffffffffffffffffffffffffff16613b23565b6134ed57600190506136d0565b606061365763150b7a0260e01b61350261296c565b888787604051602401808573ffffffffffffffffffffffffffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff16815260200183815260200180602001828103825283818151815260200191508051906020019080838360005b8381101561358657808201518184015260208101905061356b565b50505050905090810190601f1680156135b35780820380516001836020036101000a031916815260200191505b5095505050505050604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050604051806060016040528060328152602001613ea6603291398773ffffffffffffffffffffffffffffffffffffffff16613b369092919063ffffffff16565b9050600081806020019051602081101561367057600080fd5b8101908080519060200190929190505050905063150b7a0260e01b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916817bffffffffffffffffffffffffffffffffffffffffffffffffffffffff191614925050505b949350505050565b600080836001016000848152602001908152602001600020541415905092915050565b600080836001016000848152602001908152602001600020549050600081146137d7576000600182039050600060018660000180549050039050600086600001828154811061374657fe5b906000526020600020015490508087600001848154811061376357fe5b906000526020600020018190555060018301876001016000838152602001908152602001600020819055508660000180548061379b57fe5b600190038181906000526020600020016000905590558660010160008781526020019081526020016000206000905560019450505050506137dd565b60009150505b92915050565b60006137ef8383613b4e565b61384857826000018290806001815401808255809150506001900390600052602060002001600090919091909150558260000180549050836001016000848152602001908152602001600020819055506001905061384d565b600090505b92915050565b60008084600101600085815260200190815260200160002054905060008114156138fa57846000016040518060400160405280868152602001858152509080600181540180825580915050600190039060005260206000209060020201600090919091909150600082015181600001556020820151816001015550508460000180549050856001016000868152602001908152602001600020819055506001915050613928565b8285600001600183038154811061390d57fe5b90600052602060002090600202016001018190555060009150505b9392505050565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614156139d2576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4552433732313a206d696e7420746f20746865207a65726f206164647265737381525060200191505060405180910390fd5b6139db81612974565b15613a4e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601c8152602001807f4552433732313a20746f6b656e20616c7265616479206d696e7465640000000081525060200191505060405180910390fd5b613a5a600083836131bd565b613aab81600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206131dc90919063ffffffff16565b50613ac2818360026131f69092919063ffffffff16565b50808273ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60405160405180910390a45050565b600080823b905060008111915050919050565b6060613b458484600085613b71565b90509392505050565b600080836001016000848152602001908152602001600020541415905092915050565b606082471015613bcc576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526026815260200180613f226026913960400191505060405180910390fd5b613bd585613b23565b613c47576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000081525060200191505060405180910390fd5b600060608673ffffffffffffffffffffffffffffffffffffffff1685876040518082805190602001908083835b60208310613c975780518252602082019150602081019050602083039250613c74565b6001836020036101000a03801982511681845116808217855250505050505090500191505060006040518083038185875af1925050503d8060008114613cf9576040519150601f19603f3d011682016040523d82523d6000602084013e613cfe565b606091505b5091509150613d0e828286613d1a565b92505050949350505050565b60608315613d2a57829050613ddf565b600083511115613d3d5782518084602001fd5b816040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015613da4578082015181840152602081019050613d89565b50505050905090810190601f168015613dd15780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b9392505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10613e2757805160ff1916838001178555613e55565b82800160010185558215613e55579182015b82811115613e54578251825591602001919060010190613e39565b5b509050613e629190613e66565b5090565b5b80821115613e7f576000816000905550600101613e67565b509056fe456e756d657261626c655365743a20696e646578206f7574206f6620626f756e64734552433732313a207472616e7366657220746f206e6f6e20455243373231526563656976657220696d706c656d656e7465724f776e61626c653a206e6577206f776e657220697320746865207a65726f20616464726573734552433732313a207472616e7366657220746f20746865207a65726f2061646472657373416464726573733a20696e73756666696369656e742062616c616e636520666f722063616c6c4552433732313a206f70657261746f7220717565727920666f72206e6f6e6578697374656e7420746f6b656e43616e206f6e6c79206d696e7420323020746f6b656e7320617420612074696d654552433732313a20617070726f76652063616c6c6572206973206e6f74206f776e6572206e6f7220617070726f76656420666f7220616c6c4552433732313a2062616c616e636520717565727920666f7220746865207a65726f20616464726573734552433732313a206f776e657220717565727920666f72206e6f6e6578697374656e7420746f6b656e456e756d657261626c654d61703a20696e646578206f7574206f6620626f756e6473507572636861736520776f756c6420657863656564206d617820737570706c79206f662041706573536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f774552433732313a20617070726f76656420717565727920666f72206e6f6e6578697374656e7420746f6b656e4552433732313a207472616e73666572206f6620746f6b656e2074686174206973206e6f74206f776e4552433732314d657461646174613a2055524920717565727920666f72206e6f6e6578697374656e7420746f6b656e4552433732313a20617070726f76616c20746f2063757272656e74206f776e65724552433732313a207472616e736665722063616c6c6572206973206e6f74206f776e6572206e6f7220617070726f766564a2646970667358221220b0e64d1fa6c4dbeb9c6f54607d7e1996943fe27624a80652f57b53fda084621b64736f6c63430007000033000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000002710000000000000000000000000000000000000000000000000000000006080e6d70000000000000000000000000000000000000000000000000000000000000011426f7265644170655961636874436c756200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044241594300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000010f2c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000014426f72656420417065205761676d6920436c756200000000000000000000000000000000000000000000000000000000000000000000000000000000000000044241594300000000000000000000000000000000000000000000000000000000 Details: Insufficient funds for gas * price + value Version: viem@2.47.5] `) await disconnect(config, { connector }) }) ================================================ FILE: packages/core/src/actions/deployContract.ts ================================================ import type { Abi, Account, Chain, Client, ContractConstructorArgs } from 'viem' import { type DeployContractErrorType as viem_DeployContractErrorType, type DeployContractParameters as viem_DeployContractParameters, type DeployContractReturnType as viem_DeployContractReturnType, deployContract as viem_deployContract, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { BaseErrorType, ErrorType } from '../errors/base.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter, ConnectorParameter, } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' import { type GetConnectorClientErrorType, getConnectorClient, } from './getConnectorClient.js' export type DeployContractParameters< abi extends Abi | readonly unknown[] = Abi, config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], /// allArgs = ContractConstructorArgs, chains extends readonly Chain[] = SelectChains, > = { [key in keyof chains]: Compute< Omit< viem_DeployContractParameters< abi, chains[key], Account, chains[key], allArgs >, 'chain' > & ChainIdParameter & ConnectorParameter > }[number] export type DeployContractReturnType = viem_DeployContractReturnType export type DeployContractErrorType = // getConnectorClient() | GetConnectorClientErrorType // base | BaseErrorType | ErrorType // viem | viem_DeployContractErrorType /** https://wagmi.sh/core/api/actions/deployContract */ export async function deployContract< config extends Config, const abi extends Abi | readonly unknown[], chainId extends config['chains'][number]['id'], >( config: config, parameters: DeployContractParameters, ): Promise { const { account, chainId, connector, ...rest } = parameters let client: Client if (typeof account === 'object' && account?.type === 'local') client = config.getClient({ chainId }) else client = await getConnectorClient(config, { account: account ?? undefined, assertChainId: false, chainId, connector, }) const chain = (() => { if (!chainId || client.chain?.id === chainId) return client.chain return { id: chainId } })() const action = getAction(client, viem_deployContract, 'deployContract') const hash = await action({ ...(rest as any), ...(account ? { account } : {}), assertChainId: !!chainId, chain, }) return hash } ================================================ FILE: packages/core/src/actions/disconnect.test.ts ================================================ import { accounts, config } from '@wagmi/test' import { expect, test } from 'vitest' import { mock } from '../connectors/mock.js' import { connect } from './connect.js' import { disconnect } from './disconnect.js' const connector = config._internal.connectors.setup(mock({ accounts })) test('default', async () => { await connect(config, { connector }) expect(config.state.status).toEqual('connected') await disconnect(config) expect(config.state.status).toEqual('disconnected') }) test('parameters: connector', async () => { await connect(config, { connector }) expect(config.state.status).toEqual('connected') await disconnect(config, { connector }) expect(config.state.status).toEqual('disconnected') }) test('behavior: uses next connector on disconnect', async () => { const connector_ = config._internal.connectors.setup(mock({ accounts })) await connect(config, { connector: connector_ }) await connect(config, { connector }) expect(config.state.status).toEqual('connected') await disconnect(config, { connector }) expect(config.state.status).toEqual('connected') await disconnect(config, { connector: connector_ }) }) ================================================ FILE: packages/core/src/actions/disconnect.ts ================================================ import type { Config, Connection, Connector } from '../createConfig.js' import type { BaseErrorType, ErrorType } from '../errors/base.js' import type { ConnectorNotConnectedErrorType, ConnectorNotFoundErrorType, } from '../errors/config.js' import type { ConnectorParameter } from '../types/properties.js' export type DisconnectParameters = ConnectorParameter export type DisconnectReturnType = void export type DisconnectErrorType = | ConnectorNotFoundErrorType | ConnectorNotConnectedErrorType // base | BaseErrorType | ErrorType /** https://wagmi.sh/core/api/actions/disconnect */ export async function disconnect( config: Config, parameters: DisconnectParameters = {}, ): Promise { let connector: Connector | undefined if (parameters.connector) connector = parameters.connector else { const { connections, current } = config.state const connection = connections.get(current!) connector = connection?.connector } const connections = config.state.connections if (connector) { await connector.disconnect() connector.emitter.off('change', config._internal.events.change) connector.emitter.off('disconnect', config._internal.events.disconnect) connector.emitter.on('connect', config._internal.events.connect) connections.delete(connector.uid) } config.setState((x) => { // if no connections exist, move to disconnected state if (connections.size === 0) return { ...x, connections: new Map(), current: null, status: 'disconnected', } // switch over to another connection const nextConnection = connections.values().next().value as Connection return { ...x, connections: new Map(connections), current: nextConnection.connector.uid, } }) // Set recent connector if exists { const current = config.state.current if (!current) return const connector = config.state.connections.get(current)?.connector if (!connector) return await config.storage?.setItem('recentConnectorId', connector.id) } } ================================================ FILE: packages/core/src/actions/estimateFeesPerGas.test-d.ts ================================================ import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { estimateFeesPerGas } from './estimateFeesPerGas.js' test('types', async () => { // default { const result = await estimateFeesPerGas(config, {}) expectTypeOf(result).toEqualTypeOf<{ gasPrice?: undefined maxFeePerBlobGas?: undefined maxFeePerGas: bigint maxPriorityFeePerGas: bigint }>() } // legacy { const result = await estimateFeesPerGas(config, { type: 'legacy' }) expectTypeOf(result).toEqualTypeOf<{ gasPrice: bigint maxFeePerBlobGas?: undefined maxFeePerGas?: undefined maxPriorityFeePerGas?: undefined }>() } // eip1559 { const result = await estimateFeesPerGas(config, { type: 'eip1559' }) expectTypeOf(result).toEqualTypeOf<{ gasPrice?: undefined maxFeePerBlobGas?: undefined maxFeePerGas: bigint maxPriorityFeePerGas: bigint }>() } }) ================================================ FILE: packages/core/src/actions/estimateFeesPerGas.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { estimateFeesPerGas } from './estimateFeesPerGas.js' test('default', async () => { const result = await estimateFeesPerGas(config) expect(Object.keys(result)).toMatchInlineSnapshot(` [ "gasPrice", "maxFeePerGas", "maxPriorityFeePerGas", ] `) }) ================================================ FILE: packages/core/src/actions/estimateFeesPerGas.ts ================================================ import type { Chain, FeeValuesType } from 'viem' import { type EstimateFeesPerGasErrorType as viem_EstimateFeesPerGasErrorType, type EstimateFeesPerGasParameters as viem_EstimateFeesPerGasParameters, type EstimateFeesPerGasReturnType as viem_EstimateFeesPerGasReturnType, estimateFeesPerGas as viem_estimateFeesPerGas, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute, UnionCompute, UnionLooseOmit } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type EstimateFeesPerGasParameters< type extends FeeValuesType = FeeValuesType, config extends Config = Config, > = UnionCompute< UnionLooseOmit< viem_EstimateFeesPerGasParameters, 'chain' > & ChainIdParameter > export type EstimateFeesPerGasReturnType< type extends FeeValuesType = FeeValuesType, > = Compute> export type EstimateFeesPerGasErrorType = viem_EstimateFeesPerGasErrorType export async function estimateFeesPerGas< config extends Config, type extends FeeValuesType = 'eip1559', >( config: config, parameters: EstimateFeesPerGasParameters = {}, ): Promise> { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction( client, viem_estimateFeesPerGas, 'estimateFeesPerGas', ) const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = await action({ ...rest, chain: client.chain, }) return { gasPrice, maxFeePerGas, maxPriorityFeePerGas, } as EstimateFeesPerGasReturnType } ================================================ FILE: packages/core/src/actions/estimateGas.test-d.ts ================================================ import { http, parseEther } from 'viem' import { celo, mainnet } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { type EstimateGasParameters, estimateGas } from './estimateGas.js' test('chain formatters', () => { const config = createConfig({ chains: [mainnet, celo], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) type Result = EstimateGasParameters expectTypeOf().toMatchTypeOf<{ chainId?: typeof celo.id | typeof mainnet.id | undefined feeCurrency?: `0x${string}` | undefined }>() estimateGas(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), feeCurrency: '0x', }) type Result2 = EstimateGasParameters expectTypeOf().toMatchTypeOf<{ feeCurrency?: `0x${string}` | undefined }>() estimateGas(config, { chainId: celo.id, to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), feeCurrency: '0x', }) type Result3 = EstimateGasParameters expectTypeOf().not.toMatchTypeOf<{ feeCurrency?: `0x${string}` | undefined }>() estimateGas(config, { chainId: mainnet.id, to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), // @ts-expect-error feeCurrency: '0x', }) }) ================================================ FILE: packages/core/src/actions/estimateGas.test.ts ================================================ import { accounts, config } from '@wagmi/test' import { parseEther } from 'viem' import { expect, test } from 'vitest' import { mock } from '../connectors/mock.js' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { estimateGas } from './estimateGas.js' const connector = config._internal.connectors.setup(mock({ accounts })) test('parameters: account', async () => { await expect( estimateGas(config, { account: accounts[0], to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }), ).resolves.toMatchInlineSnapshot('21000n') }) test('parameters: connector', async () => { await connect(config, { connector }) await expect( estimateGas(config, { connector, to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }), ).resolves.toMatchInlineSnapshot('21000n') await disconnect(config, { connector }) }) test('behavior: no account and not connected', async () => { await expect( estimateGas(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ConnectorNotConnectedError: Connector not connected. Version: @wagmi/core@x.y.z] `) }) ================================================ FILE: packages/core/src/actions/estimateGas.ts ================================================ import type { Account, Address, Chain } from 'viem' import { type EstimateGasErrorType as viem_EstimateGasErrorType, type EstimateGasParameters as viem_EstimateGasParameters, type EstimateGasReturnType as viem_EstimateGasReturnType, estimateGas as viem_estimateGas, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { BaseErrorType, ErrorType } from '../errors/base.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter, ConnectorParameter, } from '../types/properties.js' import type { UnionCompute, UnionLooseOmit } from '../types/utils.js' import { getAction } from '../utils/getAction.js' import { type GetConnectorClientErrorType, getConnectorClient, } from './getConnectorClient.js' export type EstimateGasParameters< config extends Config = Config, chainId extends | config['chains'][number]['id'] | undefined = config['chains'][number]['id'], /// chains extends readonly Chain[] = SelectChains, > = { [key in keyof chains]: UnionCompute< UnionLooseOmit, 'chain'> & ChainIdParameter & ConnectorParameter > }[number] export type EstimateGasReturnType = viem_EstimateGasReturnType export type EstimateGasErrorType = // getConnectorClient() | GetConnectorClientErrorType // base | BaseErrorType | ErrorType // viem | viem_EstimateGasErrorType /** https://wagmi.sh/core/api/actions/estimateGas */ export async function estimateGas< config extends Config, chainId extends config['chains'][number]['id'] | undefined = undefined, >( config: config, parameters: EstimateGasParameters, ): Promise { const { chainId, connector, ...rest } = parameters let account: Address | Account if (parameters.account) account = parameters.account else { const connectorClient = await getConnectorClient(config, { account: parameters.account, assertChainId: false, chainId, connector, }) account = connectorClient.account } const client = config.getClient({ chainId }) const action = getAction(client, viem_estimateGas, 'estimateGas') return action({ ...(rest as viem_EstimateGasParameters), account }) } ================================================ FILE: packages/core/src/actions/estimateMaxPriorityFeePerGas.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { estimateMaxPriorityFeePerGas } from './estimateMaxPriorityFeePerGas.js' test('default', async () => { await expect(estimateMaxPriorityFeePerGas(config)).resolves.toBeDefined() }) test('parameters: chainId', async () => { await expect( estimateMaxPriorityFeePerGas(config, { chainId: chain.mainnet2.id, }), ).resolves.toBeDefined() }) ================================================ FILE: packages/core/src/actions/estimateMaxPriorityFeePerGas.ts ================================================ import type { Chain } from 'viem' import { type EstimateMaxPriorityFeePerGasErrorType as viem_EstimateMaxPriorityFeePerGasErrorType, type EstimateMaxPriorityFeePerGasParameters as viem_EstimateMaxPriorityFeePerGasParameters, type EstimateMaxPriorityFeePerGasReturnType as viem_EstimateMaxPriorityFeePerGasReturnType, estimateMaxPriorityFeePerGas as viem_estimateMaxPriorityFeePerGas, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute, UnionLooseOmit } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type EstimateMaxPriorityFeePerGasParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = Compute< UnionLooseOmit< viem_EstimateMaxPriorityFeePerGasParameters & ChainIdParameter, 'chain' > > export type EstimateMaxPriorityFeePerGasReturnType = viem_EstimateMaxPriorityFeePerGasReturnType export type EstimateMaxPriorityFeePerGasErrorType = viem_EstimateMaxPriorityFeePerGasErrorType /** https://wagmi.sh/core/api/actions/estimateMaxPriorityFeePerGas */ export async function estimateMaxPriorityFeePerGas< config extends Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], >( config: config, parameters: EstimateMaxPriorityFeePerGasParameters = {}, ): Promise { const { chainId } = parameters const client = config.getClient({ chainId }) const action = getAction( client, viem_estimateMaxPriorityFeePerGas, 'estimateMaxPriorityFeePerGas', ) return action({ chain: client.chain }) } ================================================ FILE: packages/core/src/actions/getBalance.test.ts ================================================ import { accounts, chain, config, testClient } from '@wagmi/test' import { parseEther } from 'viem' import { beforeEach, expect, test } from 'vitest' import { getBalance } from './getBalance.js' const address = accounts[0] beforeEach(async () => { await testClient.mainnet.setBalance({ address, value: parseEther('10000'), }) await testClient.mainnet.mine({ blocks: 1 }) await testClient.mainnet2.setBalance({ address, value: parseEther('420'), }) await testClient.mainnet2.mine({ blocks: 1 }) }) test('default', async () => { await expect(getBalance(config, { address })).resolves.toMatchInlineSnapshot(` { "decimals": 18, "symbol": "ETH", "value": 10000000000000000000000n, } `) await testClient.mainnet.setBalance({ address, value: parseEther('6969.12222215666'), }) await expect(getBalance(config, { address })).resolves.toMatchInlineSnapshot(` { "decimals": 18, "symbol": "ETH", "value": 6969122222156660000000n, } `) }) test('parameters: chainId', async () => { await expect( getBalance(config, { address, chainId: chain.mainnet2.id }), ).resolves.toMatchInlineSnapshot(` { "decimals": 18, "symbol": "WAG", "value": 420000000000000000000n, } `) }) ================================================ FILE: packages/core/src/actions/getBalance.ts ================================================ import { type GetBalanceErrorType as viem_GetBalanceErrorType, type GetBalanceParameters as viem_GetBalanceParameters, getBalance as viem_getBalance, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetBalanceParameters = Compute< ChainIdParameter & viem_GetBalanceParameters > export type GetBalanceReturnType = { decimals: number symbol: string value: bigint } export type GetBalanceErrorType = viem_GetBalanceErrorType /** https://wagmi.sh/core/api/actions/getBalance */ export async function getBalance( config: config, parameters: GetBalanceParameters, ): Promise { const { address, blockNumber, blockTag, chainId } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_getBalance, 'getBalance') const value = await action( blockNumber ? { address, blockNumber } : { address, blockTag }, ) const chain = config.chains.find((x) => x.id === chainId) ?? client.chain! return { decimals: chain.nativeCurrency.decimals, symbol: chain.nativeCurrency.symbol, value, } } ================================================ FILE: packages/core/src/actions/getBlobBaseFee.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { getBlobBaseFee } from './getBlobBaseFee.js' test('default', async () => { await expect(getBlobBaseFee(config)).resolves.toBeTypeOf('bigint') }) test('parameters: chainId', async () => { await expect( getBlobBaseFee(config, { chainId: config.chains[0].id }), ).resolves.toBeTypeOf('bigint') }) ================================================ FILE: packages/core/src/actions/getBlobBaseFee.ts ================================================ import { type GetBlobBaseFeeErrorType as viem_GetBlobBaseFeeErrorType, type GetBlobBaseFeeReturnType as viem_GetBlobBaseFeeReturnType, getBlobBaseFee as viem_getBlobBaseFee, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetBlobBaseFeeParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = Compute> export type GetBlobBaseFeeReturnType = viem_GetBlobBaseFeeReturnType export type GetBlobBaseFeeErrorType = viem_GetBlobBaseFeeErrorType /** https://wagmi.sh/core/api/actions/getBlobBaseFee */ export function getBlobBaseFee< config extends Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], >( config: config, parameters: GetBlobBaseFeeParameters = {}, ): Promise { const { chainId } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_getBlobBaseFee, 'getBlobBaseFee') return action({}) } ================================================ FILE: packages/core/src/actions/getBlock.test-d.ts ================================================ import { type Hex, http } from 'viem' import { celo, mainnet } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { getBlock } from './getBlock.js' test('chain formatters', async () => { const config = createConfig({ chains: [celo, mainnet], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) const result = await getBlock(config) if (result.chainId === celo.id) { expectTypeOf(result.difficulty).toEqualTypeOf() expectTypeOf(result.gasLimit).toEqualTypeOf() expectTypeOf(result.mixHash).toEqualTypeOf() expectTypeOf(result.nonce).toEqualTypeOf<`0x${string}`>() expectTypeOf(result.uncles).toEqualTypeOf() } }) test('chainId', async () => { const config = createConfig({ chains: [celo, mainnet], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) const result = await getBlock(config, { chainId: celo.id, }) expectTypeOf(result.difficulty).toEqualTypeOf() expectTypeOf(result.gasLimit).toEqualTypeOf() expectTypeOf(result.mixHash).toEqualTypeOf() expectTypeOf(result.nonce).toEqualTypeOf<`0x${string}`>() }) ================================================ FILE: packages/core/src/actions/getBlock.test.ts ================================================ import { config, mainnet } from '@wagmi/test' import { expect, test } from 'vitest' import { getBlock } from './getBlock.js' test('default', async () => { await expect(getBlock(config)).resolves.toBeDefined() }) test('args: blockNumber', async () => { const { transactions, ...block } = await getBlock(config, { blockNumber: mainnet.fork.blockNumber, }) expect(transactions).toMatchObject( expect.arrayContaining([expect.any(String)]), ) expect(block).toMatchInlineSnapshot(` { "baseFeePerGas": 194923488n, "blobGasUsed": 786432n, "chainId": 1, "difficulty": 0n, "excessBlobGas": 0n, "extraData": "0x546974616e2028746974616e6275696c6465722e78797a29", "gasLimit": 45000000n, "gasUsed": 30531630n, "hash": "0xe38d4bb2060a54519508612f40ef737a09c5b20488c12b0bec2d4f5ea7073c15", "logsBloom": "0x3effc77fb16497fa74fffeb6ef65dfbd7b97f8dd7f198ff37abfcf5fdeb329e7bdbc9d8caffdf765f7b75df9e737eff773fbf639ff9ffb376fb726a7ff2f68dffea0de7fafd3f7fbff8d5fdff57becf3e76f3f73fefc1ff9bbf9df7fb3fffff13f577b7fdffeb7f7ffb8cd71ff93fff3bfffd7e3bfbe576daefdfff6fb5afedf8ffbbd7d7baf977f46fbffceebfbe86fc6ffb6f1eff3fbbfbeb9eefbf954ffe3fbff9d73b8f9ecfdcfdf7df3fdd9ff3bbfdfe9efe8ffee6ff7fe4a3ff7a5fefbfffffcffcd7f2bc04bdf7c52d3fdfeff3f7dfe7b4fefa9f46edb53c2de9ffb7f3ffdff6fefa67f64f6e7f7bff5af1dffffeff9b99ff86fef589e3bbfffdfffb7", "miner": "0x4838b106fce9647bdf1e7877bf73ce8b0bad5f97", "mixHash": "0x15350a0cad9bc5cb1298b3710db038850f1df5d8ac00c4ca3b03fb64c7e8ab78", "nonce": "0x0000000000000000", "number": 23535880n, "parentBeaconBlockRoot": "0x2bd55d2f0e1a3d3e181659ebc21bb167527e517de88b39b0d7ebbeeb3e28eebc", "parentHash": "0x1fab238a9630a2e95c8b735ebc63bc2751bc6492f409ee16a7b5a532985196eb", "receiptsRoot": "0x01d0a60dd8fd8de710a191aba91f82e2a437ac21a6e77b21b2f745809e7feadf", "requestsHash": "0x965c860907968cab126093a785436ad747495ae45b21dac1b6a92ae0f4866ce0", "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", "size": 155442n, "stateRoot": "0xd3c86549e5d57f14bd0b28630b70cb68038ac3334251bd194c93a18d96492f39", "timestamp": 1759960991n, "totalDifficulty": null, "transactionsRoot": "0x9da0226f723a9da4b8df8782930c0e83bd73c4a393069ee7861465188eed989b", "uncles": [], "withdrawals": [ { "address": "0xb9d7934878b5fb9610b3fe8a5e441e8fad7e293f", "amount": "0x11a6bd6", "index": "0x633236b", "validatorIndex": "0xb8688", }, { "address": "0xb9d7934878b5fb9610b3fe8a5e441e8fad7e293f", "amount": "0x119ebba", "index": "0x633236c", "validatorIndex": "0xb8689", }, { "address": "0xb9d7934878b5fb9610b3fe8a5e441e8fad7e293f", "amount": "0x11a167c", "index": "0x633236d", "validatorIndex": "0xb868a", }, { "address": "0xb9d7934878b5fb9610b3fe8a5e441e8fad7e293f", "amount": "0x11a2017", "index": "0x633236e", "validatorIndex": "0xb868b", }, { "address": "0xb9d7934878b5fb9610b3fe8a5e441e8fad7e293f", "amount": "0x11a5b81", "index": "0x633236f", "validatorIndex": "0xb868c", }, { "address": "0xb9d7934878b5fb9610b3fe8a5e441e8fad7e293f", "amount": "0x11a4908", "index": "0x6332370", "validatorIndex": "0xb868d", }, { "address": "0xb9d7934878b5fb9610b3fe8a5e441e8fad7e293f", "amount": "0x11a74ca", "index": "0x6332371", "validatorIndex": "0xb868e", }, { "address": "0xb9d7934878b5fb9610b3fe8a5e441e8fad7e293f", "amount": "0x11a5a90", "index": "0x6332372", "validatorIndex": "0xb868f", }, { "address": "0xb9d7934878b5fb9610b3fe8a5e441e8fad7e293f", "amount": "0x11a512b", "index": "0x6332373", "validatorIndex": "0xb8690", }, { "address": "0xb9d7934878b5fb9610b3fe8a5e441e8fad7e293f", "amount": "0x11a0ba7", "index": "0x6332374", "validatorIndex": "0xb8691", }, { "address": "0xb9d7934878b5fb9610b3fe8a5e441e8fad7e293f", "amount": "0x11a313b", "index": "0x6332375", "validatorIndex": "0xb8692", }, { "address": "0xb9d7934878b5fb9610b3fe8a5e441e8fad7e293f", "amount": "0x3e72765", "index": "0x6332376", "validatorIndex": "0xb8693", }, { "address": "0xb9d7934878b5fb9610b3fe8a5e441e8fad7e293f", "amount": "0x119c821", "index": "0x6332377", "validatorIndex": "0xb8694", }, { "address": "0xb9d7934878b5fb9610b3fe8a5e441e8fad7e293f", "amount": "0x119e921", "index": "0x6332378", "validatorIndex": "0xb8695", }, { "address": "0xb9d7934878b5fb9610b3fe8a5e441e8fad7e293f", "amount": "0x119f302", "index": "0x6332379", "validatorIndex": "0xb8696", }, { "address": "0xb9d7934878b5fb9610b3fe8a5e441e8fad7e293f", "amount": "0x11a38a8", "index": "0x633237a", "validatorIndex": "0xb8697", }, ], "withdrawalsRoot": "0x0740ba007069960b2d60f77b0ce2648cffa3573accd055d4803eb771e32903e7", } `) }) test('args: includeTransactions', async () => { const { transactions } = await getBlock(config, { includeTransactions: true, blockNumber: mainnet.fork.blockNumber, }) expect(transactions).toMatchObject( expect.arrayContaining([expect.any(Object)]), ) }) ================================================ FILE: packages/core/src/actions/getBlock.ts ================================================ import type { BlockTag, Chain } from 'viem' import { type GetBlockErrorType as viem_GetBlockErrorType, type GetBlockParameters as viem_GetBlockParameters, type GetBlockReturnType as viem_GetBlockReturnType, getBlock as viem_getBlock, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute, IsNarrowable } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetBlockParameters< includeTransactions extends boolean = false, blockTag extends BlockTag = 'latest', config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = Compute< viem_GetBlockParameters & ChainIdParameter > export type GetBlockReturnType< includeTransactions extends boolean = false, blockTag extends BlockTag = 'latest', config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], /// chains extends readonly Chain[] = SelectChains, > = Compute< { [key in keyof chains]: viem_GetBlockReturnType< IsNarrowable extends true ? chains[key] : undefined, includeTransactions, blockTag > & { chainId: chains[key]['id'] } }[number] > export type GetBlockErrorType = viem_GetBlockErrorType /** https://wagmi.sh/core/actions/getBlock */ export async function getBlock< config extends Config, chainId extends config['chains'][number]['id'], includeTransactions extends boolean = false, blockTag extends BlockTag = 'latest', >( config: config, parameters: GetBlockParameters< includeTransactions, blockTag, config, chainId > = {}, ): Promise> { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_getBlock, 'getBlock') const block = await action(rest) return { ...(block as unknown as GetBlockReturnType< includeTransactions, blockTag, config, chainId >), chainId: client.chain.id, } } ================================================ FILE: packages/core/src/actions/getBlockNumber.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { getBlockNumber } from './getBlockNumber.js' test('default', async () => { await expect(getBlockNumber(config)).resolves.toBeDefined() }) ================================================ FILE: packages/core/src/actions/getBlockNumber.ts ================================================ import { type GetBlockNumberErrorType as viem_GetBlockNumberErrorType, type GetBlockNumberParameters as viem_GetBlockNumberParameters, type GetBlockNumberReturnType as viem_GetBlockNumberReturnType, getBlockNumber as viem_getBlockNumber, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetBlockNumberParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = Compute> export type GetBlockNumberReturnType = viem_GetBlockNumberReturnType export type GetBlockNumberErrorType = viem_GetBlockNumberErrorType /** https://wagmi.sh/core/api/actions/getBlockNumber */ export function getBlockNumber< config extends Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], >( config: config, parameters: GetBlockNumberParameters = {}, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_getBlockNumber, 'getBlockNumber') return action(rest) } ================================================ FILE: packages/core/src/actions/getBlockTransactionCount.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getBlockTransactionCount } from './getBlockTransactionCount.js' test('default', async () => { await expect(getBlockTransactionCount(config)).resolves.toBeTypeOf('number') }) test('parameters: chainId', async () => { await expect( getBlockTransactionCount(config, { chainId: chain.mainnet2.id }), ).resolves.toBeTypeOf('number') }) test('parameters: blockNumber', async () => { await expect( getBlockTransactionCount(config, { blockNumber: 13677382n }), ).resolves.toBeTypeOf('number') }) test('parameters: blockHash', async () => { await expect( getBlockTransactionCount(config, { blockHash: '0x6201f37a245850d1f11e4be3ac45bc51bd9d43ee4a127192cad550f351cfa575', }), ).resolves.toBeTypeOf('number') }) test('parameters: blockTag', async () => { await expect( getBlockTransactionCount(config, { blockTag: 'earliest', }), ).resolves.toBeTypeOf('number') await expect( getBlockTransactionCount(config, { blockTag: 'finalized', }), ).resolves.toBeTypeOf('number') await expect( getBlockTransactionCount(config, { blockTag: 'latest', }), ).resolves.toBeTypeOf('number') await expect( getBlockTransactionCount(config, { blockTag: 'pending', }), ).resolves.toBeTypeOf('number') await expect( getBlockTransactionCount(config, { blockTag: 'safe', }), ).resolves.toBeTypeOf('number') }) ================================================ FILE: packages/core/src/actions/getBlockTransactionCount.ts ================================================ import { type GetBlockTransactionCountErrorType as viem_GetBlockTransactionCountErrorType, type GetBlockTransactionCountParameters as viem_GetBlockTransactionCountParameters, type GetBlockTransactionCountReturnType as viem_GetBlockTransactionCountReturnType, getBlockTransactionCount as viem_getBlockTransactionCount, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { UnionCompute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetBlockTransactionCountParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = UnionCompute< viem_GetBlockTransactionCountParameters & ChainIdParameter > export type GetBlockTransactionCountReturnType = viem_GetBlockTransactionCountReturnType export type GetBlockTransactionCountErrorType = viem_GetBlockTransactionCountErrorType /** https://wagmi.sh/core/api/actions/getBlockTransactionCount */ export function getBlockTransactionCount< config extends Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], >( config: config, parameters: GetBlockTransactionCountParameters = {}, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction( client, viem_getBlockTransactionCount, 'getBlockTransactionCount', ) return action(rest) } ================================================ FILE: packages/core/src/actions/getBytecode.test.ts ================================================ import { address, chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getBytecode } from './getBytecode.js' test('default', async () => { await expect( getBytecode(config, { address: '0x0000000000000000000000000000000000000000', }), ).resolves.toBe(undefined) await expect( getBytecode(config, { address: address.wagmiMintExample, }), ).resolves.toMatch(/^0x.*/) }) test('parameters: blockNumber', async () => { await expect( getBytecode(config, { address: address.wagmiMintExample, blockNumber: 15564163n, }), ).resolves.toBe(undefined) }) test('parameters: blockTag', async () => { await expect( getBytecode(config, { address: address.wagmiMintExample, blockTag: 'earliest', }), ).resolves.toBe(undefined) }) test('parameters: chainId', async () => { await expect( getBytecode(config, { address: address.wagmiMintExample, chainId: chain.optimism.id, }), ).resolves.toBe(undefined) }) ================================================ FILE: packages/core/src/actions/getBytecode.ts ================================================ import { type GetBytecodeErrorType as viem_GetBytecodeErrorType, type GetBytecodeParameters as viem_GetBytecodeParameters, type GetBytecodeReturnType as viem_GetBytecodeReturnType, getBytecode as viem_getBytecode, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetBytecodeParameters = Compute< viem_GetBytecodeParameters & ChainIdParameter > export type GetBytecodeReturnType = viem_GetBytecodeReturnType export type GetBytecodeErrorType = viem_GetBytecodeErrorType /** https://wagmi.sh/core/api/actions/getBytecode */ export async function getBytecode( config: config, parameters: GetBytecodeParameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_getBytecode, 'getBytecode') return action(rest) } ================================================ FILE: packages/core/src/actions/getCallsStatus.test.ts ================================================ import { accounts, config, testClient } from '@wagmi/test' import { parseEther } from 'viem' import { expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { getCallsStatus } from './getCallsStatus.js' import { sendCalls } from './sendCalls.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const { id } = await sendCalls(config, { calls: [ { data: '0xdeadbeef', to: accounts[1], value: parseEther('1'), }, { to: accounts[2], value: parseEther('2'), }, { to: accounts[3], value: parseEther('3'), }, ], }) await testClient.mainnet.mine({ blocks: 1 }) const { receipts, status } = await getCallsStatus(config, { id, }) expect(status).toBe('success') expect( receipts?.map((x) => ({ ...x, blockHash: undefined, transactionHash: undefined, })), ).toMatchInlineSnapshot( ` [ { "blockHash": undefined, "blockNumber": 23535881n, "gasUsed": 21160n, "logs": [], "status": "success", "transactionHash": undefined, }, { "blockHash": undefined, "blockNumber": 23535881n, "gasUsed": 21000n, "logs": [], "status": "success", "transactionHash": undefined, }, { "blockHash": undefined, "blockNumber": 23535881n, "gasUsed": 21000n, "logs": [], "status": "success", "transactionHash": undefined, }, ] `, ) await disconnect(config, { connector }) }) ================================================ FILE: packages/core/src/actions/getCallsStatus.ts ================================================ import { type GetCallsStatusErrorType as viem_GetCallsStatusErrorType, type GetCallsStatusParameters as viem_GetCallsStatusParameters, type GetCallsStatusReturnType as viem_GetCallsStatusReturnType, getCallsStatus as viem_getCallsStatus, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ConnectorParameter } from '../types/properties.js' import { getAction } from '../utils/getAction.js' import { getConnectorClient } from './getConnectorClient.js' export type GetCallsStatusParameters = viem_GetCallsStatusParameters & ConnectorParameter export type GetCallsStatusReturnType = viem_GetCallsStatusReturnType export type GetCallsStatusErrorType = viem_GetCallsStatusErrorType /** https://wagmi.sh/core/api/actions/getCallsStatus */ export async function getCallsStatus( config: config, parameters: GetCallsStatusParameters, ): Promise { const { connector, id } = parameters const client = await getConnectorClient(config, { connector }) const action = getAction(client, viem_getCallsStatus, 'getCallsStatus') return action({ id }) } ================================================ FILE: packages/core/src/actions/getCapabilities.test.ts ================================================ import { accounts, config } from '@wagmi/test' import { expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { getCapabilities } from './getCapabilities.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const capabilities = await getCapabilities(config) expect(capabilities).toMatchInlineSnapshot(` { "8453": { "paymasterService": { "supported": true, }, "sessionKeys": { "supported": true, }, }, "84532": { "paymasterService": { "supported": true, }, }, } `) await disconnect(config, { connector }) }) test('args: account', async () => { await connect(config, { connector }) const capabilities = await getCapabilities(config, { account: accounts[1], }) expect(capabilities).toMatchInlineSnapshot(` { "8453": { "paymasterService": { "supported": false, }, "sessionKeys": { "supported": true, }, }, "84532": { "paymasterService": { "supported": false, }, }, } `) await disconnect(config, { connector }) }) test('behavior: not connected', async () => { await expect(getCapabilities(config)).rejects.toMatchInlineSnapshot(` [ConnectorNotConnectedError: Connector not connected. Version: @wagmi/core@x.y.z] `) }) ================================================ FILE: packages/core/src/actions/getCapabilities.ts ================================================ import type { Account } from 'viem' import { type GetCapabilitiesErrorType as viem_GetCapabilitiesErrorType, type GetCapabilitiesParameters as viem_GetCapabilitiesParameters, type GetCapabilitiesReturnType as viem_GetCapabilitiesReturnType, getCapabilities as viem_getCapabilities, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ConnectorParameter } from '../types/properties.js' import { getConnectorClient } from './getConnectorClient.js' export type GetCapabilitiesParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] | undefined = undefined, > = viem_GetCapabilitiesParameters & ConnectorParameter export type GetCapabilitiesReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] | undefined = undefined, > = viem_GetCapabilitiesReturnType export type GetCapabilitiesErrorType = viem_GetCapabilitiesErrorType /** https://wagmi.sh/core/api/actions/getCapabilities */ export async function getCapabilities< config extends Config, chainId extends config['chains'][number]['id'] | undefined = undefined, >( config: config, parameters: GetCapabilitiesParameters = {}, ): Promise> { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, connector }) return viem_getCapabilities(client as any, { account: account as Account, chainId, }) } ================================================ FILE: packages/core/src/actions/getChainId.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getChainId } from './getChainId.js' test('default', async () => { expect(getChainId(config)).toEqual(chain.mainnet.id) config.setState((x) => ({ ...x, chainId: chain.mainnet2.id })) expect(getChainId(config)).toEqual(chain.mainnet2.id) }) ================================================ FILE: packages/core/src/actions/getChainId.ts ================================================ import type { Config } from '../createConfig.js' export type GetChainIdReturnType = config['chains'][number]['id'] /** https://wagmi.sh/core/api/actions/getChainId */ export function getChainId( config: config, ): GetChainIdReturnType { return config.state.chainId } ================================================ FILE: packages/core/src/actions/getChains.test-d.ts ================================================ import { type chain, config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { getChains } from './getChains.js' test('default', async () => { const chains = getChains(config) expectTypeOf(chains[0]).toEqualTypeOf() expectTypeOf(chains[2]).toEqualTypeOf() }) ================================================ FILE: packages/core/src/actions/getChains.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getChains } from './getChains.js' test('default', async () => { expect(getChains(config)).toEqual([ chain.mainnet, chain.mainnet2, chain.optimism, ]) config._internal.chains.setState([chain.mainnet, chain.mainnet2]) expect(getChains(config)).toEqual([chain.mainnet, chain.mainnet2]) }) ================================================ FILE: packages/core/src/actions/getChains.ts ================================================ import type { Chain } from 'viem' import type { Config } from '../createConfig.js' import { deepEqual } from '../utils/deepEqual.js' export type GetChainsReturnType = config['chains'] let previousChains: readonly Chain[] = [] /** https://wagmi.sh/core/api/actions/getChains */ export function getChains( config: config, ): GetChainsReturnType { const chains = config.chains if (deepEqual(previousChains, chains)) return previousChains as GetChainsReturnType previousChains = chains return chains as unknown as GetChainsReturnType } ================================================ FILE: packages/core/src/actions/getClient.test-d.ts ================================================ import { chain, config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { getClient } from './getClient.js' test('default', () => { const client = getClient(config) expectTypeOf(client.chain).toEqualTypeOf<(typeof config)['chains'][number]>() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) test('parameters: chainId', () => { const client = getClient(config, { chainId: chain.mainnet.id, }) expectTypeOf(client.chain).toEqualTypeOf() expectTypeOf(client.chain).not.toEqualTypeOf() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) test('behavior: unconfigured chain', () => { const client = getClient(config, { // @ts-expect-error chainId: 123456, }) expectTypeOf(client).toEqualTypeOf() }) ================================================ FILE: packages/core/src/actions/getClient.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { getClient } from './getClient.js' test('default', () => { expect(getClient(config)).toBeDefined() }) test('behavior: unconfigured chain', () => { expect( getClient(config, { // @ts-expect-error chainId: 123456, }), ).toBeUndefined() }) ================================================ FILE: packages/core/src/actions/getClient.ts ================================================ import type { Client } from 'viem' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute, IsNarrowable } from '../types/utils.js' export type GetClientParameters< config extends Config = Config, chainId extends | config['chains'][number]['id'] | number | undefined = config['chains'][number]['id'], > = ChainIdParameter export type GetClientReturnType< config extends Config = Config, chainId extends | config['chains'][number]['id'] | undefined = config['chains'][number]['id'], /// resolvedChainId extends | config['chains'][number]['id'] | undefined = IsNarrowable< config['chains'][number]['id'], number > extends true ? IsNarrowable extends true ? chainId : config['chains'][number]['id'] : config['chains'][number]['id'] | undefined, > = resolvedChainId extends config['chains'][number]['id'] ? Compute< Client< config['_internal']['transports'][resolvedChainId], Extract > > : undefined export function getClient< config extends Config, chainId extends config['chains'][number]['id'] | number | undefined, >( config: config, parameters: GetClientParameters = {}, ): GetClientReturnType { try { return config.getClient(parameters) as GetClientReturnType } catch { return undefined as never } } ================================================ FILE: packages/core/src/actions/getConnection.test-d.ts ================================================ import { config } from '@wagmi/test' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' import type { Connector } from '../createConfig.js' import { getConnection } from './getConnection.js' test('states', () => { const result = getConnection(config) switch (result.status) { case 'reconnecting': { expectTypeOf(result).toMatchTypeOf<{ address: Address | undefined chain: (typeof config)['chains'][number] | undefined chainId: number | undefined connector: Connector | undefined isConnected: boolean isConnecting: false isDisconnected: false isReconnecting: true status: 'reconnecting' }>() break } case 'connecting': { expectTypeOf(result).toMatchTypeOf<{ address: Address | undefined chain: (typeof config)['chains'][number] | undefined chainId: number | undefined connector: Connector | undefined isConnected: false isReconnecting: false isConnecting: true isDisconnected: false status: 'connecting' }>() break } case 'connected': { expectTypeOf(result).toMatchTypeOf<{ address: Address chain: (typeof config)['chains'][number] | undefined chainId: number connector: Connector isConnected: true isConnecting: false isDisconnected: false isReconnecting: false status: 'connected' }>() break } case 'disconnected': { expectTypeOf(result).toMatchTypeOf<{ address: undefined chain: undefined chainId: undefined connector: undefined isConnected: false isReconnecting: false isConnecting: false isDisconnected: true status: 'disconnected' }>() break } } }) ================================================ FILE: packages/core/src/actions/getConnection.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { getConnection } from './getConnection.js' test('default', () => { expect(getConnection(config)).toMatchInlineSnapshot(` { "address": undefined, "addresses": undefined, "chain": undefined, "chainId": undefined, "connector": undefined, "isConnected": false, "isConnecting": false, "isDisconnected": true, "isReconnecting": false, "status": "disconnected", } `) }) test('behavior: connected', async () => { let result = getConnection(config) expect(result.status).toEqual('disconnected') await connect(config, { connector: config.connectors[0]! }) result = getConnection(config) expect(result.address).toBeDefined() expect(result.status).toEqual('connected') await disconnect(config) result = getConnection(config) expect(result.status).toEqual('disconnected') }) ================================================ FILE: packages/core/src/actions/getConnection.ts ================================================ import type { Address, Chain } from 'viem' import type { Config, Connector } from '../createConfig.js' export type GetConnectionReturnType< config extends Config = Config, /// chain = Config extends config ? Chain : config['chains'][number], > = | { address: Address addresses: readonly [Address, ...Address[]] chain: chain | undefined chainId: number connector: Connector isConnected: true isConnecting: false isDisconnected: false isReconnecting: false status: 'connected' } | { address: Address | undefined addresses: readonly Address[] | undefined chain: chain | undefined chainId: number | undefined connector: Connector | undefined isConnected: boolean isConnecting: false isDisconnected: false isReconnecting: true status: 'reconnecting' } | { address: Address | undefined addresses: readonly Address[] | undefined chain: chain | undefined chainId: number | undefined connector: Connector | undefined isConnected: false isReconnecting: false isConnecting: true isDisconnected: false status: 'connecting' } | { address: undefined addresses: undefined chain: undefined chainId: undefined connector: undefined isConnected: false isReconnecting: false isConnecting: false isDisconnected: true status: 'disconnected' } /** https://wagmi.sh/core/api/actions/getConnection */ export function getConnection( config: config, ): GetConnectionReturnType { const uid = config.state.current! const connection = config.state.connections.get(uid) const addresses = connection?.accounts const address = addresses?.[0] const chain = config.chains.find( (chain) => chain.id === connection?.chainId, ) as GetConnectionReturnType['chain'] const status = config.state.status switch (status) { case 'connected': return { address: address!, addresses: addresses!, chain, chainId: connection?.chainId!, connector: connection?.connector!, isConnected: true, isConnecting: false, isDisconnected: false, isReconnecting: false, status, } case 'reconnecting': return { address, addresses, chain, chainId: connection?.chainId, connector: connection?.connector, isConnected: !!address, isConnecting: false, isDisconnected: false, isReconnecting: true, status, } case 'connecting': return { address, addresses, chain, chainId: connection?.chainId, connector: connection?.connector, isConnected: false, isConnecting: true, isDisconnected: false, isReconnecting: false, status, } case 'disconnected': return { address: undefined, addresses: undefined, chain: undefined, chainId: undefined, connector: undefined, isConnected: false, isConnecting: false, isDisconnected: true, isReconnecting: false, status, } } } ================================================ FILE: packages/core/src/actions/getConnections.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { getConnections } from './getConnections.js' test('default', async () => { const connector = config.connectors[0]! expect(getConnections(config)).toEqual([]) await connect(config, { connector }) expect(getConnections(config).length).toEqual(1) await disconnect(config, { connector }) expect(getConnections(config)).toEqual([]) }) ================================================ FILE: packages/core/src/actions/getConnections.ts ================================================ import type { Config, Connection } from '../createConfig.js' import type { Compute } from '../types/utils.js' import { deepEqual } from '../utils/deepEqual.js' export type GetConnectionsReturnType = Compute[] let previousConnections: Connection[] = [] /** https://wagmi.sh/core/api/actions/getConnections */ export function getConnections(config: Config): GetConnectionsReturnType { const connections = [...config.state.connections.values()] if (config.state.status === 'reconnecting') return previousConnections if (deepEqual(previousConnections, connections)) return previousConnections previousConnections = connections return connections } ================================================ FILE: packages/core/src/actions/getConnectorClient.test-d.ts ================================================ import { chain, config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { getConnectorClient } from './getConnectorClient.js' test('default', async () => { const client = await getConnectorClient(config) expectTypeOf(client.chain).toEqualTypeOf<(typeof config)['chains'][number]>() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) test('parameters: chainId', async () => { const client = await getConnectorClient(config, { chainId: chain.mainnet.id, }) expectTypeOf(client.chain).toEqualTypeOf() expectTypeOf(client.chain).not.toEqualTypeOf() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) ================================================ FILE: packages/core/src/actions/getConnectorClient.test.ts ================================================ import { address, config } from '@wagmi/test' import type { Address } from 'viem' import { expect, test } from 'vitest' import type { Connector } from '../createConfig.js' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { getConnectorClient } from './getConnectorClient.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) await expect(getConnectorClient(config)).resolves.toBeDefined() await disconnect(config, { connector }) }) test('parameters: connector', async () => { const connector2 = config.connectors[1]! await connect(config, { connector }) await connect(config, { connector: connector2 }) await expect(getConnectorClient(config, { connector })).resolves.toBeDefined() await disconnect(config, { connector }) await disconnect(config, { connector: connector2 }) }) test.todo('custom connector client') test('behavior: account address is checksummed', async () => { await connect(config, { connector }) const account = '0x95132632579b073D12a6673e18Ab05777a6B86f8'.toLowerCase() as Address const client = await getConnectorClient(config, { account }) expect(client.account.address).toMatchInlineSnapshot( '"0x95132632579b073D12a6673e18Ab05777a6B86f8"', ) expect(client.account.address).not.toBe(account) await disconnect(config, { connector }) }) test('behavior: not connected', async () => { await expect( getConnectorClient(config), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ConnectorNotConnectedError: Connector not connected. Version: @wagmi/core@x.y.z] `) }) test('behavior: connector is on different chain', async () => { await connect(config, { chainId: 1, connector }) config.setState((state) => { const uid = state.current! const connection = state.connections.get(uid)! return { ...state, connections: new Map(state.connections).set(uid, { ...connection, chainId: 456, }), } }) await expect( getConnectorClient(config, { account: address.usdcHolder }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ConnectorChainMismatchError: The current chain of the connector (id: 1) does not match the connection's chain (id: 456). Current Chain ID: 1 Expected Chain ID: 456 Version: @wagmi/core@x.y.z] `) await disconnect(config, { connector }) }) test('behavior: account does not exist on connector', async () => { await connect(config, { connector }) await expect( getConnectorClient(config, { account: address.usdcHolder }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ConnectorAccountNotFoundError: Account "0x5414d89a8bF7E99d732BC52f3e6A3Ef461c0C078" not found for connector "Mock Connector". Version: @wagmi/core@x.y.z] `) await disconnect(config, { connector }) }) test('behavior: reconnecting', async () => { config.setState((state) => ({ ...state, status: 'reconnecting' })) const { id, name, type, uid } = connector await expect( getConnectorClient(config, { connector: { id, name, type, uid, } as unknown as Connector, }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ConnectorUnavailableReconnectingError: Connector "Mock Connector" unavailable while reconnecting. Details: During the reconnection step, the only connector methods guaranteed to be available are: \`id\`, \`name\`, \`type\`, \`uid\`. All other methods are not guaranteed to be available until reconnection completes and connectors are fully restored. This error commonly occurs for connectors that asynchronously inject after reconnection has already started. Version: @wagmi/core@x.y.z] `) config.setState((state) => ({ ...state, status: 'disconnected' })) }) ================================================ FILE: packages/core/src/actions/getConnectorClient.ts ================================================ import { type Account, type Address, type BaseErrorType, type Client, createClient, custom, } from 'viem' import { getAddress, parseAccount } from 'viem/utils' import type { Config, Connection } from '../createConfig.js' import type { ErrorType } from '../errors/base.js' import { ConnectorAccountNotFoundError, type ConnectorAccountNotFoundErrorType, ConnectorChainMismatchError, type ConnectorChainMismatchErrorType, ConnectorNotConnectedError, type ConnectorNotConnectedErrorType, ConnectorUnavailableReconnectingError, type ConnectorUnavailableReconnectingErrorType, } from '../errors/config.js' import type { ChainIdParameter, ConnectorParameter, } from '../types/properties.js' import type { Compute } from '../types/utils.js' export type GetConnectorClientParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = Compute< ChainIdParameter & ConnectorParameter & { /** * Account to use for the client. * * - `Account | Address`: An Account MUST exist on the connector. * - `null`: Account MAY NOT exist on the connector. This is useful for * actions that can infer the account from the connector (e.g. sending a * call without a connected account – the user will be prompted to select * an account within the wallet). */ account?: Address | Account | null | undefined /** * Assert that the current chain ID matches the connector's chain ID. */ assertChainId?: boolean | undefined } > export type GetConnectorClientReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = Compute< Client< config['_internal']['transports'][chainId], Extract, Account > > export type GetConnectorClientErrorType = | ConnectorAccountNotFoundErrorType | ConnectorChainMismatchErrorType | ConnectorNotConnectedErrorType | ConnectorUnavailableReconnectingErrorType // base | BaseErrorType | ErrorType /** https://wagmi.sh/core/api/actions/getConnectorClient */ export async function getConnectorClient< config extends Config, chainId extends config['chains'][number]['id'], >( config: config, parameters: GetConnectorClientParameters = {}, ): Promise> { const { assertChainId = true } = parameters // Get connection let connection: Connection | undefined if (parameters.connector) { const { connector } = parameters if ( config.state.status === 'reconnecting' && !connector.getAccounts && !connector.getChainId ) throw new ConnectorUnavailableReconnectingError({ connector }) const [accounts, chainId] = await Promise.all([ connector.getAccounts().catch((e) => { if (parameters.account === null) return [] throw e }), connector.getChainId(), ]) connection = { accounts: accounts as readonly [Address, ...Address[]], chainId, connector, } } else connection = config.state.connections.get(config.state.current!) if (!connection) throw new ConnectorNotConnectedError() const chainId = parameters.chainId ?? connection.chainId // Check connector using same chainId as connection const connectorChainId = await connection.connector.getChainId() if (assertChainId && connectorChainId !== chainId) throw new ConnectorChainMismatchError({ connectionChainId: chainId, connectorChainId, }) // If connector has custom `getClient` implementation type Return = GetConnectorClientReturnType const connector = connection.connector if (connector.getClient) return connector.getClient({ chainId }) as unknown as Return // Default using `custom` transport const account = parseAccount(parameters.account ?? connection.accounts[0]!) if (account) account.address = getAddress(account.address) // TODO: Checksum address as part of `parseAccount`? // If account was provided, check that it exists on the connector if ( parameters.account && !connection.accounts.some( (x) => x.toLowerCase() === account.address.toLowerCase(), ) ) throw new ConnectorAccountNotFoundError({ address: account.address, connector, }) const chain = config.chains.find((chain) => chain.id === chainId) const provider = (await connection.connector.getProvider({ chainId })) as { request(...args: any): Promise } return createClient({ account, chain, name: 'Connector Client', transport: (opts) => custom(provider)({ ...opts, retryCount: 0 }), }) as Return } ================================================ FILE: packages/core/src/actions/getConnectors.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { getConnectors } from './getConnectors.js' test('default', () => { expect(getConnectors(config)).toEqual(config.connectors) expect(getConnectors(config)).toEqual(config.connectors) }) ================================================ FILE: packages/core/src/actions/getConnectors.ts ================================================ import type { Config, Connector } from '../createConfig.js' export type GetConnectorsReturnType = config['connectors'] let previousConnectors: readonly Connector[] = [] /** https://wagmi.sh/core/api/actions/getConnectors */ export function getConnectors( config: config, ): GetConnectorsReturnType { const connectors = config.connectors if ( previousConnectors.length === connectors.length && previousConnectors.every( (connector, index) => connector === connectors[index], ) ) return previousConnectors previousConnectors = connectors return connectors } ================================================ FILE: packages/core/src/actions/getContractEvents.test-d.ts ================================================ import { abi, config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { type GetContractEventsParameters, getContractEvents, } from './getContractEvents.js' test('default', async () => { const logs = await getContractEvents(config, { address: '0x', abi: abi.erc20, eventName: 'Transfer', args: { from: '0x', to: '0x', }, }) expectTypeOf(logs[0]!.eventName).toEqualTypeOf<'Transfer'>() expectTypeOf(logs[0]!.args).toEqualTypeOf<{ from?: `0x${string}` | undefined to?: `0x${string}` | undefined value?: bigint | undefined }>() getContractEvents(config, { address: '0x', abi: abi.erc20, eventName: 'Transfer', args: { // @ts-expect-error foo: '0x', to: '0x', }, }) getContractEvents(config, { address: '0x', abi: abi.erc20, // @ts-expect-error eventName: 'Foo', args: { from: '0x', to: '0x', }, }) }) test('behavior: strict', async () => { const logs = await getContractEvents(config, { address: '0x', abi: abi.erc20, strict: true, eventName: 'Transfer', args: { from: '0x', to: '0x', }, }) expectTypeOf(logs[0]!.eventName).toEqualTypeOf<'Transfer'>() expectTypeOf(logs[0]!.args).toEqualTypeOf<{ from: `0x${string}` to: `0x${string}` value: bigint }>() expectTypeOf(logs[0]!.args).not.toEqualTypeOf<{ from?: `0x${string}` | undefined to?: `0x${string}` | undefined value?: bigint | undefined }>() }) test('behavior: no eventName', async () => { type Result = GetContractEventsParameters< typeof abi.erc20, undefined, true, undefined, undefined, typeof config > expectTypeOf().toEqualTypeOf< | { from?: `0x${string}` | `0x${string}`[] | null | undefined to?: `0x${string}` | `0x${string}`[] | null | undefined } | { owner?: `0x${string}` | `0x${string}`[] | null | undefined spender?: `0x${string}` | `0x${string}`[] | null | undefined } | undefined >() const logs = await getContractEvents(config, { address: '0x', abi: abi.erc20, args: { from: '0x', to: '0x', }, }) expectTypeOf(logs[0]!.eventName).toEqualTypeOf<'Transfer' | 'Approval'>() expectTypeOf(logs[0]!.args).toEqualTypeOf< | { from?: `0x${string}` | undefined to?: `0x${string}` | undefined value?: bigint | undefined } | { owner?: `0x${string}` | undefined spender?: `0x${string}` | undefined value?: bigint | undefined } >() }) ================================================ FILE: packages/core/src/actions/getContractEvents.test.ts ================================================ import { abi, address, config, testClient } from '@wagmi/test' import { createWalletClient, erc20Abi, getAddress, http, parseEther, } from 'viem' import { beforeEach, expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { getContractEvents } from './getContractEvents.js' import { readContract } from './readContract.js' const connector = config.connectors[0]! beforeEach(async () => { if (config.state.current === connector.uid) { await disconnect(config, { connector }) } }) test('default', async () => { const data = await connect(config, { connector }) const connectedAddress = data.accounts[0] // impersonate usdc holder account and transfer usdc to connected account await testClient.mainnet.impersonateAccount({ address: address.usdcHolder }) await testClient.mainnet.setBalance({ address: address.usdcHolder, value: 10000000000000000000000n, }) const walletClient = createWalletClient({ account: address.usdcHolder, chain: testClient.mainnet.chain, transport: http(), }) await walletClient.writeContract({ address: address.usdc, abi: abi.erc20, functionName: 'transfer', args: [connectedAddress, parseEther('100', 'gwei')], }) await walletClient.writeContract({ address: address.usdc, abi: abi.erc20, functionName: 'approve', args: [connectedAddress, parseEther('10', 'gwei')], }) await testClient.mainnet.mine({ blocks: 1 }) await testClient.mainnet.stopImpersonatingAccount({ address: address.usdcHolder, }) const balance = await readContract(config, { address: address.usdc, abi: erc20Abi, functionName: 'balanceOf', args: [connectedAddress], }) expect(balance).toBeGreaterThan(0n) const [logs, approvalLogs, transferLogs] = await Promise.all([ getContractEvents(config, { address: address.usdc, abi: abi.erc20, }), getContractEvents(config, { address: address.usdc, abi: abi.erc20, eventName: 'Approval', }), getContractEvents(config, { address: address.usdc, abi: abi.erc20, eventName: 'Transfer', }), ]) expect(logs.length).toBe(2) expect(approvalLogs.length).toBe(1) expect(transferLogs.length).toBe(1) expect(logs[0]!.eventName).toEqual('Transfer') expect(logs[0]!.args).toEqual({ from: getAddress(address.usdcHolder), to: getAddress(connectedAddress), value: parseEther('100', 'gwei'), }) expect(logs[1]!.eventName).toEqual('Approval') expect(logs[1]!.args).toEqual({ owner: getAddress(address.usdcHolder), spender: getAddress(connectedAddress), value: parseEther('10', 'gwei'), }) }) ================================================ FILE: packages/core/src/actions/getContractEvents.ts ================================================ import type { Abi, BlockNumber, BlockTag, ContractEventName } from 'viem' import { type GetContractEventsErrorType as viem_GetContractEventsErrorType, type GetContractEventsParameters as viem_GetContractEventsParameters, type GetContractEventsReturnType as viem_GetContractEventsReturnType, getContractEvents as viem_getContractEvents, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetContractEventsParameters< abi extends Abi | readonly unknown[] = Abi, eventName extends ContractEventName | undefined = | ContractEventName | undefined, strict extends boolean | undefined = undefined, fromBlock extends BlockNumber | BlockTag | undefined = undefined, toBlock extends BlockNumber | BlockTag | undefined = undefined, config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = Compute< viem_GetContractEventsParameters & ChainIdParameter > export type GetContractEventsReturnType< abi extends Abi | readonly unknown[] = Abi, eventName extends ContractEventName | undefined = | ContractEventName | undefined, strict extends boolean | undefined = undefined, fromBlock extends BlockNumber | BlockTag | undefined = undefined, toBlock extends BlockNumber | BlockTag | undefined = undefined, > = viem_GetContractEventsReturnType export type GetContractEventsErrorType = viem_GetContractEventsErrorType /** https://wagmi.sh/core/actions/getContractEvents */ export async function getContractEvents< config extends Config, chainId extends config['chains'][number]['id'], const abi extends Abi | readonly unknown[], eventName extends ContractEventName | undefined, strict extends boolean | undefined = undefined, fromBlock extends BlockNumber | BlockTag | undefined = undefined, toBlock extends BlockNumber | BlockTag | undefined = undefined, >( config: config, parameters: GetContractEventsParameters< abi, eventName, strict, fromBlock, toBlock, config, chainId >, ): Promise< GetContractEventsReturnType > { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_getContractEvents, 'getContractEvents') return action(rest) } ================================================ FILE: packages/core/src/actions/getEnsAddress.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { getEnsAddress } from './getEnsAddress.js' test('default', async () => { await expect( getEnsAddress(config, { name: 'wevm.eth' }), ).resolves.toMatchInlineSnapshot( '"0xd2135CfB216b74109775236E36d4b433F1DF507B"', ) }) ================================================ FILE: packages/core/src/actions/getEnsAddress.ts ================================================ import { type GetEnsAddressErrorType as viem_GetEnsAddressErrorType, type GetEnsAddressParameters as viem_GetEnsAddressParameters, type GetEnsAddressReturnType as viem_GetEnsAddressReturnType, getEnsAddress as viem_getEnsAddress, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetEnsAddressParameters = Compute< viem_GetEnsAddressParameters & ChainIdParameter > export type GetEnsAddressReturnType = viem_GetEnsAddressReturnType export type GetEnsAddressErrorType = viem_GetEnsAddressErrorType /** https://wagmi.sh/core/api/actions/getEnsAddress */ export function getEnsAddress( config: config, parameters: GetEnsAddressParameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_getEnsAddress, 'getEnsAddress') return action(rest) } ================================================ FILE: packages/core/src/actions/getEnsAvatar.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { getEnsAvatar } from './getEnsAvatar.js' test.skip('default', async () => { await expect( getEnsAvatar(config, { name: 'wevm.eth', }), ).resolves.toMatchInlineSnapshot('"https://euc.li/wevm.eth"') }) ================================================ FILE: packages/core/src/actions/getEnsAvatar.ts ================================================ import { type GetEnsAvatarErrorType as viem_GetEnsAvatarErrorType, type GetEnsAvatarParameters as viem_GetEnsAvatarParameters, type GetEnsAvatarReturnType as viem_GetEnsAvatarReturnType, getEnsAvatar as viem_getEnsAvatar, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetEnsAvatarParameters = Compute< viem_GetEnsAvatarParameters & ChainIdParameter > export type GetEnsAvatarReturnType = viem_GetEnsAvatarReturnType export type GetEnsAvatarErrorType = viem_GetEnsAvatarErrorType /** https://wagmi.sh/core/api/actions/getEnsAvatar */ export function getEnsAvatar( config: config, parameters: GetEnsAvatarParameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_getEnsAvatar, 'getEnsAvatar') return action(rest) } ================================================ FILE: packages/core/src/actions/getEnsName.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { getEnsName } from './getEnsName.js' test('default', async () => { await expect( getEnsName(config, { address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', }), ).resolves.toMatchInlineSnapshot('"wevm.eth"') }) ================================================ FILE: packages/core/src/actions/getEnsName.ts ================================================ import { type GetEnsNameErrorType as viem_GetEnsNameErrorType, type GetEnsNameParameters as viem_GetEnsNameParameters, type GetEnsNameReturnType as viem_GetEnsNameReturnType, getEnsName as viem_getEnsName, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetEnsNameParameters = Compute< viem_GetEnsNameParameters & ChainIdParameter > export type GetEnsNameReturnType = viem_GetEnsNameReturnType export type GetEnsNameErrorType = viem_GetEnsNameErrorType /** https://wagmi.sh/core/api/actions/getEnsName */ export function getEnsName( config: config, parameters: GetEnsNameParameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_getEnsName, 'getEnsName') return action(rest) } ================================================ FILE: packages/core/src/actions/getEnsResolver.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { getEnsResolver } from './getEnsResolver.js' test('default', async () => { await expect( getEnsResolver(config, { name: 'wevm.eth', }), ).resolves.toMatchInlineSnapshot( '"0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41"', ) }) ================================================ FILE: packages/core/src/actions/getEnsResolver.ts ================================================ import { type GetEnsResolverErrorType as viem_GetEnsResolverErrorType, type GetEnsResolverParameters as viem_GetEnsResolverParameters, type GetEnsResolverReturnType as viem_GetEnsResolverReturnType, getEnsResolver as viem_getEnsResolver, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetEnsResolverParameters = Compute< viem_GetEnsResolverParameters & ChainIdParameter > export type GetEnsResolverReturnType = viem_GetEnsResolverReturnType export type GetEnsResolverErrorType = viem_GetEnsResolverErrorType /** https://wagmi.sh/core/api/actions/getEnsResolver */ export function getEnsResolver( config: config, parameters: GetEnsResolverParameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_getEnsResolver, 'getEnsResolver') return action(rest) } ================================================ FILE: packages/core/src/actions/getEnsText.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { getEnsText } from './getEnsText.js' test('default', async () => { await expect( getEnsText(config, { name: 'wevm.eth', key: 'com.twitter', }), ).resolves.toMatchInlineSnapshot('"wevm_dev"') }) ================================================ FILE: packages/core/src/actions/getEnsText.ts ================================================ import { type GetEnsTextErrorType as viem_GetEnsTextErrorType, type GetEnsTextParameters as viem_GetEnsTextParameters, type GetEnsTextReturnType as viem_GetEnsTextReturnType, getEnsText as viem_getEnsText, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetEnsTextParameters = Compute< viem_GetEnsTextParameters & ChainIdParameter > export type GetEnsTextReturnType = viem_GetEnsTextReturnType export type GetEnsTextErrorType = viem_GetEnsTextErrorType /** https://wagmi.sh/core/api/actions/getEnsText */ export function getEnsText( config: config, parameters: GetEnsTextParameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_getEnsText, 'getEnsText') return action(rest) } ================================================ FILE: packages/core/src/actions/getFeeHistory.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getFeeHistory } from './getFeeHistory.js' test('default', async () => { await expect( getFeeHistory(config, { blockCount: 4, rewardPercentiles: [25, 75], }), ).resolves.toMatchObject({ baseFeePerGas: expect.arrayContaining([expect.any(BigInt)]), gasUsedRatio: expect.arrayContaining([expect.any(Number)]), oldestBlock: expect.any(BigInt), reward: expect.any(Array), }) }) test('parameters: chainId', async () => { await expect( getFeeHistory(config, { blockCount: 4, rewardPercentiles: [25, 75], chainId: chain.mainnet2.id, }), ).resolves.toMatchObject({ baseFeePerGas: expect.arrayContaining([expect.any(BigInt)]), gasUsedRatio: expect.arrayContaining([expect.any(Number)]), oldestBlock: expect.any(BigInt), reward: expect.any(Array), }) }) test('parameters: blockNumber', async () => { await expect( getFeeHistory(config, { blockCount: 4, rewardPercentiles: [25, 75], blockNumber: 18677379n, }), ).resolves.toMatchObject({ baseFeePerGas: expect.arrayContaining([expect.any(BigInt)]), gasUsedRatio: expect.arrayContaining([expect.any(Number)]), oldestBlock: expect.any(BigInt), reward: expect.any(Array), }) }) test('parameters: blockTag', async () => { await expect( getFeeHistory(config, { blockCount: 4, rewardPercentiles: [25, 75], blockTag: 'safe', }), ).resolves.toMatchObject({ baseFeePerGas: expect.arrayContaining([expect.any(BigInt)]), gasUsedRatio: expect.arrayContaining([expect.any(Number)]), oldestBlock: expect.any(BigInt), reward: expect.any(Array), }) }) ================================================ FILE: packages/core/src/actions/getFeeHistory.ts ================================================ import { type GetFeeHistoryErrorType as viem_GetFeeHistoryErrorType, type GetFeeHistoryParameters as viem_GetFeeHistoryParameters, type GetFeeHistoryReturnType as viem_GetFeeHistoryReturnType, getFeeHistory as viem_getFeeHistory, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetFeeHistoryParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = Compute> export type GetFeeHistoryReturnType = viem_GetFeeHistoryReturnType export type GetFeeHistoryErrorType = viem_GetFeeHistoryErrorType /** https://wagmi.sh/core/api/actions/getFeeHistory */ export function getFeeHistory< config extends Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], >( config: config, parameters: GetFeeHistoryParameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_getFeeHistory, 'getFeeHistory') return action(rest) } ================================================ FILE: packages/core/src/actions/getGasPrice.test.ts ================================================ import { chain, config, testClient } from '@wagmi/test' import { expect, test } from 'vitest' import { getGasPrice } from './getGasPrice.js' test('default', async () => { await testClient.mainnet.setNextBlockBaseFeePerGas({ baseFeePerGas: 2_000_000_000n, }) await expect(getGasPrice(config)).resolves.toBe(3000000000n) }) test('parameters: chainId', async () => { await testClient.mainnet2.setNextBlockBaseFeePerGas({ baseFeePerGas: 1_000_000_000n, }) await testClient.mainnet2.mine({ blocks: 1 }) await expect( getGasPrice(config, { chainId: chain.mainnet2.id }), ).resolves.toBe(1875000000n) }) ================================================ FILE: packages/core/src/actions/getGasPrice.ts ================================================ import { type GetGasPriceErrorType as viem_GetGasPriceErrorType, type GetGasPriceReturnType as viem_GetGasPriceReturnType, getGasPrice as viem_getGasPrice, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetGasPriceParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = Compute> export type GetGasPriceReturnType = viem_GetGasPriceReturnType export type GetGasPriceErrorType = viem_GetGasPriceErrorType /** https://wagmi.sh/core/api/actions/getGasPrice */ export function getGasPrice< config extends Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], >( config: config, parameters: GetGasPriceParameters = {}, ): Promise { const { chainId } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_getGasPrice, 'getGasPrice') return action({}) } ================================================ FILE: packages/core/src/actions/getProof.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getProof } from './getProof.js' test.skip('default', async () => { await expect( getProof(config, { chainId: chain.optimism.id, address: '0x4200000000000000000000000000000000000016', storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }), ).resolves.toBeDefined() }) ================================================ FILE: packages/core/src/actions/getProof.ts ================================================ import { type GetProofErrorType as viem_GetProofErrorType, type GetProofParameters as viem_GetProofParameters, type GetProofReturnType as viem_GetProofReturnType, getProof as viem_getProof, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetProofParameters = Compute< viem_GetProofParameters & ChainIdParameter > export type GetProofReturnType = viem_GetProofReturnType export type GetProofErrorType = viem_GetProofErrorType /** https://wagmi.sh/core/api/actions/getProof */ export async function getProof( config: config, parameters: GetProofParameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_getProof, 'getProof') return action(rest) } ================================================ FILE: packages/core/src/actions/getPublicClient.test-d.ts ================================================ import { chain, config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { getPublicClient } from './getPublicClient.js' test('default', () => { const client = getPublicClient(config) expectTypeOf(client.chain).toEqualTypeOf<(typeof config)['chains'][number]>() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) test('parameters: chainId', () => { const client = getPublicClient(config, { chainId: chain.mainnet.id, }) expectTypeOf(client.chain).toEqualTypeOf() expectTypeOf(client.chain).not.toEqualTypeOf() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) test('behavior: unconfigured chain', () => { const client = getPublicClient(config, { // @ts-expect-error chainId: 123456, }) expectTypeOf(client).toEqualTypeOf() }) ================================================ FILE: packages/core/src/actions/getPublicClient.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { getPublicClient } from './getPublicClient.js' test('default', () => { expect(getPublicClient(config)).toBeDefined() }) test('behavior: unconfigured chain', () => { expect( getPublicClient(config, { // @ts-expect-error chainId: 123456, }), ).toBeUndefined() }) ================================================ FILE: packages/core/src/actions/getPublicClient.ts ================================================ import { type Client, type PublicClient, publicActions } from 'viem' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute, IsNarrowable } from '../types/utils.js' import { getClient } from './getClient.js' export type GetPublicClientParameters< config extends Config = Config, chainId extends | config['chains'][number]['id'] | undefined = config['chains'][number]['id'], > = ChainIdParameter export type GetPublicClientReturnType< config extends Config = Config, chainId extends | config['chains'][number]['id'] | undefined = config['chains'][number]['id'], /// resolvedChainId extends | config['chains'][number]['id'] | undefined = IsNarrowable< config['chains'][number]['id'], number > extends true ? IsNarrowable extends true ? chainId : config['chains'][number]['id'] : config['chains'][number]['id'] | undefined, > = resolvedChainId extends config['chains'][number]['id'] ? Compute< PublicClient< config['_internal']['transports'][resolvedChainId], Extract > > : undefined export function getPublicClient< config extends Config, chainId extends config['chains'][number]['id'] | number | undefined, >( config: config, parameters: GetPublicClientParameters = {}, ): GetPublicClientReturnType { const client = getClient(config, parameters) return (client as Client)?.extend(publicActions) as GetPublicClientReturnType< config, chainId > } ================================================ FILE: packages/core/src/actions/getStorageAt.test.ts ================================================ import { address, chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getStorageAt } from './getStorageAt.js' test('default', async () => { await expect( getStorageAt(config, { address: address.wagmiMintExample, slot: '0x0', }), ).resolves.toBe( '0x7761676d6900000000000000000000000000000000000000000000000000000a', ) await expect( getStorageAt(config, { address: address.wagmiMintExample, slot: '0x1', }), ).resolves.toBe( '0x5741474d4900000000000000000000000000000000000000000000000000000a', ) }) test('parameters: blockNumber', async () => { await expect( getStorageAt(config, { address: address.wagmiMintExample, blockNumber: 16280770n, slot: '0x0', }), ).resolves.toBe( '0x7761676d6900000000000000000000000000000000000000000000000000000a', ) }) test('parameters: blockTag', async () => { await expect( getStorageAt(config, { address: address.wagmiMintExample, blockTag: 'safe', slot: '0x0', }), ).resolves.toBe( '0x7761676d6900000000000000000000000000000000000000000000000000000a', ) }) test('parameters: chainId', async () => { await expect( getStorageAt(config, { address: address.wagmiMintExample, chainId: chain.optimism.id, slot: '0x0', }), ).resolves.toBe( '0x0000000000000000000000000000000000000000000000000000000000000000', ) }) ================================================ FILE: packages/core/src/actions/getStorageAt.ts ================================================ import { type GetStorageAtErrorType as viem_GetStorageAtErrorType, type GetStorageAtParameters as viem_GetStorageAtParameters, type GetStorageAtReturnType as viem_GetStorageAtReturnType, getStorageAt as viem_getStorageAt, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetStorageAtParameters = Compute< viem_GetStorageAtParameters & ChainIdParameter > export type GetStorageAtReturnType = viem_GetStorageAtReturnType export type GetStorageAtErrorType = viem_GetStorageAtErrorType /** https://wagmi.sh/core/api/actions/getStorageAt */ export async function getStorageAt( config: config, parameters: GetStorageAtParameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_getStorageAt, 'getStorageAt') return action(rest) } ================================================ FILE: packages/core/src/actions/getTransaction.test-d.ts ================================================ import { http } from 'viem' import { celo, mainnet } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { getTransaction } from './getTransaction.js' test('chain formatters', async () => { const config = createConfig({ chains: [celo, mainnet], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) const result = await getTransaction(config, { hash: '0x123' }) // @ts-expect-error result.feeCurrency if (result.chainId === celo.id) { expectTypeOf(result.feeCurrency).toEqualTypeOf<`0x${string}` | null>() } }) test('chainId', async () => { const config = createConfig({ chains: [celo, mainnet], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) const result = await getTransaction(config, { hash: '0x123', chainId: celo.id, }) expectTypeOf(result.feeCurrency).toEqualTypeOf<`0x${string}` | null>() }) ================================================ FILE: packages/core/src/actions/getTransaction.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { getTransaction } from './getTransaction.js' test('default', async () => { await expect( getTransaction(config, { hash: '0xa559259bd2d0e8372421e222ff3545f705b5da60005bd787a23c2e68d6d7fefd', }), ).resolves.toMatchInlineSnapshot(` { "accessList": [], "blockHash": "0x61c4e868008b465addd7c0a5da03db28bb9911597c58e239a85dd14dd43fd56a", "blockNumber": 17488642n, "chainId": 1, "from": "0xd2135cfb216b74109775236e36d4b433f1df507b", "gas": 53671n, "gasPrice": 15806335296n, "hash": "0xa559259bd2d0e8372421e222ff3545f705b5da60005bd787a23c2e68d6d7fefd", "input": "0xa9059cbb0000000000000000000000006acbe090725d8b1cd59fe5f3e0c9c3685ebb77af00000000000000000000000000000000000000000000000000000002540be400", "maxFeePerGas": 19000000000n, "maxPriorityFeePerGas": 1000000000n, "nonce": 29, "r": "0x60a19c4a708571d2a7c661dc5494542fa2c6ddd8e7dc218e4c4795b6ba7969f5", "s": "0x7ef2778cc21f5c12861208d0c030e77193a234273e32a1dd5066d7d677aa1ef2", "to": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "transactionIndex": 58, "type": "eip1559", "typeHex": "0x2", "v": 1n, "value": 0n, "yParity": 1, } `) }) ================================================ FILE: packages/core/src/actions/getTransaction.ts ================================================ import type { Chain } from 'viem' import { type GetTransactionErrorType as viem_GetTransactionErrorType, type GetTransactionParameters as viem_GetTransactionParameters, type GetTransactionReturnType as viem_GetTransactionReturnType, getTransaction as viem_getTransaction, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute, IsNarrowable } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetTransactionParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = Compute> export type GetTransactionReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], /// chains extends readonly Chain[] = SelectChains, > = Compute< { [key in keyof chains]: viem_GetTransactionReturnType< IsNarrowable extends true ? chains[key] : undefined > & { chainId: chains[key]['id'] } }[number] > export type GetTransactionErrorType = viem_GetTransactionErrorType /** https://wagmi.sh/core/api/actions/getTransaction */ export function getTransaction< config extends Config, chainId extends config['chains'][number]['id'], >( config: config, parameters: GetTransactionParameters, ): Promise> { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_getTransaction, 'getTransaction') return action(rest) as unknown as Promise< GetTransactionReturnType > } ================================================ FILE: packages/core/src/actions/getTransactionConfirmations.test-d.ts ================================================ import { config } from '@wagmi/test' import { http } from 'viem' import { mainnet, zkSync } from 'viem/chains' import { test } from 'vitest' import { createConfig } from '../createConfig.js' import { getTransactionConfirmations } from './getTransactionConfirmations.js' test('default', async () => { getTransactionConfirmations(config, { transactionReceipt: { blockHash: '0x', blockNumber: 1n, contractAddress: '0x', cumulativeGasUsed: 1n, effectiveGasPrice: 1n, from: '0x', gasUsed: 1n, l1Fee: 1n, logs: [], logsBloom: '0x', status: 'success', to: '0x', transactionHash: '0x', transactionIndex: 1, type: 'eip1559', }, }) }) test('chain formatters', async () => { const config = createConfig({ chains: [mainnet, zkSync], transports: { [mainnet.id]: http(), [zkSync.id]: http() }, }) const transactionReceipt = { blockHash: '0x', blockNumber: 1n, contractAddress: '0x', cumulativeGasUsed: 1n, effectiveGasPrice: 1n, from: '0x', gasUsed: 1n, logsBloom: '0x', status: 'success', to: '0x', transactionHash: '0x', transactionIndex: 1, type: 'eip1559', } as const getTransactionConfirmations(config, { transactionReceipt: { ...transactionReceipt, l1BatchNumber: 1n, l1BatchTxIndex: 1n, logs: [], l2ToL1Logs: [], }, }) getTransactionConfirmations(config, { chainId: zkSync.id, transactionReceipt: { ...transactionReceipt, l1BatchNumber: 1n, l1BatchTxIndex: 1n, logs: [], l2ToL1Logs: [], }, }) getTransactionConfirmations(config, { chainId: mainnet.id, transactionReceipt: { ...transactionReceipt, // @ts-expect-error l1BatchNumber: 1n, l1BatchTxIndex: 1n, logs: [], l2ToL1Logs: [], }, }) }) ================================================ FILE: packages/core/src/actions/getTransactionConfirmations.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { getTransactionConfirmations } from './getTransactionConfirmations.js' import { getTransactionReceipt } from './getTransactionReceipt.js' test('default', async () => { await expect( getTransactionConfirmations(config, { hash: '0xa559259bd2d0e8372421e222ff3545f705b5da60005bd787a23c2e68d6d7fefd', }), ).resolves.toBeTypeOf('bigint') }) test('parameters: transactionReceipt', async () => { const transactionReceipt = await getTransactionReceipt(config, { hash: '0xa559259bd2d0e8372421e222ff3545f705b5da60005bd787a23c2e68d6d7fefd', }) await expect( getTransactionConfirmations(config, { transactionReceipt, }), ).resolves.toBeTypeOf('bigint') }) ================================================ FILE: packages/core/src/actions/getTransactionConfirmations.ts ================================================ import type { Chain } from 'viem' import { type GetTransactionConfirmationsErrorType as viem_GetTransactionConfirmationsErrorType, type GetTransactionConfirmationsParameters as viem_GetTransactionConfirmationsParameters, type GetTransactionConfirmationsReturnType as viem_GetTransactionConfirmationsReturnType, getTransactionConfirmations as viem_getTransactionConfirmations, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter } from '../types/properties.js' import { getAction } from '../utils/getAction.js' export type GetTransactionConfirmationsParameters< config extends Config = Config, chainId extends | config['chains'][number]['id'] | undefined = config['chains'][number]['id'], /// chains extends readonly Chain[] = SelectChains, > = { [key in keyof chains]: viem_GetTransactionConfirmationsParameters< chains[key] > & ChainIdParameter }[number] export type GetTransactionConfirmationsReturnType = viem_GetTransactionConfirmationsReturnType export type GetTransactionConfirmationsErrorType = viem_GetTransactionConfirmationsErrorType /** https://wagmi.sh/core/api/actions/getTransactionConfirmations */ export function getTransactionConfirmations< config extends Config, chainId extends | config['chains'][number]['id'] | undefined = config['chains'][number]['id'], >( config: config, parameters: GetTransactionConfirmationsParameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction( client, viem_getTransactionConfirmations, 'getTransactionConfirmations', ) return action(rest as viem_GetTransactionConfirmationsParameters) } ================================================ FILE: packages/core/src/actions/getTransactionCount.test.ts ================================================ import { accounts, chain, config, testClient } from '@wagmi/test' import type { BlockTag } from 'viem' import { expect, test } from 'vitest' import { getTransactionCount } from './getTransactionCount.js' const address = accounts[0] test('default', async () => { await expect(getTransactionCount(config, { address })).resolves.toBeTypeOf( 'number', ) }) test('parameters: chainId', async () => { await testClient.mainnet2.setNonce({ address, nonce: 6969, }) await testClient.mainnet2.mine({ blocks: 1 }) await expect( getTransactionCount(config, { address, chainId: chain.mainnet2.id }), ).resolves.toBeTypeOf('number') }) test('parameters: blockNumber', async () => { await expect( getTransactionCount(config, { address, blockNumber: 13677382n }), ).resolves.toBeTypeOf('number') }) test.each([ { blockTag: 'earliest' }, { blockTag: 'finalized' }, { blockTag: 'latest' }, { blockTag: 'pending' }, { blockTag: 'safe' }, ] as { blockTag: BlockTag; expected: number }[])( 'parameters: blockTag $blockTag', async ({ blockTag }) => { await testClient.mainnet.restart() await expect( getTransactionCount(config, { address, blockTag, }), ).resolves.toBeTypeOf('number') }, ) ================================================ FILE: packages/core/src/actions/getTransactionCount.ts ================================================ import { type GetTransactionCountErrorType as viem_GetTransactionCountErrorType, type GetTransactionCountParameters as viem_GetTransactionCountParameters, type GetTransactionCountReturnType as viem_GetTransactionCountReturnType, getTransactionCount as viem_getTransactionCount, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetTransactionCountParameters = Compute & viem_GetTransactionCountParameters> export type GetTransactionCountReturnType = viem_GetTransactionCountReturnType export type GetTransactionCountErrorType = viem_GetTransactionCountErrorType /** https://wagmi.sh/core/api/actions/getTransactionCount */ export async function getTransactionCount( config: config, parameters: GetTransactionCountParameters, ): Promise { const { address, blockNumber, blockTag, chainId } = parameters const client = config.getClient({ chainId }) const action = getAction( client, viem_getTransactionCount, 'getTransactionCount', ) return action(blockNumber ? { address, blockNumber } : { address, blockTag }) } ================================================ FILE: packages/core/src/actions/getTransactionReceipt.test-d.ts ================================================ import { http } from 'viem' import { mainnet, zkSync } from 'viem/chains' import type { ZkSyncL2ToL1Log, ZkSyncLog } from 'viem/zksync' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { getTransactionReceipt } from './getTransactionReceipt.js' test('chain formatters', async () => { const config = createConfig({ chains: [mainnet, zkSync], transports: { [mainnet.id]: http(), [zkSync.id]: http() }, }) const result = await getTransactionReceipt(config, { hash: '0x123' }) if (result.chainId === zkSync.id) { expectTypeOf(result.l1BatchNumber).toEqualTypeOf() expectTypeOf(result.l1BatchTxIndex).toEqualTypeOf() expectTypeOf(result.logs).toEqualTypeOf() expectTypeOf(result.l2ToL1Logs).toEqualTypeOf() } }) test('chainId', async () => { const config = createConfig({ chains: [zkSync], transports: { [zkSync.id]: http() }, }) const result = await getTransactionReceipt(config, { hash: '0x123', chainId: zkSync.id, }) expectTypeOf(result.l1BatchNumber).toEqualTypeOf() expectTypeOf(result.l1BatchTxIndex).toEqualTypeOf() expectTypeOf(result.logs).toEqualTypeOf() expectTypeOf(result.l2ToL1Logs).toEqualTypeOf() }) ================================================ FILE: packages/core/src/actions/getTransactionReceipt.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { getTransaction } from './getTransaction.js' import { getTransactionReceipt } from './getTransactionReceipt.js' test('default', async () => { const transaction = await getTransaction(config, { blockNumber: 16280769n, index: 0, }) await expect( getTransactionReceipt(config, { hash: transaction.hash, }), ).resolves.toMatchInlineSnapshot(` { "blockHash": "0xb932f77cf770d1d1c8f861153eec1e990f5d56b6ffdb4ac06aef3cca51ef37d4", "blockNumber": 16280769n, "contractAddress": null, "cumulativeGasUsed": 21000n, "effectiveGasPrice": 33427926161n, "from": "0x043022ef9fca1066024d19d681e2ccf44ff90de3", "gasUsed": 21000n, "logs": [], "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "status": "success", "to": "0x318a5fb4f1604fc46375a1db9a9018b6e423b345", "transactionHash": "0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871", "transactionIndex": 0, "type": "legacy", } `) }) ================================================ FILE: packages/core/src/actions/getTransactionReceipt.ts ================================================ import type { Chain } from 'viem' import { type GetTransactionReceiptErrorType as viem_GetTransactionReceiptErrorType, type GetTransactionReceiptParameters as viem_GetTransactionReceiptParameters, type GetTransactionReceiptReturnType as viem_GetTransactionReceiptReturnType, getTransactionReceipt as viem_getTransactionReceipt, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute, IsNarrowable } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type GetTransactionReceiptParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = Compute< viem_GetTransactionReceiptParameters & ChainIdParameter > export type GetTransactionReceiptReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], /// chains extends readonly Chain[] = SelectChains, > = Compute< { [key in keyof chains]: viem_GetTransactionReceiptReturnType< IsNarrowable extends true ? chains[key] : undefined > & { chainId: chains[key]['id'] } }[number] > export type GetTransactionReceiptErrorType = viem_GetTransactionReceiptErrorType /** https://wagmi.sh/core/api/actions/getTransactionReceipt */ export async function getTransactionReceipt< config extends Config, chainId extends config['chains'][number]['id'], >( config: config, parameters: GetTransactionReceiptParameters, ): Promise> { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction( client, viem_getTransactionReceipt, 'getTransactionReceipt', ) return action(rest) as unknown as Promise< GetTransactionReceiptReturnType > } ================================================ FILE: packages/core/src/actions/getWalletClient.test-d.ts ================================================ import { chain, config } from '@wagmi/test' import type { Account } from 'viem' import { expectTypeOf, test } from 'vitest' import { getWalletClient } from './getWalletClient.js' test('default', async () => { const client = await getWalletClient(config) expectTypeOf(client.chain).toEqualTypeOf<(typeof config)['chains'][number]>() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() expectTypeOf(client.account).toEqualTypeOf() }) test('parameters: chainId', async () => { const client = await getWalletClient(config, { chainId: chain.mainnet.id, }) expectTypeOf(client.chain).toEqualTypeOf() expectTypeOf(client.chain).not.toEqualTypeOf() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() expectTypeOf(client.account).toEqualTypeOf() }) ================================================ FILE: packages/core/src/actions/getWalletClient.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { getWalletClient } from './getWalletClient.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) await expect(getWalletClient(config)).resolves.toBeDefined() await disconnect(config, { connector }) }) test('behavior: not connected', async () => { await expect( getWalletClient(config), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ConnectorNotConnectedError: Connector not connected. Version: @wagmi/core@x.y.z] `) }) ================================================ FILE: packages/core/src/actions/getWalletClient.ts ================================================ import { type Account, type WalletClient, walletActions } from 'viem' import type { Config } from '../createConfig.js' import type { BaseErrorType, ErrorType } from '../errors/base.js' import type { Compute } from '../types/utils.js' import { type GetConnectorClientErrorType, type GetConnectorClientParameters, getConnectorClient, } from './getConnectorClient.js' export type GetWalletClientParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = GetConnectorClientParameters export type GetWalletClientReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = Compute< WalletClient< config['_internal']['transports'][chainId], Extract, Account > > export type GetWalletClientErrorType = // getConnectorClient() | GetConnectorClientErrorType // base | BaseErrorType | ErrorType export async function getWalletClient< config extends Config, chainId extends config['chains'][number]['id'], >( config: config, parameters: GetWalletClientParameters = {}, ): Promise> { const client = await getConnectorClient(config, parameters) // @ts-ignore return client.extend(walletActions) as unknown as GetWalletClientReturnType< config, chainId > } ================================================ FILE: packages/core/src/actions/multicall.bench-d.ts ================================================ import { attest } from '@ark/attest' import { abi, config } from '@wagmi/test' import { test } from 'vitest' import { multicall } from './multicall.js' test('default', () => { multicall(config, { chainId: 1, contracts: [ { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }, { address: '0x', abi: abi.wagmiMintExample, functionName: 'tokenURI', args: [123n], }, { address: '0x', abi: abi.viewOverloads, functionName: 'foo', }, { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x'], }, { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x', '0x'], }, { abi: abi.wagmigotchi, address: '0x', functionName: 'love', args: ['0x'], }, { abi: abi.wagmigotchi, address: '0x', functionName: 'love', args: ['0x'], }, { abi: abi.wagmigotchi, address: '0x', functionName: 'getAlive', }, { abi: abi.mloot, address: '0x', functionName: 'tokenOfOwnerByIndex', args: ['0x', 0n], }, { abi: abi.erc20, address: '0x', functionName: 'symbol', }, { abi: abi.erc20, address: '0x', functionName: 'balanceOf', args: ['0x'], }, ], }) attest.instantiations([523679, 'instantiations']) }) ================================================ FILE: packages/core/src/actions/multicall.test-d.ts ================================================ import { abi, config } from '@wagmi/test' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' import { multicall } from './multicall.js' test('default', async () => { const result = await multicall(config, { chainId: 1, contracts: [ { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }, { address: '0x', abi: abi.wagmiMintExample, functionName: 'tokenURI', args: [123n], }, ], }) expectTypeOf(result).toEqualTypeOf< [ ( | { error: Error; result?: undefined; status: 'failure' } | { error?: undefined; result: bigint; status: 'success' } ), ( | { error: Error; result?: undefined; status: 'failure' } | { error?: undefined; result: string; status: 'success' } ), ] >() }) test('allowFailure', async () => { const result = await multicall(config, { allowFailure: false, contracts: [ { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }, { address: '0x', abi: abi.wagmiMintExample, functionName: 'tokenURI', args: [123n], }, ], }) expectTypeOf(result).toEqualTypeOf<[bigint, string]>() }) test('MulticallParameters', async () => { type Result = Parameters< typeof multicall< typeof config, [ { address: '0x' abi: typeof abi.viewOverloads functionName: 'foo' }, ] > >[1]['contracts'][0] expectTypeOf().toEqualTypeOf<'foo' | 'bar'>() expectTypeOf().toEqualTypeOf< readonly [] | readonly [Address] | readonly [Address, Address] | undefined >() }) test('overloads', async () => { const res = await multicall(config, { allowFailure: false, contracts: [ { address: '0x', abi: abi.viewOverloads, functionName: 'foo', }, { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x'], }, { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x', '0x'], }, ], }) expectTypeOf(res).toEqualTypeOf< [number, string, { foo: Address; bar: Address }] >() }) ================================================ FILE: packages/core/src/actions/multicall.test.ts ================================================ import { abi, address, config } from '@wagmi/test' import { expect, test } from 'vitest' import { multicall } from './multicall.js' test('default', async () => { await expect( multicall(config, { contracts: [ { address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }, ], }), ).resolves.toMatchInlineSnapshot(` [ { "result": 10n, "status": "success", }, ] `) }) test('allowFailure', async () => { await expect( multicall(config, { allowFailure: false, contracts: [ { address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }, ], }), ).resolves.toMatchInlineSnapshot(` [ 10n, ] `) }) ================================================ FILE: packages/core/src/actions/multicall.ts ================================================ import type { ContractFunctionParameters, MulticallErrorType as viem_MulticallErrorType, MulticallParameters as viem_MulticallParameters, MulticallReturnType as viem_MulticallReturnType, } from 'viem' import { multicall as viem_multicall } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import { getAction } from '../utils/getAction.js' export type MulticallParameters< contracts extends readonly unknown[] = readonly ContractFunctionParameters[], allowFailure extends boolean = true, config extends Config = Config, > = viem_MulticallParameters & ChainIdParameter export type MulticallReturnType< contracts extends readonly unknown[] = readonly ContractFunctionParameters[], allowFailure extends boolean = true, > = viem_MulticallReturnType export type MulticallErrorType = viem_MulticallErrorType export async function multicall< config extends Config, const contracts extends readonly ContractFunctionParameters[], allowFailure extends boolean = true, >( config: config, parameters: MulticallParameters, ): Promise> { const { allowFailure = true, chainId, contracts, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_multicall, 'multicall') return action({ allowFailure, contracts, ...rest, }) as Promise> } ================================================ FILE: packages/core/src/actions/prepareTransactionRequest.test-d.ts ================================================ import { accounts, config } from '@wagmi/test' import { http, parseEther } from 'viem' import { celo, mainnet } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { type PrepareTransactionRequestParameters, prepareTransactionRequest, } from './prepareTransactionRequest.js' const targetAccount = accounts[1] test('default', async () => { const response = await prepareTransactionRequest(config, { chainId: 1, to: '0x', value: parseEther('1'), }) const { nonce: _nonce, ...request } = response request.to request.chainId expectTypeOf(response).toMatchTypeOf<{ chainId: 1 }>() }) test('chain formatters', async () => { const config = createConfig({ chains: [celo, mainnet], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) type Result = PrepareTransactionRequestParameters expectTypeOf().toMatchTypeOf<{ chainId?: typeof celo.id | typeof mainnet.id | undefined feeCurrency?: `0x${string}` | undefined }>() const request = await prepareTransactionRequest(config, { to: targetAccount, value: parseEther('0.01'), feeCurrency: '0x', }) if (request.chainId === celo.id) { expectTypeOf(request.chainId).toEqualTypeOf(celo.id) expectTypeOf(request.feeCurrency).toEqualTypeOf<`0x${string}` | undefined>() } type Result2 = PrepareTransactionRequestParameters< typeof config, typeof celo.id > expectTypeOf().toMatchTypeOf<{ feeCurrency?: `0x${string}` | undefined }>() const request2 = await prepareTransactionRequest(config, { chainId: celo.id, to: targetAccount, value: parseEther('0.01'), feeCurrency: '0x', }) expectTypeOf(request2.chainId).toEqualTypeOf(celo.id) expectTypeOf(request2.feeCurrency).toEqualTypeOf<`0x${string}` | undefined>() type Result3 = PrepareTransactionRequestParameters< typeof config, typeof mainnet.id > expectTypeOf().not.toMatchTypeOf<{ feeCurrency?: `0x${string}` | undefined }>() prepareTransactionRequest(config, { chainId: mainnet.id, to: targetAccount, value: parseEther('0.01'), // @ts-expect-error feeCurrency: '0x', }) }) ================================================ FILE: packages/core/src/actions/prepareTransactionRequest.test.ts ================================================ import { accounts, config, privateKey } from '@wagmi/test' import { parseEther } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { prepareTransactionRequest } from './prepareTransactionRequest.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const request = await prepareTransactionRequest(config, { to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) const { gas: _gas, gasPrice: _gasPrice, maxFeePerGas: _mfpg, maxPriorityFeePerGas: _mpfpg, nonce: _nonce, ...rest } = request expect(rest).toMatchInlineSnapshot(` { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 1, "from": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "to": "0x70997970c51812dc3a010c7d01b50e0d17dc79c8", "type": "eip1559", "value": 1000000000000000000n, } `) await disconnect(config, { connector }) }) test('parameters: account', async () => { await connect(config, { connector }) const request = await prepareTransactionRequest(config, { account: accounts[0], to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) const { gas: _gas, gasPrice: _gasPrice, maxFeePerGas: _mfpg, maxPriorityFeePerGas: _mpfpg, nonce: _nonce, ...rest } = request expect(rest).toMatchInlineSnapshot(` { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 1, "from": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "to": "0x70997970c51812dc3a010c7d01b50e0d17dc79c8", "type": "eip1559", "value": 1000000000000000000n, } `) await disconnect(config, { connector }) }) test('behavior: local account', async () => { const account = privateKeyToAccount(privateKey) const request = await prepareTransactionRequest(config, { account, to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) const { gas: _gas, gasPrice: _gasPrice, maxFeePerGas: _mfpg, maxPriorityFeePerGas: _mpfpg, nonce: _nonce, ...rest } = request expect(rest).toMatchInlineSnapshot(` { "account": { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "nonceManager": undefined, "publicKey": "0x04e997cee8adb07b5269f375399109f53c94ddb7ac9cdb9252b74ba33fd471392fc563102ff7b38c85ee9d0a88c8819e6c97ea8b0db791d59c89086f62f5516863", "sign": [Function], "signAuthorization": [Function], "signMessage": [Function], "signTransaction": [Function], "signTypedData": [Function], "source": "privateKey", "type": "local", }, "chainId": 1, "from": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "to": "0x70997970c51812dc3a010c7d01b50e0d17dc79c8", "type": "eip1559", "value": 1000000000000000000n, } `) }) ================================================ FILE: packages/core/src/actions/prepareTransactionRequest.ts ================================================ import type { Account, Address, Chain, PrepareTransactionRequestErrorType as viem_PrepareTransactionRequestErrorType, PrepareTransactionRequestParameters as viem_PrepareTransactionRequestParameters, PrepareTransactionRequestRequest as viem_PrepareTransactionRequestRequest, PrepareTransactionRequestReturnType as viem_PrepareTransactionRequestReturnType, } from 'viem' import { prepareTransactionRequest as viem_prepareTransactionRequest } from 'viem/actions' import type { Config } from '../createConfig.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter } from '../types/properties.js' import type { IsNarrowable, UnionCompute, UnionStrictOmit, } from '../types/utils.js' import { getAction } from '../utils/getAction.js' import { getConnection } from './getConnection.js' export type PrepareTransactionRequestParameters< config extends Config = Config, chainId extends | config['chains'][number]['id'] | undefined = config['chains'][number]['id'], request extends viem_PrepareTransactionRequestRequest< SelectChains[0], SelectChains[0] > = viem_PrepareTransactionRequestRequest< SelectChains[0], SelectChains[0] >, /// chains extends readonly Chain[] = SelectChains, > = { [key in keyof chains]: UnionCompute< UnionStrictOmit< viem_PrepareTransactionRequestParameters< chains[key], Account, chains[key], Account | Address, request extends viem_PrepareTransactionRequestRequest< chains[key], chains[key] > ? request : never >, 'chain' > & ChainIdParameter & { to: Address } > }[number] export type PrepareTransactionRequestReturnType< config extends Config = Config, chainId extends | config['chains'][number]['id'] | undefined = config['chains'][number]['id'], request extends viem_PrepareTransactionRequestRequest< SelectChains[0], SelectChains[0] > = viem_PrepareTransactionRequestRequest< SelectChains[0], SelectChains[0] >, /// chains extends readonly Chain[] = SelectChains, > = { [key in keyof chains]: viem_PrepareTransactionRequestReturnType< IsNarrowable extends true ? chains[key] : undefined, Account, chains[key], Account, request extends viem_PrepareTransactionRequestRequest< IsNarrowable extends true ? chains[key] : undefined, chains[key] > ? request : never > & { chainId: chains[key]['id'] } }[number] export type PrepareTransactionRequestErrorType = viem_PrepareTransactionRequestErrorType /** https://wagmi.sh/core/api/actions/prepareTransactionRequest */ export async function prepareTransactionRequest< config extends Config, chainId extends config['chains'][number]['id'] | undefined, const request extends viem_PrepareTransactionRequestRequest< SelectChains['0'], SelectChains['0'] >, >( config: config, parameters: PrepareTransactionRequestParameters, ): Promise> { const { account: account_, chainId, ...rest } = parameters const account = account_ ?? getConnection(config).address const client = config.getClient({ chainId }) const action = getAction( client, viem_prepareTransactionRequest, 'prepareTransactionRequest', ) return action({ ...rest, ...(account ? { account } : {}), } as unknown as viem_PrepareTransactionRequestParameters) as unknown as Promise< PrepareTransactionRequestReturnType > } ================================================ FILE: packages/core/src/actions/readContract.bench-d.ts ================================================ import { attest } from '@ark/attest' import type { abi } from '@wagmi/test' import { parseAbi } from 'viem' import viemPackageJson from 'viem/package.json' with { type: 'json' } import { test } from 'vitest' import type { ReadContractParameters } from './readContract.js' test('default', () => { type Result = ReadContractParameters<(typeof abi)['erc20'], 'balanceOf'> const res = {} as Result attest.instantiations([132033, 'instantiations']) attest(res.args) if (viemPackageJson.version.startsWith('2.43')) attest(res.args).type.toString.snap( // biome-ignore lint/style/noUnusedTemplateLiteral: stable `readonly [account: \`0x\${string}\`]`, ) }) const abiOverload = parseAbi([ 'function foo() view returns (int8)', 'function foo(address account) view returns (string)', 'function foo(address sender, address account) view returns ((address foo, address bar))', 'function bar() view returns (int8)', ]) test('overloads', () => { type Result = ReadContractParameters const res = {} as Result attest.instantiations([12984, 'instantiations']) attest< | readonly [] | readonly [account: `0x${string}`] | readonly [sender: `0x${string}`, account: `0x${string}`] | undefined >(res.args) if (viemPackageJson.version.startsWith('2.43')) attest(res.args).type.toString.snap(` | readonly [] | readonly [account: \`0x\${string}\`] | readonly [sender: \`0x\${string}\`, account: \`0x\${string}\`] | undefined`) }) ================================================ FILE: packages/core/src/actions/readContract.test-d.ts ================================================ import { abi, config } from '@wagmi/test' import { assertType, expectTypeOf, test } from 'vitest' import { readContract } from './readContract.js' test('default', async () => { const result = await readContract(config, { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }) expectTypeOf(result).toEqualTypeOf() }) test('overloads', async () => { const result1 = await readContract(config, { address: '0x', abi: abi.viewOverloads, functionName: 'foo', }) assertType(result1) const result2 = await readContract(config, { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: [], }) assertType(result2) const result3 = await readContract(config, { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x'], }) assertType(result3) const result4 = await readContract(config, { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x', '0x'], }) assertType<{ foo: `0x${string}` bar: `0x${string}` }>(result4) }) test('deployless read (bytecode)', async () => { const result = await readContract(config, { code: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }) expectTypeOf(result).toEqualTypeOf() }) test('deployless read (factory)', async () => { const result = await readContract(config, { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], factory: '0x', factoryData: '0x', }) expectTypeOf(result).toEqualTypeOf() }) ================================================ FILE: packages/core/src/actions/readContract.test.ts ================================================ import { abi, address, bytecode, chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { readContract } from './readContract.js' test('default', async () => { await expect( readContract(config, { address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }), ).resolves.toMatchInlineSnapshot('10n') }) test('parameters: chainId', async () => { await expect( readContract(config, { address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], chainId: chain.mainnet2.id, }), ).resolves.toMatchInlineSnapshot('10n') }) test('parameters: deployless read (bytecode)', async () => { await expect( readContract(config, { abi: abi.wagmiMintExample, functionName: 'name', code: bytecode.wagmiMintExample, }), ).resolves.toMatchInlineSnapshot(`"wagmi"`) }) ================================================ FILE: packages/core/src/actions/readContract.ts ================================================ import type { Abi, ContractFunctionArgs, ContractFunctionName } from 'viem' import { type ReadContractErrorType as viem_ReadContractErrorType, type ReadContractParameters as viem_ReadContractParameters, type ReadContractReturnType as viem_ReadContractReturnType, readContract as viem_readContract, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import { getAction } from '../utils/getAction.js' export type ReadContractParameters< abi extends Abi | readonly unknown[] = Abi, functionName extends ContractFunctionName< abi, 'pure' | 'view' > = ContractFunctionName, args extends ContractFunctionArgs< abi, 'pure' | 'view', functionName > = ContractFunctionArgs, config extends Config = Config, > = viem_ReadContractParameters & ChainIdParameter export type ReadContractReturnType< abi extends Abi | readonly unknown[] = Abi, functionName extends ContractFunctionName< abi, 'pure' | 'view' > = ContractFunctionName, args extends ContractFunctionArgs< abi, 'pure' | 'view', functionName > = ContractFunctionArgs, > = viem_ReadContractReturnType export type ReadContractErrorType = viem_ReadContractErrorType /** https://wagmi.sh/core/api/actions/readContract */ export function readContract< config extends Config, const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, const args extends ContractFunctionArgs, >( config: config, parameters: ReadContractParameters, ): Promise> { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_readContract, 'readContract') return action(rest as any) } ================================================ FILE: packages/core/src/actions/readContracts.test-d.ts ================================================ import { abi, config } from '@wagmi/test' import { assertType, expectTypeOf, test } from 'vitest' import { readContracts } from './readContracts.js' test('default', async () => { const result = await readContracts(config, { contracts: [ { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], chainId: 1, }, { address: '0x', abi: abi.wagmiMintExample, functionName: 'tokenURI', args: [123n], }, ], }) expectTypeOf(result).toEqualTypeOf< [ ( | { error: Error; result?: undefined; status: 'failure' } | { error?: undefined; result: bigint; status: 'success' } ), ( | { error: Error; result?: undefined; status: 'failure' } | { error?: undefined; result: string; status: 'success' } ), ] >() }) test('allowFailure', async () => { const result = await readContracts(config, { allowFailure: false, contracts: [ { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }, { address: '0x', abi: abi.wagmiMintExample, functionName: 'tokenURI', args: [123n], }, ], }) expectTypeOf(result).toEqualTypeOf<[bigint, string]>() }) test('overloads', async () => { const result1 = await readContracts(config, { allowFailure: false, contracts: [ { address: '0x', abi: abi.viewOverloads, functionName: 'foo', }, ], }) assertType<[number] | undefined>(result1) const result2 = await readContracts(config, { allowFailure: false, contracts: [ { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: [], }, ], }) assertType<[number] | undefined>(result2) const result3 = await readContracts(config, { allowFailure: false, contracts: [ { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x'], }, ], }) assertType<[string] | undefined>(result3) const result4 = await readContracts(config, { allowFailure: false, contracts: [ { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x', '0x'], }, ], }) assertType< | [ { foo: `0x${string}` bar: `0x${string}` }, ] | undefined >(result4) }) ================================================ FILE: packages/core/src/actions/readContracts.test.ts ================================================ import { abi, address, chain } from '@wagmi/test' import { http, type MulticallResponse } from 'viem' import { expect, expectTypeOf, test, vi } from 'vitest' import { createConfig } from '../createConfig.js' import * as multicall from './multicall.js' import * as readContract from './readContract.js' import { readContracts } from './readContracts.js' const contracts = [ { abi: abi.wagmigotchi, address: address.wagmigotchi, functionName: 'love', args: ['0x27a69ffba1e939ddcfecc8c7e0f967b872bac65c'], }, { abi: abi.wagmigotchi, address: address.wagmigotchi, functionName: 'love', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }, { abi: abi.wagmigotchi, address: address.wagmigotchi, functionName: 'getAlive', }, { abi: abi.mloot, address: address.mloot, functionName: 'tokenOfOwnerByIndex', args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 0n], }, ] const { mainnet, mainnet2, optimism } = chain const config = createConfig({ chains: [ { ...mainnet, contracts: { multicall3: undefined } }, { ...mainnet2, contracts: { multicall3: undefined } }, ], transports: { [mainnet.id]: http(), [mainnet2.id]: http(), }, }) test('default', async () => { const spy = vi.spyOn(multicall, 'multicall') const config = createConfig({ chains: [mainnet, mainnet2], transports: { [mainnet.id]: http(), [mainnet2.id]: http(), }, }) const results = await readContracts(config, { contracts }) expect(spy).toHaveBeenCalledWith(config, { allowFailure: true, contracts, chainId: mainnet.id, }) expect(results).toMatchInlineSnapshot(` [ { "result": 2n, "status": "success", }, { "result": 1n, "status": "success", }, { "result": false, "status": "success", }, { "result": 370395n, "status": "success", }, ] `) }) test('falls back to readContract if multicall is not available', async () => { const spy = vi.spyOn(readContract, 'readContract') const config = createConfig({ chains: [mainnet, { ...mainnet2, contracts: { multicall3: undefined } }], transports: { [mainnet.id]: http(), [mainnet2.id]: http(), }, }) const chainId = mainnet2.id const contracts = [ { abi: abi.wagmigotchi, address: address.wagmigotchi, chainId: mainnet2.id, functionName: 'love', args: ['0x27a69ffba1e939ddcfecc8c7e0f967b872bac65c'], }, { abi: abi.wagmigotchi, address: address.wagmigotchi, chainId: mainnet2.id, functionName: 'love', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }, { abi: abi.wagmigotchi, address: address.wagmigotchi, chainId: mainnet2.id, functionName: 'getAlive', }, { abi: abi.mloot, address: address.mloot, chainId: mainnet2.id, functionName: 'tokenOfOwnerByIndex', args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 0n], }, ] as const const results = await readContracts(config, { contracts }) expectTypeOf(results).toEqualTypeOf< [ MulticallResponse, MulticallResponse, MulticallResponse, MulticallResponse, ] >() for (const contract of contracts) { expect(spy).toBeCalledWith(config, { ...contract, chainId }) } expect(results).toMatchInlineSnapshot(` [ { "result": 2n, "status": "success", }, { "result": 1n, "status": "success", }, { "result": false, "status": "success", }, { "result": 370395n, "status": "success", }, ] `) }) test('multichain', async () => { const config = createConfig({ chains: [mainnet, mainnet2, optimism], transports: { [mainnet.id]: http(), [mainnet2.id]: http(), [optimism.id]: http(), }, }) const spy = vi.spyOn(multicall, 'multicall') const mainnetContracts = [ { abi: abi.wagmigotchi, address: address.wagmigotchi, chainId: mainnet.id, functionName: 'love', args: ['0x27a69ffba1e939ddcfecc8c7e0f967b872bac65c'], }, { abi: abi.wagmigotchi, address: address.wagmigotchi, chainId: mainnet.id, functionName: 'love', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }, { abi: abi.wagmigotchi, address: address.wagmigotchi, chainId: mainnet.id, functionName: 'love', args: ['0xd2135CfB216b74109775236E36d4b433F1DF507B'], }, ] as const const mainnet2Contracts = [ { abi: abi.wagmigotchi, address: address.wagmigotchi, chainId: mainnet2.id, functionName: 'getAlive', }, { abi: abi.mloot, address: address.mloot, chainId: mainnet2.id, functionName: 'tokenOfOwnerByIndex', args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 0n], }, ] as const // const optimismContracts = [ // { // abi: abi.erc20, // address: address.optimism.usdc, // chainId: optimism.id, // functionName: 'symbol', // }, // { // abi: abi.erc20, // address: address.optimism.usdc, // chainId: optimism.id, // functionName: 'balanceOf', // args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], // }, // ] as const const results = await readContracts(config, { contracts: [ mainnetContracts[0]!, // optimismContracts[0]!, mainnetContracts[1]!, mainnet2Contracts[0]!, // optimismContracts[1]!, mainnet2Contracts[1]!, mainnetContracts[2]!, ], }) expectTypeOf(results).toEqualTypeOf< [ MulticallResponse, // MulticallResponse, MulticallResponse, MulticallResponse, // MulticallResponse, MulticallResponse, MulticallResponse, ] >() expect(spy).toHaveBeenCalledWith(config, { allowFailure: true, contracts: mainnetContracts, chainId: mainnet.id, overrides: undefined, }) expect(spy).toHaveBeenCalledWith(config, { allowFailure: true, contracts: mainnet2Contracts, chainId: mainnet2.id, overrides: undefined, }) expect(results).toMatchInlineSnapshot(` [ { "result": 2n, "status": "success", }, { "result": 1n, "status": "success", }, { "result": false, "status": "success", }, { "result": 370395n, "status": "success", }, { "result": 0n, "status": "success", }, ] `) }, 60_000) test('multichain: falls back to readContract if multicall is not available', async () => { const config = createConfig({ chains: [{ ...mainnet, contracts: { multicall3: undefined } }, optimism], transports: { [mainnet.id]: http(), [optimism.id]: http(), }, }) const spy = vi.spyOn(readContract, 'readContract') const mainnetContracts = [ { abi: abi.wagmigotchi, address: address.wagmigotchi, chainId: mainnet.id, functionName: 'love', args: ['0x27a69ffba1e939ddcfecc8c7e0f967b872bac65c'], }, { abi: abi.wagmigotchi, address: address.wagmigotchi, chainId: mainnet.id, functionName: 'love', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }, ] as const // const optimismContracts = [ // { // abi: abi.erc20, // address: address.optimism.usdc, // chainId: optimism.id, // functionName: 'symbol', // }, // { // abi: abi.erc20, // address: address.optimism.usdc, // chainId: optimism.id, // functionName: 'balanceOf', // args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], // }, // ] as const const results = await readContracts(config, { contracts: [...mainnetContracts /** ...optimismContracts */], }) expectTypeOf(results).toEqualTypeOf< [ MulticallResponse, MulticallResponse, // MulticallResponse, // MulticallResponse, ] >() for (const contract of mainnetContracts) { expect(spy).toBeCalledWith(config, { ...contract, chainId: mainnet.id }) } // for (const contract of optimismContracts) { // expect(spy).toBeCalledWith(config, { ...contract, chainId: optimism.id }) // } expect(results).toMatchInlineSnapshot(` [ { "result": 2n, "status": "success", }, { "result": 1n, "status": "success", }, ] `) }, 15_000) test('throws if allowFailure=false & a contract method fails', async () => { await expect( readContracts(config, { allowFailure: false, contracts: [ ...contracts, { abi: abi.mloot, address: address.mloot, functionName: 'tokenOfOwnerByIndex', args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 69420n], }, ], }), ).rejects.toThrowErrorMatchingInlineSnapshot( ` [ContractFunctionExecutionError: The contract function "tokenOfOwnerByIndex" reverted with the following reason: ERC721Enumerable: owner index out of bounds Contract Call: address: 0x1dfe7ca09e99d10835bf73044a23b73fc20623df function: tokenOfOwnerByIndex(address owner, uint256 index) args: (0xA0Cf798816D4b9b9866b5330EEa46a18382f251e, 69420) Docs: https://viem.sh/docs/contract/readContract Details: execution reverted: ERC721Enumerable: owner index out of bounds Version: viem@2.47.5] `, ) }) test('allowFailure=true & a contract method fails', async () => { expect( await readContracts(config, { allowFailure: true, contracts: [ ...contracts, { abi: abi.mloot, address: address.mloot, functionName: 'tokenOfOwnerByIndex', args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 69420n], }, { abi: abi.mloot, address: address.mloot, functionName: 'tokenOfOwnerByIndex', args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 69421n], }, ], }), ).toMatchInlineSnapshot(` [ { "result": 2n, "status": "success", }, { "result": 1n, "status": "success", }, { "result": false, "status": "success", }, { "result": 370395n, "status": "success", }, { "error": [ContractFunctionExecutionError: The contract function "tokenOfOwnerByIndex" reverted with the following reason: ERC721Enumerable: owner index out of bounds Contract Call: address: 0x1dfe7ca09e99d10835bf73044a23b73fc20623df function: tokenOfOwnerByIndex(address owner, uint256 index) args: (0xA0Cf798816D4b9b9866b5330EEa46a18382f251e, 69420) Docs: https://viem.sh/docs/contract/readContract Details: execution reverted: ERC721Enumerable: owner index out of bounds Version: viem@2.47.5], "result": undefined, "status": "failure", }, { "error": [ContractFunctionExecutionError: The contract function "tokenOfOwnerByIndex" reverted with the following reason: ERC721Enumerable: owner index out of bounds Contract Call: address: 0x1dfe7ca09e99d10835bf73044a23b73fc20623df function: tokenOfOwnerByIndex(address owner, uint256 index) args: (0xA0Cf798816D4b9b9866b5330EEa46a18382f251e, 69421) Docs: https://viem.sh/docs/contract/readContract Details: execution reverted: ERC721Enumerable: owner index out of bounds Version: viem@2.47.5], "result": undefined, "status": "failure", }, ] `) }) test('throws if allowFailure=false & encoding contract function data fails', async () => { await expect( readContracts(config, { allowFailure: false, contracts: [ ...contracts, { abi: abi.mloot, functionName: 'ownerOf', // address is not the mloot contract address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', args: [10e30], }, ], }), ).rejects.toThrowErrorMatchingInlineSnapshot( ` [ContractFunctionExecutionError: The contract function "ownerOf" returned no data ("0x"). This could be due to any of the following: - The contract does not have the function "ownerOf", - The parameters passed to the contract function may be invalid, or - The address is not a contract. Contract Call: address: 0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC function: ownerOf(uint256 tokenId) args: (1e+31) Docs: https://viem.sh/docs/contract/readContract Version: viem@2.47.5] `, ) }) test('allowFailure=true & encoding contract function data fails', async () => { expect( await readContracts(config, { allowFailure: true, contracts: [ ...contracts, { abi: abi.mloot, functionName: 'ownerOf', // address is not the mloot contract address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', args: [10e30], }, { abi: abi.mloot, functionName: 'ownerOf', // address is not the mloot contract address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', args: [10e30], }, ], }), ).toMatchInlineSnapshot(` [ { "result": 2n, "status": "success", }, { "result": 1n, "status": "success", }, { "result": false, "status": "success", }, { "result": 370395n, "status": "success", }, { "error": [ContractFunctionExecutionError: The contract function "ownerOf" returned no data ("0x"). This could be due to any of the following: - The contract does not have the function "ownerOf", - The parameters passed to the contract function may be invalid, or - The address is not a contract. Contract Call: address: 0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC function: ownerOf(uint256 tokenId) args: (1e+31) Docs: https://viem.sh/docs/contract/readContract Version: viem@2.47.5], "result": undefined, "status": "failure", }, { "error": [ContractFunctionExecutionError: The contract function "ownerOf" returned no data ("0x"). This could be due to any of the following: - The contract does not have the function "ownerOf", - The parameters passed to the contract function may be invalid, or - The address is not a contract. Contract Call: address: 0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC function: ownerOf(uint256 tokenId) args: (1e+31) Docs: https://viem.sh/docs/contract/readContract Version: viem@2.47.5], "result": undefined, "status": "failure", }, ] `) }) test('should throw if allowFailure=false & a contract has no response', async () => { await expect( readContracts(config, { allowFailure: false, contracts: [ ...contracts, { abi: abi.wagmigotchi, functionName: 'love', // address is not the wagmigotchi contract address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }, ], }), ).rejects.toThrowErrorMatchingInlineSnapshot( ` [ContractFunctionExecutionError: The contract function "love" returned no data ("0x"). This could be due to any of the following: - The contract does not have the function "love", - The parameters passed to the contract function may be invalid, or - The address is not a contract. Contract Call: address: 0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC function: love(address) args: (0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC) Docs: https://viem.sh/docs/contract/readContract Version: viem@2.47.5] `, ) }) test('allowFailure=true & a contract has no response', async () => { expect( await readContracts(config, { allowFailure: true, contracts: [ ...contracts, { abi: abi.wagmigotchi, functionName: 'love', // address is not the wagmigotchi contract address: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }, ], }), ).toMatchInlineSnapshot(` [ { "result": 2n, "status": "success", }, { "result": 1n, "status": "success", }, { "result": false, "status": "success", }, { "result": 370395n, "status": "success", }, { "error": [ContractFunctionExecutionError: The contract function "love" returned no data ("0x"). This could be due to any of the following: - The contract does not have the function "love", - The parameters passed to the contract function may be invalid, or - The address is not a contract. Contract Call: address: 0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC function: love(address) args: (0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC) Docs: https://viem.sh/docs/contract/readContract Version: viem@2.47.5], "result": undefined, "status": "failure", }, ] `) }) ================================================ FILE: packages/core/src/actions/readContracts.ts ================================================ import type { ContractFunctionParameters, MulticallParameters as viem_MulticallParameters, MulticallReturnType as viem_MulticallReturnType, } from 'viem' import { ContractFunctionExecutionError } from 'viem' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import { type MulticallErrorType, multicall } from './multicall.js' import { type ReadContractErrorType, readContract } from './readContract.js' export type ReadContractsParameters< contracts extends readonly unknown[] = readonly ContractFunctionParameters[], allowFailure extends boolean = true, config extends Config = Config, > = viem_MulticallParameters< contracts, allowFailure, { properties: ChainIdParameter } > export type ReadContractsReturnType< contracts extends readonly unknown[] = readonly ContractFunctionParameters[], allowFailure extends boolean = true, > = viem_MulticallReturnType export type ReadContractsErrorType = MulticallErrorType | ReadContractErrorType export async function readContracts< config extends Config, const contracts extends readonly ContractFunctionParameters[], allowFailure extends boolean = true, >( config: config, parameters: ReadContractsParameters, ): Promise> { const { allowFailure = true, blockNumber, blockTag, ...rest } = parameters const contracts = parameters.contracts as (ContractFunctionParameters & { chainId?: number | undefined })[] try { const contractsByChainId: { [chainId: number]: { contract: ContractFunctionParameters index: number }[] } = {} for (const [index, contract] of contracts.entries()) { const chainId = contract.chainId ?? config.state.chainId if (!contractsByChainId[chainId]) contractsByChainId[chainId] = [] contractsByChainId[chainId]?.push({ contract, index }) } const promises = () => Object.entries(contractsByChainId).map(([chainId, contracts]) => multicall(config, { ...rest, allowFailure, blockNumber, blockTag, chainId: Number.parseInt(chainId, 10), contracts: contracts.map(({ contract }) => contract), }), ) const multicallResults = (await Promise.all(promises())).flat() // Reorder the contract results back to the order they were // provided in. const resultIndexes = Object.values(contractsByChainId).flatMap( (contracts) => contracts.map(({ index }) => index), ) return multicallResults.reduce((results, result, index) => { if (results) (results as unknown[])[resultIndexes[index]!] = result return results }, [] as unknown[]) as ReadContractsReturnType } catch (error) { if (error instanceof ContractFunctionExecutionError) throw error const promises = () => contracts.map((contract) => readContract(config, { ...contract, blockNumber, blockTag }), ) if (allowFailure) return (await Promise.allSettled(promises())).map((result) => { if (result.status === 'fulfilled') return { result: result.value, status: 'success' } return { error: result.reason, result: undefined, status: 'failure' } }) as ReadContractsReturnType return (await Promise.all(promises())) as ReadContractsReturnType< contracts, allowFailure > } } ================================================ FILE: packages/core/src/actions/reconnect.test.ts ================================================ import { accounts, config, mainnet } from '@wagmi/test' import { http } from 'viem' import { afterEach, expect, test, vi } from 'vitest' import { mock } from '../connectors/mock.js' import { createConfig } from '../createConfig.js' import { createStorage } from '../createStorage.js' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { reconnect } from './reconnect.js' const connector = config._internal.connectors.setup( mock({ accounts, features: { reconnect: true }, }), ) afterEach(async () => { if (config.state.current === connector.uid) await disconnect(config, { connector }) else if (config.state.current) await disconnect(config) }) test('default', async () => { await expect( reconnect(config, { connectors: [connector] }), ).resolves.toStrictEqual([]) expect(config.state.status).toEqual('disconnected') }) test('parameters: connectors (Connector)', async () => { await connect(config, { connector }) await expect( reconnect(config, { connectors: [connector] }), ).resolves.toMatchObject( expect.arrayContaining([ expect.objectContaining({ accounts: expect.any(Array), chainId: expect.any(Number), }), ]), ) expect(config.state.status).toEqual('connected') }) test('parameters: connectors (CreateConnectorFn)', async () => { const connector = mock({ accounts, features: { reconnect: true }, }) await connect(config, { connector }) await expect( reconnect(config, { connectors: [connector] }), ).resolves.toMatchObject( expect.arrayContaining([ expect.objectContaining({ accounts: expect.any(Array), chainId: expect.any(Number), }), ]), ) expect(config.state.status).toEqual('connected') }) test("behavior: doesn't reconnect if already reconnecting", async () => { const previousStatus = config.state.status config.setState((x) => ({ ...x, status: 'reconnecting' })) await expect( reconnect(config, { connectors: [connector] }), ).resolves.toStrictEqual([]) config.setState((x) => ({ ...x, status: previousStatus })) }) test('behavior: recovers from invalid state', async () => { const state = { 'wagmi.store': JSON.stringify({ state: { status: 'connected', // <-- invalid - `status` should not be kept in storage chainId: 1, current: '983b8aca245', }, version: Number.NaN, // mocked version is `'x.y.z'`, which will get interpreted as `NaN` }), } as Record Object.defineProperty(window, 'localStorage', { value: { getItem: vi.fn((key) => state[key] ?? null), removeItem: vi.fn((key) => state.delete?.[key]), setItem: vi.fn((key, value) => { state[key] = value }), }, writable: true, }) const storage = createStorage<{ store: object }>({ storage: window.localStorage, }) const config = createConfig({ chains: [mainnet], storage, transports: { [mainnet.id]: http(), }, }) await reconnect(config, { connectors: [connector] }) expect(config.state).toMatchInlineSnapshot(` { "chainId": 1, "connections": Map {}, "current": null, "status": "disconnected", } `) }) ================================================ FILE: packages/core/src/actions/reconnect.ts ================================================ import type { Address } from 'viem' import type { CreateConnectorFn } from '../connectors/createConnector.js' import type { Config, Connection, Connector } from '../createConfig.js' import type { ErrorType } from '../errors/base.js' import type { Compute } from '../types/utils.js' export type ReconnectParameters = { /** Connectors to attempt reconnect with */ connectors?: readonly (CreateConnectorFn | Connector)[] | undefined } export type ReconnectReturnType = Compute[] export type ReconnectErrorType = ErrorType let isReconnecting = false /** https://wagmi.sh/core/api/actions/reconnect */ export async function reconnect( config: Config, parameters: ReconnectParameters = {}, ): Promise { // If already reconnecting, do nothing if (isReconnecting) return [] isReconnecting = true config.setState((x) => ({ ...x, status: x.current ? 'reconnecting' : 'connecting', })) const connectors: Connector[] = [] if (parameters.connectors?.length) { for (const connector_ of parameters.connectors) { let connector: Connector // "Register" connector if not already created if (typeof connector_ === 'function') connector = config._internal.connectors.setup(connector_) else connector = connector_ connectors.push(connector) } } else connectors.push(...config.connectors) // Try recently-used connectors first let recentConnectorId: string | null | undefined try { recentConnectorId = await config.storage?.getItem('recentConnectorId') } catch {} const scores: Record = {} for (const [, connection] of config.state.connections) { scores[connection.connector.id] = 1 } if (recentConnectorId) scores[recentConnectorId] = 0 const sorted = Object.keys(scores).length > 0 ? // .toSorted() [...connectors].sort( (a, b) => (scores[a.id] ?? 10) - (scores[b.id] ?? 10), ) : connectors // Iterate through each connector and try to connect let connected = false const connections: Connection[] = [] const providers: unknown[] = [] for (const connector of sorted) { const provider = await connector.getProvider().catch(() => undefined) if (!provider) continue // If we already have an instance of this connector's provider, // then we have already checked it (ie. injected connectors can // share the same `window.ethereum` instance, so we don't want to // connect to it again). if (providers.some((x) => x === provider)) continue const isAuthorized = await connector.isAuthorized() if (!isAuthorized) continue const data = await connector .connect({ isReconnecting: true }) .catch(() => null) if (!data) continue connector.emitter.off('connect', config._internal.events.connect) connector.emitter.on('change', config._internal.events.change) connector.emitter.on('disconnect', config._internal.events.disconnect) config.setState((x) => { const connections = new Map(connected ? x.connections : new Map()).set( connector.uid, { accounts: data.accounts, chainId: data.chainId, connector }, ) return { ...x, current: connected ? x.current : connector.uid, connections, } }) connections.push({ accounts: data.accounts as readonly [Address, ...Address[]], chainId: data.chainId, connector, }) providers.push(provider) connected = true } // Prevent overwriting connected status from race condition if ( config.state.status === 'reconnecting' || config.state.status === 'connecting' ) { // If connecting didn't succeed, set to disconnected if (!connected) config.setState((x) => ({ ...x, connections: new Map(), current: null, status: 'disconnected', })) else config.setState((x) => ({ ...x, status: 'connected' })) } isReconnecting = false return connections } ================================================ FILE: packages/core/src/actions/sendCalls.test.ts ================================================ import { accounts, config } from '@wagmi/test' import { parseEther } from 'viem' import { expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { sendCalls } from './sendCalls.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) await expect( sendCalls(config, { calls: [ { data: '0xdeadbeef', to: accounts[1], value: parseEther('1'), }, { to: accounts[2], value: parseEther('2'), }, { to: accounts[3], value: parseEther('3'), }, ], }), ).resolves.toMatchInlineSnapshot( ` { "id": "0xb24b52a86aa2b0bae6f1e44868c3a13d2572e766a1f6364afd93d1757839b8a1", } `, ) await disconnect(config, { connector }) }) test('behavior: not connected', async () => { await expect( sendCalls(config, { calls: [ { to: accounts[1], value: parseEther('1'), }, { to: accounts[2], value: parseEther('2'), }, { to: accounts[3], value: parseEther('3'), }, ], }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ConnectorNotConnectedError: Connector not connected. Version: @wagmi/core@x.y.z] `) }) test('behavior: nullish account (account filled by wallet)', async () => { await expect( sendCalls(config, { account: null, connector, calls: [ { to: accounts[1], value: parseEther('1'), }, { to: accounts[2], value: parseEther('2'), }, { to: accounts[3], value: parseEther('3'), }, ], }), ).resolves.toMatchInlineSnapshot( ` { "id": "0x0a8b20024fae14dd9e854accfc8496b9d18c291206647c842a96a954133401f3", } `, ) }) test('behavior: account does not exist on connector', async () => { await connect(config, { connector }) await expect( sendCalls(config, { account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', calls: [ { to: accounts[1], value: parseEther('1'), }, { to: accounts[2], value: parseEther('2'), }, { to: accounts[3], value: parseEther('3'), }, ], }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ConnectorAccountNotFoundError: Account "0xA0Cf798816D4b9b9866b5330EEa46a18382f251e" not found for connector "Mock Connector". Version: @wagmi/core@x.y.z] `) await disconnect(config, { connector }) }) ================================================ FILE: packages/core/src/actions/sendCalls.ts ================================================ import type { Account, Chain } from 'viem' import { type SendCallsErrorType as viem_SendCallsErrorType, type SendCallsParameters as viem_SendCallsParameters, type SendCallsReturnType as viem_SendCallsReturnType, sendCalls as viem_sendCalls, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { BaseErrorType, ErrorType } from '../errors/base.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter, ConnectorParameter, } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' import { type GetConnectorClientErrorType, getConnectorClient, } from './getConnectorClient.js' export type SendCallsParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], calls extends readonly unknown[] = readonly unknown[], /// chains extends readonly Chain[] = SelectChains, > = { [key in keyof chains]: Compute< Omit< viem_SendCallsParameters, 'chain' > & ChainIdParameter & ConnectorParameter > }[number] export type SendCallsReturnType = viem_SendCallsReturnType export type SendCallsErrorType = // getConnectorClient() | GetConnectorClientErrorType // base | BaseErrorType | ErrorType // viem | viem_SendCallsErrorType /** https://wagmi.sh/core/api/actions/sendCalls */ export async function sendCalls< const calls extends readonly unknown[], config extends Config, chainId extends config['chains'][number]['id'], >( config: config, parameters: SendCallsParameters, ): Promise { const { account, chainId, connector, calls, ...rest } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) const action = getAction(client, viem_sendCalls, 'sendCalls') return action({ ...(rest as any), ...(typeof account !== 'undefined' ? { account } : {}), calls, chain: chainId ? { id: chainId } : undefined, }) } ================================================ FILE: packages/core/src/actions/sendCallsSync.test.ts ================================================ import { accounts, config, testClient, wait } from '@wagmi/test' import { parseEther } from 'viem' import { beforeEach, expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { sendCallsSync } from './sendCallsSync.js' const connector = config.connectors[0]! beforeEach(async () => { await disconnect(config).catch(() => {}) }) test('default', async () => { await connect(config, { connector }) const [status] = await Promise.all([ sendCallsSync(config, { calls: [ { data: '0xdeadbeef', to: accounts[1], value: parseEther('1'), }, { to: accounts[2], value: parseEther('2'), }, { to: accounts[3], value: parseEther('3'), }, ], }), (async () => { await wait(3000) await testClient.mainnet.mine({ blocks: 1 }) })(), ]) expect(status).toBeDefined() await disconnect(config, { connector }) }) test('behavior: not connected', async () => { await expect( sendCallsSync(config, { calls: [ { to: accounts[1], value: parseEther('1'), }, { to: accounts[2], value: parseEther('2'), }, { to: accounts[3], value: parseEther('3'), }, ], }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ConnectorNotConnectedError: Connector not connected. Version: @wagmi/core@x.y.z] `) }) test('behavior: account does not exist on connector', async () => { await connect(config, { connector }) await expect( sendCallsSync(config, { account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', calls: [ { to: accounts[1], value: parseEther('1'), }, { to: accounts[2], value: parseEther('2'), }, { to: accounts[3], value: parseEther('3'), }, ], }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ConnectorAccountNotFoundError: Account "0xA0Cf798816D4b9b9866b5330EEa46a18382f251e" not found for connector "Mock Connector". Version: @wagmi/core@x.y.z] `) await disconnect(config, { connector }) }) ================================================ FILE: packages/core/src/actions/sendCallsSync.ts ================================================ import type { Account, Chain } from 'viem' import { type SendCallsSyncErrorType as viem_SendCallsSyncErrorType, type SendCallsSyncParameters as viem_SendCallsSyncParameters, type SendCallsSyncReturnType as viem_SendCallsSyncReturnType, sendCallsSync as viem_sendCallsSync, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { BaseErrorType, ErrorType } from '../errors/base.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter, ConnectorParameter, } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' import { type GetConnectorClientErrorType, getConnectorClient, } from './getConnectorClient.js' export type SendCallsSyncParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], calls extends readonly unknown[] = readonly unknown[], /// chains extends readonly Chain[] = SelectChains, > = { [key in keyof chains]: Compute< Omit< viem_SendCallsSyncParameters, 'chain' > & ChainIdParameter & ConnectorParameter > }[number] export type SendCallsSyncReturnType = viem_SendCallsSyncReturnType export type SendCallsSyncErrorType = // getConnectorClient() | GetConnectorClientErrorType // base | BaseErrorType | ErrorType // viem | viem_SendCallsSyncErrorType /** https://wagmi.sh/core/api/actions/sendCallsSync */ export async function sendCallsSync< const calls extends readonly unknown[], config extends Config, chainId extends config['chains'][number]['id'], >( config: config, parameters: SendCallsSyncParameters, ): Promise { const { account, chainId, connector, calls, ...rest } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) const action = getAction(client, viem_sendCallsSync, 'sendCallsSync') return action({ ...(rest as any), ...(typeof account !== 'undefined' ? { account } : {}), calls, chain: chainId ? { id: chainId } : undefined, }) } ================================================ FILE: packages/core/src/actions/sendTransaction.test-d.ts ================================================ import { http, parseEther } from 'viem' import { celo, mainnet } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { type SendTransactionParameters, sendTransaction, } from './sendTransaction.js' test('chain formatters', () => { const config = createConfig({ chains: [mainnet, celo], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) type Result = SendTransactionParameters expectTypeOf().toMatchTypeOf<{ chainId?: typeof celo.id | typeof mainnet.id | undefined feeCurrency?: `0x${string}` | undefined }>() sendTransaction(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), feeCurrency: '0x', }) type Result2 = SendTransactionParameters expectTypeOf().toMatchTypeOf<{ feeCurrency?: `0x${string}` | undefined }>() sendTransaction(config, { chainId: celo.id, to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), feeCurrency: '0x', }) type Result3 = SendTransactionParameters expectTypeOf().not.toMatchTypeOf<{ feeCurrency?: `0x${string}` | undefined }>() sendTransaction(config, { chainId: mainnet.id, to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), // @ts-expect-error feeCurrency: '0x', }) }) ================================================ FILE: packages/core/src/actions/sendTransaction.test.ts ================================================ import { config, privateKey, transactionHashRegex } from '@wagmi/test' import { parseEther } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { beforeEach, expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { sendTransaction } from './sendTransaction.js' const connector = config.connectors[0]! beforeEach(async () => { if (config.state.current === connector.uid) await disconnect(config, { connector }) }) test('default', async () => { const result = await connect(config, { connector }) config.state.connections.set(connector.uid, { ...result, // Switch up the current account because the default one is running out of funds somewhere accounts: result.accounts.slice(1) as unknown as typeof result.accounts, connector, }) await expect( sendTransaction(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.0001'), }), ).resolves.toMatch(transactionHashRegex) await disconnect(config, { connector }) }) test('behavior: connector not connected', async () => { await connect(config, { connector }) await expect( sendTransaction(config, { connector: config.connectors[1], to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.0001'), }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ConnectorNotConnectedError: Connector not connected. Version: @wagmi/core@x.y.z] `) await disconnect(config, { connector }) }) test('behavior: account does not exist on connector', async () => { await connect(config, { connector }) await expect( sendTransaction(config, { account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.0001'), }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ConnectorAccountNotFoundError: Account "0xA0Cf798816D4b9b9866b5330EEa46a18382f251e" not found for connector "Mock Connector". Version: @wagmi/core@x.y.z] `) await disconnect(config, { connector }) }) test('behavior: value exceeds balance', async () => { await connect(config, { connector }) await expect( sendTransaction(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('99999'), }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [TransactionExecutionError: The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account. This error could arise when the account does not have enough funds to: - pay for the total gas fee, - pay for the value to send. The cost of the transaction is calculated as \`gas * gas fee + value\`, where: - \`gas\` is the amount of gas needed for transaction to execute, - \`gas fee\` is the gas fee, - \`value\` is the amount of ether to send to the recipient. Request Arguments: chain: Ethereum (id: 1) from: 0x95132632579b073D12a6673e18Ab05777a6B86f8 to: 0xd2135CfB216b74109775236E36d4b433F1DF507B value: 99999 ETH Details: Insufficient funds for gas * price + value Version: viem@2.47.5] `) await disconnect(config, { connector }) }) test('behavior: local account', async () => { const account = privateKeyToAccount(privateKey) await expect( sendTransaction(config, { account, to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.000001'), }), ).resolves.toMatch(transactionHashRegex) }) ================================================ FILE: packages/core/src/actions/sendTransaction.ts ================================================ import type { Account, Chain, Client, TransactionRequest, SendTransactionErrorType as viem_SendTransactionErrorType, SendTransactionParameters as viem_SendTransactionParameters, SendTransactionReturnType as viem_SendTransactionReturnType, } from 'viem' import { sendTransaction as viem_sendTransaction } from 'viem/actions' import type { Config } from '../createConfig.js' import type { BaseErrorType, ErrorType } from '../errors/base.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter, ConnectorParameter, } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' import { type GetConnectorClientErrorType, getConnectorClient, } from './getConnectorClient.js' export type SendTransactionParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], /// chains extends readonly Chain[] = SelectChains, > = { [key in keyof chains]: Compute< Omit< viem_SendTransactionParameters, 'chain' | 'gas' > & ChainIdParameter & ConnectorParameter > }[number] & { /** Gas provided for transaction execution. */ gas?: TransactionRequest['gas'] | null } export type SendTransactionReturnType = viem_SendTransactionReturnType export type SendTransactionErrorType = // getConnectorClient() | GetConnectorClientErrorType // base | BaseErrorType | ErrorType // viem | viem_SendTransactionErrorType /** https://wagmi.sh/core/api/actions/sendTransaction */ export async function sendTransaction< config extends Config, chainId extends config['chains'][number]['id'], >( config: config, parameters: SendTransactionParameters, ): Promise { const { account, chainId, connector, ...rest } = parameters let client: Client if (typeof account === 'object' && account?.type === 'local') client = config.getClient({ chainId }) else client = await getConnectorClient(config, { account: account ?? undefined, assertChainId: false, chainId, connector, }) const chain = (() => { if (!chainId || client.chain?.id === chainId) return client.chain return { id: chainId } })() const action = getAction(client, viem_sendTransaction, 'sendTransaction') const hash = await action({ ...(rest as any), ...(account ? { account } : {}), assertChainId: !!chainId, chain, gas: rest.gas ?? undefined, }) return hash } ================================================ FILE: packages/core/src/actions/sendTransactionSync.test.ts ================================================ import { config, testClient, wait } from '@wagmi/test' import { parseEther } from 'viem' import { beforeEach, expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { sendTransactionSync } from './sendTransactionSync.js' const connector = config.connectors[0]! beforeEach(async () => { if (config.state.current === connector.uid) await disconnect(config, { connector }) }) test('default', async () => { const result = await connect(config, { connector }) config.state.connections.set(connector.uid, { ...result, // Switch up the current account because the default one is running out of funds somewhere accounts: result.accounts.slice(1) as unknown as typeof result.accounts, connector, }) const [receipt] = await Promise.all([ sendTransactionSync(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.0001'), }), (async () => { await wait(3000) await testClient.mainnet.mine({ blocks: 1 }) })(), ]) expect(receipt).toBeDefined() await disconnect(config, { connector }) }) test('behavior: connector not connected', async () => { await connect(config, { connector }) await expect( sendTransactionSync(config, { connector: config.connectors[1], to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.0001'), }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ConnectorNotConnectedError: Connector not connected. Version: @wagmi/core@x.y.z] `) await disconnect(config, { connector }) }) test('behavior: account does not exist on connector', async () => { await connect(config, { connector }) await expect( sendTransactionSync(config, { account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.0001'), }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ConnectorAccountNotFoundError: Account "0xA0Cf798816D4b9b9866b5330EEa46a18382f251e" not found for connector "Mock Connector". Version: @wagmi/core@x.y.z] `) await disconnect(config, { connector }) }) test('behavior: value exceeds balance', async () => { await connect(config, { connector }) await expect( sendTransactionSync(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('99999'), }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [TransactionExecutionError: The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account. This error could arise when the account does not have enough funds to: - pay for the total gas fee, - pay for the value to send. The cost of the transaction is calculated as \`gas * gas fee + value\`, where: - \`gas\` is the amount of gas needed for transaction to execute, - \`gas fee\` is the gas fee, - \`value\` is the amount of ether to send to the recipient. Request Arguments: chain: Ethereum (id: 1) from: 0x95132632579b073D12a6673e18Ab05777a6B86f8 to: 0xd2135CfB216b74109775236E36d4b433F1DF507B value: 99999 ETH Details: Insufficient funds for gas * price + value Version: viem@2.47.5] `) await disconnect(config, { connector }) }) ================================================ FILE: packages/core/src/actions/sendTransactionSync.ts ================================================ import type { Account, Chain, Client, TransactionRequest, SendTransactionSyncErrorType as viem_SendTransactionSyncErrorType, SendTransactionSyncParameters as viem_SendTransactionSyncParameters, SendTransactionSyncReturnType as viem_SendTransactionSyncReturnType, } from 'viem' import { sendTransactionSync as viem_sendTransactionSync } from 'viem/actions' import type { Config } from '../createConfig.js' import type { BaseErrorType, ErrorType } from '../errors/base.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter, ConnectorParameter, } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' import { type GetConnectorClientErrorType, getConnectorClient, } from './getConnectorClient.js' export type SendTransactionSyncParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], /// chains extends readonly Chain[] = SelectChains, > = { [key in keyof chains]: Compute< Omit< viem_SendTransactionSyncParameters, 'chain' | 'gas' > & ChainIdParameter & ConnectorParameter > }[number] & { /** Gas provided for transaction execution. */ gas?: TransactionRequest['gas'] | null } export type SendTransactionSyncReturnType = viem_SendTransactionSyncReturnType export type SendTransactionSyncErrorType = // getConnectorClient() | GetConnectorClientErrorType // base | BaseErrorType | ErrorType // viem | viem_SendTransactionSyncErrorType /** https://wagmi.sh/core/api/actions/sendTransactionSync */ export async function sendTransactionSync< config extends Config, chainId extends config['chains'][number]['id'], >( config: config, parameters: SendTransactionSyncParameters, ): Promise { const { account, chainId, connector, ...rest } = parameters let client: Client if (typeof account === 'object' && account?.type === 'local') client = config.getClient({ chainId }) else client = await getConnectorClient(config, { account: account ?? undefined, assertChainId: false, chainId, connector, }) const chain = (() => { if (!chainId || client.chain?.id === chainId) return client.chain return { id: chainId } })() const action = getAction( client, viem_sendTransactionSync, 'sendTransactionSync', ) const hash = await action({ ...(rest as any), ...(account ? { account } : {}), assertChainId: !!chainId, chain, gas: rest.gas ?? undefined, }) return hash } ================================================ FILE: packages/core/src/actions/showCallsStatus.test.ts ================================================ import { accounts, config, testClient } from '@wagmi/test' import { parseEther } from 'viem' import { test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { sendCalls } from './sendCalls.js' import { showCallsStatus } from './showCallsStatus.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const { id } = await sendCalls(config, { calls: [ { data: '0xdeadbeef', to: accounts[1], value: parseEther('1'), }, { to: accounts[2], value: parseEther('2'), }, { to: accounts[3], value: parseEther('3'), }, ], }) await testClient.mainnet.mine({ blocks: 1 }) await showCallsStatus(config, { id, }) await disconnect(config, { connector }) }) ================================================ FILE: packages/core/src/actions/showCallsStatus.ts ================================================ import { type ShowCallsStatusErrorType as viem_ShowCallsStatusErrorType, type ShowCallsStatusParameters as viem_ShowCallsStatusParameters, type ShowCallsStatusReturnType as viem_ShowCallsStatusReturnType, showCallsStatus as viem_showCallsStatus, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ConnectorParameter } from '../types/properties.js' import { getConnectorClient } from './getConnectorClient.js' export type ShowCallsStatusParameters = viem_ShowCallsStatusParameters & ConnectorParameter export type ShowCallsStatusReturnType = viem_ShowCallsStatusReturnType export type ShowCallsStatusErrorType = viem_ShowCallsStatusErrorType /** https://wagmi.sh/core/api/actions/showCallsStatus */ export async function showCallsStatus( config: config, parameters: ShowCallsStatusParameters, ): Promise { const { connector, id } = parameters const client = await getConnectorClient(config, { connector }) return viem_showCallsStatus(client, { id }) } ================================================ FILE: packages/core/src/actions/signMessage.test.ts ================================================ import { accounts, config, privateKey } from '@wagmi/test' import { recoverMessageAddress } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { expect, test } from 'vitest' import { mock } from '../connectors/mock.js' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { getConnection } from './getConnection.js' import { signMessage } from './signMessage.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const signature = await signMessage(config, { message: 'foo bar baz' }) await expect( recoverMessageAddress({ message: 'foo bar baz', signature, }), ).resolves.toEqual(getConnection(config).address) await disconnect(config, { connector }) }) test('behavior: local account', async () => { const account = privateKeyToAccount(privateKey) const signature = await signMessage(config, { account, message: 'foo bar baz', }) await expect( recoverMessageAddress({ message: 'foo bar baz', signature, }), ).resolves.toEqual(account.address) }) test('behavior: user rejected request', async () => { const connector_ = config._internal.connectors.setup( mock({ accounts, features: { signMessageError: true }, }), ) await connect(config, { connector: connector_ }) await expect( signMessage(config, { message: 'foo bar baz' }), ).rejects.toMatchInlineSnapshot(` [UserRejectedRequestError: User rejected the request. Details: Failed to sign message. Version: viem@2.47.5] `) await disconnect(config, { connector: connector_ }) }) test('behavior: not connected', async () => { await expect( signMessage(config, { message: 'foo bar baz' }), ).rejects.toMatchInlineSnapshot(` [ConnectorNotConnectedError: Connector not connected. Version: @wagmi/core@x.y.z] `) }) ================================================ FILE: packages/core/src/actions/signMessage.ts ================================================ import type { Account, Client } from 'viem' import { type SignMessageErrorType as viem_SignMessageErrorType, type SignMessageParameters as viem_SignMessageParameters, type SignMessageReturnType as viem_SignMessageReturnType, signMessage as viem_signMessage, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { BaseErrorType, ErrorType } from '../errors/base.js' import type { ConnectorParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' import { type GetConnectorClientErrorType, getConnectorClient, } from './getConnectorClient.js' export type SignMessageParameters = Compute< viem_SignMessageParameters & ConnectorParameter > export type SignMessageReturnType = viem_SignMessageReturnType export type SignMessageErrorType = // getConnectorClient() | GetConnectorClientErrorType // base | BaseErrorType | ErrorType // viem | viem_SignMessageErrorType /** https://wagmi.sh/core/api/actions/signMessage */ export async function signMessage( config: Config, parameters: SignMessageParameters, ): Promise { const { account, connector, ...rest } = parameters let client: Client if (typeof account === 'object' && account.type === 'local') client = config.getClient() else client = await getConnectorClient(config, { account, connector }) const action = getAction(client, viem_signMessage, 'signMessage') return action({ ...rest, ...(account ? { account } : {}), } as viem_SignMessageParameters) } ================================================ FILE: packages/core/src/actions/signTransaction.test-d.ts ================================================ import { config } from '@wagmi/test' import { http, parseEther, type TransactionSerializedEIP1559, type TransactionSerializedEIP2930, type TransactionSerializedEIP4844, type TransactionSerializedEIP7702, type TransactionSerializedLegacy, } from 'viem' import { celo, mainnet } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { type SignTransactionParameters, signTransaction, } from './signTransaction.js' test('chain formatters', () => { const config = createConfig({ chains: [mainnet, celo], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) type Result = SignTransactionParameters expectTypeOf().toMatchTypeOf<{ chainId?: typeof celo.id | typeof mainnet.id | undefined feeCurrency?: `0x${string}` | undefined }>() signTransaction(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) type Result2 = SignTransactionParameters expectTypeOf().toMatchTypeOf<{ feeCurrency?: `0x${string}` | undefined }>() signTransaction(config, { chainId: celo.id, to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), feeCurrency: '0x', }) type Result3 = SignTransactionParameters expectTypeOf().not.toMatchTypeOf<{ feeCurrency?: `0x${string}` | undefined }>() signTransaction(config, { chainId: mainnet.id, to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) }) test('legacy', () => { const signature1 = signTransaction(config, { gasPrice: 0n }) const signature2 = signTransaction(config, { type: 'legacy' }) expectTypeOf(signature1).toEqualTypeOf>() expectTypeOf(signature2).toEqualTypeOf>() // @ts-expect-error signTransaction(config, { gasPrice: 0n, maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, }) // @ts-expect-error signTransaction(config, { gasPrice: 0n, maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, type: 'legacy', }) // @ts-expect-error signTransaction(config, { maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, type: 'legacy', }) }) test('eip7702', () => { const signature1 = signTransaction(config, { authorizationList: [], }) const signature2 = signTransaction(config, { authorizationList: [], type: 'eip7702', }) expectTypeOf(signature1).toEqualTypeOf< Promise >() expectTypeOf(signature2).toEqualTypeOf< Promise >() }) test('eip4844', () => { const signature1 = signTransaction(config, { blobVersionedHashes: [], maxFeePerBlobGas: 0n, to: '0x0000000000000000000000000000000000000000', }) const signature2 = signTransaction(config, { blobVersionedHashes: [], maxFeePerBlobGas: 0n, to: '0x0000000000000000000000000000000000000000', type: 'eip4844', }) expectTypeOf(signature1).toEqualTypeOf< Promise >() expectTypeOf(signature2).toEqualTypeOf< Promise >() }) test('eip1559', () => { const signature1 = signTransaction(config, { maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, }) const signature2 = signTransaction(config, { type: 'eip1559', }) expectTypeOf(signature1).toEqualTypeOf< Promise >() expectTypeOf(signature2).toEqualTypeOf< Promise >() // @ts-expect-error signTransaction(config, { gasPrice: 0n, maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, }) // @ts-expect-error signTransaction(config, { gasPrice: 0n, maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, type: 'eip1559', }) // @ts-expect-error signTransaction(config, { gasPrice: 0n, type: 'eip1559', }) }) test('eip2930', () => { const signature1 = signTransaction(config, { accessList: [], gasPrice: 0n, }) const signature2 = signTransaction(config, { type: 'eip2930', }) expectTypeOf(signature1).toEqualTypeOf< Promise >() expectTypeOf(signature2).toEqualTypeOf< Promise >() // @ts-expect-error signTransaction(config, { accessList: [], gasPrice: 0n, maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, }) // @ts-expect-error signTransaction(config, { accessList: [], gasPrice: 0n, maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, type: 'eip2930', }) // @ts-expect-error signTransaction(config, { accessList: [], maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, type: 'eip2930', }) }) ================================================ FILE: packages/core/src/actions/signTransaction.test.ts ================================================ import { config, privateKey, signedTransactionRegex } from '@wagmi/test' import { parseEther } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { beforeEach, expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { signTransaction } from './signTransaction.js' const connector = config.connectors[0]! beforeEach(async () => { if (config.state.current === connector.uid) await disconnect(config, { connector }) }) test('default', async () => { const result = await connect(config, { connector }) config.state.connections.set(connector.uid, { ...result, // Switch up the current account because the default one is running out of funds somewhere accounts: result.accounts.slice(1) as unknown as typeof result.accounts, connector, }) await expect( signTransaction(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.0001'), }), ).resolves.toMatch(signedTransactionRegex) await disconnect(config, { connector }) }) test('behavior: connector not connected', async () => { await connect(config, { connector }) await expect( signTransaction(config, { connector: config.connectors[1], to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.0001'), }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ConnectorNotConnectedError: Connector not connected. Version: @wagmi/core@x.y.z] `) await disconnect(config, { connector }) }) test('behavior: account does not exist on connector', async () => { await connect(config, { connector }) await expect( signTransaction(config, { account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.0001'), }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ConnectorAccountNotFoundError: Account "0xA0Cf798816D4b9b9866b5330EEa46a18382f251e" not found for connector "Mock Connector". Version: @wagmi/core@x.y.z] `) await disconnect(config, { connector }) }) test('behavior: local account', async () => { const account = privateKeyToAccount(privateKey) await expect( signTransaction(config, { account, to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', type: 'eip1559', value: parseEther('0.000001'), }), ).resolves.toMatch(signedTransactionRegex) }) ================================================ FILE: packages/core/src/actions/signTransaction.ts ================================================ import type { Account, Chain, Client, TransactionRequest, SignTransactionErrorType as viem_SignTransactionErrorType, SignTransactionParameters as viem_SignTransactionParameters, SignTransactionRequest as viem_SignTransactionRequest, SignTransactionReturnType as viem_SignTransactionReturnType, } from 'viem' import { signTransaction as viem_signTransaction } from 'viem/actions' import type { Config } from '../createConfig.js' import type { BaseErrorType, ErrorType } from '../errors/base.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter, ConnectorParameter, } from '../types/properties.js' import type { UnionCompute, UnionLooseOmit } from '../types/utils.js' import { getAction } from '../utils/getAction.js' import { type GetConnectorClientErrorType, getConnectorClient, } from './getConnectorClient.js' export type SignTransactionParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], request extends viem_SignTransactionRequest< SelectChains[0], SelectChains[0] > = viem_SignTransactionRequest< SelectChains[0], SelectChains[0] >, // chains extends readonly Chain[] = SelectChains, > = { [key in keyof chains]: UnionCompute< UnionLooseOmit< viem_SignTransactionParameters< chains[key], Account, chains[key], request extends viem_SignTransactionRequest ? request : never >, 'chain' | 'gas' > & ChainIdParameter & ConnectorParameter & { /** Gas provided for transaction execution. */ gas?: TransactionRequest['gas'] | null } > }[number] export type SignTransactionReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], request extends viem_SignTransactionRequest< SelectChains[0], SelectChains[0] > = viem_SignTransactionRequest< SelectChains[0], SelectChains[0] >, > = viem_SignTransactionReturnType export type SignTransactionErrorType = // getConnectorClient() | GetConnectorClientErrorType // base | BaseErrorType | ErrorType // viem | viem_SignTransactionErrorType /** https://wagmi.sh/core/api/actions/signTransaction */ export async function signTransaction< config extends Config, chainId extends config['chains'][number]['id'], const request extends viem_SignTransactionRequest< SelectChains[0], SelectChains[0] >, >( config: config, parameters: SignTransactionParameters & request, ): Promise> { const { account, chainId, connector, ...rest } = parameters let client: Client if (typeof account === 'object' && account?.type === 'local') client = config.getClient({ chainId }) else client = await getConnectorClient(config, { account: account ?? undefined, assertChainId: false, chainId, connector, }) const chain = (() => { if (!chainId || client.chain?.id === chainId) return client.chain return { id: chainId } })() const action = getAction(client, viem_signTransaction, 'signTransaction') const serializedTransaction = await action({ ...(rest as any), ...(account ? { account } : {}), assertChainId: !!chainId, chain, gas: rest.gas ?? undefined, }) return serializedTransaction as any } ================================================ FILE: packages/core/src/actions/signTypedData.test-d.ts ================================================ import { config, typedData } from '@wagmi/test' import { test } from 'vitest' import { signTypedData } from './signTypedData.js' test('default', async () => { signTypedData(config, { types: typedData.basic.types, primaryType: 'Mail', message: typedData.basic.message, }) }) test('domain', async () => { signTypedData(config, { primaryType: 'EIP712Domain', domain: {}, }) }) test('custom domain', async () => { signTypedData(config, { types: { EIP712Domain: [{ type: 'uint256', name: 'chainId' }], }, primaryType: 'EIP712Domain', domain: { chainId: 123n, }, }) }) ================================================ FILE: packages/core/src/actions/signTypedData.test.ts ================================================ import { accounts, config, privateKey, typedData } from '@wagmi/test' import { recoverTypedDataAddress } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { expect, test } from 'vitest' import { mock } from '../connectors/mock.js' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { getConnection } from './getConnection.js' import { signTypedData } from './signTypedData.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const signature = await signTypedData(config, { types: typedData.basic.types, primaryType: 'Mail', message: typedData.basic.message, }) await expect( recoverTypedDataAddress({ types: typedData.basic.types, primaryType: 'Mail', message: typedData.basic.message, signature, }), ).resolves.toBe(getConnection(config).address) await disconnect(config, { connector }) }) test('behavior: user rejected request', async () => { const connector_ = config._internal.connectors.setup( mock({ accounts, features: { signTypedDataError: true }, }), ) await connect(config, { connector: connector_ }) await expect( signTypedData(config, { types: typedData.basic.types, primaryType: 'Mail', message: typedData.basic.message, }), ).rejects.toMatchInlineSnapshot(` [UserRejectedRequestError: User rejected the request. Details: Failed to sign typed data. Version: viem@2.47.5] `) await disconnect(config, { connector: connector_ }) }) test('behavior: not connected', async () => { await expect( signTypedData(config, { types: typedData.basic.types, primaryType: 'Mail', message: typedData.basic.message, }), ).rejects.toMatchInlineSnapshot(` [ConnectorNotConnectedError: Connector not connected. Version: @wagmi/core@x.y.z] `) }) test('behavior: local account', async () => { const account = privateKeyToAccount(privateKey) const signature = await signTypedData(config, { account, types: typedData.basic.types, primaryType: 'Mail', message: typedData.basic.message, }) await expect( recoverTypedDataAddress({ types: typedData.basic.types, primaryType: 'Mail', message: typedData.basic.message, signature, }), ).resolves.toBe(account.address) }) ================================================ FILE: packages/core/src/actions/signTypedData.ts ================================================ import type { Account, Client, TypedData } from 'viem' import { type SignMessageErrorType as viem_SignMessageErrorType, type SignTypedDataParameters as viem_SignTypedDataParameters, type SignTypedDataReturnType as viem_SignTypedDataReturnType, signTypedData as viem_signTypedData, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { BaseErrorType, ErrorType } from '../errors/base.js' import type { ConnectorParameter } from '../types/properties.js' import type { UnionCompute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' import { type GetConnectorClientErrorType, getConnectorClient, } from './getConnectorClient.js' export type SignTypedDataParameters< typedData extends TypedData | Record = TypedData, primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData, /// primaryTypes = typedData extends TypedData ? keyof typedData : string, > = UnionCompute< viem_SignTypedDataParameters & ConnectorParameter > export type SignTypedDataReturnType = viem_SignTypedDataReturnType export type SignTypedDataErrorType = // getConnectorClient() | GetConnectorClientErrorType // base | BaseErrorType | ErrorType // viem | viem_SignMessageErrorType /** https://wagmi.sh/core/api/actions/signTypedData */ export async function signTypedData< const typedData extends TypedData | Record, primaryType extends keyof typedData | 'EIP712Domain', >( config: Config, parameters: SignTypedDataParameters, ): Promise { const { account, connector, ...rest } = parameters let client: Client if (typeof account === 'object' && account.type === 'local') client = config.getClient() else client = await getConnectorClient(config, { account, connector }) const action = getAction(client, viem_signTypedData, 'signTypedData') return action({ ...rest, ...(account ? { account } : {}), } as unknown as viem_SignTypedDataParameters) } ================================================ FILE: packages/core/src/actions/simulateContract.test-d.ts ================================================ import { abi, config } from '@wagmi/test' import { type Address, http } from 'viem' import { celo, mainnet } from 'viem/chains' import { assertType, expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { type SimulateContractParameters, type SimulateContractReturnType, simulateContract, } from './simulateContract.js' test('default', async () => { const response = await simulateContract(config, { address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], chainId: 1, }) expectTypeOf(response).toMatchTypeOf<{ result: boolean request: { chainId: 1 abi: readonly [ { readonly name: 'transferFrom' readonly type: 'function' readonly stateMutability: 'nonpayable' readonly inputs: readonly [ { readonly type: 'address'; readonly name: 'sender' }, { readonly type: 'address'; readonly name: 'recipient' }, { readonly type: 'uint256'; readonly name: 'amount' }, ] readonly outputs: readonly [{ type: 'bool' }] }, ] functionName: 'transferFrom' args: readonly [Address, Address, bigint] } }>() }) test('chain formatters', async () => { const config = createConfig({ chains: [celo, mainnet], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) type Result = SimulateContractParameters< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config > expectTypeOf().toMatchTypeOf<{ chainId?: typeof celo.id | typeof mainnet.id | undefined feeCurrency?: `0x${string}` | undefined }>() const response = await simulateContract(config, { account: '0x', address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], feeCurrency: '0x', }) if (response.chainId === celo.id) { expectTypeOf(response.chainId).toEqualTypeOf(celo.id) expectTypeOf(response.request.feeCurrency).toEqualTypeOf< `0x${string}` | undefined >() } type Result2 = SimulateContractParameters< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config, typeof celo.id > expectTypeOf().toMatchTypeOf<{ functionName: 'approve' | 'transfer' | 'transferFrom' args: readonly [Address, Address, bigint] feeCurrency?: `0x${string}` | undefined }>() const response2 = await simulateContract(config, { chainId: celo.id, account: '0x', address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], feeCurrency: '0x', }) expectTypeOf(response2.chainId).toEqualTypeOf(celo.id) expectTypeOf(response2.request.feeCurrency).toEqualTypeOf< `0x${string}` | undefined >() type Result3 = SimulateContractParameters< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config, typeof mainnet.id > expectTypeOf().toMatchTypeOf<{ functionName: 'approve' | 'transfer' | 'transferFrom' args: readonly [Address, Address, bigint] }>() expectTypeOf().not.toMatchTypeOf<{ feeCurrency?: `0x${string}` | undefined }>() simulateContract(config, { chainId: mainnet.id, account: '0x', address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], // @ts-expect-error feeCurrency: '0x', }) }) test('SimulateContractParameters', () => { type Result = SimulateContractParameters< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config, (typeof config)['chains'][number]['id'] > expectTypeOf().toMatchTypeOf<{ chainId?: (typeof config)['chains'][number]['id'] | undefined functionName: 'approve' | 'transfer' | 'transferFrom' args: readonly [Address, Address, bigint] }>() }) test('SimulateContractReturnType', () => { type Result = SimulateContractReturnType< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config, (typeof config)['chains'][number]['id'] > expectTypeOf().toMatchTypeOf<{ result: boolean request: { functionName: 'transferFrom' args: readonly [Address, Address, bigint] chainId: (typeof config)['chains'][number]['id'] } }>() }) test('overloads', async () => { const result1 = await simulateContract(config, { address: '0x', abi: abi.writeOverloads, functionName: 'foo', }) assertType(result1.result) const result2 = await simulateContract(config, { address: '0x', abi: abi.writeOverloads, functionName: 'foo', args: [], }) assertType(result2.result) const result3 = await simulateContract(config, { address: '0x', abi: abi.writeOverloads, functionName: 'foo', args: ['0x'], }) assertType(result3.result) const result4 = await simulateContract(config, { address: '0x', abi: abi.writeOverloads, functionName: 'foo', args: ['0x', '0x'], }) assertType<{ foo: `0x${string}` bar: `0x${string}` }>(result4.result) }) ================================================ FILE: packages/core/src/actions/simulateContract.test.ts ================================================ import { abi, accounts, address, config } from '@wagmi/test' import { expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { simulateContract } from './simulateContract.js' const connector = config.connectors[0]! test('parameters: account', async () => { await expect( simulateContract(config, { account: accounts[0], address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'mint', }), ).resolves.toMatchInlineSnapshot(` { "chainId": 1, "request": { "abi": [ { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "account": { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "type": "json-rpc", }, "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": undefined, "chainId": undefined, "dataSuffix": undefined, "functionName": "mint", }, "result": undefined, } `) }) test('parameters: connector', async () => { await connect(config, { connector }) await expect( simulateContract(config, { address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'mint', connector, }), ).resolves.toMatchInlineSnapshot(` { "chainId": 1, "request": { "abi": [ { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "account": { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "type": "json-rpc", }, "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": undefined, "chainId": undefined, "dataSuffix": undefined, "functionName": "mint", }, "result": undefined, } `) await disconnect(config, { connector }) }) ================================================ FILE: packages/core/src/actions/simulateContract.ts ================================================ import type { Abi, Account, Address, Chain, ContractFunctionArgs, ContractFunctionName, } from 'viem' import { type SimulateContractErrorType as viem_SimulateContractErrorType, type SimulateContractParameters as viem_SimulateContractParameters, type SimulateContractReturnType as viem_SimulateContractReturnType, simulateContract as viem_simulateContract, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { BaseErrorType, ErrorType } from '../errors/base.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter, ConnectorParameter, } from '../types/properties.js' import type { Compute, PartialBy, UnionCompute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' import { type GetConnectorClientErrorType, getConnectorClient, } from './getConnectorClient.js' export type SimulateContractParameters< abi extends Abi | readonly unknown[] = Abi, functionName extends ContractFunctionName< abi, 'nonpayable' | 'payable' > = ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName > = ContractFunctionArgs, config extends Config = Config, chainId extends | config['chains'][number]['id'] | undefined = config['chains'][number]['id'], /// chains extends readonly Chain[] = SelectChains, > = { [key in keyof chains]: UnionCompute< // TODO: Should use `UnionStrictOmit<..., 'chain'>` on `viem_SimulateContractParameters` result instead, but it knocks out inference for overloads viem_SimulateContractParameters< abi, functionName, args, chains[key], chains[key], Account | Address > > & { chain?: never } & ChainIdParameter & ConnectorParameter }[number] export type SimulateContractReturnType< abi extends Abi | readonly unknown[] = Abi, functionName extends ContractFunctionName< abi, 'nonpayable' | 'payable' > = ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName > = ContractFunctionArgs, config extends Config = Config, chainId extends | config['chains'][number]['id'] | undefined = config['chains'][number]['id'], /// chains extends readonly Chain[] = SelectChains, > = { [key in keyof chains]: viem_SimulateContractReturnType< abi, functionName, args, chains[key], Account, chains[key] > & { chainId: chains[key]['id'] request: Compute< PartialBy< { chainId: chainId; chain: chains[key] }, chainId extends config['chains'][number]['id'] ? never : 'chainId' > > } }[number] export type SimulateContractErrorType = // getConnectorClient() | GetConnectorClientErrorType // base | BaseErrorType | ErrorType // viem | viem_SimulateContractErrorType /** https://wagmi.sh/core/api/actions/simulateContract */ export async function simulateContract< config extends Config, const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, const args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName >, chainId extends config['chains'][number]['id'] | undefined = undefined, >( config: config, parameters: SimulateContractParameters< abi, functionName, args, config, chainId >, ): Promise< SimulateContractReturnType > { const { abi, chainId, connector, ...rest } = parameters as SimulateContractParameters let account: Address | Account if (parameters.account) account = parameters.account else { const connectorClient = await getConnectorClient(config, { assertChainId: false, chainId, connector, }) account = connectorClient.account } const client = config.getClient({ chainId }) const action = getAction(client, viem_simulateContract, 'simulateContract') const { result, request } = await action({ ...rest, abi, account }) return { chainId: client.chain.id, result, request: { ...request, chainId }, } as unknown as SimulateContractReturnType< abi, functionName, args, config, chainId > } ================================================ FILE: packages/core/src/actions/switchChain.test.ts ================================================ import { accounts, chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { mock } from '../connectors/mock.js' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { getConnection } from './getConnection.js' import { switchChain } from './switchChain.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const chainId1 = getConnection(config).chainId await switchChain(config, { chainId: chain.mainnet2.id }) const chainId2 = getConnection(config).chainId expect(chainId2).toBeDefined() expect(chainId1).not.toBe(chainId2) await switchChain(config, { chainId: chain.mainnet.id }) const chainId3 = getConnection(config).chainId expect(chainId3).toBeDefined() expect(chainId1).toBe(chainId3) await disconnect(config, { connector }) }) test('behavior: user rejected request', async () => { const connector_ = config._internal.connectors.setup( mock({ accounts, features: { switchChainError: true }, }), ) await connect(config, { connector: connector_ }) await expect( switchChain(config, { chainId: chain.mainnet.id }), ).rejects.toMatchInlineSnapshot(` [UserRejectedRequestError: User rejected the request. Details: Failed to switch chain. Version: viem@2.47.5] `) await disconnect(config, { connector: connector_ }) }) test('behavior: not supported', async () => { const { switchChain: _, ...connector_ } = config._internal.connectors.setup( mock({ accounts }), ) await connect(config, { connector: connector_ }) await expect( switchChain(config, { chainId: chain.mainnet.id }), ).rejects.toMatchInlineSnapshot(` [SwitchChainNotSupportedError: "Mock Connector" does not support programmatic chain switching. Version: @wagmi/core@x.y.z] `) await disconnect(config, { connector: connector_ }) }) test('behavior: not connected', async () => { const chainId = config.state.chainId expect(config.state.chainId).toMatchInlineSnapshot('1') await switchChain(config, { chainId: chain.mainnet2.id }) expect(config.state.chainId).toMatchInlineSnapshot('456') await switchChain(config, { chainId }) expect(config.state.chainId).toMatchInlineSnapshot('1') }) ================================================ FILE: packages/core/src/actions/switchChain.ts ================================================ import type { AddEthereumChainParameter, UserRejectedRequestErrorType, SwitchChainErrorType as viem_SwitchChainErrorType, } from 'viem' import type { Config } from '../createConfig.js' import type { BaseErrorType, ErrorType } from '../errors/base.js' import { ChainNotConfiguredError, type ChainNotConfiguredErrorType, } from '../errors/config.js' import { type ProviderNotFoundErrorType, SwitchChainNotSupportedError, type SwitchChainNotSupportedErrorType, } from '../errors/connector.js' import type { ConnectorParameter } from '../types/properties.js' import type { Compute, ExactPartial } from '../types/utils.js' export type SwitchChainParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = Compute< ConnectorParameter & { chainId: chainId | config['chains'][number]['id'] addEthereumChainParameter?: | Compute>> | undefined } > export type SwitchChainReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = Extract< config['chains'][number], { id: Config extends config ? number : chainId } > export type SwitchChainErrorType = | SwitchChainNotSupportedErrorType | ChainNotConfiguredErrorType // connector.switchChain() | ProviderNotFoundErrorType | UserRejectedRequestErrorType // base | BaseErrorType | ErrorType // viem | viem_SwitchChainErrorType /** https://wagmi.sh/core/api/actions/switchChain */ export async function switchChain< config extends Config, chainId extends config['chains'][number]['id'], >( config: config, parameters: SwitchChainParameters, ): Promise> { const { addEthereumChainParameter, chainId } = parameters const connection = config.state.connections.get( parameters.connector?.uid ?? config.state.current!, ) if (connection) { const connector = connection.connector if (!connector.switchChain) throw new SwitchChainNotSupportedError({ connector }) const chain = await connector.switchChain({ addEthereumChainParameter, chainId, }) return chain as SwitchChainReturnType } const chain = config.chains.find((x) => x.id === chainId) if (!chain) throw new ChainNotConfiguredError() config.setState((x) => ({ ...x, chainId })) return chain as SwitchChainReturnType } ================================================ FILE: packages/core/src/actions/switchConnection.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { getConnection } from './getConnection.js' import { switchConnection } from './switchConnection.js' const connector1 = config.connectors[0]! const connector2 = config.connectors[1]! test('default', async () => { await connect(config, { connector: connector2 }) await connect(config, { connector: connector1 }) const address1 = getConnection(config).address await switchConnection(config, { connector: connector2 }) const address2 = getConnection(config).address expect(address2).toBeDefined() expect(address1).not.toBe(address2) await switchConnection(config, { connector: connector1 }) const address3 = getConnection(config).address expect(address3).toBeDefined() expect(address1).toBe(address3) await disconnect(config, { connector: connector1 }) await disconnect(config, { connector: connector2 }) }) ================================================ FILE: packages/core/src/actions/switchConnection.ts ================================================ import type { Address } from 'viem' import type { Config, Connector } from '../createConfig.js' import type { BaseError, ErrorType } from '../errors/base.js' import { ConnectorNotConnectedError, type ConnectorNotConnectedErrorType, } from '../errors/config.js' export type SwitchConnectionParameters = { connector: Connector } export type SwitchConnectionReturnType = { accounts: readonly [Address, ...Address[]] chainId: | config['chains'][number]['id'] | (number extends config['chains'][number]['id'] ? number : number & {}) } export type SwitchConnectionErrorType = | ConnectorNotConnectedErrorType | BaseError | ErrorType /** https://wagmi.sh/core/api/actions/switchConnection */ export async function switchConnection( config: config, parameters: SwitchConnectionParameters, ): Promise> { const { connector } = parameters const connection = config.state.connections.get(connector.uid) if (!connection) throw new ConnectorNotConnectedError() await config.storage?.setItem('recentConnectorId', connector.id) config.setState((x) => ({ ...x, current: connector.uid, })) return { accounts: connection.accounts, chainId: connection.chainId, } } ================================================ FILE: packages/core/src/actions/verifyMessage.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { verifyMessage } from './verifyMessage.js' const eoaAddress = '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' const smartAccountAddress = '0x3FCf42e10CC70Fe75A62EB3aDD6D305Aa840d145' test('smart account: valid signature', async () => { expect( await verifyMessage(config, { address: smartAccountAddress, message: 'This is a test message for viem!', signature: '0xefd5fb29a274ea6682673d8b3caa9263e936d48d486e5df68893003e0a76496439594d12245008c6fba1c8e3ef28241cffe1bef27ff6bca487b167f261f329251c', }), ).toBe(true) }) test('smart account: invalid signature', async () => { expect( await verifyMessage(config, { address: smartAccountAddress, message: 'This is a test message for viem!', signature: '0xdead', }), ).toBe(false) }) test('smart account: account not deployed', async () => { expect( await verifyMessage(config, { blockNumber: 1234567890n, address: smartAccountAddress, message: 'This is a test message for viem!', signature: '0xefd5fb29a274ea6682673d8b3caa9263e936d48d486e5df68893003e0a76496439594d12245008c6fba1c8e3ef28241cffe1bef27ff6bca487b167f261f329251c', }), ).toBe(false) }) test('eoa: valid signature', async () => { expect( await verifyMessage(config, { address: eoaAddress, message: 'This is a test message for viem!', signature: '0xc4c7f2820177020d66d5fd00d084cdd3f575a868c059c29a2d7f23398d04819709a14f83d98b446dda539ca5dcb87d75aa3340eb15e66d67606850622a3420f61b', }), ).toBe(true) }) test('eoa: invalid signature', async () => { expect( await verifyMessage(config, { address: eoaAddress, message: 'This is a test message for viem!', signature: '0xdead', }), ).toBe(false) }) test('eoa: raw message', async () => { expect( await verifyMessage(config, { address: eoaAddress, message: { raw: '0x68656c6c6f20776f726c64' }, signature: '0xa461f509887bd19e312c0c58467ce8ff8e300d3c1a90b608a760c5b80318eaf15fe57c96f9175d6cd4daad4663763baa7e78836e067d0163e9a2ccf2ff753f5b1b', }), ).toBe(true) }) ================================================ FILE: packages/core/src/actions/verifyMessage.ts ================================================ import { type VerifyMessageErrorType as viem_VerifyMessageErrorType, type VerifyMessageParameters as viem_VerifyMessageParameters, type VerifyMessageReturnType as viem_VerifyMessageReturnType, verifyMessage as viem_verifyMessage, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type VerifyMessageParameters = Compute< viem_VerifyMessageParameters & ChainIdParameter > export type VerifyMessageReturnType = viem_VerifyMessageReturnType export type VerifyMessageErrorType = viem_VerifyMessageErrorType /** https://wagmi.sh/core/api/actions/verifyMessage */ export async function verifyMessage( config: config, parameters: VerifyMessageParameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_verifyMessage, 'verifyMessage') return action(rest) } ================================================ FILE: packages/core/src/actions/verifyTypedData.test-d.ts ================================================ import { config, typedData } from '@wagmi/test' import { test } from 'vitest' import { verifyTypedData } from './verifyTypedData.js' test('default', async () => { verifyTypedData(config, { ...typedData.basic, primaryType: 'Mail', address: '0x', signature: '0x', }) verifyTypedData(config, { ...typedData.basic, // @ts-expect-error primaryType: 'foobarbaz', address: '0x', signature: '0x', }) }) ================================================ FILE: packages/core/src/actions/verifyTypedData.test.ts ================================================ import { config, typedData } from '@wagmi/test' import { expect, test } from 'vitest' import { verifyTypedData } from './verifyTypedData.js' const smartAccountAddress = '0x3FCf42e10CC70Fe75A62EB3aDD6D305Aa840d145' const notDeployedAddress = '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef' test('valid signature', async () => { expect( await verifyTypedData(config, { ...typedData.basic, primaryType: 'Mail', address: smartAccountAddress, signature: '0x79d756d805073dc97b7bc885b0d56ddf319a2599530fe1e178c2a7de5be88980068d24f20a79b318ea0a84d33ae06f93db77e4235e5d9eeb8b1d7a63922ada3e1c', }), ).toBe(true) }) test('invalid signature', async () => { expect( await verifyTypedData(config, { ...typedData.basic, primaryType: 'Mail', address: smartAccountAddress, signature: '0xdead', }), ).toBe(false) }) test('account not deployed', async () => { expect( await verifyTypedData(config, { ...typedData.basic, primaryType: 'Mail', address: notDeployedAddress, signature: '0x79d756d805073dc97b7bc885b0d56ddf319a2599530fe1e178c2a7de5be88980068d24f20a79b318ea0a84d33ae06f93db77e4235e5d9eeb8b1d7a63922ada3e1c', }), ).toBe(false) }) ================================================ FILE: packages/core/src/actions/verifyTypedData.ts ================================================ import type { TypedData } from 'viem' import { type VerifyTypedDataErrorType as viem_VerifyTypedDataErrorType, type VerifyTypedDataParameters as viem_VerifyTypedDataParameters, type VerifyTypedDataReturnType as viem_VerifyTypedDataReturnType, verifyTypedData as viem_verifyTypedData, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ChainIdParameter } from '../types/properties.js' import type { UnionCompute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type VerifyTypedDataParameters< typedData extends TypedData | Record = TypedData, primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData, config extends Config = Config, > = UnionCompute< viem_VerifyTypedDataParameters & ChainIdParameter > export type VerifyTypedDataReturnType = viem_VerifyTypedDataReturnType export type VerifyTypedDataErrorType = viem_VerifyTypedDataErrorType /** https://wagmi.sh/core/api/actions/verifyTypedData */ export async function verifyTypedData< config extends Config, const typedData extends TypedData | Record, primaryType extends keyof typedData | 'EIP712Domain', >( config: config, parameters: VerifyTypedDataParameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction(client, viem_verifyTypedData, 'verifyTypedData') return action(rest as viem_VerifyTypedDataParameters) } ================================================ FILE: packages/core/src/actions/waitForCallsStatus.test.ts ================================================ import { accounts, config, testClient, wait } from '@wagmi/test' import { parseEther } from 'viem' import { expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { sendCalls } from './sendCalls.js' import { waitForCallsStatus } from './waitForCallsStatus.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const { id } = await sendCalls(config, { calls: [ { data: '0xdeadbeef', to: accounts[1], value: parseEther('1'), }, { to: accounts[2], value: parseEther('2'), }, { to: accounts[3], value: parseEther('3'), }, ], }) const [{ receipts, status }] = await Promise.all([ waitForCallsStatus(config, { id, }), (async () => { await wait(100) await testClient.mainnet.mine({ blocks: 1 }) })(), ]) expect(status).toBe('success') expect( receipts?.map((x) => ({ ...x, blockHash: undefined, transactionHash: undefined, })), ).toMatchInlineSnapshot( ` [ { "blockHash": undefined, "blockNumber": 23535881n, "gasUsed": 21160n, "logs": [], "status": "success", "transactionHash": undefined, }, { "blockHash": undefined, "blockNumber": 23535881n, "gasUsed": 21000n, "logs": [], "status": "success", "transactionHash": undefined, }, { "blockHash": undefined, "blockNumber": 23535881n, "gasUsed": 21000n, "logs": [], "status": "success", "transactionHash": undefined, }, ] `, ) await disconnect(config, { connector }) }) ================================================ FILE: packages/core/src/actions/waitForCallsStatus.ts ================================================ import { type WaitForCallsStatusErrorType as viem_WaitForCallsStatusErrorType, type WaitForCallsStatusParameters as viem_WaitForCallsStatusParameters, type WaitForCallsStatusReturnType as viem_WaitForCallsStatusReturnType, waitForCallsStatus as viem_waitForCallsStatus, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { ConnectorParameter } from '../types/properties.js' import { getConnectorClient } from './getConnectorClient.js' export type WaitForCallsStatusParameters = viem_WaitForCallsStatusParameters & ConnectorParameter export type WaitForCallsStatusReturnType = viem_WaitForCallsStatusReturnType export type WaitForCallsStatusErrorType = viem_WaitForCallsStatusErrorType /** https://wagmi.sh/core/api/actions/waitForCallsStatus */ export async function waitForCallsStatus( config: config, parameters: WaitForCallsStatusParameters, ): Promise { const { connector } = parameters const client = await getConnectorClient(config, { connector }) return viem_waitForCallsStatus(client, parameters) } ================================================ FILE: packages/core/src/actions/waitForTransactionReceipt.test-d.ts ================================================ import { http } from 'viem' import { mainnet, zkSync } from 'viem/chains' import type { ZkSyncL2ToL1Log, ZkSyncLog } from 'viem/zksync' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { waitForTransactionReceipt } from './waitForTransactionReceipt.js' test('chain formatters', async () => { const config = createConfig({ chains: [mainnet, zkSync], transports: { [mainnet.id]: http(), [zkSync.id]: http() }, }) const result = await waitForTransactionReceipt(config, { hash: '0x123' }) if (result.chainId === zkSync.id) { expectTypeOf(result.l1BatchNumber).toEqualTypeOf() expectTypeOf(result.l1BatchTxIndex).toEqualTypeOf() expectTypeOf(result.logs).toEqualTypeOf() expectTypeOf(result.l2ToL1Logs).toEqualTypeOf() } }) test('chainId', async () => { const config = createConfig({ chains: [zkSync], transports: { [zkSync.id]: http() }, }) const result = await waitForTransactionReceipt(config, { hash: '0x123', chainId: zkSync.id, }) expectTypeOf(result.l1BatchNumber).toEqualTypeOf() expectTypeOf(result.l1BatchTxIndex).toEqualTypeOf() expectTypeOf(result.logs).toEqualTypeOf() expectTypeOf(result.l2ToL1Logs).toEqualTypeOf() }) ================================================ FILE: packages/core/src/actions/waitForTransactionReceipt.test.ts ================================================ import { config, testClient, wait } from '@wagmi/test' import { parseEther } from 'viem' import { beforeEach, expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { sendTransaction } from './sendTransaction.js' import { waitForTransactionReceipt } from './waitForTransactionReceipt.js' const connector = config.connectors[0]! beforeEach(async () => { if (config.state.current === connector.uid) await disconnect(config, { connector }) }) test('default', async () => { await connect(config, { connector }) const hash = await sendTransaction(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) await expect( waitForTransactionReceipt(config, { hash }), ).resolves.toMatchObject({ chainId: 1, transactionHash: hash, }) await disconnect(config, { connector }) }) test('behavior: transaction reverted', async () => { await expect( waitForTransactionReceipt(config, { hash: '0x745367f76807d411b7fa4c3a552a62e3e45303ef40145fff04d84b867c2575d3', }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [CallExecutionError: Execution reverted with reason: PartyBid::claim: contribution already claimed. Raw Call Arguments: from: 0xa0cf798816d4b9b9866b5330eea46a18382f251e to: 0xf1332f21487e74612ed3a0fb36da729b73f1ae19 value: 0 ETH data: 0x1e83409a000000000000000000000000a0cf798816d4b9b9866b5330eea46a18382f251e gas: 128730 maxFeePerGas: 43.307900987 gwei maxPriorityFeePerGas: 1.5 gwei nonce: 43 Details: execution reverted: PartyBid::claim: contribution already claimed Version: viem@2.47.5] `) }) ================================================ FILE: packages/core/src/actions/waitForTransactionReceipt.ts ================================================ import type { Chain } from 'viem' import { hexToString } from 'viem' import { call, getTransaction, type WaitForTransactionReceiptErrorType as viem_WaitForTransactionReceiptErrorType, type WaitForTransactionReceiptParameters as viem_WaitForTransactionReceiptParameters, type WaitForTransactionReceiptReturnType as viem_WaitForTransactionReceiptReturnType, waitForTransactionReceipt as viem_waitForTransactionReceipt, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter } from '../types/properties.js' import type { Compute, IsNarrowable } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type WaitForTransactionReceiptParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = Compute< viem_WaitForTransactionReceiptParameters & ChainIdParameter > export type WaitForTransactionReceiptReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], /// chains extends readonly Chain[] = SelectChains, > = Compute< { [key in keyof chains]: viem_WaitForTransactionReceiptReturnType< IsNarrowable extends true ? chains[key] : undefined > & { chainId: chains[key]['id'] } }[number] > export type WaitForTransactionReceiptErrorType = viem_WaitForTransactionReceiptErrorType export async function waitForTransactionReceipt< config extends Config, chainId extends config['chains'][number]['id'], >( config: config, parameters: WaitForTransactionReceiptParameters, ): Promise> { const { chainId, timeout = 0, ...rest } = parameters const client = config.getClient({ chainId }) const action = getAction( client, viem_waitForTransactionReceipt, 'waitForTransactionReceipt', ) const receipt = await action({ ...rest, timeout }) if (receipt.status === 'reverted') { const action_getTransaction = getAction( client, getTransaction, 'getTransaction', ) const { from: account, ...txn } = await action_getTransaction({ hash: receipt.transactionHash, }) const action_call = getAction(client, call, 'call') const code = await action_call({ ...(txn as any), account, data: txn.input, gasPrice: txn.type !== 'eip1559' ? txn.gasPrice : undefined, maxFeePerGas: txn.type === 'eip1559' ? txn.maxFeePerGas : undefined, maxPriorityFeePerGas: txn.type === 'eip1559' ? txn.maxPriorityFeePerGas : undefined, }) const reason = code?.data ? hexToString(`0x${code.data.substring(138)}`) : 'unknown reason' throw new Error(reason) } return { ...receipt, chainId: client.chain.id, } as WaitForTransactionReceiptReturnType } ================================================ FILE: packages/core/src/actions/watchAsset.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { watchAsset } from './watchAsset.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) await expect( watchAsset(config, { type: 'ERC20', options: { address: '0x0000000000000000000000000000000000000000', symbol: 'NULL', decimals: 18, }, }), ).resolves.toMatchInlineSnapshot('true') await disconnect(config, { connector }) }) ================================================ FILE: packages/core/src/actions/watchAsset.ts ================================================ import { type WatchAssetErrorType as viem_WatchAssetErrorType, type WatchAssetParameters as viem_WatchAssetParameters, type WatchAssetReturnType as viem_WatchAssetReturnType, watchAsset as viem_watchAsset, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { BaseErrorType, ErrorType } from '../errors/base.js' import type { ConnectorParameter } from '../types/properties.js' import type { Compute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' import { type GetConnectorClientErrorType, getConnectorClient, } from './getConnectorClient.js' export type WatchAssetParameters = Compute< viem_WatchAssetParameters & ConnectorParameter > export type WatchAssetReturnType = viem_WatchAssetReturnType export type WatchAssetErrorType = // getConnectorClient() | GetConnectorClientErrorType // base | BaseErrorType | ErrorType // viem | viem_WatchAssetErrorType /** https://wagmi.sh/core/api/actions/watchAsset */ export async function watchAsset( config: Config, parameters: WatchAssetParameters, ): Promise { const { connector, ...rest } = parameters const client = await getConnectorClient(config, { connector }) const action = getAction(client, viem_watchAsset, 'watchAsset') return action(rest as viem_WatchAssetParameters) } ================================================ FILE: packages/core/src/actions/watchBlockNumber.test-d.ts ================================================ import { http, webSocket } from 'viem' import { mainnet, optimism } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { type WatchBlockNumberParameters, watchBlockNumber, } from './watchBlockNumber.js' test('differing transports', () => { const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: webSocket(), }, }) type Result = WatchBlockNumberParameters< typeof config, typeof mainnet.id | typeof optimism.id > expectTypeOf().toEqualTypeOf() watchBlockNumber(config, { poll: false, onBlockNumber() {}, }) type Result2 = WatchBlockNumberParameters expectTypeOf().toEqualTypeOf() watchBlockNumber(config, { chainId: mainnet.id, poll: true, onBlockNumber() {}, }) watchBlockNumber(config, { chainId: mainnet.id, // @ts-expect-error poll: false, onBlockNumber() {}, }) type Result3 = WatchBlockNumberParameters expectTypeOf().toEqualTypeOf() watchBlockNumber(config, { chainId: optimism.id, poll: true, onBlockNumber() {}, }) watchBlockNumber(config, { chainId: optimism.id, poll: false, onBlockNumber() {}, }) }) ================================================ FILE: packages/core/src/actions/watchBlockNumber.test.ts ================================================ import { config, testClient, wait } from '@wagmi/test' import { expect, test, vi } from 'vitest' import { watchBlockNumber } from './watchBlockNumber.js' test('default', async () => { const blockNumbers: bigint[] = [] const unwatch = watchBlockNumber(config, { onBlockNumber(blockNumber) { blockNumbers.push(blockNumber) }, }) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitUntil(() => blockNumbers.length === 3, { timeout: 10_000 }) expect(blockNumbers.length).toBe(3) unwatch() await wait(100) }) ================================================ FILE: packages/core/src/actions/watchBlockNumber.ts ================================================ import type { Chain, Transport, WebSocketTransport } from 'viem' import { type WatchBlockNumberParameters as viem_WatchBlockNumberParameters, type WatchBlockNumberReturnType as viem_WatchBlockNumberReturnType, watchBlockNumber as viem_watchBlockNumber, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter, SyncConnectedChainParameter, } from '../types/properties.js' import type { UnionCompute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type WatchBlockNumberParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], /// chains extends readonly Chain[] = SelectChains, > = { [key in keyof chains]: UnionCompute< viem_WatchBlockNumberParameters< config['_internal']['transports'][chains[key]['id']] extends infer transport extends Transport ? Transport extends transport ? WebSocketTransport : transport : WebSocketTransport > & ChainIdParameter & SyncConnectedChainParameter > }[number] export type WatchBlockNumberReturnType = viem_WatchBlockNumberReturnType // TODO: wrap in viem's `observe` to avoid duplicate invocations. /** https://wagmi.sh/core/api/actions/watchBlockNumber */ export function watchBlockNumber< config extends Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], >( config: config, parameters: WatchBlockNumberParameters, ): WatchBlockNumberReturnType { const { syncConnectedChain = config._internal.syncConnectedChain, ...rest } = parameters as WatchBlockNumberParameters let unwatch: WatchBlockNumberReturnType | undefined const listener = (chainId: number | undefined) => { if (unwatch) unwatch() const client = config.getClient({ chainId }) const action = getAction(client, viem_watchBlockNumber, 'watchBlockNumber') unwatch = action(rest as viem_WatchBlockNumberParameters) return unwatch } // set up listener for block number changes const unlisten = listener(parameters.chainId) // set up subscriber for connected chain changes let unsubscribe: (() => void) | undefined if (syncConnectedChain && !parameters.chainId) unsubscribe = config.subscribe( ({ chainId }) => chainId, async (chainId) => listener(chainId), ) return () => { unlisten?.() unsubscribe?.() } } ================================================ FILE: packages/core/src/actions/watchBlocks.test-d.ts ================================================ import { http, webSocket } from 'viem' import { mainnet, optimism } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { type WatchBlocksParameters, watchBlocks } from './watchBlocks.js' test('differing transports', () => { const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: webSocket(), }, }) type Result = WatchBlocksParameters< false, 'latest', typeof config, typeof mainnet.id | typeof optimism.id > expectTypeOf().toEqualTypeOf() watchBlocks(config, { poll: false, onBlock() {}, }) type Result2 = WatchBlocksParameters< false, 'latest', typeof config, typeof mainnet.id > expectTypeOf().toEqualTypeOf() watchBlocks(config, { chainId: mainnet.id, poll: true, onBlock() {}, }) type Result3 = WatchBlocksParameters< false, 'latest', typeof config, typeof optimism.id > expectTypeOf().toEqualTypeOf() watchBlocks(config, { chainId: optimism.id, poll: true, onBlock() {}, }) watchBlocks(config, { chainId: optimism.id, poll: false, onBlock() {}, }) }) ================================================ FILE: packages/core/src/actions/watchBlocks.test.ts ================================================ import { config, testClient, wait } from '@wagmi/test' import type { Block } from 'viem' import { expect, test, vi } from 'vitest' import { watchBlocks } from './watchBlocks.js' test('default', async () => { const blocks: Block[] = [] const unwatch = watchBlocks(config, { onBlock(block) { blocks.push(block) }, }) await testClient.mainnet.mine({ blocks: 1 }) await wait(500) await testClient.mainnet.mine({ blocks: 1 }) await wait(500) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitUntil(() => blocks.length === 3, { timeout: 10_000 }) expect(blocks.length).toBe(3) unwatch() await wait(100) }) ================================================ FILE: packages/core/src/actions/watchBlocks.ts ================================================ import type { BlockTag, Chain, Transport, WebSocketTransport } from 'viem' import { type WatchBlocksParameters as viem_WatchBlocksParameters, type WatchBlocksReturnType as viem_WatchBlocksReturnType, watchBlocks as viem_watchBlocks, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter, SyncConnectedChainParameter, } from '../types/properties.js' import type { IsNarrowable, UnionCompute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type WatchBlocksParameters< includeTransactions extends boolean = false, blockTag extends BlockTag = 'latest', config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], /// chains extends readonly Chain[] = SelectChains, > = { [key in keyof chains]: UnionCompute< viem_WatchBlocksParameters< config['_internal']['transports'][chains[key]['id']] extends infer transport extends Transport ? Transport extends transport ? WebSocketTransport : transport : WebSocketTransport, IsNarrowable extends true ? chains[key] : undefined, includeTransactions, blockTag > & ChainIdParameter & SyncConnectedChainParameter > }[number] export type WatchBlocksReturnType = viem_WatchBlocksReturnType // TODO: wrap in viem's `observe` to avoid duplicate invocations. /** https://wagmi.sh/core/actions/watchBlocks */ export function watchBlocks< config extends Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], includeTransactions extends boolean = false, blockTag extends BlockTag = 'latest', >( config: config, parameters: WatchBlocksParameters< includeTransactions, blockTag, config, chainId >, ): WatchBlocksReturnType { const { syncConnectedChain = config._internal.syncConnectedChain, ...rest } = parameters as WatchBlocksParameters let unwatch: WatchBlocksReturnType | undefined const listener = (chainId: number | undefined) => { if (unwatch) unwatch() const client = config.getClient({ chainId }) const action = getAction(client, viem_watchBlocks, 'watchBlocks') unwatch = action(rest as viem_WatchBlocksParameters) return unwatch } // set up listener for block number changes const unlisten = listener(parameters.chainId) // set up subscriber for connected chain changes let unsubscribe: (() => void) | undefined if (syncConnectedChain && !parameters.chainId) unsubscribe = config.subscribe( ({ chainId }) => chainId, async (chainId) => listener(chainId), ) return () => { unlisten?.() unsubscribe?.() } } ================================================ FILE: packages/core/src/actions/watchChainId.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { watchChainId } from './watchChainId.js' test('default', async () => { const chainIds: number[] = [] const unwatch = watchChainId(config, { onChange(chainId) { chainIds.push(chainId) }, }) config.setState((x) => ({ ...x, chainId: chain.mainnet2.id })) config.setState((x) => ({ ...x, chainId: chain.mainnet.id })) config.setState((x) => ({ ...x, chainId: chain.mainnet2.id })) expect(chainIds).toMatchInlineSnapshot(` [ 456, 1, 456, ] `) unwatch() }) ================================================ FILE: packages/core/src/actions/watchChainId.ts ================================================ import type { Config } from '../createConfig.js' import type { GetChainIdReturnType } from './getChainId.js' export type WatchChainIdParameters = { onChange( chainId: GetChainIdReturnType, prevChainId: GetChainIdReturnType, ): void } export type WatchChainIdReturnType = () => void /** https://wagmi.sh/core/api/actions/watchChainId */ export function watchChainId( config: config, parameters: WatchChainIdParameters, ): WatchChainIdReturnType { const { onChange } = parameters return config.subscribe((state) => state.chainId, onChange) } ================================================ FILE: packages/core/src/actions/watchChains.test.ts ================================================ import { chain, config } from '@wagmi/test' import type { Chain } from 'viem' import { expect, test } from 'vitest' import { watchChains } from './watchChains.js' test('default', async () => { let chains: readonly [Chain, ...Chain[]] = config.chains const unwatch = watchChains(config, { onChange(nextChains) { chains = nextChains }, }) config._internal.chains.setState([chain.mainnet, chain.mainnet2]) expect(chains.map((x) => x.id)).toMatchInlineSnapshot(` [ 1, 456, ] `) config._internal.chains.setState([ chain.mainnet, chain.mainnet2, chain.optimism, ]) expect(chains.map((x) => x.id)).toMatchInlineSnapshot(` [ 1, 456, 10, ] `) unwatch() }) ================================================ FILE: packages/core/src/actions/watchChains.ts ================================================ import type { Config } from '../createConfig.js' import type { GetChainsReturnType } from './getChains.js' export type WatchChainsParameters = { onChange( chains: GetChainsReturnType, prevChains: GetChainsReturnType, ): void } export type WatchChainsReturnType = () => void /** * @internal * We don't expose this because as far as consumers know, you can't chainge (lol) `config.chains` at runtime. * Setting `config.chains` via `config._internal.chains.setState(...)` is an extremely advanced use case that's not worth documenting or supporting in the public API at this time. */ export function watchChains( config: config, parameters: WatchChainsParameters, ): WatchChainsReturnType { const { onChange } = parameters return config._internal.chains.subscribe((chains, prevChains) => { onChange( chains as unknown as GetChainsReturnType, prevChains as unknown as GetChainsReturnType, ) }) } ================================================ FILE: packages/core/src/actions/watchClient.test-d.ts ================================================ import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { watchClient } from './watchClient.js' test('default', () => { watchClient(config, { onChange(client) { expectTypeOf(client.chain).toEqualTypeOf< (typeof config)['chains'][number] >() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }, }) }) ================================================ FILE: packages/core/src/actions/watchClient.test.ts ================================================ import { config } from '@wagmi/test' import type { Client } from 'viem' import { expect, test } from 'vitest' import { switchChain } from './switchChain.js' import { watchClient } from './watchClient.js' test('default', async () => { const clients: Client[] = [] const unwatch = watchClient(config, { onChange(client) { clients.push(client) }, }) switchChain(config, { chainId: 456 }) switchChain(config, { chainId: 10 }) switchChain(config, { chainId: 1 }) expect(clients.length).toBe(3) unwatch() }) ================================================ FILE: packages/core/src/actions/watchClient.ts ================================================ import type { Config } from '../createConfig.js' import { type GetClientReturnType, getClient } from './getClient.js' export type WatchClientParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = { onChange( publicClient: GetClientReturnType, prevClient: GetClientReturnType, ): void } export type WatchClientReturnType = () => void /** https://wagmi.sh/core/api/actions/watchClient */ export function watchClient< config extends Config, chainId extends config['chains'][number]['id'], >( config: config, parameters: WatchClientParameters, ): WatchClientReturnType { const { onChange } = parameters return config.subscribe( () => getClient(config) as GetClientReturnType, onChange, { equalityFn(a, b) { return a?.uid === b?.uid }, }, ) } ================================================ FILE: packages/core/src/actions/watchConnection.test.ts ================================================ import { config } from '@wagmi/test' import type { Address } from 'viem' import { expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { watchConnection } from './watchConnection.js' test('default', async () => { const connections: { address: Address | undefined; status: string }[] = [] const unwatch = watchConnection(config, { onChange(data) { connections.push({ address: data.address, status: data.status }) }, }) await connect(config, { connector: config.connectors[0]! }) await disconnect(config) expect(connections).toMatchInlineSnapshot(` [ { "address": undefined, "status": "connecting", }, { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "status": "connected", }, { "address": undefined, "status": "disconnected", }, ] `) unwatch() }) ================================================ FILE: packages/core/src/actions/watchConnection.ts ================================================ import type { Config } from '../createConfig.js' import { deepEqual } from '../utils/deepEqual.js' import { type GetConnectionReturnType, getConnection } from './getConnection.js' export type WatchConnectionParameters = { onChange( connection: GetConnectionReturnType, prevConnection: GetConnectionReturnType, ): void } export type WatchConnectionReturnType = () => void /** https://wagmi.sh/core/api/actions/watchConnection */ export function watchConnection( config: config, parameters: WatchConnectionParameters, ): WatchConnectionReturnType { const { onChange } = parameters return config.subscribe(() => getConnection(config), onChange, { equalityFn(a, b) { const { connector: aConnector, ...aRest } = a const { connector: bConnector, ...bRest } = b return ( deepEqual(aRest, bRest) && // check connector separately aConnector?.id === bConnector?.id && aConnector?.uid === bConnector?.uid ) }, }) } ================================================ FILE: packages/core/src/actions/watchConnections.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import type { Connection } from '../createConfig.js' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { watchConnections } from './watchConnections.js' test('default', async () => { const connections: Connection[][] = [] const unwatch = watchConnections(config, { onChange(connection) { connections.push(connection) }, }) const connector = config.connectors[0]! expect(connections).toEqual([]) await connect(config, { connector }) expect(connections[0]?.length).toEqual(1) await disconnect(config, { connector }) expect(connections[1]).toEqual([]) unwatch() }) ================================================ FILE: packages/core/src/actions/watchConnections.ts ================================================ import type { Config } from '../createConfig.js' import { deepEqual } from '../utils/deepEqual.js' import { type GetConnectionsReturnType, getConnections, } from './getConnections.js' export type WatchConnectionsParameters = { onChange( connections: GetConnectionsReturnType, prevConnections: GetConnectionsReturnType, ): void } export type WatchConnectionsReturnType = () => void /** https://wagmi.sh/core/api/actions/watchConnections */ export function watchConnections( config: Config, parameters: WatchConnectionsParameters, ): WatchConnectionsReturnType { const { onChange } = parameters return config.subscribe(() => getConnections(config), onChange, { equalityFn: deepEqual, }) } ================================================ FILE: packages/core/src/actions/watchConnectors.test.ts ================================================ import { accounts, config } from '@wagmi/test' import { expect, test } from 'vitest' import { mock } from '../connectors/mock.js' import type { Connector } from '../createConfig.js' import { watchConnectors } from './watchConnectors.js' test('default', async () => { const connectors: (readonly Connector[])[] = [] const unwatch = watchConnectors(config, { onChange(connector) { connectors.push(connector) }, }) const count = config.connectors.length expect(config.connectors).toEqual(config.connectors) config._internal.connectors.setState(() => [ ...config.connectors, config._internal.connectors.setup(mock({ accounts })), ]) expect(config.connectors.length).toBe(count + 1) unwatch() }) ================================================ FILE: packages/core/src/actions/watchConnectors.ts ================================================ import type { Config } from '../createConfig.js' import type { GetConnectorsReturnType } from './getConnectors.js' export type WatchConnectorsParameters = { onChange( connections: GetConnectorsReturnType, prevConnectors: GetConnectorsReturnType, ): void } export type WatchConnectorsReturnType = () => void /** https://wagmi.sh/core/api/actions/watchConnectors */ export function watchConnectors( config: config, parameters: WatchConnectorsParameters, ): WatchConnectorsReturnType { const { onChange } = parameters return config._internal.connectors.subscribe((connectors, prevConnectors) => { onChange(Object.values(connectors), prevConnectors) }) } ================================================ FILE: packages/core/src/actions/watchContractEvent.test-d.ts ================================================ import { abi, config } from '@wagmi/test' import { http, webSocket } from 'viem' import { mainnet, optimism } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { type WatchContractEventParameters, watchContractEvent, } from './watchContractEvent.js' test('default', () => { watchContractEvent(config, { address: '0x', abi: abi.erc20, eventName: 'Transfer', args: { from: '0x', to: '0x', }, onLogs(logs) { expectTypeOf(logs[0]!.eventName).toEqualTypeOf<'Transfer'>() expectTypeOf(logs[0]!.args).toEqualTypeOf<{ from?: `0x${string}` | undefined to?: `0x${string}` | undefined value?: bigint | undefined }>() }, }) }) test('behavior: no eventName', () => { type Result = WatchContractEventParameters< typeof abi.erc20, undefined, true, typeof config > expectTypeOf().toEqualTypeOf< | { from?: `0x${string}` | `0x${string}`[] | null | undefined to?: `0x${string}` | `0x${string}`[] | null | undefined } | { owner?: `0x${string}` | `0x${string}`[] | null | undefined spender?: `0x${string}` | `0x${string}`[] | null | undefined } | undefined >() watchContractEvent(config, { address: '0x', abi: abi.erc20, args: { // TODO: Figure out why this is not working // @ts-ignore from: '0x', to: '0x', }, onLogs(logs) { expectTypeOf(logs[0]!.eventName).toEqualTypeOf<'Transfer' | 'Approval'>() expectTypeOf(logs[0]!.args).toEqualTypeOf< | { from?: `0x${string}` | undefined to?: `0x${string}` | undefined value?: bigint | undefined } | { owner?: `0x${string}` | undefined spender?: `0x${string}` | undefined value?: bigint | undefined } >() }, }) }) test('differing transports', () => { const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: webSocket(), }, }) type Result = WatchContractEventParameters< typeof abi.erc20, 'Transfer' | 'Approval', true, typeof config, typeof mainnet.id | typeof optimism.id > expectTypeOf().toEqualTypeOf() watchContractEvent(config, { poll: false, address: '0x', abi: abi.erc20, onLogs() {}, }) type Result2 = WatchContractEventParameters< typeof abi.erc20, 'Transfer' | 'Approval', true, typeof config, typeof mainnet.id > expectTypeOf().toEqualTypeOf() watchContractEvent(config, { chainId: mainnet.id, poll: true, address: '0x', abi: abi.erc20, onLogs() {}, }) type Result3 = WatchContractEventParameters< typeof abi.erc20, 'Transfer' | 'Approval', true, typeof config, typeof optimism.id > expectTypeOf().toEqualTypeOf() watchContractEvent(config, { chainId: optimism.id, poll: true, address: '0x', abi: abi.erc20, onLogs() {}, }) watchContractEvent(config, { chainId: optimism.id, poll: false, address: '0x', abi: abi.erc20, onLogs() {}, }) }) ================================================ FILE: packages/core/src/actions/watchContractEvent.test.ts ================================================ import { abi, accounts, address, config, testClient, transactionHashRegex, wait, } from '@wagmi/test' import { createWalletClient, erc20Abi, http, parseEther } from 'viem' import type { WatchEventOnLogsParameter } from 'viem/actions' import { beforeEach, expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { readContract } from './readContract.js' import { watchContractEvent } from './watchContractEvent.js' import { writeContract } from './writeContract.js' const connector = config.connectors[0]! // TODO: Some test does not call disconnect after finishing. Remove once fixing it. beforeEach(async () => { if (config.state.current) { const connection = config.state.connections.get(config.state.current)! const connector = connection.connector await disconnect(config, { connector }) } }) test('default', async () => { const data = await connect(config, { connector }) const connectedAddress = data.accounts[0] // impersonate usdc holder account and transfer usdc to connected account await testClient.mainnet.impersonateAccount({ address: address.usdcHolder }) await testClient.mainnet.setBalance({ address: address.usdcHolder, value: 10000000000000000000000n, }) await createWalletClient({ account: address.usdcHolder, chain: testClient.mainnet.chain, transport: http(), }).writeContract({ address: address.usdc, abi: abi.erc20, functionName: 'transfer', args: [connectedAddress, parseEther('10', 'gwei')], }) await testClient.mainnet.mine({ blocks: 1 }) await testClient.mainnet.stopImpersonatingAccount({ address: address.usdcHolder, }) const balance = await readContract(config, { address: address.usdc, abi: erc20Abi, functionName: 'balanceOf', args: [connectedAddress], }) expect(balance).toBeGreaterThan(0n) // start watching transfer events let logs: WatchEventOnLogsParameter = [] const unwatch = watchContractEvent(config, { address: address.usdc, abi: abi.erc20, eventName: 'Transfer', onLogs(next) { logs = logs.concat(next) }, }) await writeContract(config, { address: address.usdc, abi: abi.erc20, functionName: 'transfer', args: [accounts[1], parseEther('1', 'gwei')], }) await writeContract(config, { address: address.usdc, abi: abi.erc20, functionName: 'transfer', args: [accounts[3], parseEther('1', 'gwei')], }) await testClient.mainnet.mine({ blocks: 1 }) await testClient.mainnet.mine({ blocks: 1 }) await wait(1000) // wait for events to be emitted unwatch() await wait(100) expect(logs.length).toBe(2) expect(logs[0]?.transactionHash).toMatch(transactionHashRegex) await disconnect(config, { connector }) }) ================================================ FILE: packages/core/src/actions/watchContractEvent.ts ================================================ import type { Abi, Chain, ContractEventName, Transport, WebSocketTransport, } from 'viem' import { type WatchContractEventParameters as viem_WatchContractEventParameters, type WatchContractEventReturnType as viem_WatchContractEventReturnType, watchContractEvent as viem_watchContractEvent, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter, SyncConnectedChainParameter, } from '../types/properties.js' import type { UnionCompute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type WatchContractEventParameters< abi extends Abi | readonly unknown[] = Abi, eventName extends ContractEventName | undefined = ContractEventName, strict extends boolean | undefined = undefined, config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], /// chains extends readonly Chain[] = SelectChains, > = { [key in keyof chains]: UnionCompute< viem_WatchContractEventParameters< abi, eventName, strict, config['_internal']['transports'][chains[key]['id']] extends infer transport extends Transport ? Transport extends transport ? WebSocketTransport : transport : WebSocketTransport > & ChainIdParameter & SyncConnectedChainParameter > }[number] export type WatchContractEventReturnType = viem_WatchContractEventReturnType // TODO: wrap in viem's `observe` to avoid duplicate invocations. /** https://wagmi.sh/core/api/actions/watchContractEvent */ export function watchContractEvent< config extends Config, chainId extends config['chains'][number]['id'], const abi extends Abi | readonly unknown[], eventName extends ContractEventName | undefined, strict extends boolean | undefined = undefined, >( config: config, parameters: WatchContractEventParameters< abi, eventName, strict, config, chainId >, ) { const { syncConnectedChain = config._internal.syncConnectedChain, ...rest } = parameters let unwatch: WatchContractEventReturnType | undefined const listener = (chainId: number | undefined) => { if (unwatch) unwatch() const client = config.getClient({ chainId }) const action = getAction( client, viem_watchContractEvent, 'watchContractEvent', ) unwatch = action(rest as unknown as viem_WatchContractEventParameters) return unwatch } // set up listener for transaction changes const unlisten = listener(parameters.chainId) // set up subscriber for connected chain changes let unsubscribe: (() => void) | undefined if (syncConnectedChain && !parameters.chainId) unsubscribe = config.subscribe( ({ chainId }) => chainId, async (chainId) => listener(chainId), ) return () => { unlisten?.() unsubscribe?.() } } ================================================ FILE: packages/core/src/actions/watchPendingTransactions.test-d.ts ================================================ import { http, webSocket } from 'viem' import { mainnet, optimism } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { type WatchPendingTransactionsParameters, watchPendingTransactions, } from './watchPendingTransactions.js' test('differing transports', () => { const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: webSocket(), }, }) type Result = WatchPendingTransactionsParameters< typeof config, typeof mainnet.id | typeof optimism.id > expectTypeOf().toEqualTypeOf() watchPendingTransactions(config, { poll: false, onTransactions() {}, }) type Result2 = WatchPendingTransactionsParameters< typeof config, typeof mainnet.id > expectTypeOf().toEqualTypeOf() watchPendingTransactions(config, { chainId: mainnet.id, poll: true, onTransactions() {}, }) type Result3 = WatchPendingTransactionsParameters< typeof config, typeof optimism.id > expectTypeOf().toEqualTypeOf() watchPendingTransactions(config, { chainId: optimism.id, poll: true, onTransactions() {}, }) watchPendingTransactions(config, { chainId: optimism.id, poll: false, onTransactions() {}, }) }) ================================================ FILE: packages/core/src/actions/watchPendingTransactions.test.ts ================================================ import { accounts, config, testClient, transactionHashRegex, wait, } from '@wagmi/test' import { parseEther } from 'viem' import type { OnTransactionsParameter } from 'viem/actions' import { expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { sendTransaction } from './sendTransaction.js' import { watchPendingTransactions } from './watchPendingTransactions.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) let transactions: OnTransactionsParameter = [] const unwatch = watchPendingTransactions(config, { onTransactions(next) { transactions = [...transactions, ...next] }, }) await wait(500) await sendTransaction(config, { to: accounts[1], value: parseEther('1'), }) await wait(100) await sendTransaction(config, { to: accounts[3], value: parseEther('1'), }) await wait(100) await testClient.mainnet.mine({ blocks: 1 }) unwatch() await wait(100) expect(transactions.length).toBe(2) expect(transactions[0]).toMatch(transactionHashRegex) await disconnect(config, { connector }) }) ================================================ FILE: packages/core/src/actions/watchPendingTransactions.ts ================================================ import type { Chain, Transport, WebSocketTransport } from 'viem' import { type WatchPendingTransactionsParameters as viem_WatchPendingTransactionsParameters, type WatchPendingTransactionsReturnType as viem_WatchPendingTransactionsReturnType, watchPendingTransactions as viem_watchPendingTransactions, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter, SyncConnectedChainParameter, } from '../types/properties.js' import type { UnionCompute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' export type WatchPendingTransactionsParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], /// chains extends readonly Chain[] = SelectChains, > = { [key in keyof chains]: UnionCompute< viem_WatchPendingTransactionsParameters< config['_internal']['transports'][chains[key]['id']] extends infer transport extends Transport ? Transport extends transport ? WebSocketTransport : transport : WebSocketTransport > & ChainIdParameter & SyncConnectedChainParameter > }[number] export type WatchPendingTransactionsReturnType = viem_WatchPendingTransactionsReturnType // TODO: wrap in viem's `observe` to avoid duplicate invocations. /** https://wagmi.sh/core/api/actions/watchPendingTransactions */ export function watchPendingTransactions< config extends Config, chainId extends config['chains'][number]['id'], >( config: config, parameters: WatchPendingTransactionsParameters, ) { const { syncConnectedChain = config._internal.syncConnectedChain, ...rest } = parameters let unwatch: WatchPendingTransactionsReturnType | undefined const listener = (chainId: number | undefined) => { if (unwatch) unwatch() const client = config.getClient({ chainId }) const action = getAction( client, viem_watchPendingTransactions, 'watchPendingTransactions', ) unwatch = action(rest as viem_WatchPendingTransactionsParameters) return unwatch } // set up listener for transaction changes const unlisten = listener(parameters.chainId) // set up subscriber for connected chain changes let unsubscribe: (() => void) | undefined if (syncConnectedChain && !parameters.chainId) unsubscribe = config.subscribe( ({ chainId }) => chainId, async (chainId) => listener(chainId), ) return () => { unlisten?.() unsubscribe?.() } } ================================================ FILE: packages/core/src/actions/watchPublicClient.test-d.ts ================================================ import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { watchPublicClient } from './watchPublicClient.js' test('default', () => { watchPublicClient(config, { onChange(client) { expectTypeOf(client.chain).toEqualTypeOf< (typeof config)['chains'][number] >() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }, }) }) ================================================ FILE: packages/core/src/actions/watchPublicClient.test.ts ================================================ import { config } from '@wagmi/test' import type { Client } from 'viem' import { expect, test } from 'vitest' import { switchChain } from './switchChain.js' import { watchPublicClient } from './watchPublicClient.js' test('default', async () => { const clients: Client[] = [] const unwatch = watchPublicClient(config, { onChange(client) { clients.push(client) }, }) switchChain(config, { chainId: 456 }) switchChain(config, { chainId: 10 }) switchChain(config, { chainId: 1 }) expect(clients.length).toBe(3) unwatch() }) ================================================ FILE: packages/core/src/actions/watchPublicClient.ts ================================================ import type { Config } from '../createConfig.js' import { type GetPublicClientReturnType, getPublicClient, } from './getPublicClient.js' export type WatchPublicClientParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = { onChange( publicClient: GetPublicClientReturnType, prevPublicClient: GetPublicClientReturnType, ): void } export type WatchPublicClientReturnType = () => void /** https://wagmi.sh/core/api/actions/watchPublicClient */ export function watchPublicClient< config extends Config, chainId extends config['chains'][number]['id'], >( config: config, parameters: WatchPublicClientParameters, ): WatchPublicClientReturnType { const { onChange } = parameters return config.subscribe( () => getPublicClient(config) as GetPublicClientReturnType, onChange, { equalityFn(a, b) { return a?.uid === b?.uid }, }, ) } ================================================ FILE: packages/core/src/actions/writeContract.bench-d.ts ================================================ import { attest } from '@ark/attest' import type { abi } from '@wagmi/test' import { parseAbi } from 'viem' import viemPackageJson from 'viem/package.json' with { type: 'json' } import { test } from 'vitest' import type { WriteContractParameters } from './writeContract.js' test('default', () => { type Result = WriteContractParameters<(typeof abi)['erc20'], 'approve'> const res = {} as Result attest.instantiations([143162, 'instantiations']) attest(res.args) if (viemPackageJson.version.startsWith('2.43')) attest(res.args).type.toString.snap( // biome-ignore lint/style/noUnusedTemplateLiteral: stable `readonly [spender: \`0x\${string}\`, amount: bigint]`, ) }) const abiOverload = parseAbi([ 'function foo() returns (int8)', 'function foo(address account) returns (string)', 'function foo(address sender, address account) returns ((address foo, address bar))', 'function bar() returns (int8)', ]) test('overloads', () => { type Result = WriteContractParameters const res = {} as Result attest.instantiations([21691, 'instantiations']) attest< | readonly [] | readonly [account: `0x${string}`] | readonly [sender: `0x${string}`, account: `0x${string}`] | undefined >(res.args) if (viemPackageJson.version.startsWith('2.43')) attest(res.args).type.toString.snap(` | readonly [] | readonly [account: \`0x\${string}\`] | readonly [sender: \`0x\${string}\`, account: \`0x\${string}\`] | undefined`) }) ================================================ FILE: packages/core/src/actions/writeContract.test-d.ts ================================================ import { abi, config } from '@wagmi/test' import { type Address, http, parseAbi } from 'viem' import { celo, mainnet } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { simulateContract } from './simulateContract.js' import { type WriteContractParameters, writeContract } from './writeContract.js' test('default', async () => { await writeContract(config, { address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], chainId: 1, }) }) test('simulateContract', async () => { const { request } = await simulateContract(config, { account: '0x', address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], chainId: 1, }) await writeContract(config, request) await writeContract(config, { address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], }) }) test('chain formatters', () => { const config = createConfig({ chains: [mainnet, celo], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) type Result = WriteContractParameters< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config > expectTypeOf().toMatchTypeOf<{ chainId?: typeof celo.id | typeof mainnet.id | undefined feeCurrency?: `0x${string}` | undefined }>() writeContract(config, { address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], feeCurrency: '0x', }) type Result2 = WriteContractParameters< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config, typeof celo.id > expectTypeOf().toMatchTypeOf<{ functionName: 'approve' | 'transfer' | 'transferFrom' args: readonly [Address, Address, bigint] feeCurrency?: `0x${string}` | undefined }>() writeContract(config, { chainId: celo.id, address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], feeCurrency: '0x', }) type Result3 = WriteContractParameters< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config, typeof mainnet.id > expectTypeOf().toMatchTypeOf<{ functionName: 'approve' | 'transfer' | 'transferFrom' args: readonly [Address, Address, bigint] }>() expectTypeOf().not.toMatchTypeOf<{ feeCurrency?: `0x${string}` | undefined }>() writeContract(config, { chainId: mainnet.id, address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], // @ts-expect-error feeCurrency: '0x', }) }) test('overloads', async () => { const abi = parseAbi([ 'function foo() returns (int8)', 'function foo(address) returns (string)', 'function foo(address, address) returns ((address foo, address bar))', 'function bar(uint256) returns (int8)', ]) type Result = WriteContractParameters expectTypeOf().toEqualTypeOf<'foo' | 'bar'>() expectTypeOf().toEqualTypeOf< | readonly [] | readonly [`0x${string}`] | readonly [`0x${string}`, `0x${string}`] | undefined >() writeContract(config, { address: '0x', abi, functionName: 'foo', }) writeContract(config, { address: '0x', abi, functionName: 'foo', args: ['0x'], }) writeContract(config, { address: '0x', abi, functionName: 'foo', args: ['0x', '0x'], }) writeContract(config, { address: '0x', abi, functionName: 'foo', // @ts-expect-error args: ['0x', 123n], }) type Result2 = WriteContractParameters expectTypeOf().toEqualTypeOf<'foo' | 'bar'>() expectTypeOf().toEqualTypeOf() }) ================================================ FILE: packages/core/src/actions/writeContract.ts ================================================ import type { Abi, Account, Chain, Client, ContractFunctionArgs, ContractFunctionName, } from 'viem' import { type WriteContractErrorType as viem_WriteContractErrorType, type WriteContractParameters as viem_WriteContractParameters, type WriteContractReturnType as viem_WriteContractReturnType, writeContract as viem_writeContract, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { BaseErrorType, ErrorType } from '../errors/base.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter, ConnectorParameter, } from '../types/properties.js' import type { Compute, UnionCompute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' import { type GetConnectorClientErrorType, getConnectorClient, } from './getConnectorClient.js' export type WriteContractParameters< abi extends Abi | readonly unknown[] = Abi, functionName extends ContractFunctionName< abi, 'nonpayable' | 'payable' > = ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName > = ContractFunctionArgs, config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], /// allFunctionNames = ContractFunctionName, chains extends readonly Chain[] = SelectChains, > = UnionCompute< { // TODO: Should use `UnionStrictOmit<..., 'chain'>` on `viem_WriteContractParameters` result instead // temp workaround that doesn't affect runtime behavior for https://github.com/wevm/wagmi/issues/3981 [key in keyof chains]: viem_WriteContractParameters< abi, functionName, args, chains[key], Account, chains[key], allFunctionNames > }[number] & Compute> & ConnectorParameter > export type WriteContractReturnType = viem_WriteContractReturnType export type WriteContractErrorType = // getConnectorClient() | GetConnectorClientErrorType // base | BaseErrorType | ErrorType // viem | viem_WriteContractErrorType /** https://wagmi.sh/core/api/actions/writeContract */ export async function writeContract< config extends Config, const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName >, chainId extends config['chains'][number]['id'], >( config: config, parameters: WriteContractParameters, ): Promise { const { account, chainId, connector, ...request } = parameters let client: Client if (typeof account === 'object' && account?.type === 'local') client = config.getClient({ chainId }) else client = await getConnectorClient(config, { account: account ?? undefined, assertChainId: false, chainId, connector, }) const chain = (() => { if (!chainId || client.chain?.id === chainId) return client.chain return { id: chainId } })() const action = getAction(client, viem_writeContract, 'writeContract') const hash = await action({ ...(request as any), ...(account ? { account } : {}), assertChainId: !!chainId, chain, }) return hash } ================================================ FILE: packages/core/src/actions/writeContractSync.test.ts ================================================ import { abi, address, config, testClient, wait } from '@wagmi/test' import { beforeEach, expect, test } from 'vitest' import { connect } from './connect.js' import { disconnect } from './disconnect.js' import { writeContractSync } from './writeContractSync.js' const connector = config.connectors[0]! beforeEach(async () => { if (config.state.current === connector.uid) await disconnect(config, { connector }) }) test('default', async () => { await connect(config, { connector }) const [receipt] = await Promise.all([ writeContractSync(config, { abi: abi.wagmiMintExample, address: address.wagmiMintExample, functionName: 'mint', }), (async () => { await wait(3000) await testClient.mainnet.mine({ blocks: 1 }) })(), ]) expect(receipt).toBeDefined() expect(receipt.status).toBe('success') expect(receipt.blockNumber).toBeDefined() await disconnect(config, { connector }) }) test('behavior: connector not connected', async () => { await connect(config, { connector }) await expect( writeContractSync(config, { connector: config.connectors[1], abi: abi.wagmiMintExample, address: address.wagmiMintExample, functionName: 'mint', }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ConnectorNotConnectedError: Connector not connected. Version: @wagmi/core@x.y.z] `) await disconnect(config, { connector }) }) test('behavior: account does not exist on connector', async () => { await connect(config, { connector }) await expect( writeContractSync(config, { account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', abi: abi.wagmiMintExample, address: address.wagmiMintExample, functionName: 'mint', }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ConnectorAccountNotFoundError: Account "0xA0Cf798816D4b9b9866b5330EEa46a18382f251e" not found for connector "Mock Connector". Version: @wagmi/core@x.y.z] `) await disconnect(config, { connector }) }) ================================================ FILE: packages/core/src/actions/writeContractSync.ts ================================================ import type { Abi, Account, Chain, Client, ContractFunctionArgs, ContractFunctionName, } from 'viem' import { type WriteContractSyncErrorType as viem_WriteContractSyncErrorType, type WriteContractSyncParameters as viem_WriteContractSyncParameters, type WriteContractSyncReturnType as viem_WriteContractSyncReturnType, writeContractSync as viem_writeContractSync, } from 'viem/actions' import type { Config } from '../createConfig.js' import type { BaseErrorType, ErrorType } from '../errors/base.js' import type { SelectChains } from '../types/chain.js' import type { ChainIdParameter, ConnectorParameter, } from '../types/properties.js' import type { Compute, UnionCompute } from '../types/utils.js' import { getAction } from '../utils/getAction.js' import { type GetConnectorClientErrorType, getConnectorClient, } from './getConnectorClient.js' export type WriteContractSyncParameters< abi extends Abi | readonly unknown[] = Abi, functionName extends ContractFunctionName< abi, 'nonpayable' | 'payable' > = ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName > = ContractFunctionArgs, config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], /// chains extends readonly Chain[] = SelectChains, > = UnionCompute< { [key in keyof chains]: viem_WriteContractSyncParameters< abi, functionName, args, chains[key], Account, chains[key] > }[number] & Compute> & ConnectorParameter > export type WriteContractSyncReturnType = viem_WriteContractSyncReturnType export type WriteContractSyncErrorType = // getConnectorClient() | GetConnectorClientErrorType // base | BaseErrorType | ErrorType // viem | viem_WriteContractSyncErrorType /** https://wagmi.sh/core/api/actions/writeContractSync */ export async function writeContractSync< config extends Config, const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName >, chainId extends config['chains'][number]['id'], >( config: config, parameters: WriteContractSyncParameters< abi, functionName, args, config, chainId >, ): Promise { const { account, chainId, connector, ...request } = parameters let client: Client if (typeof account === 'object' && account?.type === 'local') client = config.getClient({ chainId }) else client = await getConnectorClient(config, { account: account ?? undefined, assertChainId: false, chainId, connector, }) const chain = (() => { if (!chainId || client.chain?.id === chainId) return client.chain return { id: chainId } })() const action = getAction(client, viem_writeContractSync, 'writeContractSync') const receipt = await action({ ...(request as any), ...(account ? { account } : {}), assertChainId: !!chainId, chain, }) return receipt } ================================================ FILE: packages/core/src/connectors/createConnector.test.ts ================================================ import { test } from 'vitest' import { createConnector } from './createConnector.js' test('default', () => { createConnector(() => { return { id: 'test', name: 'Test Connector', type: 'test', async setup() {}, async connect() { return { accounts: [] as never, chainId: 123 } }, async disconnect() {}, async getAccounts() { return [] }, async getChainId() { return 123 }, async isAuthorized() { return true }, onAccountsChanged() {}, onChainChanged() {}, async onDisconnect(_error) {}, async getProvider() {}, } }) }) ================================================ FILE: packages/core/src/connectors/createConnector.ts ================================================ import type { AddEthereumChainParameter, Address, Chain, Client, ProviderConnectInfo, ProviderMessage, } from 'viem' import type { Transport } from '../createConfig.js' import type { Emitter } from '../createEmitter.js' import type { Storage } from '../createStorage.js' import type { Compute, ExactPartial, StrictOmit } from '../types/utils.js' export type ConnectorEventMap = { change: { accounts?: readonly Address[] | undefined chainId?: number | undefined } connect: { accounts: readonly Address[]; chainId: number } disconnect: never error: { error: Error } message: { type: string; data?: unknown | undefined } } export type CreateConnectorFn< provider = unknown, properties extends Record = Record, storageItem extends Record = Record, > = (config: { chains: readonly [Chain, ...Chain[]] emitter: Emitter storage?: Compute> | null | undefined transports?: Record | undefined }) => Compute< { readonly icon?: string | undefined readonly id: string readonly name: string readonly rdns?: string | readonly string[] | undefined readonly type: string setup?(): Promise // TODO(v3): Make `withCapabilities: true` default behavior connect( parameters?: | { chainId?: number | undefined isReconnecting?: boolean | undefined withCapabilities?: withCapabilities | boolean | undefined } | undefined, ): Promise<{ // TODO(v3): Add `capabilities` (e.g. `readonly { address: Address; capabilities: Record | undefined }`) accounts: withCapabilities extends true ? readonly { address: Address; capabilities: Record }[] : readonly Address[] chainId: number }> disconnect(): Promise getAccounts(): Promise getChainId(): Promise getProvider( parameters?: { chainId?: number | undefined } | undefined, ): Promise getClient?( parameters?: { chainId?: number | undefined } | undefined, ): Promise isAuthorized(): Promise switchChain?( parameters: Compute<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number }>, ): Promise onAccountsChanged(accounts: string[]): void onChainChanged(chainId: string): void onConnect?(connectInfo: ProviderConnectInfo): void onDisconnect(error?: Error | undefined): void onMessage?(message: ProviderMessage): void } & properties > export function createConnector< provider, properties extends Record = Record, storageItem extends Record = Record, /// createConnectorFn extends CreateConnectorFn< provider, properties, storageItem > = CreateConnectorFn, >(createConnectorFn: createConnectorFn) { return createConnectorFn } ================================================ FILE: packages/core/src/connectors/injected.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { injected } from './injected.js' test('setup', () => { const connectorFn = injected() const connector = config._internal.connectors.setup(connectorFn) expect(connector.name).toEqual('Injected') }) test.each([ { wallet: undefined, expected: 'Injected' }, { wallet: 'coinbaseWallet', expected: 'Coinbase Wallet' }, { wallet: 'metaMask', expected: 'MetaMask' }, { wallet: 'phantom', expected: 'Phantom' }, { wallet: 'rainbow', expected: 'Rainbow' }, ] as const satisfies readonly { wallet: string | undefined expected: string }[])('injected({ wallet: $wallet })', ({ wallet, expected }) => { const connectorFn = injected({ target: wallet }) const connector = config._internal.connectors.setup(connectorFn) expect(connector.name).toEqual(expected) }) ================================================ FILE: packages/core/src/connectors/injected.ts ================================================ import { type AddEthereumChainParameter, type Address, type EIP1193Provider, getAddress, numberToHex, type ProviderConnectInfo, type ProviderRpcError, ResourceUnavailableRpcError, type RpcError, SwitchChainError, UserRejectedRequestError, withRetry, withTimeout, } from 'viem' import type { Connector } from '../createConfig.js' import { ChainNotConfiguredError } from '../errors/config.js' import { ProviderNotFoundError } from '../errors/connector.js' import type { Compute } from '../types/utils.js' import { createConnector } from './createConnector.js' export type InjectedParameters = { /** * Some injected providers do not support programmatic disconnect. * This flag simulates the disconnect behavior by keeping track of connection status in storage. * @default true */ shimDisconnect?: boolean | undefined /** * [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) Ethereum Provider to target */ target?: TargetId | Target | (() => Target | undefined) | undefined unstable_shimAsyncInject?: boolean | number | undefined } injected.type = 'injected' as const export function injected(parameters: InjectedParameters = {}) { const { shimDisconnect = true, unstable_shimAsyncInject } = parameters function getTarget(): Compute { const target = parameters.target if (typeof target === 'function') { const result = target() if (result) return result } if (typeof target === 'object') return target if (typeof target === 'string') return { ...(targetMap[target as keyof typeof targetMap] ?? { id: target, name: `${target[0]!.toUpperCase()}${target.slice(1)}`, provider: `is${target[0]!.toUpperCase()}${target.slice(1)}`, }), } return { id: 'injected', name: 'Injected', provider(window) { return window?.ethereum }, } } type Provider = WalletProvider | undefined type Properties = { onConnect(connectInfo: ProviderConnectInfo): void } type StorageItem = { [_ in 'injected.connected' | `${string}.disconnected`]: true } let accountsChanged: Connector['onAccountsChanged'] | undefined let chainChanged: Connector['onChainChanged'] | undefined let connect: Connector['onConnect'] | undefined let disconnect: Connector['onDisconnect'] | undefined return createConnector((config) => ({ get icon() { return getTarget().icon }, get id() { return getTarget().id }, get name() { return getTarget().name }, type: injected.type, async setup() { const provider = await this.getProvider() // Only start listening for events if `target` is set, otherwise `injected()` will also receive events if (provider?.on && parameters.target) { if (!connect) { connect = this.onConnect.bind(this) provider.on('connect', connect) } // We shouldn't need to listen for `'accountsChanged'` here since the `'connect'` event should suffice (and wallet shouldn't be connected yet). // Some wallets, like MetaMask, do not implement the `'connect'` event and overload `'accountsChanged'` instead. if (!accountsChanged) { accountsChanged = this.onAccountsChanged.bind(this) provider.on('accountsChanged', accountsChanged) } } }, async connect({ chainId, isReconnecting, withCapabilities } = {}) { const provider = await this.getProvider() if (!provider) throw new ProviderNotFoundError() let accounts: readonly Address[] = [] if (isReconnecting) accounts = await this.getAccounts().catch(() => []) else if (shimDisconnect) { // Attempt to show another prompt for selecting account if `shimDisconnect` flag is enabled try { const permissions = await provider.request({ method: 'wallet_requestPermissions', params: [{ eth_accounts: {} }], }) accounts = (permissions[0]?.caveats?.[0]?.value as string[])?.map( (x) => getAddress(x), ) // `'wallet_requestPermissions'` can return a different order of accounts than `'eth_accounts'` // switch to `'eth_accounts'` ordering if more than one account is connected // https://github.com/wevm/wagmi/issues/4140 if (accounts.length > 0) { const sortedAccounts = await this.getAccounts() accounts = sortedAccounts } } catch (err) { const error = err as RpcError // Not all injected providers support `wallet_requestPermissions` (e.g. MetaMask iOS). // Only bubble up error if user rejects request if (error.code === UserRejectedRequestError.code) throw new UserRejectedRequestError(error) // Or prompt is already open if (error.code === ResourceUnavailableRpcError.code) throw error } } try { if (!accounts?.length && !isReconnecting) { const requestedAccounts = await provider.request({ method: 'eth_requestAccounts', }) accounts = requestedAccounts.map((x) => getAddress(x)) } // Manage EIP-1193 event listeners // https://eips.ethereum.org/EIPS/eip-1193#events if (connect) { provider.removeListener('connect', connect) connect = undefined } if (!accountsChanged) { accountsChanged = this.onAccountsChanged.bind(this) provider.on('accountsChanged', accountsChanged) } if (!chainChanged) { chainChanged = this.onChainChanged.bind(this) provider.on('chainChanged', chainChanged) } if (!disconnect) { disconnect = this.onDisconnect.bind(this) provider.on('disconnect', disconnect) } // Switch to chain if provided let currentChainId = await this.getChainId() if (chainId && currentChainId !== chainId) { const chain = await this.switchChain!({ chainId }).catch((error) => { if (error.code === UserRejectedRequestError.code) throw error return { id: currentChainId } }) currentChainId = chain?.id ?? currentChainId } // Remove disconnected shim if it exists if (shimDisconnect) await config.storage?.removeItem(`${this.id}.disconnected`) // Add connected shim if no target exists if (!parameters.target) await config.storage?.setItem('injected.connected', true) return { accounts: (withCapabilities ? accounts.map((address) => ({ address, capabilities: {} })) : accounts) as never, chainId: currentChainId, } } catch (err) { const error = err as RpcError if (error.code === UserRejectedRequestError.code) throw new UserRejectedRequestError(error) if (error.code === ResourceUnavailableRpcError.code) throw new ResourceUnavailableRpcError(error) throw error } }, async disconnect() { const provider = await this.getProvider() if (!provider) throw new ProviderNotFoundError() // Manage EIP-1193 event listeners if (chainChanged) { provider.removeListener('chainChanged', chainChanged) chainChanged = undefined } if (disconnect) { provider.removeListener('disconnect', disconnect) disconnect = undefined } if (!connect) { connect = this.onConnect.bind(this) provider.on('connect', connect) } // Experimental support for MetaMask disconnect // https://github.com/MetaMask/metamask-improvement-proposals/blob/main/MIPs/mip-2.md try { // Adding timeout as not all wallets support this method and can hang // https://github.com/wevm/wagmi/issues/4064 await withTimeout( () => // TODO: Remove explicit type for viem@3 provider.request<{ Method: 'wallet_revokePermissions' Parameters: [permissions: { eth_accounts: Record }] ReturnType: null }>({ // `'wallet_revokePermissions'` added in `viem@2.10.3` method: 'wallet_revokePermissions', params: [{ eth_accounts: {} }], }), { timeout: 100 }, ) } catch {} // Add shim signalling connector is disconnected if (shimDisconnect) { await config.storage?.setItem(`${this.id}.disconnected`, true) } if (!parameters.target) await config.storage?.removeItem('injected.connected') }, async getAccounts() { const provider = await this.getProvider() if (!provider) throw new ProviderNotFoundError() const accounts = await provider.request({ method: 'eth_accounts' }) return accounts.map((x) => getAddress(x)) }, async getChainId() { const provider = await this.getProvider() if (!provider) throw new ProviderNotFoundError() const hexChainId = await provider.request({ method: 'eth_chainId' }) return Number(hexChainId) }, async getProvider() { if (typeof window === 'undefined') return undefined let provider: Provider const target = getTarget() if (typeof target.provider === 'function') provider = target.provider(window as Window | undefined) else if (typeof target.provider === 'string') provider = findProvider(window, target.provider) else provider = target.provider // Some wallets do not conform to EIP-1193 (e.g. Trust Wallet) // https://github.com/wevm/wagmi/issues/3526#issuecomment-1912683002 if (provider && !provider.removeListener) { // Try using `off` handler if it exists, otherwise noop if ('off' in provider && typeof provider.off === 'function') provider.removeListener = provider.off as typeof provider.removeListener else provider.removeListener = () => {} } return provider }, async isAuthorized() { try { const isDisconnected = shimDisconnect && // If shim exists in storage, connector is disconnected (await config.storage?.getItem(`${this.id}.disconnected`)) if (isDisconnected) return false // Don't allow injected connector to connect if no target is set and it hasn't already connected // (e.g. flag in storage is not set). This prevents a targetless injected connector from connecting // automatically whenever there is a targeted connector configured. if (!parameters.target) { const connected = await config.storage?.getItem('injected.connected') if (!connected) return false } const provider = await this.getProvider() if (!provider) { if ( unstable_shimAsyncInject !== undefined && unstable_shimAsyncInject !== false ) { // If no provider is found, check for async injection // https://github.com/wevm/references/issues/167 // https://github.com/MetaMask/detect-provider const handleEthereum = async () => { if (typeof window !== 'undefined') window.removeEventListener( 'ethereum#initialized', handleEthereum, ) const provider = await this.getProvider() return !!provider } const timeout = typeof unstable_shimAsyncInject === 'number' ? unstable_shimAsyncInject : 1_000 const res = await Promise.race([ ...(typeof window !== 'undefined' ? [ new Promise((resolve) => window.addEventListener( 'ethereum#initialized', () => resolve(handleEthereum()), { once: true }, ), ), ] : []), new Promise((resolve) => setTimeout(() => resolve(handleEthereum()), timeout), ), ]) if (res) return true } throw new ProviderNotFoundError() } // Use retry strategy as some injected wallets (e.g. MetaMask) fail to // immediately resolve JSON-RPC requests on page load. const accounts = await withRetry(() => this.getAccounts()) return !!accounts.length } catch { return false } }, async switchChain({ addEthereumChainParameter, chainId }) { const provider = await this.getProvider() if (!provider) throw new ProviderNotFoundError() const chain = config.chains.find((x) => x.id === chainId) if (!chain) throw new SwitchChainError(new ChainNotConfiguredError()) const promise = new Promise((resolve) => { const listener = ((data) => { if ('chainId' in data && data.chainId === chainId) { config.emitter.off('change', listener) resolve() } }) satisfies Parameters[1] config.emitter.on('change', listener) }) try { await Promise.all([ provider .request({ method: 'wallet_switchEthereumChain', params: [{ chainId: numberToHex(chainId) }], }) // During `'wallet_switchEthereumChain'`, MetaMask makes a `'net_version'` RPC call to the target chain. // If this request fails, MetaMask does not emit the `'chainChanged'` event, but will still switch the chain. // To counter this behavior, we request and emit the current chain ID to confirm the chain switch either via // this callback or an externally emitted `'chainChanged'` event. // https://github.com/MetaMask/metamask-extension/issues/24247 .then(async () => { const currentChainId = await this.getChainId() if (currentChainId === chainId) config.emitter.emit('change', { chainId }) }), promise, ]) return chain } catch (err) { const error = err as RpcError // Indicates chain is not added to provider if ( error.code === 4902 || // Unwrapping for MetaMask Mobile // https://github.com/MetaMask/metamask-mobile/issues/2944#issuecomment-976988719 (error as ProviderRpcError<{ originalError?: { code: number } }>) ?.data?.originalError?.code === 4902 ) { try { const { default: blockExplorer, ...blockExplorers } = chain.blockExplorers ?? {} let blockExplorerUrls: string[] | undefined if (addEthereumChainParameter?.blockExplorerUrls) blockExplorerUrls = addEthereumChainParameter.blockExplorerUrls else if (blockExplorer) blockExplorerUrls = [ blockExplorer.url, ...Object.values(blockExplorers).map((x) => x.url), ] let rpcUrls: readonly string[] if (addEthereumChainParameter?.rpcUrls?.length) rpcUrls = addEthereumChainParameter.rpcUrls else rpcUrls = [chain.rpcUrls.default?.http[0] ?? ''] const addEthereumChain = { blockExplorerUrls, chainId: numberToHex(chainId), chainName: addEthereumChainParameter?.chainName ?? chain.name, iconUrls: addEthereumChainParameter?.iconUrls, nativeCurrency: addEthereumChainParameter?.nativeCurrency ?? chain.nativeCurrency, rpcUrls, } satisfies AddEthereumChainParameter await Promise.all([ provider .request({ method: 'wallet_addEthereumChain', params: [addEthereumChain], }) .then(async () => { const currentChainId = await this.getChainId() if (currentChainId === chainId) config.emitter.emit('change', { chainId }) else throw new UserRejectedRequestError( new Error('User rejected switch after adding network.'), ) }), promise, ]) return chain } catch (error) { throw new UserRejectedRequestError(error as Error) } } if (error.code === UserRejectedRequestError.code) throw new UserRejectedRequestError(error) throw new SwitchChainError(error) } }, async onAccountsChanged(accounts) { // Disconnect if there are no accounts if (accounts.length === 0) this.onDisconnect() // Connect if emitter is listening for connect event (e.g. is disconnected and connects through wallet interface) else if (config.emitter.listenerCount('connect')) { const chainId = (await this.getChainId()).toString() this.onConnect({ chainId }) // Remove disconnected shim if it exists if (shimDisconnect) await config.storage?.removeItem(`${this.id}.disconnected`) } // Regular change event else config.emitter.emit('change', { accounts: accounts.map((x) => getAddress(x)), }) }, onChainChanged(chain) { const chainId = Number(chain) config.emitter.emit('change', { chainId }) }, async onConnect(connectInfo) { const accounts = await this.getAccounts() if (accounts.length === 0) return const chainId = Number(connectInfo.chainId) config.emitter.emit('connect', { accounts, chainId }) // Manage EIP-1193 event listeners const provider = await this.getProvider() if (provider) { if (connect) { provider.removeListener('connect', connect) connect = undefined } if (!accountsChanged) { accountsChanged = this.onAccountsChanged.bind(this) provider.on('accountsChanged', accountsChanged) } if (!chainChanged) { chainChanged = this.onChainChanged.bind(this) provider.on('chainChanged', chainChanged) } if (!disconnect) { disconnect = this.onDisconnect.bind(this) provider.on('disconnect', disconnect) } } }, async onDisconnect(error) { const provider = await this.getProvider() // If MetaMask emits a `code: 1013` error, wait for reconnection before disconnecting // https://github.com/MetaMask/providers/pull/120 if (error && (error as RpcError<1013>).code === 1013) { if (provider && !!(await this.getAccounts()).length) return } // No need to remove `${this.id}.disconnected` from storage because `onDisconnect` is typically // only called when the wallet is disconnected through the wallet's interface, meaning the wallet // actually disconnected and we don't need to simulate it. config.emitter.emit('disconnect') // Manage EIP-1193 event listeners if (provider) { if (chainChanged) { provider.removeListener('chainChanged', chainChanged) chainChanged = undefined } if (disconnect) { provider.removeListener('disconnect', disconnect) disconnect = undefined } if (!connect) { connect = this.onConnect.bind(this) provider.on('connect', connect) } } }, })) } const targetMap = { coinbaseWallet: { id: 'coinbaseWallet', name: 'Coinbase Wallet', provider(window) { if (window?.coinbaseWalletExtension) return window.coinbaseWalletExtension return findProvider(window, 'isCoinbaseWallet') }, }, metaMask: { id: 'metaMask', name: 'MetaMask', provider(window) { return findProvider(window, (provider) => { if (!provider.isMetaMask) return false // Brave tries to make itself look like MetaMask // Could also try RPC `web3_clientVersion` if following is unreliable if (provider.isBraveWallet && !provider._events && !provider._state) return false // Other wallets that try to look like MetaMask const flags = [ 'isApexWallet', 'isAvalanche', 'isBitKeep', 'isBlockWallet', 'isKuCoinWallet', 'isMathWallet', 'isOkxWallet', 'isOKExWallet', 'isOneInchIOSWallet', 'isOneInchAndroidWallet', 'isOpera', 'isPhantom', 'isPortal', 'isRabby', 'isTokenPocket', 'isTokenary', 'isUniswapWallet', 'isZerion', ] satisfies WalletProviderFlags[] for (const flag of flags) if (provider[flag]) return false return true }) }, }, phantom: { id: 'phantom', name: 'Phantom', provider(window) { if (window?.phantom?.ethereum) return window.phantom?.ethereum return findProvider(window, 'isPhantom') }, }, } as const satisfies TargetMap type TargetMap = { [_ in TargetId]?: Target | undefined } type Target = { icon?: string | undefined id: string name: string provider: | WalletProviderFlags | WalletProvider | ((window?: Window | undefined) => WalletProvider | undefined) } /** @deprecated */ type TargetId = Compute extends `is${infer name}` ? name extends `${infer char}${infer rest}` ? `${Lowercase}${rest}` : never : never /** * @deprecated As of 2024/10/16, we are no longer accepting new provider flags as EIP-6963 should be used instead. */ type WalletProviderFlags = | 'isApexWallet' | 'isAvalanche' | 'isBackpack' | 'isBifrost' | 'isBitKeep' | 'isBitski' | 'isBlockWallet' | 'isBraveWallet' | 'isCoinbaseWallet' | 'isDawn' | 'isEnkrypt' | 'isExodus' | 'isFrame' | 'isFrontier' | 'isGamestop' | 'isHyperPay' | 'isImToken' | 'isKuCoinWallet' | 'isMathWallet' | 'isMetaMask' | 'isOkxWallet' | 'isOKExWallet' | 'isOneInchAndroidWallet' | 'isOneInchIOSWallet' | 'isOpera' | 'isPhantom' | 'isPortal' | 'isRabby' | 'isRainbow' | 'isStatus' | 'isTally' | 'isTokenPocket' | 'isTokenary' | 'isTrust' | 'isTrustWallet' | 'isUniswapWallet' | 'isXDEFI' | 'isZerion' type WalletProvider = Compute< EIP1193Provider & { [key in WalletProviderFlags]?: true | undefined } & { providers?: WalletProvider[] | undefined /** Only exists in MetaMask as of 2022/04/03 */ _events?: { connect?: (() => void) | undefined } | undefined /** Only exists in MetaMask as of 2022/04/03 */ _state?: | { accounts?: string[] initialized?: boolean isConnected?: boolean isPermanentlyDisconnected?: boolean isUnlocked?: boolean } | undefined } > type Window = { coinbaseWalletExtension?: WalletProvider | undefined ethereum?: WalletProvider | undefined phantom?: { ethereum: WalletProvider } | undefined } function findProvider( window: globalThis.Window | Window | undefined, select?: WalletProviderFlags | ((provider: WalletProvider) => boolean), ) { function isProvider(provider: WalletProvider) { if (typeof select === 'function') return select(provider) if (typeof select === 'string') return provider[select] return true } const ethereum = (window as Window).ethereum if (ethereum?.providers) return ethereum.providers.find((provider) => isProvider(provider)) if (ethereum && isProvider(ethereum)) return ethereum return undefined } ================================================ FILE: packages/core/src/connectors/mock.test.ts ================================================ import { accounts, config } from '@wagmi/test' import type { Address, Hex } from 'viem' import { expect, expectTypeOf, test } from 'vitest' import type { Connector } from '../createConfig.js' import type { CreateConnectorFn } from './createConnector.js' import { mock } from './mock.js' test('setup', () => { const connectorFn = mock({ accounts }) const connector = config._internal.connectors.setup(connectorFn) expect(connector.name).toEqual('Mock Connector') expectTypeOf< typeof connectorFn extends CreateConnectorFn ? true : false >().toEqualTypeOf() expectTypeOf< typeof connector extends Connector ? true : false >().toEqualTypeOf() type ConnectFnParameters = NonNullable< Parameters<(typeof connector)['connect']>[0] > expectTypeOf().toMatchTypeOf() type ConnectFnReturnType = Awaited> expectTypeOf().toMatchTypeOf< | readonly `0x${string}`[] | readonly { address: Address capabilities: { foo: { bar: Hex } } }[] >() }) test('behavior: connect#withCapabilities', async () => { const connectorFn = mock({ accounts }) const connector = config._internal.connectors.setup(connectorFn) const res = await connector.connect({ withCapabilities: true }) expectTypeOf(res.accounts).toEqualTypeOf< readonly { address: Address capabilities: Record }[] >() expect(res).toMatchObject( expect.objectContaining({ accounts: expect.arrayContaining([ expect.objectContaining({ address: expect.any(String) }), ]), }), ) }) test('behavior: features.connectError', async () => { const connectorFn = mock({ accounts, features: { connectError: true } }) const connector = config._internal.connectors.setup(connectorFn) await expect(() => connector.connect(), ).rejects.toThrowErrorMatchingInlineSnapshot(` [UserRejectedRequestError: User rejected the request. Details: Failed to connect. Version: viem@2.47.5] `) }) test('behavior: connector.getProvider request errors', async () => { const connectorFn = mock({ accounts, features: { signMessageError: true, signTypedDataError: true, switchChainError: true, watchAssetError: true, }, }) const connector = config._internal.connectors.setup( connectorFn, ) as ReturnType const provider = await connector.getProvider() await expect( provider.request({ method: 'eth_signTypedData_v4', params: [] as any, }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [UserRejectedRequestError: User rejected the request. Details: Failed to sign typed data. Version: viem@2.47.5] `) await expect( provider.request({ method: 'wallet_switchEthereumChain', params: [] as any, }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [UserRejectedRequestError: User rejected the request. Details: Failed to switch chain. Version: viem@2.47.5] `) await expect( provider.request({ method: 'wallet_watchAsset', params: [] as any, }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [UserRejectedRequestError: User rejected the request. Details: Failed to switch chain. Version: viem@2.47.5] `) await expect( provider.request({ method: 'personal_sign', params: [] as any, }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [UserRejectedRequestError: User rejected the request. Details: Failed to sign message. Version: viem@2.47.5] `) }) test('behavior: reconnect', async () => { const connectorFn = mock({ accounts, features: { defaultConnected: true, reconnect: true, }, }) const connector = config._internal.connectors.setup(connectorFn) await expect(connector.isAuthorized()).resolves.toBeTruthy() }) ================================================ FILE: packages/core/src/connectors/mock.ts ================================================ import { type Address, custom, type EIP1193RequestFn, fromHex, getAddress, type Hex, keccak256, numberToHex, RpcRequestError, SwitchChainError, stringToHex, type Transport, UserRejectedRequestError, type WalletCallReceipt, type WalletGetCallsStatusReturnType, type WalletRpcSchema, } from 'viem' import { rpc } from 'viem/utils' import { ChainNotConfiguredError, ConnectorNotConnectedError, } from '../errors/config.js' import { createConnector } from './createConnector.js' export type MockParameters = { accounts: readonly [Address, ...Address[]] features?: | { defaultConnected?: boolean | undefined connectError?: boolean | Error | undefined switchChainError?: boolean | Error | undefined signMessageError?: boolean | Error | undefined signTypedDataError?: boolean | Error | undefined reconnect?: boolean | undefined watchAssetError?: boolean | Error | undefined } | undefined } mock.type = 'mock' as const export function mock(parameters: MockParameters) { const transactionCache = new Map() const features = parameters.features ?? ({ defaultConnected: false } satisfies MockParameters['features']) type Provider = ReturnType< Transport<'custom', unknown, EIP1193RequestFn> > type Properties = { // TODO(v3): Make `withCapabilities: true` default behavior connect(parameters?: { chainId?: number | undefined isReconnecting?: boolean | undefined foo?: string | undefined withCapabilities?: withCapabilities | boolean | undefined }): Promise<{ accounts: withCapabilities extends true ? readonly { address: Address capabilities: { foo: { bar: Hex } } }[] : readonly Address[] chainId: number }> } let connected = features.defaultConnected let connectedChainId: number return createConnector((config) => ({ id: 'mock', name: 'Mock Connector', type: mock.type, async setup() { connectedChainId = config.chains[0].id }, async connect({ chainId, withCapabilities } = {}) { if (features.connectError) { if (typeof features.connectError === 'boolean') throw new UserRejectedRequestError(new Error('Failed to connect.')) throw features.connectError } const provider = await this.getProvider() const accounts = await provider.request({ method: 'eth_requestAccounts', }) let currentChainId = await this.getChainId() if (chainId && currentChainId !== chainId) { const chain = await this.switchChain!({ chainId }) currentChainId = chain.id } connected = true return { accounts: (withCapabilities ? accounts.map((x) => ({ address: getAddress(x), capabilities: { foo: { bar: x } }, })) : accounts.map((x) => getAddress(x))) as never, chainId: currentChainId, } }, async disconnect() { connected = false }, async getAccounts() { if (!connected) throw new ConnectorNotConnectedError() const provider = await this.getProvider() const accounts = await provider.request({ method: 'eth_accounts' }) return accounts.map((x) => getAddress(x)) }, async getChainId() { const provider = await this.getProvider() const hexChainId = await provider.request({ method: 'eth_chainId' }) return fromHex(hexChainId, 'number') }, async isAuthorized() { if (!features.reconnect) return false if (!connected) return false const accounts = await this.getAccounts() return !!accounts.length }, async switchChain({ chainId }) { const provider = await this.getProvider() const chain = config.chains.find((x) => x.id === chainId) if (!chain) throw new SwitchChainError(new ChainNotConfiguredError()) await provider.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: numberToHex(chainId) }], }) return chain }, onAccountsChanged(accounts) { if (accounts.length === 0) this.onDisconnect() else config.emitter.emit('change', { accounts: accounts.map((x) => getAddress(x)), }) }, onChainChanged(chain) { const chainId = Number(chain) config.emitter.emit('change', { chainId }) }, async onDisconnect(_error) { config.emitter.emit('disconnect') connected = false }, async getProvider({ chainId } = {}) { const chain = config.chains.find((x) => x.id === chainId) ?? config.chains[0] const url = chain.rpcUrls.default.http[0]! const request: EIP1193RequestFn = async ({ method, params }) => { // eth methods if (method === 'eth_chainId') return numberToHex(connectedChainId) if (method === 'eth_accounts') return parameters.accounts if (method === 'eth_requestAccounts') return parameters.accounts if (method === 'eth_signTypedData_v4') if (features.signTypedDataError) { if (typeof features.signTypedDataError === 'boolean') throw new UserRejectedRequestError( new Error('Failed to sign typed data.'), ) throw features.signTypedDataError } // wallet methods if (method === 'wallet_switchEthereumChain') { if (features.switchChainError) { if (typeof features.switchChainError === 'boolean') throw new UserRejectedRequestError( new Error('Failed to switch chain.'), ) throw features.switchChainError } type Params = [{ chainId: Hex }] connectedChainId = fromHex((params as Params)[0].chainId, 'number') this.onChainChanged(connectedChainId.toString()) return } if (method === 'wallet_watchAsset') { if (features.watchAssetError) { if (typeof features.watchAssetError === 'boolean') throw new UserRejectedRequestError( new Error('Failed to switch chain.'), ) throw features.watchAssetError } return connected } if (method === 'wallet_getCapabilities') return { '0x2105': { paymasterService: { supported: (params as [Hex])[0] === '0x95132632579b073D12a6673e18Ab05777a6B86f8', }, sessionKeys: { supported: true, }, }, '0x14A34': { paymasterService: { supported: (params as [Hex])[0] === '0x95132632579b073D12a6673e18Ab05777a6B86f8', }, }, } if (method === 'wallet_sendCalls') { const hashes = [] const calls = (params as any)[0].calls const from = (params as any)[0].from for (const call of calls) { const { result, error } = await rpc.http(url, { body: { method: 'eth_sendTransaction', params: [ { ...call, ...(typeof from !== 'undefined' ? { from } : {}), }, ], }, }) if (error) throw new RpcRequestError({ body: { method, params }, error, url, }) hashes.push(result) } const id = keccak256(stringToHex(JSON.stringify(calls))) transactionCache.set(id, hashes) return { id } } if (method === 'wallet_getCallsStatus') { const hashes = transactionCache.get((params as any)[0]) if (!hashes) return { atomic: false, chainId: '0x1', id: (params as any)[0], status: 100, receipts: [], version: '2.0.0', } satisfies WalletGetCallsStatusReturnType const receipts = await Promise.all( hashes.map(async (hash) => { const { result, error } = await rpc.http(url, { body: { method: 'eth_getTransactionReceipt', params: [hash], id: 0, }, }) if (error) throw new RpcRequestError({ body: { method, params }, error, url, }) if (!result) return null return { blockHash: result.blockHash, blockNumber: result.blockNumber, gasUsed: result.gasUsed, logs: result.logs, status: result.status, transactionHash: result.transactionHash, } satisfies WalletCallReceipt }), ) const receipts_ = receipts.filter((x) => x !== null) if (receipts_.length === 0) return { atomic: false, chainId: '0x1', id: (params as any)[0], status: 100, receipts: [], version: '2.0.0', } satisfies WalletGetCallsStatusReturnType return { atomic: false, chainId: '0x1', id: (params as any)[0], status: 200, receipts: receipts_, version: '2.0.0', } satisfies WalletGetCallsStatusReturnType } if (method === 'wallet_showCallsStatus') return // other methods if (method === 'personal_sign') { if (features.signMessageError) { if (typeof features.signMessageError === 'boolean') throw new UserRejectedRequestError( new Error('Failed to sign message.'), ) throw features.signMessageError } // Change `personal_sign` to `eth_sign` and swap params method = 'eth_sign' type Params = [data: Hex, address: Address] params = [(params as Params)[1], (params as Params)[0]] } const body = { method, params } const { error, result } = await rpc.http(url, { body }) if (error) throw new RpcRequestError({ body, error, url }) return result } return custom({ request })({ retryCount: 0 }) }, })) } ================================================ FILE: packages/core/src/createConfig.test-d.ts ================================================ import { accounts } from '@wagmi/test' import { createClient, http, webSocket } from 'viem' import { mainnet, sepolia } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { mock } from './connectors/mock.js' import { type CreateConfigParameters, createConfig } from './createConfig.js' test('high-level config', () => { // Create config without needing to import viem modules. const config = createConfig({ cacheTime: 100, chains: [mainnet, sepolia], connectors: [mock({ accounts })], batch: { multicall: true }, pollingInterval: { [mainnet.id]: 100 }, transports: { [mainnet.id]: webSocket(), [sepolia.id]: http(), }, }) const client = config.getClient({ chainId: mainnet.id }) expectTypeOf(client.chain).toEqualTypeOf(mainnet) expectTypeOf(client.transport.type).toEqualTypeOf<'webSocket'>() }) test('low-level config', () => { // Create a "multi chain" config using viem modules. const config = createConfig({ chains: [mainnet, sepolia], connectors: [mock({ accounts })], client({ chain }) { return createClient({ chain, transport: http() }) }, }) const client = config.getClient({ chainId: mainnet.id }) expectTypeOf(client.chain).toEqualTypeOf(mainnet) }) test('behavior: `chains` must have at least one chain', () => { createConfig({ // @ts-expect-error chains: [], connectors: [mock({ accounts })], transports: { [mainnet.id]: http(), }, }) createConfig({ // @ts-expect-error chains: [], connectors: [mock({ accounts })], client: ({ chain }) => createClient({ chain, transport: http(), }), }) }) test('behavior: missing transport for chain', () => { createConfig({ chains: [mainnet, sepolia], connectors: [mock({ accounts })], // @ts-expect-error transports: { [mainnet.id]: http(), }, }) createConfig({ chains: [mainnet, sepolia], connectors: [mock({ accounts })], transports: { [mainnet.id]: http(), // @ts-expect-error 123: http(), }, }) }) test('behavior: parameters should not include certain client config properties', () => { type Result = keyof CreateConfigParameters expectTypeOf<'account' extends Result ? true : false>().toEqualTypeOf() expectTypeOf<'chain' extends Result ? true : false>().toEqualTypeOf() expectTypeOf< 'transport' extends Result ? true : false >().toEqualTypeOf() }) test('infer connectors', () => { const connectorFn = mock({ accounts }) const config = createConfig({ chains: [mainnet, sepolia], connectors: [connectorFn], transports: { [mainnet.id]: webSocket(), [sepolia.id]: http(), }, }) const connector = config.connectors[0]! expectTypeOf(connector).toEqualTypeOf( config._internal.connectors.setup(connectorFn), ) type ConnectFnParameters = NonNullable< Parameters<(typeof connector)['connect']>[0] > expectTypeOf().toMatchTypeOf() }) ================================================ FILE: packages/core/src/createConfig.test.ts ================================================ import { accounts, chain, wait } from '@wagmi/test' import { announceProvider, type EIP1193Provider, type EIP6963ProviderDetail, } from 'mipd' import { http } from 'viem' import { expect, test, vi } from 'vitest' import { connect } from './actions/connect.js' import { disconnect } from './actions/disconnect.js' import { switchChain } from './actions/switchChain.js' import { createConnector } from './connectors/createConnector.js' import { mock } from './connectors/mock.js' import { type Connection, createConfig } from './createConfig.js' import { createStorage } from './createStorage.js' import { serialize } from './utils/serialize.js' const { mainnet, optimism } = chain vi.mock(import('mipd'), async (importOriginal) => { const mod = await importOriginal() let cache: typeof mod | undefined if (!cache) cache = { ...mod, createStore() { const store = mod.createStore() return { ...store, getProviders() { return [ getProviderDetail({ name: 'Example', rdns: 'com.example' }), getProviderDetail({ name: 'Mock', rdns: 'com.mock' }), ] }, } }, } return cache }) test('default', () => { const config = createConfig({ chains: [mainnet], connectors: [mock({ accounts })], transports: { [mainnet.id]: http(), }, }) expect(config).toBeDefined() }) test('getClient', () => { const config = createConfig({ chains: [mainnet, optimism], connectors: [mock({ accounts })], syncConnectedChain: true, transports: { [mainnet.id]: http(), [optimism.id]: http(), }, }) { const client = config.getClient() expect(client.chain.id).toBe(mainnet.id) } { const client = config.getClient({ chainId: mainnet.id }) expect(client.chain.id).toBe(mainnet.id) } expect(() => config.getClient({ // @ts-expect-error chainId: 123456, }), ).toThrowErrorMatchingInlineSnapshot(` [ChainNotConfiguredError: Chain not configured. Version: @wagmi/core@x.y.z] `) expect(() => { // @ts-expect-error config.state.chainId = 123456 config.getClient() }).toThrowErrorMatchingInlineSnapshot(` [ChainNotConfiguredError: Chain not configured. Version: @wagmi/core@x.y.z] `) }) test('behavior: syncConnectedChain', async () => { const config = createConfig({ chains: [mainnet, optimism], connectors: [mock({ accounts })], syncConnectedChain: true, transports: { [mainnet.id]: http(), [optimism.id]: http(), }, }) // defaults to first chain in `createConfig({ chains })` expect(config.getClient().chain.id).toBe(mainnet.id) // switches to optimism await switchChain(config, { chainId: optimism.id }) expect(config.getClient().chain.id).toBe(optimism.id) // connects to mainnet await connect(config, { chainId: mainnet.id, connector: config.connectors[0]!, }) expect(config.getClient().chain.id).toBe(mainnet.id) // switches to optimism await switchChain(config, { chainId: optimism.id }) expect(config.getClient().chain.id).toBe(optimism.id) // disconnects, still connected to optimism await disconnect(config) expect(config.getClient().chain.id).toBe(optimism.id) }) test('behavior: migrate for current version', async () => { const state = { 'wagmi.store': JSON.stringify({ state: { connections: { __type: 'Map', value: [ [ '983b8aca245', { accounts: [ '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', '0xd2135CfB216b74109775236E36d4b433F1DF507B', ], chainId: 1, connector: { id: 'io.metamask', name: 'MetaMask', type: 'injected', uid: '983b8aca245', }, }, ], ], }, chainId: 1, current: '983b8aca245', }, version: Number.NaN, // mocked version is `'x.y.z'`, which will get interpreted as `NaN` }), } as Record Object.defineProperty(window, 'localStorage', { value: { getItem: vi.fn((key) => state[key] ?? null), removeItem: vi.fn((key) => state.delete?.[key]), setItem: vi.fn((key, value) => { state[key] = value }), }, writable: true, }) const storage = createStorage<{ store: object }>({ storage: window.localStorage, }) const config = createConfig({ chains: [mainnet], storage, transports: { [mainnet.id]: http() }, }) await wait(100) expect(config.state).toMatchInlineSnapshot(` { "chainId": 1, "connections": Map { "983b8aca245" => { "accounts": [ "0xA0Cf798816D4b9b9866b5330EEa46a18382f251e", "0xd2135CfB216b74109775236E36d4b433F1DF507B", ], "chainId": 1, "connector": { "id": "io.metamask", "name": "MetaMask", "type": "injected", "uid": "983b8aca245", }, }, }, "current": "983b8aca245", "status": "disconnected", } `) }) test('behavior: migrate chainId', async () => { const state = { 'wagmi.store': JSON.stringify({ state: { chainId: 10 }, version: 1, }), } as Record Object.defineProperty(window, 'localStorage', { value: { getItem: vi.fn((key) => state[key] ?? null), removeItem: vi.fn((key) => state.delete?.[key]), setItem: vi.fn((key, value) => { state[key] = value }), }, writable: true, }) const storage = createStorage<{ store: object }>({ storage: window.localStorage, }) const config = createConfig({ chains: [mainnet, optimism], storage, transports: { [mainnet.id]: http(), [optimism.id]: http(), }, }) await wait(100) expect(config.state).toMatchInlineSnapshot(` { "chainId": 10, "connections": Map {}, "current": null, "status": "disconnected", } `) }) test('behavior: properties passed through to Viem Client via getClient', () => { { const properties = { batch: { multicall: { batchSize: 102_400, }, }, cacheTime: 5_000, pollingInterval: 1_000, } const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: http(), }, ...properties, }) const { account: _a, chain: _c, extend: _e, key: _k, name: _n, request: _r, transport: _tr, uid: _u, type: _ty, ...rest } = config.getClient() expect(rest).toEqual(properties) } { const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: http(), }, batch: { [mainnet.id]: { multicall: { batchSize: 1024, }, }, }, }) const client = config.getClient() expect(client.batch).toMatchInlineSnapshot(` { "multicall": { "batchSize": 1024, }, } `) const client2 = config.getClient({ chainId: optimism.id }) expect(client2.batch).toMatchInlineSnapshot(` { "multicall": true, } `) } }) test('behavior: restore unconfigured chainId', () => { const state = { 'wagmi.store': JSON.stringify({ state: { chainId: 10 }, version: 1, }), } as Record Object.defineProperty(window, 'localStorage', { value: { getItem: vi.fn((key) => state[key] ?? null), removeItem: vi.fn((key) => state.delete?.[key]), setItem: vi.fn((key, value) => { state[key] = value }), }, writable: true, }) const storage = createStorage<{ store: object }>({ storage: window.localStorage, }) const config = createConfig({ chains: [mainnet], storage, transports: { [mainnet.id]: http(), }, }) expect(config.state).toMatchInlineSnapshot(` { "chainId": 1, "connections": Map {}, "current": null, "status": "disconnected", } `) const client = config.getClient() expect(client.chain.id).toBe(mainnet.id) }) test('behavior: setup connector', async () => { const config = createConfig({ chains: [mainnet], transports: { [mainnet.id]: http(), }, }) const connectorFn = mock({ accounts }) const connector = config._internal.connectors.setup(connectorFn) config._internal.connectors.setState((x) => [...x, connector]) await connect(config, { chainId: mainnet.id, connector: config.connectors.find((x) => x.uid === connector.uid)!, }) expect(config.state.current).toBe(connector.uid) await disconnect(config) }) test('behavior: eip 6963 providers', async () => { const detail_1 = getProviderDetail({ name: 'Foo Wallet', rdns: 'com.foo' }) const detail_2 = getProviderDetail({ name: 'Bar Wallet', rdns: 'com.bar' }) const detail_3 = getProviderDetail({ name: 'Mock', rdns: 'com.mock' }) const config = createConfig({ chains: [mainnet], connectors: [ createConnector((c) => { return { ...mock({ accounts })(c), rdns: ['com.mock', 'com.baz'], } }), ], transports: { [mainnet.id]: http(), }, }) await wait(100) announceProvider(detail_1)() await wait(100) announceProvider(detail_1)() await wait(100) announceProvider(detail_2)() await wait(100) announceProvider(detail_3)() await wait(100) expect( config.connectors.flatMap((x) => x.rdns ?? x.id), ).toMatchInlineSnapshot(` [ "com.mock", "com.baz", "com.example", "com.foo", "com.bar", ] `) }) test('behavior: revalidate connections', async () => { const state = { 'wagmi.store': serialize({ state: { chainId: 1 }, version: 1, }), } as Record Object.defineProperty(window, 'localStorage', { value: { getItem: vi.fn((key) => state[key] ?? null), removeItem: vi.fn((key) => state.delete?.[key]), setItem: vi.fn((key, value) => { state[key] = value }), }, writable: true, }) const config = createConfig({ chains: [mainnet], connectors: [ mock({ accounts }), mock({ accounts, features: { defaultConnected: true, reconnect: true } }), mock({ accounts }), ], storage: createStorage<{ store: object }>({ storage: window.localStorage, }), transports: { [mainnet.id]: http(), }, }) const connections = new Map() const c1 = config.connectors.at(0)! const c2 = config.connectors.at(1)! const c3 = config.connectors.at(2)! connections.set(c1.uid, { accounts: ['0x'], chainId: 1, connector: c1 }) connections.set(c2.uid, { accounts: ['0x'], chainId: 1, connector: c2 }) connections.set(c3.uid, { accounts: ['0x'], chainId: 1, connector: c3 }) connections.set('foo', { accounts: ['0x'], chainId: 1, connector: { id: 'foo', name: 'foo', type: 'foo', uid: 'foo', } as Connection['connector'], }) config.setState((state) => ({ ...state, connections })) await config._internal.revalidate() expect([...config.state.connections.keys()]).toEqual([c2.uid]) }) function getProviderDetail( info: Pick, ): EIP6963ProviderDetail { return { info: { icon: 'data:image/svg+xml,', uuid: crypto.randomUUID(), ...info, }, provider: `` as unknown as EIP1193Provider, } } ================================================ FILE: packages/core/src/createConfig.ts ================================================ import { createStore as createMipd, type EIP6963ProviderDetail, type Store as MipdStore, } from 'mipd' import { type Address, type Chain, type Client, createClient, type EIP1193RequestFn, type ClientConfig as viem_ClientConfig, type Transport as viem_Transport, } from 'viem' import { persist, subscribeWithSelector } from 'zustand/middleware' import { createStore, type Mutate, type StoreApi } from 'zustand/vanilla' import type { ConnectorEventMap, CreateConnectorFn, } from './connectors/createConnector.js' import { injected } from './connectors/injected.js' import { createEmitter, type Emitter, type EventData } from './createEmitter.js' import { createStorage, getDefaultStorage, type Storage, } from './createStorage.js' import { ChainNotConfiguredError } from './errors/config.js' import type { Compute, ExactPartial, LooseOmit, OneOf, RemoveUndefined, } from './types/utils.js' import { uid } from './utils/uid.js' import { version } from './version.js' export function createConfig< const chains extends readonly [Chain, ...Chain[]], transports extends Record, const connectorFns extends readonly CreateConnectorFn[], >( parameters: CreateConfigParameters, ): Config { const { multiInjectedProviderDiscovery = true, storage = createStorage({ storage: getDefaultStorage(), }), syncConnectedChain = true, ssr = false, ...rest } = parameters ///////////////////////////////////////////////////////////////////////////////////////////////// // Set up connectors, clients, etc. ///////////////////////////////////////////////////////////////////////////////////////////////// const mipd = typeof window !== 'undefined' && multiInjectedProviderDiscovery ? createMipd() : undefined const chains = createStore(() => rest.chains) const connectors = createStore(() => { const collection = [] const rdnsSet = new Set() for (const connectorFns of rest.connectors ?? []) { const connector = setup(connectorFns) collection.push(connector) if (!ssr && connector.rdns) { const rdnsValues = typeof connector.rdns === 'string' ? [connector.rdns] : connector.rdns for (const rdns of rdnsValues) { rdnsSet.add(rdns) } } } if (!ssr && mipd) { const providers = mipd.getProviders() for (const provider of providers) { if (rdnsSet.has(provider.info.rdns)) continue collection.push(setup(providerDetailToConnector(provider))) } } return collection }) function setup(connectorFn: CreateConnectorFn): Connector { // Set up emitter with uid and add to connector so they are "linked" together. const emitter = createEmitter(uid()) const connector = { ...connectorFn({ emitter, chains: chains.getState(), storage, transports: rest.transports, }), emitter, uid: emitter.uid, } // Start listening for `connect` events on connector setup // This allows connectors to "connect" themselves without user interaction (e.g. MetaMask's "Manually connect to current site") emitter.on('connect', connect) connector.setup?.() return connector } function providerDetailToConnector(providerDetail: EIP6963ProviderDetail) { const { info } = providerDetail const provider = providerDetail.provider as any return injected({ target: { ...info, id: info.rdns, provider } }) } const clients = new Map>() function getClient( config: { chainId?: chainId | chains[number]['id'] | undefined } = {}, ): Client> { const chainId = config.chainId ?? store.getState().chainId const chain = chains.getState().find((x) => x.id === chainId) // chainId specified and not configured if (config.chainId && !chain) throw new ChainNotConfiguredError() // If the target chain is not configured, use the client of the current chain. type Return = Client> { const client = clients.get(store.getState().chainId) if (client && !chain) return client as Return if (!chain) throw new ChainNotConfiguredError() } // If a memoized client exists for a chain id, use that. { const client = clients.get(chainId) if (client) return client as Return } let client: Client if (rest.client) client = rest.client({ chain }) else { const chainId = chain.id as chains[number]['id'] const chainIds = chains.getState().map((x) => x.id) // Grab all properties off `rest` and resolve for use in `createClient` const properties: Partial = {} const entries = Object.entries(rest) as [keyof typeof rest, any][] for (const [key, value] of entries) { if ( key === 'chains' || key === 'client' || key === 'connectors' || key === 'transports' ) continue if (typeof value === 'object') { // check if value is chainId-specific since some values can be objects // e.g. { batch: { multicall: { batchSize: 1024 } } } if (chainId in value) properties[key] = value[chainId] else { // check if value is chainId-specific, but does not have value for current chainId const hasChainSpecificValue = chainIds.some((x) => x in value) if (hasChainSpecificValue) continue properties[key] = value } } else properties[key] = value } client = createClient({ ...properties, chain, batch: properties.batch ?? { multicall: true }, transport: (parameters) => rest.transports[chainId]({ ...parameters, connectors }), }) } clients.set(chainId, client) return client as Return } ///////////////////////////////////////////////////////////////////////////////////////////////// // Create store ///////////////////////////////////////////////////////////////////////////////////////////////// function getInitialState(): State { return { chainId: chains.getState()[0].id, connections: new Map(), current: null, status: 'disconnected', } } let currentVersion: number const prefix = '0.0.0-canary-' if (version.startsWith(prefix)) currentVersion = Number.parseInt(version.replace(prefix, ''), 10) // use package major version to version store else currentVersion = Number.parseInt(version.split('.')[0] ?? '0', 10) const store = createStore( subscribeWithSelector( // only use persist middleware if storage exists storage ? persist(getInitialState, { migrate(persistedState, version) { if (version === currentVersion) return persistedState as State const initialState = getInitialState() const chainId = validatePersistedChainId( persistedState, initialState.chainId, ) return { ...initialState, chainId } }, name: 'store', partialize(state) { // Only persist "critical" store properties to preserve storage size. return { connections: { __type: 'Map', value: Array.from(state.connections.entries()).map( ([key, connection]) => { const { id, name, type, uid } = connection.connector const connector = { id, name, type, uid } return [key, { ...connection, connector }] }, ), } as unknown as PartializedState['connections'], chainId: state.chainId, current: state.current, } satisfies PartializedState }, merge(persistedState, currentState) { // `status` should not be persisted as it messes with reconnection if ( typeof persistedState === 'object' && persistedState && 'status' in persistedState ) delete persistedState.status // Make sure persisted `chainId` is valid const chainId = validatePersistedChainId( persistedState, currentState.chainId, ) return { ...currentState, ...(persistedState as object), chainId, } }, skipHydration: ssr, storage: storage as Storage>, version: currentVersion, }) : getInitialState, ), ) store.setState(getInitialState()) function validatePersistedChainId( persistedState: unknown, defaultChainId: number, ) { return persistedState && typeof persistedState === 'object' && 'chainId' in persistedState && typeof persistedState.chainId === 'number' && chains.getState().some((x) => x.id === persistedState.chainId) ? persistedState.chainId : defaultChainId } ///////////////////////////////////////////////////////////////////////////////////////////////// // Subscribe to changes ///////////////////////////////////////////////////////////////////////////////////////////////// // Update default chain when connector chain changes if (syncConnectedChain) store.subscribe( ({ connections, current }) => current ? connections.get(current)?.chainId : undefined, (chainId) => { // If chain is not configured, then don't switch over to it. const isChainConfigured = chains .getState() .some((x) => x.id === chainId) if (!isChainConfigured) return return store.setState((x) => ({ ...x, chainId: chainId ?? x.chainId, })) }, ) // EIP-6963 subscribe for new wallet providers mipd?.subscribe((providerDetails) => { const connectorIdSet = new Set() const connectorRdnsSet = new Set() for (const connector of connectors.getState()) { connectorIdSet.add(connector.id) if (connector.rdns) { const rdnsValues = typeof connector.rdns === 'string' ? [connector.rdns] : connector.rdns for (const rdns of rdnsValues) { connectorRdnsSet.add(rdns) } } } const newConnectors: Connector[] = [] for (const providerDetail of providerDetails) { if (connectorRdnsSet.has(providerDetail.info.rdns)) continue const connector = setup(providerDetailToConnector(providerDetail)) if (connectorIdSet.has(connector.id)) continue newConnectors.push(connector) } if (storage && !store.persist.hasHydrated()) return connectors.setState((x) => [...x, ...newConnectors], true) }) ///////////////////////////////////////////////////////////////////////////////////////////////// // Emitter listeners ///////////////////////////////////////////////////////////////////////////////////////////////// function change(data: EventData) { store.setState((x) => { const connection = x.connections.get(data.uid) if (!connection) return x return { ...x, connections: new Map(x.connections).set(data.uid, { accounts: (data.accounts as readonly [Address, ...Address[]]) ?? connection.accounts, chainId: data.chainId ?? connection.chainId, connector: connection.connector, }), } }) } function connect(data: EventData) { // Disable handling if reconnecting/connecting if ( store.getState().status === 'connecting' || store.getState().status === 'reconnecting' ) return store.setState((x) => { const connector = connectors.getState().find((x) => x.uid === data.uid) if (!connector) return x if (connector.emitter.listenerCount('connect')) connector.emitter.off('connect', change) if (!connector.emitter.listenerCount('change')) connector.emitter.on('change', change) if (!connector.emitter.listenerCount('disconnect')) connector.emitter.on('disconnect', disconnect) return { ...x, connections: new Map(x.connections).set(data.uid, { accounts: data.accounts as readonly [Address, ...Address[]], chainId: data.chainId, connector: connector, }), current: data.uid, status: 'connected', } }) } function disconnect(data: EventData) { store.setState((x) => { const connection = x.connections.get(data.uid) if (connection) { const connector = connection.connector if (connector.emitter.listenerCount('change')) connection.connector.emitter.off('change', change) if (connector.emitter.listenerCount('disconnect')) connection.connector.emitter.off('disconnect', disconnect) if (!connector.emitter.listenerCount('connect')) connection.connector.emitter.on('connect', connect) } x.connections.delete(data.uid) if (x.connections.size === 0) return { ...x, connections: new Map(), current: null, status: 'disconnected', } const nextConnection = x.connections.values().next().value as Connection return { ...x, connections: new Map(x.connections), current: nextConnection.connector.uid, } }) } return { get chains() { return chains.getState() as chains }, get connectors() { return connectors.getState() as Readonly<{ [key in keyof connectorFns]: Connector }> }, storage, getClient, get state() { return store.getState() as unknown as State }, setState(value) { let newState: State if (typeof value === 'function') newState = value(store.getState() as any) else newState = value // Reset state if it got set to something not matching the base state const initialState = getInitialState() if (typeof newState !== 'object') newState = initialState const isCorrupt = Object.keys(initialState).some((x) => !(x in newState)) if (isCorrupt) newState = initialState store.setState(newState, true) }, subscribe(selector, listener, options) { return store.subscribe( selector as unknown as (state: State) => any, listener, options ? ({ ...options, fireImmediately: options.emitImmediately, // Workaround cast since Zustand does not support `'exactOptionalPropertyTypes'` } as RemoveUndefined) : undefined, ) }, _internal: { mipd, async revalidate() { // Check connections to see if they are still active const state = store.getState() const connections = state.connections let current = state.current for (const [, connection] of connections) { const connector = connection.connector // check if `connect.isAuthorized` exists // partial connectors in storage do not have it const isAuthorized = connector.isAuthorized ? await connector.isAuthorized() : false if (isAuthorized) continue // Remove stale connection connections.delete(connector.uid) if (current === connector.uid) current = null } // set connections store.setState((x) => ({ ...x, connections, current })) }, store, ssr: Boolean(ssr), syncConnectedChain, transports: rest.transports as transports, chains: { setState(value) { const nextChains = ( typeof value === 'function' ? value(chains.getState()) : value ) as chains if (nextChains.length === 0) return return chains.setState(nextChains, true) }, subscribe(listener) { return chains.subscribe(listener) }, }, connectors: { providerDetailToConnector, setup: setup as ( connectorFn: connectorFn, ) => Connector, setState(value) { return connectors.setState( typeof value === 'function' ? value(connectors.getState()) : value, true, ) }, subscribe(listener) { return connectors.subscribe(listener) }, }, events: { change, connect, disconnect }, }, } } ///////////////////////////////////////////////////////////////////////////////////////////////// // Types ///////////////////////////////////////////////////////////////////////////////////////////////// export type CreateConfigParameters< chains extends readonly [Chain, ...Chain[]] = readonly [Chain, ...Chain[]], transports extends Record = Record< chains[number]['id'], Transport >, connectorFns extends readonly CreateConnectorFn[] = readonly CreateConnectorFn[], > = Compute< { chains: chains connectors?: connectorFns | undefined multiInjectedProviderDiscovery?: boolean | undefined storage?: Storage | null | undefined ssr?: boolean | undefined syncConnectedChain?: boolean | undefined } & OneOf< | ({ transports: transports } & { [key in keyof ClientConfig]?: | ClientConfig[key] | { [_ in chains[number]['id']]?: ClientConfig[key] | undefined } | undefined }) | { client(parameters: { chain: chains[number] }): Client } > > export type Config< chains extends readonly [Chain, ...Chain[]] = readonly [Chain, ...Chain[]], transports extends Record = Record< chains[number]['id'], Transport >, connectorFns extends readonly CreateConnectorFn[] = readonly CreateConnectorFn[], > = { readonly chains: chains readonly connectors: Readonly<{ [key in keyof connectorFns]: Connector }> readonly storage: Storage | null readonly state: State setState( value: State | ((state: State) => State), ): void subscribe( selector: (state: State) => state, listener: (state: state, previousState: state) => void, options?: | { emitImmediately?: boolean | undefined equalityFn?: ((a: state, b: state) => boolean) | undefined } | undefined, ): () => void getClient(parameters?: { chainId?: chainId | chains[number]['id'] | undefined }): Client> /** * Not part of versioned API, proceed with caution. * @internal */ _internal: Internal } type Internal< chains extends readonly [Chain, ...Chain[]] = readonly [Chain, ...Chain[]], transports extends Record = Record< chains[number]['id'], Transport >, > = { readonly mipd: MipdStore | undefined revalidate: () => Promise readonly store: Mutate, [['zustand/persist', any]]> readonly ssr: boolean readonly syncConnectedChain: boolean readonly transports: transports chains: { setState( value: | readonly [Chain, ...Chain[]] | (( state: readonly [Chain, ...Chain[]], ) => readonly [Chain, ...Chain[]]), ): void subscribe( listener: ( state: readonly [Chain, ...Chain[]], prevState: readonly [Chain, ...Chain[]], ) => void, ): () => void } connectors: { providerDetailToConnector( providerDetail: EIP6963ProviderDetail, ): CreateConnectorFn setup( connectorFn: connectorFn, ): Connector setState(value: Connector[] | ((state: Connector[]) => Connector[])): void subscribe( listener: (state: Connector[], prevState: Connector[]) => void, ): () => void } events: { change(data: EventData): void connect(data: EventData): void disconnect(data: EventData): void } } export type State< chains extends readonly [Chain, ...Chain[]] = readonly [Chain, ...Chain[]], > = { chainId: chains[number]['id'] connections: Map current: string | null status: 'connected' | 'connecting' | 'disconnected' | 'reconnecting' } export type PartializedState = Compute< ExactPartial> > export type Connection = { accounts: readonly [Address, ...Address[]] chainId: number connector: Connector } export type Connector< createConnectorFn extends CreateConnectorFn = CreateConnectorFn, > = ReturnType & { emitter: Emitter uid: string } export type Transport< type extends string = string, rpcAttributes = Record, eip1193RequestFn extends EIP1193RequestFn = EIP1193RequestFn, > = ( params: Parameters< viem_Transport >[0] & { connectors?: StoreApi | undefined }, ) => ReturnType> type ClientConfig = LooseOmit< viem_ClientConfig, 'account' | 'chain' | 'key' | 'name' | 'transport' | 'type' > ================================================ FILE: packages/core/src/createEmitter.test.ts ================================================ import { expect, test, vi } from 'vitest' import type { ConnectorEventMap } from './connectors/createConnector.js' import { createEmitter } from './createEmitter.js' import { uid } from './utils/uid.js' test('default', () => { const emitter = createEmitter(uid()) const onMessage = vi.fn() emitter.on('message', onMessage) emitter.emit('message', { type: 'bar', data: 'baz' }) expect(onMessage).toHaveBeenCalledWith({ type: 'bar', data: 'baz', uid: emitter.uid, }) }) ================================================ FILE: packages/core/src/createEmitter.ts ================================================ import { EventEmitter } from 'eventemitter3' type EventMap = Record type EventKey = string & keyof eventMap type EventFn = ( ...parameters: parameters ) => void export type EventData< eventMap extends EventMap, eventName extends keyof eventMap, > = (eventMap[eventName] extends [never] ? unknown : eventMap[eventName]) & { uid: string } export class Emitter { _emitter = new EventEmitter() constructor(public uid: string) {} on>( eventName: key, fn: EventFn< eventMap[key] extends [never] ? [{ uid: string }] : [data: eventMap[key] & { uid: string }] >, ) { this._emitter.on(eventName, fn as EventFn) } once>( eventName: key, fn: EventFn< eventMap[key] extends [never] ? [{ uid: string }] : [data: eventMap[key] & { uid: string }] >, ) { this._emitter.once(eventName, fn as EventFn) } off>( eventName: key, fn: EventFn< eventMap[key] extends [never] ? [{ uid: string }] : [data: eventMap[key] & { uid: string }] >, ) { this._emitter.off(eventName, fn as EventFn) } emit>( eventName: key, ...params: eventMap[key] extends [never] ? [] : [data: eventMap[key]] ) { const data = params[0] this._emitter.emit(eventName, { uid: this.uid, ...data }) } listenerCount>(eventName: key) { return this._emitter.listenerCount(eventName) } } export function createEmitter(uid: string) { return new Emitter(uid) } ================================================ FILE: packages/core/src/createStorage.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import type { Connection } from './createConfig.js' import { createStorage } from './createStorage.js' test('getItem', () => { const storage = createStorage({ storage: localStorage }) expectTypeOf(storage.getItem('recentConnectorId')).toEqualTypeOf< string | null | Promise >() expectTypeOf(storage.getItem('recentConnectorId', 'foo')).toEqualTypeOf< string | Promise >() expectTypeOf(storage.getItem('foo')).toEqualTypeOf() // @ts-expect-error incorrect argument type storage.getItem('recentConnectorId', 1n) expectTypeOf(storage.getItem('state')).toEqualTypeOf< | { chainId?: number | undefined connections?: Map | undefined current?: string | null | undefined status?: | 'connected' | 'connecting' | 'reconnecting' | 'disconnected' | undefined } | null | Promise<{ chainId?: number | undefined connections?: Map | undefined current?: string | null | undefined status?: | 'connected' | 'connecting' | 'reconnecting' | 'disconnected' | undefined } | null> >() const customStorage = createStorage<{ foo: number }>({ storage: localStorage, }) expectTypeOf(customStorage.getItem('foo')).toEqualTypeOf< number | null | Promise >() expectTypeOf(customStorage.getItem('foo', 1)).toEqualTypeOf< number | Promise >() }) test('setItem', () => { const storage = createStorage({ storage: localStorage }) storage.setItem('recentConnectorId', 'foo') // @ts-expect-error incorrect argument type storage.setItem('recentConnectorId', 1n) }) test('serialize/deserialize types', () => { createStorage({ deserialize(value) { return value }, serialize(value) { return value }, storage: localStorage, }) }) ================================================ FILE: packages/core/src/createStorage.test.ts ================================================ import { expect, test, vi } from 'vitest' import { createStorage } from './createStorage.js' Object.defineProperty(window, 'localStorage', { value: { getItem: vi.fn(() => null), removeItem: vi.fn(() => null), setItem: vi.fn(() => null), }, writable: true, }) test('inits', () => { const storage = createStorage({ storage: window.localStorage }) expect(storage).toBeDefined() }) test('getItem', () => { const storage = createStorage({ storage: window.localStorage }) storage.getItem('recentConnectorId') expect(window.localStorage.getItem).toHaveBeenCalledTimes(1) expect(window.localStorage.getItem).toHaveBeenCalledWith( 'wagmi.recentConnectorId', ) }) test('setItem', () => { const storage = createStorage({ storage: window.localStorage }) storage.setItem('recentConnectorId', 'bar') expect(window.localStorage.setItem).toHaveBeenCalledTimes(1) expect(window.localStorage.setItem).toHaveBeenCalledWith( 'wagmi.recentConnectorId', '"bar"', ) }) test('removeItem', () => { const storage = createStorage({ storage: window.localStorage }) storage.removeItem('recentConnectorId') expect(window.localStorage.removeItem).toHaveBeenCalledTimes(1) expect(window.localStorage.removeItem).toHaveBeenCalledWith( 'wagmi.recentConnectorId', ) }) ================================================ FILE: packages/core/src/createStorage.ts ================================================ import type { PartializedState } from './createConfig.js' import type { Compute } from './types/utils.js' import { deserialize as deserialize_ } from './utils/deserialize.js' import { serialize as serialize_ } from './utils/serialize.js' // key-values for loose autocomplete and typing export type StorageItemMap = { recentConnectorId: string state: PartializedState } export type Storage< itemMap extends Record = Record, /// storageItemMap extends StorageItemMap = StorageItemMap & itemMap, > = { key: string getItem< key extends keyof storageItemMap, value extends storageItemMap[key], defaultValue extends value | null | undefined, >( key: key, defaultValue?: defaultValue | undefined, ): | (defaultValue extends null ? value | null : value) | Promise setItem< key extends keyof storageItemMap, value extends storageItemMap[key] | null, >(key: key, value: value): void | Promise removeItem(key: keyof storageItemMap): void | Promise } export type BaseStorage = { getItem( key: string, ): string | null | undefined | Promise setItem(key: string, value: string): void | Promise removeItem(key: string): void | Promise } export type CreateStorageParameters = { deserialize?: ((value: string) => type | unknown) | undefined key?: string | undefined serialize?: ((value: type | any) => string) | undefined storage?: Compute | undefined } export function createStorage< itemMap extends Record = Record, storageItemMap extends StorageItemMap = StorageItemMap & itemMap, >(parameters: CreateStorageParameters): Compute> { const { deserialize = deserialize_, key: prefix = 'wagmi', serialize = serialize_, storage = noopStorage, } = parameters function unwrap(value: type): type | Promise { if (value instanceof Promise) return value.then((x) => x).catch(() => null) return value } return { ...storage, key: prefix, async getItem(key, defaultValue) { const value = storage.getItem(`${prefix}.${key as string}`) const unwrapped = await unwrap(value) if (unwrapped) return deserialize(unwrapped) ?? null return (defaultValue ?? null) as any }, async setItem(key, value) { const storageKey = `${prefix}.${key as string}` if (value === null) await unwrap(storage.removeItem(storageKey)) else await unwrap(storage.setItem(storageKey, serialize(value))) }, async removeItem(key) { await unwrap(storage.removeItem(`${prefix}.${key as string}`)) }, } } export const noopStorage = { getItem: () => null, setItem: () => {}, removeItem: () => {}, } satisfies BaseStorage export function getDefaultStorage() { const storage = (() => { // biome-ignore lint/complexity/useOptionalChain: _ if (typeof window !== 'undefined' && window.localStorage) return window.localStorage return noopStorage })() return { getItem(key) { return storage.getItem(key) }, removeItem(key) { storage.removeItem(key) }, setItem(key, value) { try { storage.setItem(key, value) // silence errors by default (QuotaExceededError, SecurityError, etc.) } catch {} }, } satisfies BaseStorage } ================================================ FILE: packages/core/src/errors/base.test.ts ================================================ import { expect, test } from 'vitest' import { BaseError } from './base.js' test('BaseError', () => { expect(new BaseError('An error occurred.')).toMatchInlineSnapshot(` [WagmiCoreError: An error occurred. Version: @wagmi/core@x.y.z] `) expect( new BaseError('An error occurred.', { details: 'details' }), ).toMatchInlineSnapshot(` [WagmiCoreError: An error occurred. Details: details Version: @wagmi/core@x.y.z] `) expect(new BaseError('', { details: 'details' })).toMatchInlineSnapshot(` [WagmiCoreError: An error occurred. Details: details Version: @wagmi/core@x.y.z] `) }) test('BaseError (w/ docsPath)', () => { expect( new BaseError('An error occurred.', { details: 'details', docsPath: '/lol', }), ).toMatchInlineSnapshot(` [WagmiCoreError: An error occurred. Docs: https://wagmi.sh/core/lol.html Details: details Version: @wagmi/core@x.y.z] `) expect( new BaseError('An error occurred.', { cause: new BaseError('error', { docsPath: '/docs' }), }), ).toMatchInlineSnapshot(` [WagmiCoreError: An error occurred. Docs: https://wagmi.sh/core/docs.html Version: @wagmi/core@x.y.z] `) expect( new BaseError('An error occurred.', { cause: new BaseError('error'), docsPath: '/lol', }), ).toMatchInlineSnapshot(` [WagmiCoreError: An error occurred. Docs: https://wagmi.sh/core/lol.html Version: @wagmi/core@x.y.z] `) expect( new BaseError('An error occurred.', { details: 'details', docsPath: '/lol', docsSlug: 'test', }), ).toMatchInlineSnapshot(` [WagmiCoreError: An error occurred. Docs: https://wagmi.sh/core/lol.html#test Details: details Version: @wagmi/core@x.y.z] `) }) test('BaseError (w/ metaMessages)', () => { expect( new BaseError('An error occurred.', { details: 'details', metaMessages: ['Reason: idk', 'Cause: lol'], }), ).toMatchInlineSnapshot(` [WagmiCoreError: An error occurred. Reason: idk Cause: lol Details: details Version: @wagmi/core@x.y.z] `) }) test('inherited BaseError', () => { const err = new BaseError('An error occurred.', { details: 'details', docsPath: '/lol', }) expect( new BaseError('An internal error occurred.', { cause: err, }), ).toMatchInlineSnapshot(` [WagmiCoreError: An internal error occurred. Docs: https://wagmi.sh/core/lol.html Details: details Version: @wagmi/core@x.y.z] `) }) test('inherited Error', () => { const err = new Error('details') expect( new BaseError('An internal error occurred.', { cause: err, docsPath: '/lol', }), ).toMatchInlineSnapshot(` [WagmiCoreError: An internal error occurred. Docs: https://wagmi.sh/core/lol.html Details: details Version: @wagmi/core@x.y.z] `) }) test('walk: no predicate fn (walks to leaf)', () => { class FooError extends BaseError {} class BarError extends BaseError {} const err = new BaseError('test1', { cause: new FooError('test2', { cause: new BarError('test3') }), }) expect(err.walk()).toMatchInlineSnapshot(` [WagmiCoreError: test3 Version: @wagmi/core@x.y.z] `) }) test('walk: predicate fn', () => { class FooError extends BaseError {} class BarError extends BaseError {} const err = new BaseError('test1', { cause: new FooError('test2', { cause: new BarError('test3') }), }) expect(err.walk((err) => err instanceof FooError)).toMatchInlineSnapshot(` [WagmiCoreError: test2 Version: @wagmi/core@x.y.z] `) }) ================================================ FILE: packages/core/src/errors/base.ts ================================================ import type { Compute, OneOf } from '../types/utils.js' import { getVersion } from '../utils/getVersion.js' export type ErrorType = Error & { name: name } type BaseErrorOptions = Compute< OneOf<{ details?: string | undefined } | { cause: BaseError | Error }> & { docsPath?: string | undefined docsSlug?: string | undefined metaMessages?: string[] | undefined } > export type BaseErrorType = BaseError & { name: 'WagmiCoreError' } export class BaseError extends Error { details: string docsPath?: string | undefined metaMessages?: string[] | undefined shortMessage: string override name = 'WagmiCoreError' get docsBaseUrl() { return 'https://wagmi.sh/core' } get version() { return getVersion() } constructor(shortMessage: string, options: BaseErrorOptions = {}) { super() const details = options.cause instanceof BaseError ? options.cause.details : options.cause?.message ? options.cause.message : options.details! const docsPath = options.cause instanceof BaseError ? options.cause.docsPath || options.docsPath : options.docsPath this.message = [ shortMessage || 'An error occurred.', '', ...(options.metaMessages ? [...options.metaMessages, ''] : []), ...(docsPath ? [ `Docs: ${this.docsBaseUrl}${docsPath}.html${ options.docsSlug ? `#${options.docsSlug}` : '' }`, ] : []), ...(details ? [`Details: ${details}`] : []), `Version: ${this.version}`, ].join('\n') if (options.cause) this.cause = options.cause this.details = details this.docsPath = docsPath this.metaMessages = options.metaMessages this.shortMessage = shortMessage } walk(fn?: (err: unknown) => boolean) { return this.#walk(this, fn) } #walk(err: unknown, fn?: (err: unknown) => boolean): unknown { if (fn?.(err)) return err if ((err as Error).cause) return this.#walk((err as Error).cause, fn) return err } } ================================================ FILE: packages/core/src/errors/config.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { ChainNotConfiguredError, ConnectorAccountNotFoundError, ConnectorAlreadyConnectedError, ConnectorChainMismatchError, ConnectorNotConnectedError, ConnectorNotFoundError, ConnectorUnavailableReconnectingError, } from './config.js' test('constructors', () => { expect(new ChainNotConfiguredError()).toMatchInlineSnapshot(` [ChainNotConfiguredError: Chain not configured. Version: @wagmi/core@x.y.z] `) expect(new ConnectorAlreadyConnectedError()).toMatchInlineSnapshot(` [ConnectorAlreadyConnectedError: Connector already connected. Version: @wagmi/core@x.y.z] `) expect(new ConnectorNotConnectedError()).toMatchInlineSnapshot(` [ConnectorNotConnectedError: Connector not connected. Version: @wagmi/core@x.y.z] `) expect(new ConnectorNotFoundError()).toMatchInlineSnapshot(` [ConnectorNotFoundError: Connector not found. Version: @wagmi/core@x.y.z] `) expect( new ConnectorAccountNotFoundError({ address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', connector: config.connectors[0]!, }), ).toMatchInlineSnapshot(` [ConnectorAccountNotFoundError: Account "0xA0Cf798816D4b9b9866b5330EEa46a18382f251e" not found for connector "Mock Connector". Version: @wagmi/core@x.y.z] `) expect( new ConnectorChainMismatchError({ connectionChainId: 1, connectorChainId: 123, }), ).toMatchInlineSnapshot(` [ConnectorChainMismatchError: The current chain of the connector (id: 123) does not match the connection's chain (id: 1). Current Chain ID: 123 Expected Chain ID: 1 Version: @wagmi/core@x.y.z] `) expect( new ConnectorUnavailableReconnectingError({ connector: { name: 'Rabby Wallet' }, }), ).toMatchInlineSnapshot(` [ConnectorUnavailableReconnectingError: Connector "Rabby Wallet" unavailable while reconnecting. Details: During the reconnection step, the only connector methods guaranteed to be available are: \`id\`, \`name\`, \`type\`, \`uid\`. All other methods are not guaranteed to be available until reconnection completes and connectors are fully restored. This error commonly occurs for connectors that asynchronously inject after reconnection has already started. Version: @wagmi/core@x.y.z] `) }) ================================================ FILE: packages/core/src/errors/config.ts ================================================ import type { Address } from 'viem' import type { Connector } from '../createConfig.js' import { BaseError } from './base.js' export type ChainNotConfiguredErrorType = ChainNotConfiguredError & { name: 'ChainNotConfiguredError' } export class ChainNotConfiguredError extends BaseError { override name = 'ChainNotConfiguredError' constructor() { super('Chain not configured.') } } export type ConnectorAlreadyConnectedErrorType = ConnectorAlreadyConnectedError & { name: 'ConnectorAlreadyConnectedError' } export class ConnectorAlreadyConnectedError extends BaseError { override name = 'ConnectorAlreadyConnectedError' constructor() { super('Connector already connected.') } } export type ConnectorNotConnectedErrorType = ConnectorNotConnectedError & { name: 'ConnectorNotConnectedError' } export class ConnectorNotConnectedError extends BaseError { override name = 'ConnectorNotConnectedError' constructor() { super('Connector not connected.') } } export type ConnectorNotFoundErrorType = ConnectorNotFoundError & { name: 'ConnectorNotFoundError' } export class ConnectorNotFoundError extends BaseError { override name = 'ConnectorNotFoundError' constructor() { super('Connector not found.') } } export type ConnectorAccountNotFoundErrorType = ConnectorAccountNotFoundError & { name: 'ConnectorAccountNotFoundError' } export class ConnectorAccountNotFoundError extends BaseError { override name = 'ConnectorAccountNotFoundError' constructor({ address, connector, }: { address: Address connector: Connector }) { super(`Account "${address}" not found for connector "${connector.name}".`) } } export type ConnectorChainMismatchErrorType = ConnectorAccountNotFoundError & { name: 'ConnectorChainMismatchError' } export class ConnectorChainMismatchError extends BaseError { override name = 'ConnectorChainMismatchError' constructor({ connectionChainId, connectorChainId, }: { connectionChainId: number connectorChainId: number }) { super( `The current chain of the connector (id: ${connectorChainId}) does not match the connection's chain (id: ${connectionChainId}).`, { metaMessages: [ `Current Chain ID: ${connectorChainId}`, `Expected Chain ID: ${connectionChainId}`, ], }, ) } } export type ConnectorUnavailableReconnectingErrorType = ConnectorUnavailableReconnectingError & { name: 'ConnectorUnavailableReconnectingError' } export class ConnectorUnavailableReconnectingError extends BaseError { override name = 'ConnectorUnavailableReconnectingError' constructor({ connector }: { connector: { name: string } }) { super(`Connector "${connector.name}" unavailable while reconnecting.`, { details: [ 'During the reconnection step, the only connector methods guaranteed to be available are: `id`, `name`, `type`, `uid`.', 'All other methods are not guaranteed to be available until reconnection completes and connectors are fully restored.', 'This error commonly occurs for connectors that asynchronously inject after reconnection has already started.', ].join(' '), }) } } ================================================ FILE: packages/core/src/errors/connector.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { ProviderNotFoundError, SwitchChainNotSupportedError, } from './connector.js' test('constructors', () => { expect(new ProviderNotFoundError()).toMatchInlineSnapshot(` [ProviderNotFoundError: Provider not found. Version: @wagmi/core@x.y.z] `) expect( new SwitchChainNotSupportedError({ connector: config.connectors[0]!, }), ).toMatchInlineSnapshot(` [SwitchChainNotSupportedError: "Mock Connector" does not support programmatic chain switching. Version: @wagmi/core@x.y.z] `) }) ================================================ FILE: packages/core/src/errors/connector.ts ================================================ import type { Connector } from '../createConfig.js' import { BaseError } from './base.js' export type ProviderNotFoundErrorType = ProviderNotFoundError & { name: 'ProviderNotFoundError' } export class ProviderNotFoundError extends BaseError { override name = 'ProviderNotFoundError' constructor() { super('Provider not found.') } } export type SwitchChainNotSupportedErrorType = SwitchChainNotSupportedError & { name: 'SwitchChainNotSupportedError' } export class SwitchChainNotSupportedError extends BaseError { override name = 'SwitchChainNotSupportedError' constructor({ connector }: { connector: Connector }) { super(`"${connector.name}" does not support programmatic chain switching.`) } } ================================================ FILE: packages/core/src/exports/actions.test.ts ================================================ import { expect, test } from 'vitest' import * as actions from './actions.js' test('exports', () => { expect(Object.keys(actions)).toMatchInlineSnapshot(` [ "call", "connect", "deployContract", "disconnect", "estimateFeesPerGas", "estimateGas", "estimateMaxPriorityFeePerGas", "getBalance", "getBlobBaseFee", "getBlock", "getBlockNumber", "getBlockTransactionCount", "getBytecode", "getCallsStatus", "getCapabilities", "getChainId", "getChains", "getClient", "getAccount", "getConnection", "getConnections", "getConnectorClient", "getConnectors", "getContractEvents", "getEnsAddress", "getEnsAvatar", "getEnsName", "getEnsResolver", "getEnsText", "getFeeHistory", "getGasPrice", "getProof", "getPublicClient", "getStorageAt", "getTransaction", "getTransactionConfirmations", "getTransactionCount", "getTransactionReceipt", "getWalletClient", "multicall", "prepareTransactionRequest", "readContract", "readContracts", "reconnect", "sendCalls", "sendTransaction", "showCallsStatus", "signMessage", "signTransaction", "signTypedData", "simulateContract", "switchChain", "switchAccount", "switchConnection", "verifyMessage", "verifyTypedData", "waitForCallsStatus", "waitForTransactionReceipt", "watchAsset", "watchBlockNumber", "watchBlocks", "watchChainId", "watchClient", "watchAccount", "watchConnection", "watchConnections", "watchConnectors", "watchContractEvent", "watchPendingTransactions", "watchPublicClient", "writeContract", ] `) }) ================================================ FILE: packages/core/src/exports/actions.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // Actions //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module export { type CallErrorType, type CallParameters, type CallReturnType, call, } from '../actions/call.js' export { type ConnectErrorType, type ConnectParameters, type ConnectReturnType, connect, } from '../actions/connect.js' export { type DeployContractErrorType, type DeployContractParameters, type DeployContractReturnType, deployContract, } from '../actions/deployContract.js' export { type DisconnectErrorType, type DisconnectParameters, type DisconnectReturnType, disconnect, } from '../actions/disconnect.js' export { type EstimateFeesPerGasErrorType, type EstimateFeesPerGasParameters, type EstimateFeesPerGasReturnType, estimateFeesPerGas, } from '../actions/estimateFeesPerGas.js' export { type EstimateGasErrorType, type EstimateGasParameters, type EstimateGasReturnType, estimateGas, } from '../actions/estimateGas.js' export { type EstimateMaxPriorityFeePerGasErrorType, type EstimateMaxPriorityFeePerGasParameters, type EstimateMaxPriorityFeePerGasReturnType, estimateMaxPriorityFeePerGas, } from '../actions/estimateMaxPriorityFeePerGas.js' export { type GetBalanceErrorType, type GetBalanceParameters, type GetBalanceReturnType, getBalance, } from '../actions/getBalance.js' export { type GetBlobBaseFeeErrorType, type GetBlobBaseFeeParameters, type GetBlobBaseFeeReturnType, getBlobBaseFee, } from '../actions/getBlobBaseFee.js' export { type GetBlockErrorType, type GetBlockParameters, type GetBlockReturnType, getBlock, } from '../actions/getBlock.js' export { type GetBlockNumberErrorType, type GetBlockNumberParameters, type GetBlockNumberReturnType, getBlockNumber, } from '../actions/getBlockNumber.js' export { type GetBlockTransactionCountErrorType, type GetBlockTransactionCountParameters, type GetBlockTransactionCountReturnType, getBlockTransactionCount, } from '../actions/getBlockTransactionCount.js' export { type GetBytecodeErrorType, type GetBytecodeParameters, type GetBytecodeReturnType, getBytecode, } from '../actions/getBytecode.js' export { type GetCallsStatusErrorType, type GetCallsStatusParameters, type GetCallsStatusReturnType, getCallsStatus, } from '../actions/getCallsStatus.js' export { type GetCapabilitiesErrorType, type GetCapabilitiesParameters, type GetCapabilitiesReturnType, getCapabilities, } from '../actions/getCapabilities.js' export { type GetChainIdReturnType, getChainId, } from '../actions/getChainId.js' export { type GetChainsReturnType, getChains, } from '../actions/getChains.js' export { type GetClientParameters, type GetClientReturnType, getClient, } from '../actions/getClient.js' export { /** @deprecated use `GetConnectionReturnType` instead */ type GetConnectionReturnType as GetAccountReturnType, type GetConnectionReturnType, /** @deprecated use `getConnection` instead */ getConnection as getAccount, getConnection, } from '../actions/getConnection.js' export { type GetConnectionsReturnType, getConnections, } from '../actions/getConnections.js' export { type GetConnectorClientErrorType, type GetConnectorClientParameters, type GetConnectorClientReturnType, getConnectorClient, } from '../actions/getConnectorClient.js' export { type GetConnectorsReturnType, getConnectors, } from '../actions/getConnectors.js' export { type GetContractEventsErrorType, type GetContractEventsParameters, type GetContractEventsReturnType, getContractEvents, } from '../actions/getContractEvents.js' export { type GetEnsAddressErrorType, type GetEnsAddressParameters, type GetEnsAddressReturnType, getEnsAddress, } from '../actions/getEnsAddress.js' export { type GetEnsAvatarErrorType, type GetEnsAvatarParameters, type GetEnsAvatarReturnType, getEnsAvatar, } from '../actions/getEnsAvatar.js' export { type GetEnsNameErrorType, type GetEnsNameParameters, type GetEnsNameReturnType, getEnsName, } from '../actions/getEnsName.js' export { type GetEnsResolverErrorType, type GetEnsResolverParameters, type GetEnsResolverReturnType, getEnsResolver, } from '../actions/getEnsResolver.js' export { type GetEnsTextErrorType, type GetEnsTextParameters, type GetEnsTextReturnType, getEnsText, } from '../actions/getEnsText.js' export { type GetFeeHistoryErrorType, type GetFeeHistoryParameters, type GetFeeHistoryReturnType, getFeeHistory, } from '../actions/getFeeHistory.js' export { type GetGasPriceErrorType, type GetGasPriceParameters, type GetGasPriceReturnType, getGasPrice, } from '../actions/getGasPrice.js' export { type GetProofErrorType, type GetProofParameters, type GetProofReturnType, getProof, } from '../actions/getProof.js' export { type GetPublicClientParameters, type GetPublicClientReturnType, getPublicClient, } from '../actions/getPublicClient.js' export { type GetStorageAtErrorType, type GetStorageAtParameters, type GetStorageAtReturnType, getStorageAt, } from '../actions/getStorageAt.js' export { type GetTransactionErrorType, type GetTransactionParameters, type GetTransactionReturnType, getTransaction, } from '../actions/getTransaction.js' export { type GetTransactionConfirmationsErrorType, type GetTransactionConfirmationsParameters, type GetTransactionConfirmationsReturnType, getTransactionConfirmations, } from '../actions/getTransactionConfirmations.js' export { type GetTransactionCountErrorType, type GetTransactionCountParameters, type GetTransactionCountReturnType, getTransactionCount, } from '../actions/getTransactionCount.js' export { type GetTransactionReceiptErrorType, type GetTransactionReceiptParameters, type GetTransactionReceiptReturnType, getTransactionReceipt, } from '../actions/getTransactionReceipt.js' export { type GetWalletClientErrorType, type GetWalletClientParameters, type GetWalletClientReturnType, getWalletClient, } from '../actions/getWalletClient.js' export { type MulticallParameters, type MulticallReturnType, multicall, } from '../actions/multicall.js' export { type PrepareTransactionRequestErrorType, type PrepareTransactionRequestParameters, type PrepareTransactionRequestReturnType, prepareTransactionRequest, } from '../actions/prepareTransactionRequest.js' export { type ReadContractErrorType, type ReadContractParameters, type ReadContractReturnType, readContract, } from '../actions/readContract.js' export { type ReadContractsErrorType, type ReadContractsParameters, type ReadContractsReturnType, readContracts, } from '../actions/readContracts.js' export { type ReconnectErrorType, type ReconnectParameters, type ReconnectReturnType, reconnect, } from '../actions/reconnect.js' export { type SendCallsErrorType, type SendCallsParameters, type SendCallsReturnType, sendCalls, } from '../actions/sendCalls.js' export { type SendTransactionErrorType, type SendTransactionParameters, type SendTransactionReturnType, sendTransaction, } from '../actions/sendTransaction.js' export { type ShowCallsStatusErrorType, type ShowCallsStatusParameters, type ShowCallsStatusReturnType, showCallsStatus, } from '../actions/showCallsStatus.js' export { type SignMessageErrorType, type SignMessageParameters, type SignMessageReturnType, signMessage, } from '../actions/signMessage.js' export { type SignTransactionErrorType, type SignTransactionParameters, type SignTransactionReturnType, signTransaction, } from '../actions/signTransaction.js' export { type SignTypedDataErrorType, type SignTypedDataParameters, type SignTypedDataReturnType, signTypedData, } from '../actions/signTypedData.js' export { type SimulateContractErrorType, type SimulateContractParameters, type SimulateContractReturnType, simulateContract, } from '../actions/simulateContract.js' export { type SwitchChainErrorType, type SwitchChainParameters, type SwitchChainReturnType, switchChain, } from '../actions/switchChain.js' export { /** @deprecated use `SwitchConnectionErrorType` instead */ type SwitchConnectionErrorType as SwitchAccountErrorType, type SwitchConnectionErrorType, /** @deprecated use `SwitchConnectionParameters` instead */ type SwitchConnectionParameters as SwitchAccountParameters, type SwitchConnectionParameters, /** @deprecated use `SwitchConnectionReturnType` instead */ type SwitchConnectionReturnType as SwitchAccountReturnType, type SwitchConnectionReturnType, /** @deprecated use `switchConnection` instead */ switchConnection as switchAccount, switchConnection, } from '../actions/switchConnection.js' export { type VerifyMessageParameters, type VerifyMessageReturnType, verifyMessage, } from '../actions/verifyMessage.js' export { type VerifyTypedDataParameters, type VerifyTypedDataReturnType, verifyTypedData, } from '../actions/verifyTypedData.js' export { type WaitForCallsStatusErrorType, type WaitForCallsStatusParameters, type WaitForCallsStatusReturnType, waitForCallsStatus, } from '../actions/waitForCallsStatus.js' export { type WaitForTransactionReceiptErrorType, type WaitForTransactionReceiptParameters, type WaitForTransactionReceiptReturnType, waitForTransactionReceipt, } from '../actions/waitForTransactionReceipt.js' export { type WatchAssetParameters, type WatchAssetReturnType, watchAsset, } from '../actions/watchAsset.js' export { type WatchBlockNumberParameters, type WatchBlockNumberReturnType, watchBlockNumber, } from '../actions/watchBlockNumber.js' export { type WatchBlocksParameters, type WatchBlocksReturnType, watchBlocks, } from '../actions/watchBlocks.js' export { type WatchChainIdParameters, type WatchChainIdReturnType, watchChainId, } from '../actions/watchChainId.js' export { type WatchClientParameters, type WatchClientReturnType, watchClient, } from '../actions/watchClient.js' export { /** @deprecated use `WatchConnectionParameters` instead */ type WatchConnectionParameters as WatchAccountParameters, type WatchConnectionParameters, /** @deprecated use `WatchConnectionReturnType` instead */ type WatchConnectionReturnType as WatchAccountReturnType, type WatchConnectionReturnType, /** @deprecated use `watchConnection` instead */ watchConnection as watchAccount, watchConnection, } from '../actions/watchConnection.js' export { type WatchConnectionsParameters, type WatchConnectionsReturnType, watchConnections, } from '../actions/watchConnections.js' export { type WatchConnectorsParameters, type WatchConnectorsReturnType, watchConnectors, } from '../actions/watchConnectors.js' export { type WatchContractEventParameters, type WatchContractEventReturnType, watchContractEvent, } from '../actions/watchContractEvent.js' export { type WatchPendingTransactionsParameters, type WatchPendingTransactionsReturnType, watchPendingTransactions, } from '../actions/watchPendingTransactions.js' export { type WatchPublicClientParameters, type WatchPublicClientReturnType, watchPublicClient, } from '../actions/watchPublicClient.js' export { type WriteContractErrorType, type WriteContractParameters, type WriteContractReturnType, writeContract, } from '../actions/writeContract.js' ================================================ FILE: packages/core/src/exports/chains.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // viem/chains //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module // biome-ignore lint/performance/noReExportAll: entrypoint module export * from 'viem/chains' ================================================ FILE: packages/core/src/exports/codegen.test.ts ================================================ import { expect, test } from 'vitest' import * as codegen from './codegen.js' test('exports', () => { expect(Object.keys(codegen)).toMatchInlineSnapshot(` [ "createReadContract", "createSimulateContract", "createWatchContractEvent", "createWriteContract", ] `) }) ================================================ FILE: packages/core/src/exports/codegen.ts ================================================ // biome-ignore lint/performance/noBarrelFile: entrypoint module export { type CreateReadContractParameters, type CreateReadContractReturnType, createReadContract, } from '../actions/codegen/createReadContract.js' export { type CreateSimulateContractParameters, type CreateSimulateContractReturnType, createSimulateContract, } from '../actions/codegen/createSimulateContract.js' export { type CreateWatchContractEventParameters, type CreateWatchContractEventReturnType, createWatchContractEvent, } from '../actions/codegen/createWatchContractEvent.js' export { type CreateWriteContractParameters, type CreateWriteContractReturnType, createWriteContract, } from '../actions/codegen/createWriteContract.js' ================================================ FILE: packages/core/src/exports/index.test.ts ================================================ import { expect, test } from 'vitest' import * as core from './index.js' test('exports', () => { expect(Object.keys(core)).toMatchInlineSnapshot(` [ "call", "connect", "deployContract", "disconnect", "estimateFeesPerGas", "estimateGas", "estimateMaxPriorityFeePerGas", "getBalance", "getBlobBaseFee", "getBlock", "getBlockNumber", "getBlockTransactionCount", "getBytecode", "getCallsStatus", "getCapabilities", "getChainId", "getChains", "getClient", "getAccount", "getConnection", "getConnections", "getConnectorClient", "getConnectors", "getContractEvents", "getEnsAddress", "getEnsAvatar", "getEnsName", "getEnsResolver", "getEnsText", "getFeeHistory", "getGasPrice", "getProof", "getPublicClient", "getStorageAt", "getTransaction", "getTransactionConfirmations", "getTransactionCount", "getTransactionReceipt", "getWalletClient", "multicall", "prepareTransactionRequest", "readContract", "readContracts", "reconnect", "sendCalls", "sendCallsSync", "sendTransaction", "sendTransactionSync", "showCallsStatus", "signMessage", "signTransaction", "signTypedData", "simulateContract", "switchChain", "switchAccount", "switchConnection", "verifyMessage", "verifyTypedData", "waitForCallsStatus", "waitForTransactionReceipt", "watchAsset", "watchBlockNumber", "watchBlocks", "watchChainId", "watchClient", "watchAccount", "watchConnection", "watchConnections", "watchConnectors", "watchContractEvent", "watchPendingTransactions", "watchPublicClient", "writeContract", "writeContractSync", "createConnector", "injected", "mock", "createConfig", "createStorage", "noopStorage", "hydrate", "BaseError", "ChainNotConfiguredError", "ConnectorAccountNotFoundError", "ConnectorAlreadyConnectedError", "ConnectorChainMismatchError", "ConnectorNotConnectedError", "ConnectorNotFoundError", "ConnectorUnavailableReconnectingError", "ProviderNotFoundError", "SwitchChainNotSupportedError", "custom", "http", "webSocket", "unstable_connector", "fallback", "cookieStorage", "cookieToInitialState", "parseCookie", "deepEqual", "deserialize", "extractRpcUrls", "serialize", "version", ] `) }) ================================================ FILE: packages/core/src/exports/index.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // Actions //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module export { type CallErrorType, type CallParameters, type CallReturnType, call, } from '../actions/call.js' export { type ConnectErrorType, type ConnectParameters, type ConnectReturnType, connect, } from '../actions/connect.js' export { type DeployContractErrorType, type DeployContractParameters, type DeployContractReturnType, deployContract, } from '../actions/deployContract.js' export { type DisconnectErrorType, type DisconnectParameters, type DisconnectReturnType, disconnect, } from '../actions/disconnect.js' export { type EstimateFeesPerGasErrorType, type EstimateFeesPerGasParameters, type EstimateFeesPerGasReturnType, estimateFeesPerGas, } from '../actions/estimateFeesPerGas.js' export { type EstimateGasErrorType, type EstimateGasParameters, type EstimateGasReturnType, estimateGas, } from '../actions/estimateGas.js' export { type EstimateMaxPriorityFeePerGasErrorType, type EstimateMaxPriorityFeePerGasParameters, type EstimateMaxPriorityFeePerGasReturnType, estimateMaxPriorityFeePerGas, } from '../actions/estimateMaxPriorityFeePerGas.js' export { type GetBalanceErrorType, type GetBalanceParameters, type GetBalanceReturnType, getBalance, } from '../actions/getBalance.js' export { type GetBlobBaseFeeErrorType, type GetBlobBaseFeeParameters, type GetBlobBaseFeeReturnType, getBlobBaseFee, } from '../actions/getBlobBaseFee.js' export { type GetBlockErrorType, type GetBlockParameters, type GetBlockReturnType, getBlock, } from '../actions/getBlock.js' export { type GetBlockNumberErrorType, type GetBlockNumberParameters, type GetBlockNumberReturnType, getBlockNumber, } from '../actions/getBlockNumber.js' export { type GetBlockTransactionCountErrorType, type GetBlockTransactionCountParameters, type GetBlockTransactionCountReturnType, getBlockTransactionCount, } from '../actions/getBlockTransactionCount.js' export { type GetBytecodeErrorType, type GetBytecodeParameters, type GetBytecodeReturnType, getBytecode, } from '../actions/getBytecode.js' export { type GetCallsStatusErrorType, type GetCallsStatusParameters, type GetCallsStatusReturnType, getCallsStatus, } from '../actions/getCallsStatus.js' export { type GetCapabilitiesErrorType, type GetCapabilitiesParameters, type GetCapabilitiesReturnType, getCapabilities, } from '../actions/getCapabilities.js' export { type GetChainIdReturnType, getChainId, } from '../actions/getChainId.js' export { type GetChainsReturnType, getChains, } from '../actions/getChains.js' export { type GetClientParameters, type GetClientReturnType, getClient, } from '../actions/getClient.js' export { /** @deprecated use `GetConnectionReturnType` instead */ type GetConnectionReturnType as GetAccountReturnType, type GetConnectionReturnType, /** @deprecated use `getConnection` instead */ getConnection as getAccount, getConnection, } from '../actions/getConnection.js' export { type GetConnectionsReturnType, getConnections, } from '../actions/getConnections.js' export { type GetConnectorClientErrorType, type GetConnectorClientParameters, type GetConnectorClientReturnType, getConnectorClient, } from '../actions/getConnectorClient.js' export { type GetConnectorsReturnType, getConnectors, } from '../actions/getConnectors.js' export { type GetContractEventsErrorType, type GetContractEventsParameters, type GetContractEventsReturnType, getContractEvents, } from '../actions/getContractEvents.js' export { type GetEnsAddressErrorType, type GetEnsAddressParameters, type GetEnsAddressReturnType, getEnsAddress, } from '../actions/getEnsAddress.js' export { type GetEnsAvatarErrorType, type GetEnsAvatarParameters, type GetEnsAvatarReturnType, getEnsAvatar, } from '../actions/getEnsAvatar.js' export { type GetEnsNameErrorType, type GetEnsNameParameters, type GetEnsNameReturnType, getEnsName, } from '../actions/getEnsName.js' export { type GetEnsResolverErrorType, type GetEnsResolverParameters, type GetEnsResolverReturnType, getEnsResolver, } from '../actions/getEnsResolver.js' export { type GetEnsTextErrorType, type GetEnsTextParameters, type GetEnsTextReturnType, getEnsText, } from '../actions/getEnsText.js' export { type GetFeeHistoryErrorType, type GetFeeHistoryParameters, type GetFeeHistoryReturnType, getFeeHistory, } from '../actions/getFeeHistory.js' export { type GetGasPriceErrorType, type GetGasPriceParameters, type GetGasPriceReturnType, getGasPrice, } from '../actions/getGasPrice.js' export { type GetProofErrorType, type GetProofParameters, type GetProofReturnType, getProof, } from '../actions/getProof.js' export { type GetPublicClientParameters, type GetPublicClientReturnType, getPublicClient, } from '../actions/getPublicClient.js' export { type GetStorageAtErrorType, type GetStorageAtParameters, type GetStorageAtReturnType, getStorageAt, } from '../actions/getStorageAt.js' export { type GetTransactionErrorType, type GetTransactionParameters, type GetTransactionReturnType, getTransaction, } from '../actions/getTransaction.js' export { type GetTransactionConfirmationsErrorType, type GetTransactionConfirmationsParameters, type GetTransactionConfirmationsReturnType, getTransactionConfirmations, } from '../actions/getTransactionConfirmations.js' export { type GetTransactionCountErrorType, type GetTransactionCountParameters, type GetTransactionCountReturnType, getTransactionCount, } from '../actions/getTransactionCount.js' export { type GetTransactionReceiptErrorType, type GetTransactionReceiptParameters, type GetTransactionReceiptReturnType, getTransactionReceipt, } from '../actions/getTransactionReceipt.js' export { type GetWalletClientErrorType, type GetWalletClientParameters, type GetWalletClientReturnType, getWalletClient, } from '../actions/getWalletClient.js' export { type MulticallParameters, type MulticallReturnType, multicall, } from '../actions/multicall.js' export { type PrepareTransactionRequestErrorType, type PrepareTransactionRequestParameters, type PrepareTransactionRequestReturnType, prepareTransactionRequest, } from '../actions/prepareTransactionRequest.js' export { type ReadContractErrorType, type ReadContractParameters, type ReadContractReturnType, readContract, } from '../actions/readContract.js' export { type ReadContractsErrorType, type ReadContractsParameters, type ReadContractsReturnType, readContracts, } from '../actions/readContracts.js' export { type ReconnectErrorType, type ReconnectParameters, type ReconnectReturnType, reconnect, } from '../actions/reconnect.js' export { type SendCallsErrorType, type SendCallsParameters, type SendCallsReturnType, sendCalls, } from '../actions/sendCalls.js' export { type SendCallsSyncErrorType, type SendCallsSyncParameters, type SendCallsSyncReturnType, sendCallsSync, } from '../actions/sendCallsSync.js' export { type SendTransactionErrorType, type SendTransactionParameters, type SendTransactionReturnType, sendTransaction, } from '../actions/sendTransaction.js' export { type SendTransactionSyncErrorType, type SendTransactionSyncParameters, type SendTransactionSyncReturnType, sendTransactionSync, } from '../actions/sendTransactionSync.js' export { type ShowCallsStatusErrorType, type ShowCallsStatusParameters, type ShowCallsStatusReturnType, showCallsStatus, } from '../actions/showCallsStatus.js' export { type SignMessageErrorType, type SignMessageParameters, type SignMessageReturnType, signMessage, } from '../actions/signMessage.js' export { type SignTransactionErrorType, type SignTransactionParameters, type SignTransactionReturnType, signTransaction, } from '../actions/signTransaction.js' export { type SignTypedDataErrorType, type SignTypedDataParameters, type SignTypedDataReturnType, signTypedData, } from '../actions/signTypedData.js' export { type SimulateContractErrorType, type SimulateContractParameters, type SimulateContractReturnType, simulateContract, } from '../actions/simulateContract.js' export { type SwitchChainErrorType, type SwitchChainParameters, type SwitchChainReturnType, switchChain, } from '../actions/switchChain.js' export { /** @deprecated use `SwitchConnectionErrorType` instead */ type SwitchConnectionErrorType as SwitchAccountErrorType, type SwitchConnectionErrorType, /** @deprecated use `SwitchConnectionParameters` instead */ type SwitchConnectionParameters as SwitchAccountParameters, type SwitchConnectionParameters, /** @deprecated use `SwitchConnectionReturnType` instead */ type SwitchConnectionReturnType as SwitchAccountReturnType, type SwitchConnectionReturnType, /** @deprecated use `switchConnection` instead */ switchConnection as switchAccount, switchConnection, } from '../actions/switchConnection.js' export { type VerifyMessageErrorType, type VerifyMessageParameters, type VerifyMessageReturnType, verifyMessage, } from '../actions/verifyMessage.js' export { type VerifyTypedDataErrorType, type VerifyTypedDataParameters, type VerifyTypedDataReturnType, verifyTypedData, } from '../actions/verifyTypedData.js' export { type WaitForCallsStatusErrorType, type WaitForCallsStatusParameters, type WaitForCallsStatusReturnType, waitForCallsStatus, } from '../actions/waitForCallsStatus.js' export { type WaitForTransactionReceiptErrorType, type WaitForTransactionReceiptParameters, type WaitForTransactionReceiptReturnType, waitForTransactionReceipt, } from '../actions/waitForTransactionReceipt.js' export { type WatchAssetErrorType, type WatchAssetParameters, type WatchAssetReturnType, watchAsset, } from '../actions/watchAsset.js' export { type WatchBlockNumberParameters, type WatchBlockNumberReturnType, watchBlockNumber, } from '../actions/watchBlockNumber.js' export { type WatchBlocksParameters, type WatchBlocksReturnType, watchBlocks, } from '../actions/watchBlocks.js' export { type WatchChainIdParameters, type WatchChainIdReturnType, watchChainId, } from '../actions/watchChainId.js' export { type WatchClientParameters, type WatchClientReturnType, watchClient, } from '../actions/watchClient.js' export { /** @deprecated use `WatchConnectionParameters` instead */ type WatchConnectionParameters as WatchAccountParameters, type WatchConnectionParameters, /** @deprecated use `WatchConnectionReturnType` instead */ type WatchConnectionReturnType as WatchAccountReturnType, type WatchConnectionReturnType, /** @deprecated use `watchConnection` instead */ watchConnection as watchAccount, watchConnection, } from '../actions/watchConnection.js' export { type WatchConnectionsParameters, type WatchConnectionsReturnType, watchConnections, } from '../actions/watchConnections.js' export { type WatchConnectorsParameters, type WatchConnectorsReturnType, watchConnectors, } from '../actions/watchConnectors.js' export { type WatchContractEventParameters, type WatchContractEventReturnType, watchContractEvent, } from '../actions/watchContractEvent.js' export { type WatchPendingTransactionsParameters, type WatchPendingTransactionsReturnType, watchPendingTransactions, } from '../actions/watchPendingTransactions.js' export { type WatchPublicClientParameters, type WatchPublicClientReturnType, watchPublicClient, } from '../actions/watchPublicClient.js' export { type WriteContractErrorType, type WriteContractParameters, type WriteContractReturnType, writeContract, } from '../actions/writeContract.js' export { type WriteContractSyncErrorType, type WriteContractSyncParameters, type WriteContractSyncReturnType, writeContractSync, } from '../actions/writeContractSync.js' //////////////////////////////////////////////////////////////////////////////// // Connectors //////////////////////////////////////////////////////////////////////////////// export { type ConnectorEventMap, type CreateConnectorFn, createConnector, } from '../connectors/createConnector.js' export { type InjectedParameters, injected, } from '../connectors/injected.js' export { type MockParameters, mock, } from '../connectors/mock.js' //////////////////////////////////////////////////////////////////////////////// // createConfig //////////////////////////////////////////////////////////////////////////////// export { type Config, type Connection, type Connector, type CreateConfigParameters, createConfig, type PartializedState, type State, type Transport, } from '../createConfig.js' //////////////////////////////////////////////////////////////////////////////// // createStorage //////////////////////////////////////////////////////////////////////////////// export { type CreateStorageParameters, createStorage, noopStorage, type Storage, type StorageItemMap, } from '../createStorage.js' //////////////////////////////////////////////////////////////////////////////// // Hydrate //////////////////////////////////////////////////////////////////////////////// export { hydrate } from '../hydrate.js' //////////////////////////////////////////////////////////////////////////////// // Errors //////////////////////////////////////////////////////////////////////////////// export { BaseError } from '../errors/base.js' export { ChainNotConfiguredError, type ChainNotConfiguredErrorType, ConnectorAccountNotFoundError, type ConnectorAccountNotFoundErrorType, ConnectorAlreadyConnectedError, type ConnectorAlreadyConnectedErrorType, ConnectorChainMismatchError, type ConnectorChainMismatchErrorType, ConnectorNotConnectedError, type ConnectorNotConnectedErrorType, ConnectorNotFoundError, type ConnectorNotFoundErrorType, ConnectorUnavailableReconnectingError, type ConnectorUnavailableReconnectingErrorType, } from '../errors/config.js' export { ProviderNotFoundError, type ProviderNotFoundErrorType, SwitchChainNotSupportedError, type SwitchChainNotSupportedErrorType, } from '../errors/connector.js' //////////////////////////////////////////////////////////////////////////////// // Transports //////////////////////////////////////////////////////////////////////////////// export { custom, http, webSocket } from 'viem' export { type ConnectorTransport, type ConnectorTransportConfig, unstable_connector, } from '../transports/connector.js' export { fallback } from '../transports/fallback.js' //////////////////////////////////////////////////////////////////////////////// // Types //////////////////////////////////////////////////////////////////////////////// export type { SelectChains } from '../types/chain.js' export type { Register, ResolvedRegister } from '../types/register.js' //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// export { cookieStorage, cookieToInitialState, parseCookie, } from '../utils/cookie.js' export { deepEqual } from '../utils/deepEqual.js' export { deserialize } from '../utils/deserialize.js' export { extractRpcUrls } from '../utils/extractRpcUrls.js' export { serialize } from '../utils/serialize.js' //////////////////////////////////////////////////////////////////////////////// // Version //////////////////////////////////////////////////////////////////////////////// export { version } from '../version.js' ================================================ FILE: packages/core/src/exports/internal.test.ts ================================================ import { expect, test } from 'vitest' import * as internal from './internal.js' test('exports', () => { expect(Object.keys(internal)).toMatchInlineSnapshot(` [ "watchChains", "createEmitter", "Emitter", "deepEqual", "uid", ] `) }) ================================================ FILE: packages/core/src/exports/internal.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // Actions //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module export { type WatchChainsParameters, type WatchChainsReturnType, watchChains, } from '../actions/watchChains.js' //////////////////////////////////////////////////////////////////////////////// // Emitter //////////////////////////////////////////////////////////////////////////////// export { createEmitter, Emitter, type EventData, } from '../createEmitter.js' //////////////////////////////////////////////////////////////////////////////// // Types //////////////////////////////////////////////////////////////////////////////// export type { SelectChains } from '../types/chain.js' export type { ChainIdParameter, ConfigParameter, ConnectorParameter, EnabledParameter, ScopeKeyParameter, } from '../types/properties.js' export type { QueryParameter } from '../types/query.js' export type { Compute, ExactPartial, FixedArray, Mutable, OneOf, PartialBy, RemoveUndefined, RequiredBy, StrictOmit as Omit, UnionCompute, UnionExactPartial, UnionLooseOmit, UnionStrictOmit, } from '../types/utils.js' //////////////////////////////////////////////////////////////////////////////// // Utilities //////////////////////////////////////////////////////////////////////////////// export { deepEqual } from '../utils/deepEqual.js' export { uid } from '../utils/uid.js' ================================================ FILE: packages/core/src/exports/query.test.ts ================================================ import { expect, test } from 'vitest' import * as query from './query.js' test('exports', () => { expect(Object.keys(query)).toMatchInlineSnapshot(` [ "callQueryKey", "callQueryOptions", "connectMutationOptions", "deployContractMutationOptions", "disconnectMutationOptions", "estimateFeesPerGasQueryKey", "estimateFeesPerGasQueryOptions", "estimateGasQueryKey", "estimateGasQueryOptions", "estimateMaxPriorityFeePerGasQueryKey", "estimateMaxPriorityFeePerGasQueryOptions", "getBalanceQueryKey", "getBalanceQueryOptions", "getBlobBaseFeeQueryKey", "getBlobBaseFeeQueryOptions", "getBlockQueryKey", "getBlockQueryOptions", "getBlockNumberQueryKey", "getBlockNumberQueryOptions", "getBlockTransactionCountQueryKey", "getBlockTransactionCountQueryOptions", "getBytecodeQueryKey", "getBytecodeQueryOptions", "getCallsStatusQueryKey", "getCallsStatusQueryOptions", "getCapabilitiesQueryKey", "getCapabilitiesQueryOptions", "getConnectorClientQueryKey", "getConnectorClientQueryOptions", "getContractEventsQueryKey", "getContractEventsQueryOptions", "getEnsAddressQueryKey", "getEnsAddressQueryOptions", "getEnsAvatarQueryKey", "getEnsAvatarQueryOptions", "getEnsNameQueryKey", "getEnsNameQueryOptions", "getEnsResolverQueryKey", "getEnsResolverQueryOptions", "getEnsTextQueryKey", "getEnsTextQueryOptions", "getFeeHistoryQueryKey", "getFeeHistoryQueryOptions", "getGasPriceQueryKey", "getGasPriceQueryOptions", "getProofQueryKey", "getProofQueryOptions", "getStorageAtQueryKey", "getStorageAtQueryOptions", "getTransactionQueryKey", "getTransactionQueryOptions", "getTransactionConfirmationsQueryKey", "getTransactionConfirmationsQueryOptions", "getTransactionCountQueryKey", "getTransactionCountQueryOptions", "getTransactionReceiptQueryKey", "getTransactionReceiptQueryOptions", "getWalletClientQueryKey", "getWalletClientQueryOptions", "infiniteReadContractsQueryKey", "infiniteReadContractsQueryOptions", "prepareTransactionRequestQueryKey", "prepareTransactionRequestQueryOptions", "readContractQueryKey", "readContractQueryOptions", "readContractsQueryKey", "readContractsQueryOptions", "reconnectMutationOptions", "sendCallsMutationOptions", "sendCallsSyncMutationOptions", "sendTransactionMutationOptions", "sendTransactionSyncMutationOptions", "showCallsStatusMutationOptions", "signMessageMutationOptions", "signTransactionMutationOptions", "signTypedDataMutationOptions", "simulateContractQueryKey", "simulateContractQueryOptions", "switchChainMutationOptions", "switchAccountMutationOptions", "switchConnectionMutationOptions", "hashFn", "structuralSharing", "verifyMessageQueryKey", "verifyMessageQueryOptions", "verifyTypedDataQueryKey", "verifyTypedDataQueryOptions", "waitForCallsStatusQueryKey", "waitForCallsStatusQueryOptions", "waitForTransactionReceiptQueryKey", "waitForTransactionReceiptQueryOptions", "watchAssetMutationOptions", "writeContractMutationOptions", "writeContractSyncMutationOptions", ] `) }) ================================================ FILE: packages/core/src/exports/query.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // Tanstack Query //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module export { type CallData, type CallOptions, type CallQueryFnData, type CallQueryKey, type CallQueryOptions, callQueryKey, callQueryOptions, } from '../query/call.js' export { type ConnectData, type ConnectMutate, type ConnectMutateAsync, type ConnectMutationOptions, type ConnectOptions, type ConnectVariables, connectMutationOptions, } from '../query/connect.js' export { type DeployContractData, type DeployContractMutate, type DeployContractMutateAsync, type DeployContractMutationOptions, type DeployContractOptions, type DeployContractVariables, deployContractMutationOptions, } from '../query/deployContract.js' export { type DisconnectData, type DisconnectMutate, type DisconnectMutateAsync, type DisconnectMutationOptions, type DisconnectOptions, type DisconnectVariables, disconnectMutationOptions, } from '../query/disconnect.js' export { type EstimateFeesPerGasData, type EstimateFeesPerGasOptions, type EstimateFeesPerGasQueryFnData, type EstimateFeesPerGasQueryKey, type EstimateFeesPerGasQueryOptions, estimateFeesPerGasQueryKey, estimateFeesPerGasQueryOptions, } from '../query/estimateFeesPerGas.js' export { type EstimateGasData, type EstimateGasOptions, type EstimateGasQueryFnData, type EstimateGasQueryKey, type EstimateGasQueryOptions, estimateGasQueryKey, estimateGasQueryOptions, } from '../query/estimateGas.js' export { type EstimateMaxPriorityFeePerGasData, type EstimateMaxPriorityFeePerGasOptions, type EstimateMaxPriorityFeePerGasQueryFnData, type EstimateMaxPriorityFeePerGasQueryKey, type EstimateMaxPriorityFeePerGasQueryOptions, estimateMaxPriorityFeePerGasQueryKey, estimateMaxPriorityFeePerGasQueryOptions, } from '../query/estimateMaxPriorityFeePerGas.js' export { type GetBalanceData, type GetBalanceOptions, type GetBalanceQueryFnData, type GetBalanceQueryKey, type GetBalanceQueryOptions, getBalanceQueryKey, getBalanceQueryOptions, } from '../query/getBalance.js' export { type GetBlobBaseFeeData, type GetBlobBaseFeeOptions, type GetBlobBaseFeeQueryFnData, type GetBlobBaseFeeQueryKey, type GetBlobBaseFeeQueryOptions, getBlobBaseFeeQueryKey, getBlobBaseFeeQueryOptions, } from '../query/getBlobBaseFee.js' export { type GetBlockData, type GetBlockOptions, type GetBlockQueryFnData, type GetBlockQueryKey, type GetBlockQueryOptions, getBlockQueryKey, getBlockQueryOptions, } from '../query/getBlock.js' export { type GetBlockNumberData, type GetBlockNumberOptions, type GetBlockNumberQueryFnData, type GetBlockNumberQueryKey, type GetBlockNumberQueryOptions, getBlockNumberQueryKey, getBlockNumberQueryOptions, } from '../query/getBlockNumber.js' export { type GetBlockTransactionCountData, type GetBlockTransactionCountOptions, type GetBlockTransactionCountQueryFnData, type GetBlockTransactionCountQueryKey, type GetBlockTransactionCountQueryOptions, getBlockTransactionCountQueryKey, getBlockTransactionCountQueryOptions, } from '../query/getBlockTransactionCount.js' export { type GetBytecodeData, type GetBytecodeOptions, type GetBytecodeQueryFnData, type GetBytecodeQueryKey, type GetBytecodeQueryOptions, getBytecodeQueryKey, getBytecodeQueryOptions, } from '../query/getBytecode.js' export { type GetCallsStatusData, type GetCallsStatusOptions, type GetCallsStatusQueryFnData, type GetCallsStatusQueryKey, type GetCallsStatusQueryOptions, getCallsStatusQueryKey, getCallsStatusQueryOptions, } from '../query/getCallsStatus.js' export { type GetCapabilitiesData, type GetCapabilitiesOptions, type GetCapabilitiesQueryFnData, type GetCapabilitiesQueryKey, type GetCapabilitiesQueryOptions, getCapabilitiesQueryKey, getCapabilitiesQueryOptions, } from '../query/getCapabilities.js' export { type GetConnectorClientData, type GetConnectorClientOptions, type GetConnectorClientQueryFnData, type GetConnectorClientQueryKey, type GetConnectorClientQueryOptions, getConnectorClientQueryKey, getConnectorClientQueryOptions, } from '../query/getConnectorClient.js' export { type GetContractEventsData, type GetContractEventsOptions, type GetContractEventsQueryFnData, type GetContractEventsQueryKey, type GetContractEventsQueryOptions, getContractEventsQueryKey, getContractEventsQueryOptions, } from '../query/getContractEvents.js' export { type GetEnsAddressData, type GetEnsAddressOptions, type GetEnsAddressQueryFnData, type GetEnsAddressQueryKey, type GetEnsAddressQueryOptions, getEnsAddressQueryKey, getEnsAddressQueryOptions, } from '../query/getEnsAddress.js' export { type GetEnsAvatarData, type GetEnsAvatarOptions, type GetEnsAvatarQueryFnData, type GetEnsAvatarQueryKey, type GetEnsAvatarQueryOptions, getEnsAvatarQueryKey, getEnsAvatarQueryOptions, } from '../query/getEnsAvatar.js' export { type GetEnsNameData, type GetEnsNameOptions, type GetEnsNameQueryFnData, type GetEnsNameQueryKey, type GetEnsNameQueryOptions, getEnsNameQueryKey, getEnsNameQueryOptions, } from '../query/getEnsName.js' export { type GetEnsResolverData, type GetEnsResolverOptions, type GetEnsResolverQueryFnData, type GetEnsResolverQueryKey, type GetEnsResolverQueryOptions, getEnsResolverQueryKey, getEnsResolverQueryOptions, } from '../query/getEnsResolver.js' export { type GetEnsTextData, type GetEnsTextOptions, type GetEnsTextQueryFnData, type GetEnsTextQueryKey, type GetEnsTextQueryOptions, getEnsTextQueryKey, getEnsTextQueryOptions, } from '../query/getEnsText.js' export { type GetFeeHistoryData, type GetFeeHistoryOptions, type GetFeeHistoryQueryFnData, type GetFeeHistoryQueryKey, type GetFeeHistoryQueryOptions, getFeeHistoryQueryKey, getFeeHistoryQueryOptions, } from '../query/getFeeHistory.js' export { type GetGasPriceData, type GetGasPriceOptions, type GetGasPriceQueryFnData, type GetGasPriceQueryKey, type GetGasPriceQueryOptions, getGasPriceQueryKey, getGasPriceQueryOptions, } from '../query/getGasPrice.js' export { type GetProofData, type GetProofOptions, type GetProofQueryFnData, type GetProofQueryKey, type GetProofQueryOptions, getProofQueryKey, getProofQueryOptions, } from '../query/getProof.js' export { type GetStorageAtData, type GetStorageAtOptions, type GetStorageAtQueryFnData, type GetStorageAtQueryKey, type GetStorageAtQueryOptions, getStorageAtQueryKey, getStorageAtQueryOptions, } from '../query/getStorageAt.js' export { type GetTransactionData, type GetTransactionOptions, type GetTransactionQueryFnData, type GetTransactionQueryKey, type GetTransactionQueryOptions, getTransactionQueryKey, getTransactionQueryOptions, } from '../query/getTransaction.js' export { type GetTransactionConfirmationsData, type GetTransactionConfirmationsOptions, type GetTransactionConfirmationsQueryFnData, type GetTransactionConfirmationsQueryKey, type GetTransactionConfirmationsQueryOptions, getTransactionConfirmationsQueryKey, getTransactionConfirmationsQueryOptions, } from '../query/getTransactionConfirmations.js' export { type GetTransactionCountData, type GetTransactionCountOptions, type GetTransactionCountQueryFnData, type GetTransactionCountQueryKey, type GetTransactionCountQueryOptions, getTransactionCountQueryKey, getTransactionCountQueryOptions, } from '../query/getTransactionCount.js' export { type GetTransactionReceiptData, type GetTransactionReceiptOptions, type GetTransactionReceiptQueryFnData, type GetTransactionReceiptQueryKey, type GetTransactionReceiptQueryOptions, getTransactionReceiptQueryKey, getTransactionReceiptQueryOptions, } from '../query/getTransactionReceipt.js' export { type GetWalletClientData, type GetWalletClientOptions, type GetWalletClientQueryFnData, type GetWalletClientQueryKey, type GetWalletClientQueryOptions, getWalletClientQueryKey, getWalletClientQueryOptions, } from '../query/getWalletClient.js' export { type InfiniteReadContractsData, type InfiniteReadContractsOptions, type InfiniteReadContractsQueryFnData, type InfiniteReadContractsQueryKey, infiniteReadContractsQueryKey, infiniteReadContractsQueryOptions, } from '../query/infiniteReadContracts.js' export { type PrepareTransactionRequestData, type PrepareTransactionRequestOptions, type PrepareTransactionRequestQueryFnData, type PrepareTransactionRequestQueryKey, type PrepareTransactionRequestQueryOptions, prepareTransactionRequestQueryKey, prepareTransactionRequestQueryOptions, } from '../query/prepareTransactionRequest.js' export { type ReadContractData, type ReadContractOptions, type ReadContractQueryFnData, type ReadContractQueryKey, type ReadContractQueryOptions, readContractQueryKey, readContractQueryOptions, } from '../query/readContract.js' export { type ReadContractsData, type ReadContractsOptions, type ReadContractsQueryFnData, type ReadContractsQueryKey, type ReadContractsQueryOptions, readContractsQueryKey, readContractsQueryOptions, } from '../query/readContracts.js' export { type ReconnectData, type ReconnectMutate, type ReconnectMutateAsync, type ReconnectMutationOptions, type ReconnectOptions, type ReconnectVariables, reconnectMutationOptions, } from '../query/reconnect.js' export { type SendCallsData, type SendCallsMutate, type SendCallsMutateAsync, type SendCallsMutationOptions, type SendCallsOptions, type SendCallsVariables, sendCallsMutationOptions, } from '../query/sendCalls.js' export { type SendCallsSyncData, type SendCallsSyncMutate, type SendCallsSyncMutateAsync, type SendCallsSyncMutationOptions, type SendCallsSyncOptions, type SendCallsSyncVariables, sendCallsSyncMutationOptions, } from '../query/sendCallsSync.js' export { type SendTransactionData, type SendTransactionMutate, type SendTransactionMutateAsync, type SendTransactionMutationOptions, type SendTransactionOptions, type SendTransactionVariables, sendTransactionMutationOptions, } from '../query/sendTransaction.js' export { type SendTransactionSyncData, type SendTransactionSyncMutate, type SendTransactionSyncMutateAsync, type SendTransactionSyncMutationOptions, type SendTransactionSyncOptions, type SendTransactionSyncVariables, sendTransactionSyncMutationOptions, } from '../query/sendTransactionSync.js' export { type ShowCallsStatusData, type ShowCallsStatusMutate, type ShowCallsStatusMutateAsync, type ShowCallsStatusMutationOptions, type ShowCallsStatusOptions, type ShowCallsStatusVariables, showCallsStatusMutationOptions, } from '../query/showCallsStatus.js' export { type SignMessageData, type SignMessageMutate, type SignMessageMutateAsync, type SignMessageMutationOptions, type SignMessageOptions, type SignMessageVariables, signMessageMutationOptions, } from '../query/signMessage.js' export { type SignTransactionData, type SignTransactionMutate, type SignTransactionMutateAsync, type SignTransactionMutationOptions, type SignTransactionOptions, type SignTransactionVariables, signTransactionMutationOptions, } from '../query/signTransaction.js' export { type SignTypedDataData, type SignTypedDataMutate, type SignTypedDataMutateAsync, type SignTypedDataMutationOptions, type SignTypedDataOptions, type SignTypedDataVariables, signTypedDataMutationOptions, } from '../query/signTypedData.js' export { type SimulateContractData, type SimulateContractOptions, type SimulateContractQueryFnData, type SimulateContractQueryKey, type SimulateContractQueryOptions, simulateContractQueryKey, simulateContractQueryOptions, } from '../query/simulateContract.js' export { type SwitchChainData, type SwitchChainMutate, type SwitchChainMutateAsync, type SwitchChainMutationOptions, type SwitchChainOptions, type SwitchChainVariables, switchChainMutationOptions, } from '../query/switchChain.js' export { /** @deprecated use `SwitchConnectionData` instead */ type SwitchConnectionData as SwitchAccountData, type SwitchConnectionData, /** @deprecated use `SwitchConnectionMutate` instead */ type SwitchConnectionMutate as SwitchAccountMutate, type SwitchConnectionMutate, /** @deprecated use `SwitchConnectionMutateAsync` instead */ type SwitchConnectionMutateAsync as SwitchAccountMutateAsync, type SwitchConnectionMutateAsync, /** @deprecated use `SwitchConnectionMutationOptions` instead */ type SwitchConnectionMutationOptions as SwitchAccountMutationOptions, type SwitchConnectionMutationOptions, /** @deprecated use `SwitchConnectionOptions` instead */ type SwitchConnectionOptions as SwitchAccountOptions, type SwitchConnectionOptions, /** @deprecated use `SwitchConnectionVariables` instead */ type SwitchConnectionVariables as SwitchAccountVariables, type SwitchConnectionVariables, /** @deprecated use `switchConnectionMutationOptions` instead */ switchConnectionMutationOptions as switchAccountMutationOptions, switchConnectionMutationOptions, } from '../query/switchConnection.js' export { hashFn, structuralSharing, } from '../query/utils.js' export { type VerifyMessageData, type VerifyMessageOptions, type VerifyMessageQueryFnData, type VerifyMessageQueryKey, type VerifyMessageQueryOptions, verifyMessageQueryKey, verifyMessageQueryOptions, } from '../query/verifyMessage.js' export { type VerifyTypedDataData, type VerifyTypedDataOptions, type VerifyTypedDataQueryFnData, type VerifyTypedDataQueryKey, type VerifyTypedDataQueryOptions, verifyTypedDataQueryKey, verifyTypedDataQueryOptions, } from '../query/verifyTypedData.js' export { type WaitForCallsStatusData, type WaitForCallsStatusOptions, type WaitForCallsStatusQueryFnData, type WaitForCallsStatusQueryKey, type WaitForCallsStatusQueryOptions, waitForCallsStatusQueryKey, waitForCallsStatusQueryOptions, } from '../query/waitForCallsStatus.js' export { type WaitForTransactionReceiptData, type WaitForTransactionReceiptOptions, type WaitForTransactionReceiptQueryFnData, type WaitForTransactionReceiptQueryKey, type WaitForTransactionReceiptQueryOptions, waitForTransactionReceiptQueryKey, waitForTransactionReceiptQueryOptions, } from '../query/waitForTransactionReceipt.js' export { type WatchAssetData, type WatchAssetMutate, type WatchAssetMutateAsync, type WatchAssetMutationOptions, type WatchAssetOptions, type WatchAssetVariables, watchAssetMutationOptions, } from '../query/watchAsset.js' export { type WriteContractData, type WriteContractMutate, type WriteContractMutateAsync, type WriteContractMutationOptions, type WriteContractOptions, type WriteContractVariables, writeContractMutationOptions, } from '../query/writeContract.js' export { type WriteContractSyncData, type WriteContractSyncMutate, type WriteContractSyncMutateAsync, type WriteContractSyncMutationOptions, type WriteContractSyncOptions, type WriteContractSyncVariables, writeContractSyncMutationOptions, } from '../query/writeContractSync.js' ================================================ FILE: packages/core/src/exports/tempo.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // Tempo //////////////////////////////////////////////////////////////////////////////// /** biome-ignore-all lint/performance/noReExportAll: entrypoint */ // biome-ignore lint/performance/noBarrelFile: entrypoint module export * as Actions from '../tempo/actions/index.js' export { type Dangerous_Secp256k1Parameters, dangerous_secp256k1, type WebAuthnParameters, webAuthn, } from '../tempo/Connectors.js' export * as KeyManager from '../tempo/KeyManager.js' ================================================ FILE: packages/core/src/hydrate.test.ts ================================================ import { accounts, config, wait } from '@wagmi/test' import type { EIP1193Provider } from 'mipd' import { http } from 'viem' import { mainnet } from 'viem/chains' import { expect, test, vi } from 'vitest' import { createConnector } from './connectors/createConnector.js' import { mock } from './connectors/mock.js' import { createConfig } from './createConfig.js' import { createStorage } from './createStorage.js' import { hydrate } from './hydrate.js' import { cookieStorage } from './utils/cookie.js' vi.mock(import('mipd'), async (importOriginal) => { const mod = await importOriginal() let cache: typeof mod | undefined if (!cache) cache = { ...mod, createStore() { const store = mod.createStore() return { ...store, getProviders() { const info = { icon: 'data:image/svg+xml,', uuid: crypto.randomUUID(), } as const const provider = '' as unknown as EIP1193Provider return [ { info: { ...info, name: 'Foo', rdns: 'com.foo' }, provider }, { info: { ...info, name: 'Bar', rdns: 'com.bar' }, provider }, { info: { ...info, name: 'Mock', rdns: 'com.mock' }, provider }, ] }, } }, } return cache }) test('default', () => { const { onMount } = hydrate(config, { initialState: undefined, reconnectOnMount: false, }) onMount() expect(onMount).toBeDefined() }) test('initialState', () => { const config = createConfig({ chains: [mainnet], transports: { [mainnet.id]: http() }, ssr: true, storage: createStorage({ storage: cookieStorage }), }) const { onMount } = hydrate(config, { initialState: { chainId: 1, current: null, connections: new Map(), status: 'disconnected', }, reconnectOnMount: true, }) onMount() expect(onMount).toBeDefined() }) test('ssr', async () => { const config = createConfig({ chains: [mainnet], connectors: [ createConnector((c) => { return { ...mock({ accounts })(c), rdns: 'com.mock', } }), ], ssr: true, storage: createStorage({ storage: cookieStorage }), transports: { [mainnet.id]: http() }, }) const { onMount } = hydrate(config, { initialState: { chainId: 10, current: null, connections: new Map(), status: 'disconnected', }, reconnectOnMount: false, }) onMount() expect(onMount).toBeDefined() expect(config.chains[0].id).toBe(1) await wait(100) expect(config.connectors.map((x) => x.rdns ?? x.id)).toMatchInlineSnapshot( ` [ "com.mock", "com.foo", "com.bar", ] `, ) }) ================================================ FILE: packages/core/src/hydrate.ts ================================================ import { reconnect } from './actions/reconnect.js' import type { Config, State } from './createConfig.js' type HydrateParameters = { initialState?: State | undefined reconnectOnMount?: boolean | undefined } export function hydrate(config: Config, parameters: HydrateParameters) { const { initialState, reconnectOnMount } = parameters if (initialState && !config._internal.store.persist.hasHydrated()) config.setState({ ...initialState, chainId: config.chains.some((x) => x.id === initialState.chainId) ? initialState.chainId : config.chains[0].id, connections: reconnectOnMount ? initialState.connections : new Map(), status: reconnectOnMount ? 'reconnecting' : 'disconnected', }) return { async onMount() { if (config._internal.ssr) { await config._internal.store.persist.rehydrate() if (config._internal.mipd) { config._internal.connectors.setState((connectors) => { const rdnsSet = new Set() for (const connector of connectors ?? []) { if (connector.rdns) { const rdnsValues = Array.isArray(connector.rdns) ? connector.rdns : [connector.rdns] for (const rdns of rdnsValues) { rdnsSet.add(rdns) } } } const mipdConnectors = [] const providers = config._internal.mipd?.getProviders() ?? [] for (const provider of providers) { if (rdnsSet.has(provider.info.rdns)) continue const connectorFn = config._internal.connectors.providerDetailToConnector(provider) const connector = config._internal.connectors.setup(connectorFn) mipdConnectors.push(connector) } return [...connectors, ...mipdConnectors] }) } } if (reconnectOnMount) reconnect(config) else if (config.storage) // Reset connections that may have been hydrated from storage. config.setState((x) => ({ ...x, connections: new Map(), })) }, } } ================================================ FILE: packages/core/src/query/AGENTS.md ================================================ # Agent Guidelines Agent guidance for query options > **Communication Style**: Be brief, concise. Maximize information density, minimize tokens. Incomplete sentences acceptable when clear. Remove filler words. Prioritize clarity over grammar. ## Query Options Format ```ts export function myActionQueryOptions< config extends Config, selectData = MyActionData >( config: config, options: MyActionOptions = {}, ): MyActionQueryOptions { return { ...options.query, enabled: Boolean(options.foo && (options.query?.enabled ?? true)), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.foo) throw new Error('foo is required') const result = await myAction(config, { foo: parameters.foo, ...parameters, }) return result ?? null }, queryKey: myActionQueryKey(options), structuralSharing, // include when action returns objects, nested values, or arrays } } export function myActionQueryKey< config extends Config, selectData = MyActionData >( parameters: Compute> & ScopeKeyParameter> = {}, ) { return ['myAction', filterQueryOptions(parameters)] as const } export type MyActionOptions< config extends Config, selectData = MyActionData, > = Compute> & ScopeKeyParameter> & QueryParameter< MyActionQueryFnData, MyActionErrorType, selectData, MyActionQueryKey > export type MyActionQueryOptions< config extends Config, selectData = MyActionData > = QueryOptions< MyActionQueryFnData, MyActionErrorType, selectData, MyActionQueryKey > export type MyActionQueryFnData = Compute export type MyActionData = MyActionQueryFnData export type MyActionQueryKey = ReturnType< typeof myActionQueryKey > ``` ## Style Conventions ### `queryFn` Syntax - Use arrow function property syntax: `queryFn: async (context) =>` (not method shorthand `async queryFn(context)`) - Use `context` parameter, not destructuring: `async (context) =>` (not `async ({ queryKey }) =>`) - Access `queryKey` via `context.queryKey` ### Destructuring `queryKey` Use array destructuring with `parameters`, then access properties via `parameters.foo`: ```ts // ✓ Correct const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.account) throw new Error('account is required') // ✗ Avoid const { account, scopeKey: _, ...parameters } = context.queryKey[1] ``` ### Calling Actions When calling actions, spread parameters first, then pass required parameters: ```ts // ✓ Correct - spread, then explicit required param return myAction(config, { ...parameters, foo: parameters.foo }) // ✗ Avoid - just passing parameters directly return myAction(config, parameters) ``` ### Accessing Skipped Properties Properties filtered from the queryKey (e.g., `connector`, `abi`) should be accessed via `options.`: ```ts queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey // ✓ Use rest.connector for properties not in queryKey const result = await myAction(config, { ...parameters, connector: options.connector }) return result ?? null } ``` ## Type Parameter Nuances ### `const` Modifier Use `const` for type parameters that need literal type inference (e.g., abi, args): ```ts export function readContractQueryOptions< const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, const args extends ContractFunctionArgs, config extends Config, > ``` ### `ExactPartial` vs `UnionExactPartial` - **`ExactPartial`**: Use for simple cases with straightforward parameter types - **`UnionExactPartial`**: Use for complex type inference or action parameter types with lots of unions (e.g., contract-related actions) If unsure, check the underlying action's parameter types or ask. ### Default Parameter Value - **Simple cases**: `options: MyActionOptions = {}` - **Complex generics** (e.g., contract actions with abi/args): `options: MyActionOptions<...> = {} as any` ## `structuralSharing` Include `structuralSharing` from `./utils.js` when the action returns: - Objects - Nested values - Arrays See `packages/react/src/hooks` for more examples. ## Special Query Key Handling For `getConnectorClient`, include `connectorUid` separately in the query key: ```ts return [ 'connectorClient', { ...filterQueryOptions(options), connectorUid: options.connector?.uid }, ] as const ``` ================================================ FILE: packages/core/src/query/call.test.ts ================================================ import { accounts, address, chain, config } from '@wagmi/test' import { parseEther, parseGwei } from 'viem' import { expect, test } from 'vitest' import { callQueryOptions } from './call.js' const name4bytes = '0x06fdde03' const account = accounts[0] test('default', () => { expect( callQueryOptions(config, { account, data: name4bytes, to: address.wagmiMintExample, }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "call", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "data": "0x06fdde03", "to": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", }, ], } `) }) test('parameters: accessList', () => { expect( callQueryOptions(config, { account, data: name4bytes, to: address.wagmiMintExample, accessList: [ { address: '0x1', storageKeys: ['0x1'], }, ], }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "call", { "accessList": [ { "address": "0x1", "storageKeys": [ "0x1", ], }, ], "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "data": "0x06fdde03", "to": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", }, ], } `) }) test('parameters: blockNumber', () => { expect( callQueryOptions(config, { account, data: name4bytes, to: address.wagmiMintExample, blockNumber: 1234567890n, }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "call", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "blockNumber": 1234567890n, "data": "0x06fdde03", "to": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", }, ], } `) }) test('parameters: blockTag', () => { expect( callQueryOptions(config, { account, data: name4bytes, to: address.wagmiMintExample, blockTag: 'safe', }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "call", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "blockTag": "safe", "data": "0x06fdde03", "to": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", }, ], } `) }) test('parameters: chainId', () => { expect( callQueryOptions(config, { account, data: name4bytes, to: address.wagmiMintExample, chainId: chain.mainnet2.id, }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "call", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 456, "data": "0x06fdde03", "to": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", }, ], } `) }) test('parameters: gas', () => { expect( callQueryOptions(config, { account, data: name4bytes, to: address.wagmiMintExample, gas: 100000n, }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "call", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "data": "0x06fdde03", "gas": 100000n, "to": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", }, ], } `) }) test('parameters: gasPrice', () => { expect( callQueryOptions(config, { account, data: name4bytes, to: address.wagmiMintExample, gasPrice: parseGwei('20'), }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "call", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "data": "0x06fdde03", "gasPrice": 20000000000n, "to": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", }, ], } `) }) test('parameters: maxFeePerGas', () => { expect( callQueryOptions(config, { account, data: name4bytes, to: address.wagmiMintExample, maxFeePerGas: parseGwei('20'), }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "call", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "data": "0x06fdde03", "maxFeePerGas": 20000000000n, "to": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", }, ], } `) }) test('parameters: maxPriorityFeePerGas', () => { expect( callQueryOptions(config, { account, data: name4bytes, to: address.wagmiMintExample, maxPriorityFeePerGas: parseGwei('2'), }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "call", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "data": "0x06fdde03", "maxPriorityFeePerGas": 2000000000n, "to": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", }, ], } `) }) test('parameters: nonce', () => { expect( callQueryOptions(config, { account, data: name4bytes, to: address.wagmiMintExample, nonce: 123, }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "call", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "data": "0x06fdde03", "nonce": 123, "to": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", }, ], } `) }) test('parameters: type', () => { expect( callQueryOptions(config, { account, data: name4bytes, to: address.wagmiMintExample, type: 'eip1559', }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "call", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "data": "0x06fdde03", "to": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "type": "eip1559", }, ], } `) }) test('parameters: value', () => { expect( callQueryOptions(config, { account, data: name4bytes, to: address.wagmiMintExample, value: parseEther('1'), }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "call", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "data": "0x06fdde03", "to": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "value": 1000000000000000000n, }, ], } `) }) ================================================ FILE: packages/core/src/query/call.ts ================================================ import { type CallErrorType, type CallParameters, type CallReturnType, call, } from '../actions/call.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type CallOptions = Compute< ExactPartial> & ScopeKeyParameter > & QueryParameter< CallQueryFnData, CallErrorType, selectData, CallQueryKey > export function callQueryOptions( config: config, options: CallOptions = {}, ): CallQueryOptions { return { ...options.query, queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey const data = await call(config, { ...parameters, } as CallParameters) return data ?? null }, queryKey: callQueryKey(options), } } export type CallQueryFnData = CallReturnType export type CallData = CallQueryFnData export function callQueryKey( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['call', filterQueryOptions(options)] as const } export type CallQueryKey = ReturnType< typeof callQueryKey > export type CallQueryOptions< config extends Config, selectData = CallData, > = QueryOptions< CallQueryFnData, CallErrorType, selectData, CallQueryKey > ================================================ FILE: packages/core/src/query/connect.test-d.ts ================================================ import { accounts } from '@wagmi/test' import { type Address, type Hex, http } from 'viem' import { mainnet } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import type { CreateConnectorFn } from '../connectors/createConnector.js' import { mock } from '../connectors/mock.js' import { type Connector, createConfig } from '../createConfig.js' import type { ConnectMutate, ConnectMutateAsync } from './connect.js' const config = createConfig({ chains: [mainnet], transports: { [mainnet.id]: http() }, }) test('parameters: connector (ConnectorFn)', () => { const connectorFn = mock({ accounts }) const mutate: ConnectMutate = () => {} mutate({ connector: connectorFn, foo: 'bar', }) expectTypeOf< typeof connectorFn extends CreateConnectorFn ? true : false >().toEqualTypeOf() type Result = NonNullable>[0]> expectTypeOf().toEqualTypeOf() }) test('parameters: connector (Connector)', () => { const connector = config._internal.connectors.setup(mock({ accounts })) const mutate: ConnectMutate = () => {} mutate({ connector, foo: 'bar', }) expectTypeOf< typeof connector extends Connector ? true : false >().toEqualTypeOf() type Result = NonNullable>[0]> expectTypeOf().toEqualTypeOf() }) test('parameters: withCapabilities', async () => { const connectorFn = mock({ accounts }) const mutateAsync: ConnectMutateAsync = () => ({}) as any const res0 = await mutateAsync({ connector: connectorFn }) expectTypeOf(res0.accounts).toEqualTypeOf() const res1 = await mutateAsync({ connector: connectorFn, withCapabilities: false, }) expectTypeOf(res1.accounts).toEqualTypeOf() const res2 = await mutateAsync({ connector: connectorFn, withCapabilities: true, }) expectTypeOf(res2.accounts).toEqualTypeOf< readonly [ { address: Address capabilities: { foo: { bar: Hex } } }, ...{ address: Address capabilities: { foo: { bar: Hex } } }[], ] >() }) ================================================ FILE: packages/core/src/query/connect.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { connectMutationOptions } from './connect.js' test('default', () => { expect(connectMutationOptions(config)).toMatchInlineSnapshot(` { "mutationFn": [Function], "mutationKey": [ "connect", ], } `) }) ================================================ FILE: packages/core/src/query/connect.ts ================================================ import type { MutateOptions, MutationOptions } from '@tanstack/query-core' import { type ConnectErrorType, type ConnectParameters, type ConnectReturnType, connect, } from '../actions/connect.js' import type { CreateConnectorFn } from '../connectors/createConnector.js' import type { Config, Connector } from '../createConfig.js' import type { MutationParameter } from '../types/query.js' import type { Compute } from '../types/utils.js' export type ConnectOptions< config extends Config, context = unknown, > = MutationParameter< ConnectData, ConnectErrorType, ConnectVariables, context > export function connectMutationOptions( config: config, options: ConnectOptions = {}, ): ConnectMutationOptions { return { ...(options.mutation as any), mutationFn: async (variables) => { return connect(config, variables) }, mutationKey: ['connect'], } } export type ConnectMutationOptions = MutationOptions< ConnectData, ConnectErrorType, ConnectVariables > export type ConnectData< config extends Config, connector extends Connector | CreateConnectorFn, withCapabilities extends boolean, > = ConnectReturnType export type ConnectVariables< config extends Config, connector extends Connector | CreateConnectorFn, withCapabilities extends boolean, > = ConnectParameters export type ConnectMutate = < connector extends | config['connectors'][number] | Connector | CreateConnectorFn, withCapabilities extends boolean = false, >( variables: ConnectVariables, options?: | Compute< MutateOptions< ConnectData, ConnectErrorType, Compute>, context > > | undefined, ) => void export type ConnectMutateAsync = < connector extends | config['connectors'][number] | Connector | CreateConnectorFn, withCapabilities extends boolean = false, >( variables: ConnectVariables, options?: | Compute< MutateOptions< ConnectData, ConnectErrorType, Compute>, context > > | undefined, ) => Promise> ================================================ FILE: packages/core/src/query/deployContract.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { deployContractMutationOptions } from './deployContract.js' test('default', () => { expect(deployContractMutationOptions(config)).toMatchInlineSnapshot(` { "mutationFn": [Function], "mutationKey": [ "deployContract", ], } `) }) ================================================ FILE: packages/core/src/query/deployContract.ts ================================================ import type { MutateOptions, MutationOptions } from '@tanstack/query-core' import type { Abi, ContractConstructorArgs } from 'viem' import { type DeployContractErrorType, type DeployContractParameters, type DeployContractReturnType, deployContract, } from '../actions/deployContract.js' import type { Config } from '../createConfig.js' import type { MutationParameter } from '../types/query.js' import type { Compute } from '../types/utils.js' export type DeployContractOptions< config extends Config, context = unknown, > = MutationParameter< DeployContractData, DeployContractErrorType, DeployContractVariables, context > export function deployContractMutationOptions( config: config, options: DeployContractOptions = {}, ): DeployContractMutationOptions { return { ...(options.mutation as any), mutationFn(variables) { return deployContract(config, variables) }, mutationKey: ['deployContract'], } } export type DeployContractMutationOptions = MutationOptions< DeployContractData, DeployContractErrorType, DeployContractVariables > export type DeployContractData = Compute export type DeployContractVariables< abi extends Abi | readonly unknown[], config extends Config, chainId extends config['chains'][number]['id'], /// allArgs = ContractConstructorArgs, > = DeployContractParameters export type DeployContractMutate = < abi extends Abi | readonly unknown[], chainId extends config['chains'][number]['id'], >( variables: DeployContractVariables, options?: | Compute< MutateOptions< DeployContractData, DeployContractErrorType, Compute>, context > > | undefined, ) => void export type DeployContractMutateAsync< config extends Config, context = unknown, > = < abi extends Abi | readonly unknown[], chainId extends config['chains'][number]['id'], >( variables: DeployContractVariables, options?: | Compute< MutateOptions< DeployContractData, DeployContractErrorType, Compute>, context > > | undefined, ) => Promise ================================================ FILE: packages/core/src/query/disconnect.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { disconnectMutationOptions } from './disconnect.js' test('default', () => { expect(disconnectMutationOptions(config)).toMatchInlineSnapshot(` { "mutationFn": [Function], "mutationKey": [ "disconnect", ], } `) }) ================================================ FILE: packages/core/src/query/disconnect.ts ================================================ import type { MutationOptions } from '@tanstack/query-core' import { type DisconnectErrorType, type DisconnectParameters, type DisconnectReturnType, disconnect, } from '../actions/disconnect.js' import type { Config } from '../createConfig.js' import type { MutationParameter } from '../types/query.js' import type { Mutate, MutateAsync } from './types.js' export type DisconnectOptions = MutationParameter< DisconnectData, DisconnectErrorType, DisconnectVariables, context > export function disconnectMutationOptions( config: config, options: DisconnectOptions = {}, ): DisconnectMutationOptions { return { ...(options.mutation as any), mutationFn: async (variables) => { return disconnect(config, variables) }, mutationKey: ['disconnect'], } } export type DisconnectMutationOptions = MutationOptions< DisconnectData, DisconnectErrorType, DisconnectVariables > export type DisconnectData = DisconnectReturnType export type DisconnectVariables = DisconnectParameters | undefined export type DisconnectMutate = Mutate< DisconnectData, DisconnectErrorType, DisconnectVariables, context > export type DisconnectMutateAsync = MutateAsync< DisconnectData, DisconnectErrorType, DisconnectVariables, context > ================================================ FILE: packages/core/src/query/estimateFeesPerGas.test-d.ts ================================================ import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { estimateFeesPerGasQueryOptions } from './estimateFeesPerGas.js' const context = {} as any test('types', async () => { // default { const options = estimateFeesPerGasQueryOptions(config, {}) const result = await options.queryFn(context) expectTypeOf(result).toEqualTypeOf<{ gasPrice?: undefined maxFeePerBlobGas?: undefined maxFeePerGas: bigint maxPriorityFeePerGas: bigint }>() } // legacy { const options = estimateFeesPerGasQueryOptions(config, { type: 'legacy' }) const result = await options.queryFn(context) expectTypeOf(result).toEqualTypeOf<{ gasPrice: bigint maxFeePerBlobGas?: undefined maxFeePerGas?: undefined maxPriorityFeePerGas?: undefined }>() } // eip1559 { const options = estimateFeesPerGasQueryOptions(config, { type: 'eip1559' }) const result = await options.queryFn(context) expectTypeOf(result).toEqualTypeOf<{ gasPrice?: undefined maxFeePerBlobGas?: undefined maxFeePerGas: bigint maxPriorityFeePerGas: bigint }>() } }) ================================================ FILE: packages/core/src/query/estimateFeesPerGas.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { estimateFeesPerGasQueryOptions } from './estimateFeesPerGas.js' test('default', () => { expect(estimateFeesPerGasQueryOptions(config)).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "estimateFeesPerGas", {}, ], } `) }) test('parameters: chainId', () => { expect( estimateFeesPerGasQueryOptions(config, { chainId: chain.mainnet.id }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "estimateFeesPerGas", { "chainId": 1, }, ], } `) }) ================================================ FILE: packages/core/src/query/estimateFeesPerGas.ts ================================================ import type { FeeValuesType } from 'viem' import { type EstimateFeesPerGasErrorType, type EstimateFeesPerGasParameters, type EstimateFeesPerGasReturnType, estimateFeesPerGas, } from '../actions/estimateFeesPerGas.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type EstimateFeesPerGasOptions< type extends FeeValuesType, config extends Config, selectData = EstimateFeesPerGasData, > = Compute< ExactPartial> & ScopeKeyParameter > & QueryParameter< EstimateFeesPerGasQueryFnData, EstimateFeesPerGasErrorType, selectData, EstimateFeesPerGasQueryKey > export function estimateFeesPerGasQueryOptions< config extends Config, type extends FeeValuesType = 'eip1559', selectData = EstimateFeesPerGasData, >( config: config, options: EstimateFeesPerGasOptions = {}, ): EstimateFeesPerGasQueryOptions { return { ...options.query, queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey return estimateFeesPerGas(config, parameters) }, queryKey: estimateFeesPerGasQueryKey(options), } } export type EstimateFeesPerGasQueryFnData = EstimateFeesPerGasReturnType export type EstimateFeesPerGasData = EstimateFeesPerGasQueryFnData export function estimateFeesPerGasQueryKey< config extends Config, type extends FeeValuesType = 'eip1559', >( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['estimateFeesPerGas', filterQueryOptions(options)] as const } export type EstimateFeesPerGasQueryKey< config extends Config, type extends FeeValuesType, > = ReturnType> export type EstimateFeesPerGasQueryOptions< type extends FeeValuesType, config extends Config, selectData = EstimateFeesPerGasData, > = QueryOptions< EstimateFeesPerGasQueryFnData, EstimateFeesPerGasErrorType, selectData, EstimateFeesPerGasQueryKey > ================================================ FILE: packages/core/src/query/estimateGas.test-d.ts ================================================ import { type Address, http, parseEther } from 'viem' import { celo, mainnet } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { type EstimateGasOptions, estimateGasQueryOptions, } from './estimateGas.js' test('chain formatters', () => { const config = createConfig({ chains: [mainnet, celo], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) type Result = EstimateGasOptions< typeof config, (typeof config)['chains'][number]['id'] > expectTypeOf().toMatchTypeOf<{ chainId?: typeof celo.id | typeof mainnet.id | undefined feeCurrency?: `0x${string}` | undefined }>() estimateGasQueryOptions(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), feeCurrency: '0x', }) type Result2 = EstimateGasOptions expectTypeOf().toMatchTypeOf<{ functionName?: 'approve' | 'transfer' | 'transferFrom' | undefined args?: readonly [Address, Address, bigint] | undefined feeCurrency?: `0x${string}` | undefined }>() estimateGasQueryOptions(config, { chainId: celo.id, to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), feeCurrency: '0x', }) type Result3 = EstimateGasOptions expectTypeOf().not.toMatchTypeOf<{ feeCurrency?: `0x${string}` | undefined }>() estimateGasQueryOptions(config, { chainId: mainnet.id, to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) }) ================================================ FILE: packages/core/src/query/estimateGas.test.ts ================================================ import { config } from '@wagmi/test' import { parseEther } from 'viem' import { expect, test } from 'vitest' import { estimateGasQueryOptions } from './estimateGas.js' test('default', () => { expect( estimateGasQueryOptions(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }), ).toMatchInlineSnapshot(` { "enabled": false, "queryFn": [Function], "queryKey": [ "estimateGas", { "to": "0xd2135CfB216b74109775236E36d4b433F1DF507B", "value": 10000000000000000n, }, ], } `) }) ================================================ FILE: packages/core/src/query/estimateGas.ts ================================================ import { type EstimateGasErrorType, type EstimateGasParameters, type EstimateGasReturnType, estimateGas, } from '../actions/estimateGas.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, UnionExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type EstimateGasOptions< config extends Config, chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = EstimateGasData, > = Compute< UnionExactPartial> & ScopeKeyParameter > & QueryParameter< EstimateGasQueryFnData, EstimateGasErrorType, selectData, EstimateGasQueryKey > export function estimateGasQueryOptions< config extends Config, chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = EstimateGasData, >( config: config, options: EstimateGasOptions = {} as any, ): EstimateGasQueryOptions { return { ...options.query, enabled: Boolean( (options.account || options.connector) && (options.query?.enabled ?? true), ), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.account && !options.connector) throw new Error('account or connector is required') return estimateGas(config, { ...(parameters as any), account: parameters.account, connector: options.connector, }) }, queryKey: estimateGasQueryKey(options), } } export type EstimateGasQueryFnData = EstimateGasReturnType export type EstimateGasData = EstimateGasQueryFnData export function estimateGasQueryKey< config extends Config, chainId extends config['chains'][number]['id'] | undefined = undefined, >( options: Compute< UnionExactPartial> & ScopeKeyParameter > = {} as any, ) { return ['estimateGas', filterQueryOptions(options)] as const } export type EstimateGasQueryKey< config extends Config, chainId extends config['chains'][number]['id'] | undefined = undefined, > = ReturnType> export type EstimateGasQueryOptions< config extends Config, chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = EstimateGasData, > = QueryOptions< EstimateGasQueryFnData, EstimateGasErrorType, selectData, EstimateGasQueryKey > ================================================ FILE: packages/core/src/query/estimateMaxPriorityFeePerGas.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { estimateMaxPriorityFeePerGasQueryOptions } from './estimateMaxPriorityFeePerGas.js' test('default', () => { expect( estimateMaxPriorityFeePerGasQueryOptions(config), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "estimateMaxPriorityFeePerGas", {}, ], } `) }) test('parameters: chainId', () => { expect( estimateMaxPriorityFeePerGasQueryOptions(config, { chainId: chain.mainnet.id, }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "estimateMaxPriorityFeePerGas", { "chainId": 1, }, ], } `) }) ================================================ FILE: packages/core/src/query/estimateMaxPriorityFeePerGas.ts ================================================ import { type EstimateMaxPriorityFeePerGasErrorType, type EstimateMaxPriorityFeePerGasParameters, type EstimateMaxPriorityFeePerGasReturnType, estimateMaxPriorityFeePerGas, } from '../actions/estimateMaxPriorityFeePerGas.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type EstimateMaxPriorityFeePerGasOptions< config extends Config, selectData = EstimateMaxPriorityFeePerGasData, > = Compute< ExactPartial> & ScopeKeyParameter > & QueryParameter< EstimateMaxPriorityFeePerGasQueryFnData, EstimateMaxPriorityFeePerGasErrorType, selectData, EstimateMaxPriorityFeePerGasQueryKey > export function estimateMaxPriorityFeePerGasQueryOptions< config extends Config, selectData = EstimateMaxPriorityFeePerGasData, >( config: config, options: EstimateMaxPriorityFeePerGasOptions = {}, ): EstimateMaxPriorityFeePerGasQueryOptions { return { ...options.query, queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey return estimateMaxPriorityFeePerGas(config, parameters) }, queryKey: estimateMaxPriorityFeePerGasQueryKey(options), } } export type EstimateMaxPriorityFeePerGasQueryFnData = EstimateMaxPriorityFeePerGasReturnType export type EstimateMaxPriorityFeePerGasData = EstimateMaxPriorityFeePerGasQueryFnData export function estimateMaxPriorityFeePerGasQueryKey( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['estimateMaxPriorityFeePerGas', filterQueryOptions(options)] as const } export type EstimateMaxPriorityFeePerGasQueryKey = ReturnType> export type EstimateMaxPriorityFeePerGasQueryOptions< config extends Config, selectData = EstimateMaxPriorityFeePerGasData, > = QueryOptions< EstimateMaxPriorityFeePerGasQueryFnData, EstimateMaxPriorityFeePerGasErrorType, selectData, EstimateMaxPriorityFeePerGasQueryKey > ================================================ FILE: packages/core/src/query/getBalance.test.ts ================================================ import { accounts, chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getBalanceQueryOptions } from './getBalance.js' const address = accounts[0] test('default', () => { expect(getBalanceQueryOptions(config, { address })).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "balance", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", }, ], } `) }) test('parameters: chainId', () => { expect( getBalanceQueryOptions(config, { address, chainId: chain.mainnet.id }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "balance", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 1, }, ], } `) }) ================================================ FILE: packages/core/src/query/getBalance.ts ================================================ import { type GetBalanceErrorType, type GetBalanceParameters, type GetBalanceReturnType, getBalance, } from '../actions/getBalance.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetBalanceOptions< config extends Config, selectData = GetBalanceData, > = Compute> & ScopeKeyParameter> & QueryParameter< GetBalanceQueryFnData, GetBalanceErrorType, selectData, GetBalanceQueryKey > export function getBalanceQueryOptions< config extends Config, selectData = GetBalanceData, >( config: config, options: GetBalanceOptions = {}, ): GetBalanceQueryOptions { return { ...options.query, enabled: Boolean(options.address && (options.query?.enabled ?? true)), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.address) throw new Error('address is required') const balance = await getBalance(config, { ...(parameters as GetBalanceParameters), address: parameters.address, }) return balance ?? null }, queryKey: getBalanceQueryKey(options), } } export type GetBalanceQueryFnData = Compute export type GetBalanceData = GetBalanceQueryFnData export function getBalanceQueryKey( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['balance', filterQueryOptions(options)] as const } export type GetBalanceQueryKey = ReturnType< typeof getBalanceQueryKey > export type GetBalanceQueryOptions< config extends Config, selectData = GetBalanceData, > = QueryOptions< GetBalanceQueryFnData, GetBalanceErrorType, selectData, GetBalanceQueryKey > ================================================ FILE: packages/core/src/query/getBlobBaseFee.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { getBlobBaseFeeQueryOptions } from './getBlobBaseFee.js' test('default', () => { expect(getBlobBaseFeeQueryOptions(config)).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "blobBaseFee", {}, ], } `) }) ================================================ FILE: packages/core/src/query/getBlobBaseFee.ts ================================================ import { type GetBlobBaseFeeErrorType, type GetBlobBaseFeeParameters, type GetBlobBaseFeeReturnType, getBlobBaseFee, } from '../actions/getBlobBaseFee.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetBlobBaseFeeOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetBlobBaseFeeData, > = Compute< ExactPartial> & ScopeKeyParameter > & QueryParameter< GetBlobBaseFeeQueryFnData, GetBlobBaseFeeErrorType, selectData, GetBlobBaseFeeQueryKey > export function getBlobBaseFeeQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetBlobBaseFeeData, >( config: config, options: GetBlobBaseFeeOptions = {}, ): GetBlobBaseFeeQueryOptions { return { ...options.query, queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey const blobBaseFee = await getBlobBaseFee(config, parameters) return blobBaseFee ?? null }, queryKey: getBlobBaseFeeQueryKey(options), } } export type GetBlobBaseFeeQueryFnData = GetBlobBaseFeeReturnType export type GetBlobBaseFeeData = GetBlobBaseFeeQueryFnData export function getBlobBaseFeeQueryKey< config extends Config, chainId extends config['chains'][number]['id'], >( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['blobBaseFee', filterQueryOptions(options)] as const } export type GetBlobBaseFeeQueryKey< config extends Config, chainId extends config['chains'][number]['id'], > = ReturnType> export type GetBlobBaseFeeQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetBlobBaseFeeData, > = QueryOptions< GetBlobBaseFeeQueryFnData, GetBlobBaseFeeErrorType, selectData, GetBlobBaseFeeQueryKey > ================================================ FILE: packages/core/src/query/getBlock.test-d.ts ================================================ import { type Hex, http } from 'viem' import { celo, mainnet } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { getBlockQueryOptions } from './getBlock.js' const context = {} as any test('chain formatters', async () => { const config = createConfig({ chains: [celo, mainnet], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) const options = getBlockQueryOptions(config) const result = await options.queryFn(context) if (result.chainId === celo.id) { expectTypeOf(result.difficulty).toEqualTypeOf() expectTypeOf(result.gasLimit).toEqualTypeOf() expectTypeOf(result.mixHash).toEqualTypeOf() expectTypeOf(result.nonce).toEqualTypeOf<`0x${string}`>() expectTypeOf(result.uncles).toEqualTypeOf() } }) test('chainId', async () => { const config = createConfig({ chains: [celo, mainnet], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) const options = getBlockQueryOptions(config, { chainId: celo.id }) const result = await options.queryFn(context) expectTypeOf(result.difficulty).toEqualTypeOf() expectTypeOf(result.gasLimit).toEqualTypeOf() expectTypeOf(result.mixHash).toEqualTypeOf() expectTypeOf(result.nonce).toEqualTypeOf<`0x${string}`>() }) ================================================ FILE: packages/core/src/query/getBlock.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getBlockQueryOptions } from './getBlock.js' test('default', () => { expect(getBlockQueryOptions(config)).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "block", {}, ], } `) }) test('parameters: chainId', () => { expect( getBlockQueryOptions(config, { chainId: chain.mainnet.id }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "block", { "chainId": 1, }, ], } `) }) ================================================ FILE: packages/core/src/query/getBlock.ts ================================================ import type { BlockTag } from 'viem' import { type GetBlockErrorType, type GetBlockParameters, type GetBlockReturnType, getBlock, } from '../actions/getBlock.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetBlockOptions< includeTransactions extends boolean, blockTag extends BlockTag, config extends Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetBlockData, > = Compute< ExactPartial< GetBlockParameters > & ScopeKeyParameter > & QueryParameter< GetBlockQueryFnData, GetBlockErrorType, selectData, GetBlockQueryKey > export function getBlockQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], includeTransactions extends boolean = false, blockTag extends BlockTag = 'latest', selectData = GetBlockData, >( config: config, options: GetBlockOptions< includeTransactions, blockTag, config, chainId, selectData > = {}, ): GetBlockQueryOptions< includeTransactions, blockTag, config, chainId, selectData > { return { ...options.query, queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey const block = await getBlock(config, parameters as any) return (block ?? null) as any }, queryKey: getBlockQueryKey(options), } } export type GetBlockQueryFnData< includeTransactions extends boolean, blockTag extends BlockTag, config extends Config, chainId extends config['chains'][number]['id'], > = GetBlockReturnType export type GetBlockData< includeTransactions extends boolean, blockTag extends BlockTag, config extends Config, chainId extends config['chains'][number]['id'], > = GetBlockQueryFnData export function getBlockQueryKey< config extends Config, chainId extends config['chains'][number]['id'], includeTransactions extends boolean = false, blockTag extends BlockTag = 'latest', >( options: Compute< ExactPartial< GetBlockParameters > & ScopeKeyParameter > = {}, ) { return ['block', filterQueryOptions(options)] as const } export type GetBlockQueryKey< includeTransactions extends boolean, blockTag extends BlockTag, config extends Config, chainId extends config['chains'][number]['id'], > = ReturnType< typeof getBlockQueryKey > export type GetBlockQueryOptions< includeTransactions extends boolean, blockTag extends BlockTag, config extends Config, chainId extends config['chains'][number]['id'], selectData = GetBlockData, > = QueryOptions< GetBlockQueryFnData, GetBlockErrorType, selectData, GetBlockQueryKey > ================================================ FILE: packages/core/src/query/getBlockNumber.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getBlockNumberQueryOptions } from './getBlockNumber.js' test('default', () => { expect(getBlockNumberQueryOptions(config)).toMatchInlineSnapshot(` { "gcTime": 0, "queryFn": [Function], "queryKey": [ "blockNumber", {}, ], } `) }) test('parameters: chainId', () => { expect( getBlockNumberQueryOptions(config, { chainId: chain.mainnet.id }), ).toMatchInlineSnapshot(` { "gcTime": 0, "queryFn": [Function], "queryKey": [ "blockNumber", { "chainId": 1, }, ], } `) }) ================================================ FILE: packages/core/src/query/getBlockNumber.ts ================================================ import { type GetBlockNumberErrorType, type GetBlockNumberParameters, type GetBlockNumberReturnType, getBlockNumber, } from '../actions/getBlockNumber.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetBlockNumberOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetBlockNumberData, > = Compute< ExactPartial> & ScopeKeyParameter > & QueryParameter< GetBlockNumberQueryFnData, GetBlockNumberErrorType, selectData, GetBlockNumberQueryKey > export function getBlockNumberQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetBlockNumberData, >( config: config, options: GetBlockNumberOptions = {}, ): GetBlockNumberQueryOptions { return { ...options.query, gcTime: 0, queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey const blockNumber = await getBlockNumber(config, parameters) return blockNumber ?? null }, queryKey: getBlockNumberQueryKey(options), } } export type GetBlockNumberQueryFnData = GetBlockNumberReturnType export type GetBlockNumberData = GetBlockNumberQueryFnData export function getBlockNumberQueryKey< config extends Config, chainId extends config['chains'][number]['id'], >( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['blockNumber', filterQueryOptions(options)] as const } export type GetBlockNumberQueryKey< config extends Config, chainId extends config['chains'][number]['id'], > = ReturnType> export type GetBlockNumberQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetBlockNumberData, > = QueryOptions< GetBlockNumberQueryFnData, GetBlockNumberErrorType, selectData, GetBlockNumberQueryKey > ================================================ FILE: packages/core/src/query/getBlockTransactionCount.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getBlockTransactionCountQueryOptions } from './getBlockTransactionCount.js' test('default', () => { expect(getBlockTransactionCountQueryOptions(config)).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "blockTransactionCount", {}, ], } `) }) test('parameters: chainId', () => { expect( getBlockTransactionCountQueryOptions(config, { chainId: chain.mainnet.id }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "blockTransactionCount", { "chainId": 1, }, ], } `) }) test('parameters: blockTag', () => { expect( getBlockTransactionCountQueryOptions(config, { blockTag: 'earliest', }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "blockTransactionCount", { "blockTag": "earliest", }, ], } `) }) ================================================ FILE: packages/core/src/query/getBlockTransactionCount.ts ================================================ import { type GetBlockTransactionCountErrorType, type GetBlockTransactionCountParameters, type GetBlockTransactionCountReturnType, getBlockTransactionCount, } from '../actions/getBlockTransactionCount.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { ExactPartial, UnionCompute } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetBlockTransactionCountOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetBlockTransactionCountData, > = UnionCompute< ExactPartial> & ScopeKeyParameter > & QueryParameter< GetBlockTransactionCountQueryFnData, GetBlockTransactionCountErrorType, selectData, GetBlockTransactionCountQueryKey > export function getBlockTransactionCountQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetBlockTransactionCountData, >( config: config, options: GetBlockTransactionCountOptions = {}, ): GetBlockTransactionCountQueryOptions { return { ...options.query, queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey const blockTransactionCount = await getBlockTransactionCount( config, parameters as any, ) return blockTransactionCount ?? null }, queryKey: getBlockTransactionCountQueryKey(options), } } export type GetBlockTransactionCountQueryFnData = GetBlockTransactionCountReturnType export type GetBlockTransactionCountData = GetBlockTransactionCountQueryFnData export function getBlockTransactionCountQueryKey< config extends Config, chainId extends config['chains'][number]['id'], >( options: UnionCompute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['blockTransactionCount', filterQueryOptions(options)] as const } export type GetBlockTransactionCountQueryKey< config extends Config, chainId extends config['chains'][number]['id'], > = ReturnType> export type GetBlockTransactionCountQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetBlockTransactionCountData, > = QueryOptions< GetBlockTransactionCountQueryFnData, GetBlockTransactionCountErrorType, selectData, GetBlockTransactionCountQueryKey > ================================================ FILE: packages/core/src/query/getBytecode.test.ts ================================================ import { address, chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getBytecodeQueryOptions } from './getBytecode.js' test('default', () => { expect( getBytecodeQueryOptions(config, { address: address.wagmiMintExample, }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "getBytecode", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", }, ], } `) }) test('parameters: chainId', () => { expect( getBytecodeQueryOptions(config, { address: address.wagmiMintExample, chainId: chain.mainnet2.id, }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "getBytecode", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "chainId": 456, }, ], } `) }) test('parameters: blockNumber', () => { expect( getBytecodeQueryOptions(config, { address: address.wagmiMintExample, blockNumber: 1234567890n, }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "getBytecode", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "blockNumber": 1234567890n, }, ], } `) }) test('parameters: blockTag', () => { expect( getBytecodeQueryOptions(config, { address: address.wagmiMintExample, blockTag: 'safe', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "getBytecode", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "blockTag": "safe", }, ], } `) }) ================================================ FILE: packages/core/src/query/getBytecode.ts ================================================ import { type GetBytecodeErrorType, type GetBytecodeParameters, type GetBytecodeReturnType, getBytecode, } from '../actions/getBytecode.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetBytecodeOptions< config extends Config, selectData = GetBytecodeData, > = Compute> & ScopeKeyParameter> & QueryParameter< GetBytecodeQueryFnData, GetBytecodeErrorType, selectData, GetBytecodeQueryKey > export function getBytecodeQueryOptions< config extends Config, selectData = GetBytecodeData, >( config: config, options: GetBytecodeOptions = {}, ): GetBytecodeQueryOptions { return { ...options.query, enabled: Boolean(options.address && (options.query?.enabled ?? true)), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.address) throw new Error('address is required') const bytecode = await getBytecode(config, { ...(parameters as any), address: parameters.address, }) return (bytecode ?? null) as any }, queryKey: getBytecodeQueryKey(options), } } export type GetBytecodeQueryFnData = GetBytecodeReturnType export type GetBytecodeData = GetBytecodeQueryFnData export function getBytecodeQueryKey( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['getBytecode', filterQueryOptions(options)] as const } export type GetBytecodeQueryKey = ReturnType< typeof getBytecodeQueryKey > export type GetBytecodeQueryOptions< config extends Config, selectData = GetBytecodeData, > = QueryOptions< GetBytecodeQueryFnData, GetBytecodeErrorType, selectData, GetBytecodeQueryKey > ================================================ FILE: packages/core/src/query/getCallsStatus.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { getCallsStatusQueryOptions } from './getCallsStatus.js' test('default', () => { expect( getCallsStatusQueryOptions(config, { id: '0x0000000000000000000000000000000000000000', }), ).toMatchInlineSnapshot(` { "enabled": false, "queryFn": [Function], "queryKey": [ "callsStatus", { "id": "0x0000000000000000000000000000000000000000", }, ], } `) }) ================================================ FILE: packages/core/src/query/getCallsStatus.ts ================================================ import { type GetCallsStatusErrorType, type GetCallsStatusParameters, type GetCallsStatusReturnType, getCallsStatus, } from '../actions/getCallsStatus.js' import type { Config } from '../createConfig.js' import { filterQueryOptions } from '../query/utils.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute } from '../types/utils.js' export type GetCallsStatusOptions = Compute< GetCallsStatusParameters & ScopeKeyParameter > & QueryParameter< GetCallsStatusQueryFnData, GetCallsStatusErrorType, selectData, GetCallsStatusQueryKey > export function getCallsStatusQueryOptions< config extends Config, selectData = GetCallsStatusData, >( config: config, options: GetCallsStatusOptions, ): GetCallsStatusQueryOptions { return { ...options.query, enabled: Boolean( options.connector?.getProvider && (options.query?.enabled ?? true), ), queryFn: async (context) => { if (!options.connector?.getProvider) throw new Error('connector is required') const [, { connectorUid: _, scopeKey: __, ...parameters }] = context.queryKey const status = await getCallsStatus(config, parameters) return status }, queryKey: getCallsStatusQueryKey(options), } } export type GetCallsStatusQueryFnData = GetCallsStatusReturnType export type GetCallsStatusData = GetCallsStatusQueryFnData export function getCallsStatusQueryKey( options: Compute, ) { return ['callsStatus', filterQueryOptions(options)] as const } export type GetCallsStatusQueryKey = ReturnType export type GetCallsStatusQueryOptions = QueryOptions< GetCallsStatusQueryFnData, GetCallsStatusErrorType, selectData, GetCallsStatusQueryKey > ================================================ FILE: packages/core/src/query/getCapabilities.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { getCapabilitiesQueryOptions } from './getCapabilities.js' test('default', () => { expect(getCapabilitiesQueryOptions(config)).toMatchInlineSnapshot(` { "enabled": false, "queryFn": [Function], "queryKey": [ "capabilities", {}, ], } `) }) test('parameters: chainId', () => { expect( getCapabilitiesQueryOptions(config, { account: '0x0000000000000000000000000000000000000000', }), ).toMatchInlineSnapshot(` { "enabled": false, "queryFn": [Function], "queryKey": [ "capabilities", { "account": "0x0000000000000000000000000000000000000000", }, ], } `) }) ================================================ FILE: packages/core/src/query/getCapabilities.ts ================================================ import { type GetCapabilitiesErrorType, type GetCapabilitiesParameters, type GetCapabilitiesReturnType, getCapabilities, } from '../actions/getCapabilities.js' import type { Config } from '../createConfig.js' import { filterQueryOptions } from '../query/utils.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' export type GetCapabilitiesOptions< config extends Config = Config, chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = GetCapabilitiesData, > = Compute< ExactPartial> & ScopeKeyParameter > & QueryParameter< GetCapabilitiesQueryFnData, GetCapabilitiesErrorType, selectData, GetCapabilitiesQueryKey > export function getCapabilitiesQueryOptions< config extends Config, chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = GetCapabilitiesData, >( config: config, options: GetCapabilitiesOptions = {}, ): GetCapabilitiesQueryOptions { return { ...options.query, enabled: Boolean( options.connector?.getProvider && (options.query?.enabled ?? true), ), queryFn: async (context) => { if (!options.connector?.getProvider) throw new Error('connector is required') const [, { connectorUid: _, scopeKey: __, ...parameters }] = context.queryKey const capabilities = await getCapabilities(config, parameters) return capabilities }, queryKey: getCapabilitiesQueryKey(options), } } export type GetCapabilitiesQueryFnData< config extends Config = Config, chainId extends config['chains'][number]['id'] | undefined = undefined, > = GetCapabilitiesReturnType export type GetCapabilitiesData< config extends Config = Config, chainId extends config['chains'][number]['id'] | undefined = undefined, > = GetCapabilitiesQueryFnData export function getCapabilitiesQueryKey< config extends Config, chainId extends config['chains'][number]['id'] | undefined = undefined, >( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['capabilities', filterQueryOptions(options)] as const } export type GetCapabilitiesQueryKey< config extends Config, chainId extends config['chains'][number]['id'] | undefined = undefined, > = ReturnType> export type GetCapabilitiesQueryOptions< config extends Config, chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = GetCapabilitiesData, > = QueryOptions< GetCapabilitiesQueryFnData, GetCapabilitiesErrorType, selectData, GetCapabilitiesQueryKey > ================================================ FILE: packages/core/src/query/getConnectorClient.test-d.ts ================================================ import { chain, config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { getConnectorClientQueryOptions } from './getConnectorClient.js' const context = {} as any test('default', async () => { const options = getConnectorClientQueryOptions(config) const client = await options.queryFn(context) expectTypeOf(client.chain).toEqualTypeOf<(typeof config)['chains'][number]>() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) test('parameters: chainId', async () => { const options = getConnectorClientQueryOptions(config, { chainId: chain.mainnet.id, }) const client = await options.queryFn(context) expectTypeOf(client.chain).toEqualTypeOf() expectTypeOf(client.chain).not.toEqualTypeOf() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) ================================================ FILE: packages/core/src/query/getConnectorClient.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getConnectorClientQueryOptions } from './getConnectorClient.js' test('default', () => { expect(getConnectorClientQueryOptions(config)).toMatchInlineSnapshot(` { "enabled": false, "gcTime": 0, "queryFn": [Function], "queryKey": [ "connectorClient", {}, ], "staleTime": Infinity, } `) }) test('parameters: chainId', () => { expect( getConnectorClientQueryOptions(config, { chainId: chain.mainnet.id }), ).toMatchInlineSnapshot(` { "enabled": false, "gcTime": 0, "queryFn": [Function], "queryKey": [ "connectorClient", { "chainId": 1, }, ], "staleTime": Infinity, } `) }) ================================================ FILE: packages/core/src/query/getConnectorClient.ts ================================================ import { type GetConnectorClientErrorType, type GetConnectorClientParameters, type GetConnectorClientReturnType, getConnectorClient, } from '../actions/getConnectorClient.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetConnectorClientOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetConnectorClientData, > = Compute< ExactPartial> & ScopeKeyParameter > & Omit< QueryParameter< GetConnectorClientQueryFnData, GetConnectorClientErrorType, selectData, GetConnectorClientQueryKey >, 'gcTime' | 'staleTime' > export function getConnectorClientQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetConnectorClientData, >( config: config, options: GetConnectorClientOptions = {}, ): GetConnectorClientQueryOptions { return { ...options.query, enabled: Boolean( options.connector?.getProvider && (options.query?.enabled ?? true), ), gcTime: 0, queryFn: async (context) => { const [, { connectorUid: _, scopeKey: __, ...parameters }] = context.queryKey return getConnectorClient(config, { ...parameters, connector: options.connector, }) as unknown as Promise> }, queryKey: getConnectorClientQueryKey(options), staleTime: Number.POSITIVE_INFINITY, } } export type GetConnectorClientQueryFnData< config extends Config, chainId extends config['chains'][number]['id'], > = GetConnectorClientReturnType export type GetConnectorClientData< config extends Config, chainId extends config['chains'][number]['id'], > = GetConnectorClientQueryFnData export function getConnectorClientQueryKey< config extends Config, chainId extends config['chains'][number]['id'], >( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['connectorClient', filterQueryOptions(options)] as const } export type GetConnectorClientQueryKey< config extends Config, chainId extends config['chains'][number]['id'], > = ReturnType> export type GetConnectorClientQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetConnectorClientData, > = QueryOptions< GetConnectorClientQueryFnData, GetConnectorClientErrorType, selectData, GetConnectorClientQueryKey > ================================================ FILE: packages/core/src/query/getContractEvents.test-d.ts ================================================ import { abi, config } from '@wagmi/test' import { test } from 'vitest' import { getContractEventsQueryOptions } from './getContractEvents.js' test('default', () => { getContractEventsQueryOptions(config, { address: '0x', abi: abi.erc20, eventName: 'Transfer', args: { from: '0x', to: '0x', }, }) getContractEventsQueryOptions(config, { address: '0x', abi: abi.erc20, // @ts-expect-error eventName: 'Foo', }) getContractEventsQueryOptions(config, { address: '0x', abi: abi.erc20, eventName: 'Transfer', args: { // @ts-expect-error foo: '0x', to: '0x', }, }) }) ================================================ FILE: packages/core/src/query/getContractEvents.test.ts ================================================ import { abi, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getContractEventsQueryOptions } from './getContractEvents.js' test('default', () => { expect( getContractEventsQueryOptions(config, { address: '0x', abi: abi.erc20, eventName: 'Approval', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "getContractEvents", { "address": "0x", "eventName": "Approval", }, ], "structuralSharing": [Function], } `) }) test('enabled', () => { expect( getContractEventsQueryOptions(config, { address: '0x', eventName: 'Approval', }).enabled, ).toBe(false) }) ================================================ FILE: packages/core/src/query/getContractEvents.ts ================================================ import type { Abi, BlockNumber, BlockTag, ContractEventName } from 'viem' import { type GetContractEventsErrorType, type GetContractEventsParameters, type GetContractEventsReturnType, getContractEvents, } from '../actions/getContractEvents.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { UnionExactPartial } from '../types/utils.js' import { filterQueryOptions, structuralSharing } from './utils.js' export type GetContractEventsOptions< abi extends Abi | readonly unknown[], eventName extends ContractEventName | undefined, strict extends boolean | undefined, fromBlock extends BlockNumber | BlockTag | undefined, toBlock extends BlockNumber | BlockTag | undefined, config extends Config, chainId extends config['chains'][number]['id'], selectData = GetContractEventsData< abi, eventName, strict, fromBlock, toBlock >, > = UnionExactPartial< GetContractEventsParameters< abi, eventName, strict, fromBlock, toBlock, config, chainId > > & ScopeKeyParameter & QueryParameter< GetContractEventsQueryFnData, GetContractEventsErrorType, selectData, GetContractEventsQueryKey< config, chainId, abi, eventName, strict, fromBlock, toBlock > > export function getContractEventsQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], const abi extends Abi | readonly unknown[], eventName extends ContractEventName | undefined, strict extends boolean | undefined = undefined, fromBlock extends BlockNumber | BlockTag | undefined = undefined, toBlock extends BlockNumber | BlockTag | undefined = undefined, selectData = GetContractEventsData< abi, eventName, strict, fromBlock, toBlock >, >( config: config, options: GetContractEventsOptions< abi, eventName, strict, fromBlock, toBlock, config, chainId, selectData > = {} as any, ): GetContractEventsQueryOptions< abi, eventName, strict, fromBlock, toBlock, config, chainId, selectData > { return { ...options.query, enabled: Boolean(options.abi && (options.query?.enabled ?? true)), queryFn: async (context) => { if (!options.abi) throw new Error('abi is required') const [, { scopeKey: _, ...parameters }] = context.queryKey const result = await getContractEvents(config, { ...(parameters as any), abi: options.abi, }) return result as GetContractEventsData< abi, eventName, strict, fromBlock, toBlock > }, queryKey: getContractEventsQueryKey(options as any) as any, structuralSharing, } as GetContractEventsQueryOptions< abi, eventName, strict, fromBlock, toBlock, config, chainId, selectData > } export type GetContractEventsQueryFnData< abi extends Abi | readonly unknown[], eventName extends ContractEventName | undefined, strict extends boolean | undefined, fromBlock extends BlockNumber | BlockTag | undefined, toBlock extends BlockNumber | BlockTag | undefined, > = GetContractEventsReturnType export type GetContractEventsData< abi extends Abi | readonly unknown[], eventName extends ContractEventName | undefined, strict extends boolean | undefined, fromBlock extends BlockNumber | BlockTag | undefined, toBlock extends BlockNumber | BlockTag | undefined, > = GetContractEventsQueryFnData export function getContractEventsQueryKey< config extends Config, chainId extends config['chains'][number]['id'], const abi extends Abi | readonly unknown[], eventName extends ContractEventName | undefined, strict extends boolean | undefined = undefined, fromBlock extends BlockNumber | BlockTag | undefined = undefined, toBlock extends BlockNumber | BlockTag | undefined = undefined, >( options: UnionExactPartial< GetContractEventsParameters< abi, eventName, strict, fromBlock, toBlock, config, chainId > > & ScopeKeyParameter = {} as any, ) { return ['getContractEvents', filterQueryOptions(options)] as const } export type GetContractEventsQueryKey< config extends Config, chainId extends config['chains'][number]['id'], abi extends Abi | readonly unknown[], eventName extends ContractEventName | undefined, strict extends boolean | undefined, fromBlock extends BlockNumber | BlockTag | undefined, toBlock extends BlockNumber | BlockTag | undefined, > = ReturnType< typeof getContractEventsQueryKey< config, chainId, abi, eventName, strict, fromBlock, toBlock > > export type GetContractEventsQueryOptions< abi extends Abi | readonly unknown[], eventName extends ContractEventName | undefined, strict extends boolean | undefined, fromBlock extends BlockNumber | BlockTag | undefined, toBlock extends BlockNumber | BlockTag | undefined, config extends Config, chainId extends config['chains'][number]['id'], selectData = GetContractEventsData< abi, eventName, strict, fromBlock, toBlock >, > = QueryOptions< GetContractEventsQueryFnData, GetContractEventsErrorType, selectData, GetContractEventsQueryKey< config, chainId, abi, eventName, strict, fromBlock, toBlock > > ================================================ FILE: packages/core/src/query/getEnsAddress.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getEnsAddressQueryOptions } from './getEnsAddress.js' test('default', () => { expect(getEnsAddressQueryOptions(config)).toMatchInlineSnapshot(` { "enabled": false, "queryFn": [Function], "queryKey": [ "ensAddress", {}, ], } `) }) test('parameters: chainId', () => { expect( getEnsAddressQueryOptions(config, { chainId: chain.mainnet.id }), ).toMatchInlineSnapshot(` { "enabled": false, "queryFn": [Function], "queryKey": [ "ensAddress", { "chainId": 1, }, ], } `) }) ================================================ FILE: packages/core/src/query/getEnsAddress.ts ================================================ import { type GetEnsAddressErrorType, type GetEnsAddressParameters, type GetEnsAddressReturnType, getEnsAddress, } from '../actions/getEnsAddress.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetEnsAddressOptions< config extends Config, selectData = GetEnsAddressData, > = Compute> & ScopeKeyParameter> & QueryParameter< GetEnsAddressQueryFnData, GetEnsAddressErrorType, selectData, GetEnsAddressQueryKey > export function getEnsAddressQueryOptions< config extends Config, selectData = GetEnsAddressData, >( config: config, options: GetEnsAddressOptions = {}, ): GetEnsAddressQueryOptions { return { ...options.query, enabled: Boolean(options.name && (options.query?.enabled ?? true)), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.name) throw new Error('name is required') return getEnsAddress(config, { ...parameters, name: parameters.name }) }, queryKey: getEnsAddressQueryKey(options), } } export type GetEnsAddressQueryFnData = GetEnsAddressReturnType export type GetEnsAddressData = GetEnsAddressQueryFnData export function getEnsAddressQueryKey( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['ensAddress', filterQueryOptions(options)] as const } export type GetEnsAddressQueryKey = ReturnType< typeof getEnsAddressQueryKey > export type GetEnsAddressQueryOptions< config extends Config, selectData = GetEnsAddressData, > = QueryOptions< GetEnsAddressQueryFnData, GetEnsAddressErrorType, selectData, GetEnsAddressQueryKey > ================================================ FILE: packages/core/src/query/getEnsAvatar.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getEnsAvatarQueryOptions } from './getEnsAvatar.js' test('default', () => { expect(getEnsAvatarQueryOptions(config)).toMatchInlineSnapshot(` { "enabled": false, "queryFn": [Function], "queryKey": [ "ensAvatar", {}, ], } `) }) test('parameters: chainId', () => { expect( getEnsAvatarQueryOptions(config, { chainId: chain.mainnet.id }), ).toMatchInlineSnapshot(` { "enabled": false, "queryFn": [Function], "queryKey": [ "ensAvatar", { "chainId": 1, }, ], } `) }) ================================================ FILE: packages/core/src/query/getEnsAvatar.ts ================================================ import { type GetEnsAvatarErrorType, type GetEnsAvatarParameters, type GetEnsAvatarReturnType, getEnsAvatar, } from '../actions/getEnsAvatar.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetEnsAvatarOptions< config extends Config, selectData = GetEnsAvatarData, > = Compute> & ScopeKeyParameter> & QueryParameter< GetEnsAvatarQueryFnData, GetEnsAvatarErrorType, selectData, GetEnsAvatarQueryKey > export function getEnsAvatarQueryOptions< config extends Config, selectData = GetEnsAvatarData, >( config: config, options: GetEnsAvatarOptions = {}, ): GetEnsAvatarQueryOptions { return { ...options.query, enabled: Boolean(options.name && (options.query?.enabled ?? true)), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.name) throw new Error('name is required') return getEnsAvatar(config, { ...parameters, name: parameters.name }) }, queryKey: getEnsAvatarQueryKey(options), } } export type GetEnsAvatarQueryFnData = GetEnsAvatarReturnType export type GetEnsAvatarData = GetEnsAvatarQueryFnData export function getEnsAvatarQueryKey( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['ensAvatar', filterQueryOptions(options)] as const } export type GetEnsAvatarQueryKey = ReturnType< typeof getEnsAvatarQueryKey > export type GetEnsAvatarQueryOptions< config extends Config, selectData = GetEnsAvatarData, > = QueryOptions< GetEnsAvatarQueryFnData, GetEnsAvatarErrorType, selectData, GetEnsAvatarQueryKey > ================================================ FILE: packages/core/src/query/getEnsName.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getEnsNameQueryOptions } from './getEnsName.js' test('default', () => { expect(getEnsNameQueryOptions(config)).toMatchInlineSnapshot(` { "enabled": false, "queryFn": [Function], "queryKey": [ "ensName", {}, ], } `) }) test('parameters: chainId', () => { expect( getEnsNameQueryOptions(config, { chainId: chain.mainnet.id }), ).toMatchInlineSnapshot(` { "enabled": false, "queryFn": [Function], "queryKey": [ "ensName", { "chainId": 1, }, ], } `) }) ================================================ FILE: packages/core/src/query/getEnsName.ts ================================================ import { type GetEnsNameErrorType, type GetEnsNameParameters, type GetEnsNameReturnType, getEnsName, } from '../actions/getEnsName.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetEnsNameOptions< config extends Config, selectData = GetEnsNameData, > = Compute> & ScopeKeyParameter> & QueryParameter< GetEnsNameQueryFnData, GetEnsNameErrorType, selectData, GetEnsNameQueryKey > export function getEnsNameQueryOptions< config extends Config, selectData = GetEnsNameData, >( config: config, options: GetEnsNameOptions = {}, ): GetEnsNameQueryOptions { return { ...options.query, enabled: Boolean(options.address && (options.query?.enabled ?? true)), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.address) throw new Error('address is required') return getEnsName(config, { ...parameters, address: parameters.address }) }, queryKey: getEnsNameQueryKey(options), } } export type GetEnsNameQueryFnData = GetEnsNameReturnType export type GetEnsNameData = GetEnsNameQueryFnData export function getEnsNameQueryKey( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['ensName', filterQueryOptions(options)] as const } export type GetEnsNameQueryKey = ReturnType< typeof getEnsNameQueryKey > export type GetEnsNameQueryOptions< config extends Config, selectData = GetEnsNameData, > = QueryOptions< GetEnsNameQueryFnData, GetEnsNameErrorType, selectData, GetEnsNameQueryKey > ================================================ FILE: packages/core/src/query/getEnsResolver.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getEnsResolverQueryOptions } from './getEnsResolver.js' test('default', () => { expect(getEnsResolverQueryOptions(config)).toMatchInlineSnapshot(` { "enabled": false, "queryFn": [Function], "queryKey": [ "ensResolver", {}, ], } `) }) test('parameters: chainId', () => { expect( getEnsResolverQueryOptions(config, { chainId: chain.mainnet.id }), ).toMatchInlineSnapshot(` { "enabled": false, "queryFn": [Function], "queryKey": [ "ensResolver", { "chainId": 1, }, ], } `) }) ================================================ FILE: packages/core/src/query/getEnsResolver.ts ================================================ import { type GetEnsResolverErrorType, type GetEnsResolverParameters, type GetEnsResolverReturnType, getEnsResolver, } from '../actions/getEnsResolver.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetEnsResolverOptions< config extends Config, selectData = GetEnsResolverData, > = Compute< ExactPartial> & ScopeKeyParameter > & QueryParameter< GetEnsResolverQueryFnData, GetEnsResolverErrorType, selectData, GetEnsResolverQueryKey > export function getEnsResolverQueryOptions< config extends Config, selectData = GetEnsResolverData, >( config: config, options: GetEnsResolverOptions = {}, ): GetEnsResolverQueryOptions { return { ...options.query, enabled: Boolean(options.name && (options.query?.enabled ?? true)), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.name) throw new Error('name is required') return getEnsResolver(config, { ...parameters, name: parameters.name }) }, queryKey: getEnsResolverQueryKey(options), } } export type GetEnsResolverQueryFnData = GetEnsResolverReturnType export type GetEnsResolverData = GetEnsResolverQueryFnData export function getEnsResolverQueryKey( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['ensResolver', filterQueryOptions(options)] as const } export type GetEnsResolverQueryKey = ReturnType< typeof getEnsResolverQueryKey > export type GetEnsResolverQueryOptions< config extends Config, selectData = GetEnsResolverData, > = QueryOptions< GetEnsResolverQueryFnData, GetEnsResolverErrorType, selectData, GetEnsResolverQueryKey > ================================================ FILE: packages/core/src/query/getEnsText.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getEnsTextQueryOptions } from './getEnsText.js' test('default', () => { expect( getEnsTextQueryOptions(config, { name: 'wevm.eth', key: 'com.twitter', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "ensText", { "key": "com.twitter", "name": "wevm.eth", }, ], } `) }) test('parameters: chainId', () => { expect( getEnsTextQueryOptions(config, { chainId: chain.mainnet.id, name: 'wevm.eth', key: 'com.twitter', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "ensText", { "chainId": 1, "key": "com.twitter", "name": "wevm.eth", }, ], } `) }) ================================================ FILE: packages/core/src/query/getEnsText.ts ================================================ import { type GetEnsTextErrorType, type GetEnsTextParameters, type GetEnsTextReturnType, getEnsText, } from '../actions/getEnsText.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetEnsTextOptions< config extends Config, selectData = GetEnsTextData, > = Compute> & ScopeKeyParameter> & QueryParameter< GetEnsTextQueryFnData, GetEnsTextErrorType, selectData, GetEnsTextQueryKey > export function getEnsTextQueryOptions< config extends Config, selectData = GetEnsTextData, >( config: config, options: GetEnsTextOptions = {}, ): GetEnsTextQueryOptions { return { ...options.query, enabled: Boolean( options.key && options.name && (options.query?.enabled ?? true), ), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.key || !parameters.name) throw new Error('key and name are required') return getEnsText(config, { ...parameters, key: parameters.key, name: parameters.name, }) }, queryKey: getEnsTextQueryKey(options), } } export type GetEnsTextQueryFnData = GetEnsTextReturnType export type GetEnsTextData = GetEnsTextQueryFnData export function getEnsTextQueryKey( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['ensText', filterQueryOptions(options)] as const } export type GetEnsTextQueryKey = ReturnType< typeof getEnsTextQueryKey > export type GetEnsTextQueryOptions< config extends Config, selectData = GetEnsTextData, > = QueryOptions< GetEnsTextQueryFnData, GetEnsTextErrorType, selectData, GetEnsTextQueryKey > ================================================ FILE: packages/core/src/query/getFeeHistory.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getFeeHistoryQueryOptions } from './getFeeHistory.js' test('default', async () => { expect( getFeeHistoryQueryOptions(config, { blockCount: 4, rewardPercentiles: [25, 75], }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "feeHistory", { "blockCount": 4, "rewardPercentiles": [ 25, 75, ], }, ], } `) }) test('parameters: chainId', async () => { expect( getFeeHistoryQueryOptions(config, { blockCount: 4, rewardPercentiles: [25, 75], chainId: chain.mainnet2.id, }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "feeHistory", { "blockCount": 4, "chainId": 456, "rewardPercentiles": [ 25, 75, ], }, ], } `) }) test('parameters: blockNumber', async () => { expect( getFeeHistoryQueryOptions(config, { blockCount: 4, rewardPercentiles: [25, 75], blockNumber: 18677379n, }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "feeHistory", { "blockCount": 4, "blockNumber": 18677379n, "rewardPercentiles": [ 25, 75, ], }, ], } `) }) test('parameters: blockTag', async () => { expect( getFeeHistoryQueryOptions(config, { blockCount: 4, rewardPercentiles: [25, 75], blockTag: 'safe', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "feeHistory", { "blockCount": 4, "blockTag": "safe", "rewardPercentiles": [ 25, 75, ], }, ], } `) }) test('behavior: blockCount is required', async () => { const options = getFeeHistoryQueryOptions(config, {}) await expect( options.queryFn({ queryKey: options.queryKey, signal: new AbortSignal(), meta: undefined, }), ).rejects.toThrowErrorMatchingInlineSnapshot( '[Error: blockCount is required]', ) }) test('behavior: rewardPercentiles is required', async () => { const options = getFeeHistoryQueryOptions(config, { blockCount: 4 }) await expect( options.queryFn({ queryKey: options.queryKey, signal: new AbortSignal(), meta: undefined, }), ).rejects.toThrowErrorMatchingInlineSnapshot( '[Error: rewardPercentiles is required]', ) }) ================================================ FILE: packages/core/src/query/getFeeHistory.ts ================================================ import { type GetFeeHistoryErrorType, type GetFeeHistoryParameters, type GetFeeHistoryReturnType, getFeeHistory, } from '../actions/getFeeHistory.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetFeeHistoryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetFeeHistoryData, > = Compute< ExactPartial> & ScopeKeyParameter > & QueryParameter< GetFeeHistoryQueryFnData, GetFeeHistoryErrorType, selectData, GetFeeHistoryQueryKey > export function getFeeHistoryQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetFeeHistoryData, >( config: config, options: GetFeeHistoryOptions = {}, ): GetFeeHistoryQueryOptions { return { ...options.query, enabled: Boolean( options.blockCount && options.rewardPercentiles && (options.query?.enabled ?? true), ), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.blockCount) throw new Error('blockCount is required') if (!parameters.rewardPercentiles) throw new Error('rewardPercentiles is required') const feeHistory = await getFeeHistory(config, { ...(parameters as GetFeeHistoryParameters), blockCount: parameters.blockCount, rewardPercentiles: parameters.rewardPercentiles, }) return feeHistory ?? null }, queryKey: getFeeHistoryQueryKey(options), } } export type GetFeeHistoryQueryFnData = GetFeeHistoryReturnType export type GetFeeHistoryData = GetFeeHistoryQueryFnData export function getFeeHistoryQueryKey< config extends Config, chainId extends config['chains'][number]['id'], >( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['feeHistory', filterQueryOptions(options)] as const } export type GetFeeHistoryQueryKey< config extends Config, chainId extends config['chains'][number]['id'], > = ReturnType> export type GetFeeHistoryQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetFeeHistoryData, > = QueryOptions< GetFeeHistoryQueryFnData, GetFeeHistoryErrorType, selectData, GetFeeHistoryQueryKey > ================================================ FILE: packages/core/src/query/getGasPrice.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getGasPriceQueryOptions } from './getGasPrice.js' test('default', () => { expect(getGasPriceQueryOptions(config)).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "gasPrice", {}, ], } `) }) test('parameters: chainId', () => { expect( getGasPriceQueryOptions(config, { chainId: chain.mainnet.id }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "gasPrice", { "chainId": 1, }, ], } `) }) ================================================ FILE: packages/core/src/query/getGasPrice.ts ================================================ import { type GetGasPriceErrorType, type GetGasPriceParameters, type GetGasPriceReturnType, getGasPrice, } from '../actions/getGasPrice.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetGasPriceOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetGasPriceData, > = Compute< ExactPartial> & ScopeKeyParameter > & QueryParameter< GetGasPriceQueryFnData, GetGasPriceErrorType, selectData, GetGasPriceQueryKey > export function getGasPriceQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetGasPriceData, >( config: config, options: GetGasPriceOptions = {}, ): GetGasPriceQueryOptions { return { ...options.query, queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey const gasPrice = await getGasPrice(config, parameters) return gasPrice ?? null }, queryKey: getGasPriceQueryKey(options), } } export type GetGasPriceQueryFnData = GetGasPriceReturnType export type GetGasPriceData = GetGasPriceQueryFnData export function getGasPriceQueryKey< config extends Config, chainId extends config['chains'][number]['id'], >( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['gasPrice', filterQueryOptions(options)] as const } export type GetGasPriceQueryKey< config extends Config, chainId extends config['chains'][number]['id'], > = ReturnType> export type GetGasPriceQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetGasPriceData, > = QueryOptions< GetGasPriceQueryFnData, GetGasPriceErrorType, selectData, GetGasPriceQueryKey > ================================================ FILE: packages/core/src/query/getProof.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getProofQueryOptions } from './getProof.js' test('default', () => { expect( getProofQueryOptions(config, { address: '0x4200000000000000000000000000000000000016', storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "getProof", { "address": "0x4200000000000000000000000000000000000016", "storageKeys": [ "0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99", ], }, ], } `) }) test('parameters: blockNumber', () => { expect( getProofQueryOptions(config, { address: '0x4200000000000000000000000000000000000016', blockNumber: 1234567890n, storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "getProof", { "address": "0x4200000000000000000000000000000000000016", "blockNumber": 1234567890n, "storageKeys": [ "0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99", ], }, ], } `) }) test('parameters: blockTag', () => { expect( getProofQueryOptions(config, { address: '0x4200000000000000000000000000000000000016', blockTag: 'safe', storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "getProof", { "address": "0x4200000000000000000000000000000000000016", "blockTag": "safe", "storageKeys": [ "0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99", ], }, ], } `) }) test('parameters: chainId', () => { expect( getProofQueryOptions(config, { address: '0x4200000000000000000000000000000000000016', chainId: chain.mainnet2.id, storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "getProof", { "address": "0x4200000000000000000000000000000000000016", "chainId": 456, "storageKeys": [ "0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99", ], }, ], } `) }) ================================================ FILE: packages/core/src/query/getProof.ts ================================================ import { type GetProofErrorType, type GetProofParameters, type GetProofReturnType, getProof, } from '../actions/getProof.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetProofOptions< config extends Config, selectData = GetProofData, > = Compute> & ScopeKeyParameter> & QueryParameter< GetProofQueryFnData, GetProofErrorType, selectData, GetProofQueryKey > export function getProofQueryOptions< config extends Config, selectData = GetProofData, >( config: config, options: GetProofOptions = {}, ): GetProofQueryOptions { return { ...options.query, enabled: Boolean( options.address && options.storageKeys && (options.query?.enabled ?? true), ), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.address || !parameters.storageKeys) throw new Error('address and storageKeys are required') return getProof(config, { ...(parameters as GetProofParameters), address: parameters.address, storageKeys: parameters.storageKeys, }) }, queryKey: getProofQueryKey(options), } } export type GetProofQueryFnData = GetProofReturnType export type GetProofData = GetProofQueryFnData export function getProofQueryKey( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['getProof', filterQueryOptions(options)] as const } export type GetProofQueryKey = ReturnType< typeof getProofQueryKey > export type GetProofQueryOptions< config extends Config, selectData = GetProofData, > = QueryOptions< GetProofQueryFnData, GetProofErrorType, selectData, GetProofQueryKey > ================================================ FILE: packages/core/src/query/getStorageAt.test.ts ================================================ import { address, chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getStorageAtQueryOptions } from './getStorageAt.js' test('default', () => { expect( getStorageAtQueryOptions(config, { address: address.wagmiMintExample, slot: '0x0', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "getStorageAt", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "slot": "0x0", }, ], } `) }) test('parameters: blockNumber', () => { expect( getStorageAtQueryOptions(config, { address: address.wagmiMintExample, blockNumber: 16280770n, slot: '0x0', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "getStorageAt", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "blockNumber": 16280770n, "slot": "0x0", }, ], } `) }) test('parameters: blockTag', () => { expect( getStorageAtQueryOptions(config, { address: address.wagmiMintExample, blockTag: 'safe', slot: '0x0', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "getStorageAt", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "blockTag": "safe", "slot": "0x0", }, ], } `) }) test('parameters: chainId', () => { expect( getStorageAtQueryOptions(config, { address: address.wagmiMintExample, chainId: chain.mainnet2.id, slot: '0x0', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "getStorageAt", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "chainId": 456, "slot": "0x0", }, ], } `) }) ================================================ FILE: packages/core/src/query/getStorageAt.ts ================================================ import { type GetStorageAtErrorType, type GetStorageAtParameters, type GetStorageAtReturnType, getStorageAt, } from '../actions/getStorageAt.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetStorageAtOptions< config extends Config, selectData = GetStorageAtData, > = Compute> & ScopeKeyParameter> & QueryParameter< GetStorageAtQueryFnData, GetStorageAtErrorType, selectData, GetStorageAtQueryKey > export function getStorageAtQueryOptions< config extends Config, selectData = GetStorageAtData, >( config: config, options: GetStorageAtOptions = {}, ): GetStorageAtQueryOptions { return { ...options.query, enabled: Boolean( options.address && options.slot && (options.query?.enabled ?? true), ), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.address || !parameters.slot) throw new Error('address and slot are required') return getStorageAt(config, { ...(parameters as GetStorageAtParameters), address: parameters.address, slot: parameters.slot, }) }, queryKey: getStorageAtQueryKey(options), } } export type GetStorageAtQueryFnData = GetStorageAtReturnType export type GetStorageAtData = GetStorageAtQueryFnData export function getStorageAtQueryKey( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['getStorageAt', filterQueryOptions(options)] as const } export type GetStorageAtQueryKey = ReturnType< typeof getStorageAtQueryKey > export type GetStorageAtQueryOptions< config extends Config, selectData = GetStorageAtData, > = QueryOptions< GetStorageAtQueryFnData, GetStorageAtErrorType, selectData, GetStorageAtQueryKey > ================================================ FILE: packages/core/src/query/getTransaction.test-d.ts ================================================ import { http } from 'viem' import { celo, mainnet } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { getTransactionQueryOptions } from './getTransaction.js' const context = {} as any test('chain formatters', async () => { const config = createConfig({ chains: [celo, mainnet], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) const options = getTransactionQueryOptions(config, { hash: '0x123', }) const result = await options.queryFn(context) if (result.chainId === celo.id) { expectTypeOf(result.feeCurrency).toEqualTypeOf<`0x${string}` | null>() } // @ts-expect-error result.feeCurrency }) test('chainId', async () => { const config = createConfig({ chains: [celo, mainnet], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) const options = getTransactionQueryOptions(config, { hash: '0x123', chainId: celo.id, }) const result = await options.queryFn(context) expectTypeOf(result.feeCurrency).toEqualTypeOf<`0x${string}` | null>() }) ================================================ FILE: packages/core/src/query/getTransaction.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getTransactionQueryOptions } from './getTransaction.js' test('default', () => { expect(getTransactionQueryOptions(config)).toMatchInlineSnapshot(` { "enabled": false, "queryFn": [Function], "queryKey": [ "transaction", {}, ], } `) }) test('parameters: chainId', () => { expect( getTransactionQueryOptions(config, { chainId: chain.mainnet.id }), ).toMatchInlineSnapshot(` { "enabled": false, "queryFn": [Function], "queryKey": [ "transaction", { "chainId": 1, }, ], } `) }) ================================================ FILE: packages/core/src/query/getTransaction.ts ================================================ import { type GetTransactionErrorType, type GetTransactionParameters, type GetTransactionReturnType, getTransaction, } from '../actions/getTransaction.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetTransactionOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetTransactionData, > = Compute< ExactPartial> & ScopeKeyParameter > & QueryParameter< GetTransactionQueryFnData, GetTransactionErrorType, selectData, GetTransactionQueryKey > export function getTransactionQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetTransactionData, >( config: config, options: GetTransactionOptions = {}, ): GetTransactionQueryOptions { return { ...options.query, enabled: Boolean( (options.hash || (options.index && (options.blockHash || options.blockNumber || options.blockTag))) && (options.query?.enabled ?? true), ), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if ( !( parameters.hash || (parameters.index && (parameters.blockHash || parameters.blockNumber || parameters.blockTag)) ) ) throw new Error( 'hash OR index AND blockHash, blockNumber, blockTag is required', ) return getTransaction( config, parameters as GetTransactionParameters, ) as unknown as Promise> }, queryKey: getTransactionQueryKey(options), } } export type GetTransactionQueryFnData< config extends Config, chainId extends config['chains'][number]['id'], > = GetTransactionReturnType export type GetTransactionData< config extends Config, chainId extends config['chains'][number]['id'], > = GetTransactionQueryFnData export function getTransactionQueryKey< config extends Config, chainId extends config['chains'][number]['id'], >( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['transaction', filterQueryOptions(options)] as const } export type GetTransactionQueryKey< config extends Config, chainId extends config['chains'][number]['id'], > = ReturnType> export type GetTransactionQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetTransactionData, > = QueryOptions< GetTransactionQueryFnData, GetTransactionErrorType, selectData, GetTransactionQueryKey > ================================================ FILE: packages/core/src/query/getTransactionConfirmations.test-d.ts ================================================ import { config } from '@wagmi/test' import { http } from 'viem' import { mainnet, zkSync } from 'viem/chains' import { test } from 'vitest' import { createConfig } from '../createConfig.js' import { getTransactionConfirmationsQueryOptions } from './getTransactionConfirmations.js' test('default', async () => { getTransactionConfirmationsQueryOptions(config, { transactionReceipt: { blockHash: '0x', blockNumber: 1n, contractAddress: '0x', cumulativeGasUsed: 1n, effectiveGasPrice: 1n, from: '0x', gasUsed: 1n, l1Fee: 1n, logs: [], logsBloom: '0x', status: 'success', to: '0x', transactionHash: '0x', transactionIndex: 1, type: 'eip1559', }, }) }) test('chain formatters', async () => { const config = createConfig({ chains: [mainnet, zkSync], transports: { [mainnet.id]: http(), [zkSync.id]: http() }, }) const transactionReceipt = { blockHash: '0x', blockNumber: 1n, contractAddress: '0x', cumulativeGasUsed: 1n, effectiveGasPrice: 1n, from: '0x', gasUsed: 1n, logsBloom: '0x', status: 'success', to: '0x', transactionHash: '0x', transactionIndex: 1, type: 'eip1559', } as const getTransactionConfirmationsQueryOptions(config, { transactionReceipt: { ...transactionReceipt, l1BatchNumber: 1n, l1BatchTxIndex: 1n, logs: [], l2ToL1Logs: [], }, }) getTransactionConfirmationsQueryOptions(config, { chainId: zkSync.id, transactionReceipt: { ...transactionReceipt, l1BatchNumber: 1n, l1BatchTxIndex: 1n, logs: [], l2ToL1Logs: [], }, }) getTransactionConfirmationsQueryOptions(config, { chainId: mainnet.id, transactionReceipt: { ...transactionReceipt, // @ts-expect-error l1BatchNumber: 1n, l1BatchTxIndex: 1n, logs: [], l2ToL1Logs: [], }, }) }) ================================================ FILE: packages/core/src/query/getTransactionConfirmations.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getTransactionConfirmationsQueryOptions } from './getTransactionConfirmations.js' test('default', () => { expect( getTransactionConfirmationsQueryOptions(config, { hash: '0xa559259bd2d0e8372421e222ff3545f705b5da60005bd787a23c2e68d6d7fefd', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "transactionConfirmations", { "hash": "0xa559259bd2d0e8372421e222ff3545f705b5da60005bd787a23c2e68d6d7fefd", }, ], } `) }) test('parameters: chainId', () => { expect( getTransactionConfirmationsQueryOptions(config, { chainId: chain.mainnet.id, hash: '0xa559259bd2d0e8372421e222ff3545f705b5da60005bd787a23c2e68d6d7fefd', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "transactionConfirmations", { "chainId": 1, "hash": "0xa559259bd2d0e8372421e222ff3545f705b5da60005bd787a23c2e68d6d7fefd", }, ], } `) }) ================================================ FILE: packages/core/src/query/getTransactionConfirmations.ts ================================================ import { type GetTransactionConfirmationsErrorType, type GetTransactionConfirmationsParameters, type GetTransactionConfirmationsReturnType, getTransactionConfirmations, } from '../actions/getTransactionConfirmations.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { UnionExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetTransactionConfirmationsOptions< config extends Config, chainId extends | config['chains'][number]['id'] | undefined = config['chains'][number]['id'], selectData = GetTransactionConfirmationsData, > = UnionExactPartial> & ScopeKeyParameter & QueryParameter< GetTransactionConfirmationsQueryFnData, GetTransactionConfirmationsErrorType, selectData, GetTransactionConfirmationsQueryKey > export function getTransactionConfirmationsQueryOptions< config extends Config, chainId extends | config['chains'][number]['id'] | undefined = config['chains'][number]['id'], selectData = GetTransactionConfirmationsData, >( config: config, options: GetTransactionConfirmationsOptions< config, chainId, selectData > = {} as any, ): GetTransactionConfirmationsQueryOptions { return { ...options.query, enabled: Boolean( (options.hash || options.transactionReceipt) && (options.query?.enabled ?? true), ), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.hash && !parameters.transactionReceipt) throw new Error('hash or transactionReceipt is required') const confirmations = await getTransactionConfirmations(config, { ...(parameters as any), hash: parameters.hash, transactionReceipt: parameters.transactionReceipt, }) return confirmations ?? null }, queryKey: getTransactionConfirmationsQueryKey(options), } } export type GetTransactionConfirmationsQueryFnData = GetTransactionConfirmationsReturnType export type GetTransactionConfirmationsData = GetTransactionConfirmationsQueryFnData export function getTransactionConfirmationsQueryKey< config extends Config, chainId extends | config['chains'][number]['id'] | undefined = config['chains'][number]['id'], >( options: UnionExactPartial< GetTransactionConfirmationsParameters > & ScopeKeyParameter = {} as any, ) { return ['transactionConfirmations', filterQueryOptions(options)] as const } export type GetTransactionConfirmationsQueryKey< config extends Config, chainId extends | config['chains'][number]['id'] | undefined = config['chains'][number]['id'], > = ReturnType> export type GetTransactionConfirmationsQueryOptions< config extends Config, chainId extends | config['chains'][number]['id'] | undefined = config['chains'][number]['id'], selectData = GetTransactionConfirmationsData, > = QueryOptions< GetTransactionConfirmationsQueryFnData, GetTransactionConfirmationsErrorType, selectData, GetTransactionConfirmationsQueryKey > ================================================ FILE: packages/core/src/query/getTransactionCount.test.ts ================================================ import { accounts, chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getTransactionCountQueryOptions } from './getTransactionCount.js' const address = accounts[0] test('default', () => { expect( getTransactionCountQueryOptions(config, { address }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "transactionCount", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", }, ], } `) }) test('parameters: chainId', () => { expect( getTransactionCountQueryOptions(config, { address, chainId: chain.mainnet.id, }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "transactionCount", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 1, }, ], } `) }) test('parameters: blockNumber', () => { expect( getTransactionCountQueryOptions(config, { address, blockNumber: 13677382n, }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "transactionCount", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "blockNumber": 13677382n, }, ], } `) }) test('parameters: blockTag', () => { expect( getTransactionCountQueryOptions(config, { address, blockTag: 'earliest', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "transactionCount", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "blockTag": "earliest", }, ], } `) }) ================================================ FILE: packages/core/src/query/getTransactionCount.ts ================================================ import { type GetTransactionCountErrorType, type GetTransactionCountParameters, type GetTransactionCountReturnType, getTransactionCount, } from '../actions/getTransactionCount.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetTransactionCountOptions< config extends Config, selectData = GetTransactionCountData, > = Compute< ExactPartial> & ScopeKeyParameter > & QueryParameter< GetTransactionCountQueryFnData, GetTransactionCountErrorType, selectData, GetTransactionCountQueryKey > export function getTransactionCountQueryOptions< config extends Config, selectData = GetTransactionCountData, >( config: config, options: GetTransactionCountOptions = {}, ): GetTransactionCountQueryOptions { return { ...options.query, enabled: Boolean(options.address && (options.query?.enabled ?? true)), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.address) throw new Error('address is required') const transactionCount = await getTransactionCount(config, { ...(parameters as any), address: parameters.address, }) return transactionCount ?? null }, queryKey: getTransactionCountQueryKey(options), } } export type GetTransactionCountQueryFnData = Compute export type GetTransactionCountData = GetTransactionCountQueryFnData export function getTransactionCountQueryKey( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['transactionCount', filterQueryOptions(options)] as const } export type GetTransactionCountQueryKey = ReturnType< typeof getTransactionCountQueryKey > export type GetTransactionCountQueryOptions< config extends Config, selectData = GetTransactionCountData, > = QueryOptions< GetTransactionCountQueryFnData, GetTransactionCountErrorType, selectData, GetTransactionCountQueryKey > ================================================ FILE: packages/core/src/query/getTransactionReceipt.test-d.ts ================================================ import { http } from 'viem' import { mainnet, zkSync } from 'viem/chains' import type { ZkSyncL2ToL1Log, ZkSyncLog } from 'viem/zksync' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { getTransactionReceiptQueryOptions } from './getTransactionReceipt.js' const context = {} as any test('chain formatters', async () => { const config = createConfig({ chains: [mainnet, zkSync], transports: { [mainnet.id]: http(), [zkSync.id]: http() }, }) const options = getTransactionReceiptQueryOptions(config, { hash: '0x123' }) const result = await options.queryFn(context) if (result.chainId === zkSync.id) { expectTypeOf(result.l1BatchNumber).toEqualTypeOf() expectTypeOf(result.l1BatchTxIndex).toEqualTypeOf() expectTypeOf(result.logs).toEqualTypeOf() expectTypeOf(result.l2ToL1Logs).toEqualTypeOf() } // @ts-expect-error result.l1BatchNumber }) test('chainId', async () => { const config = createConfig({ chains: [zkSync], transports: { [zkSync.id]: http() }, }) const options = getTransactionReceiptQueryOptions(config, { hash: '0x123', chainId: zkSync.id, }) const result = await options.queryFn(context) expectTypeOf(result.l1BatchNumber).toEqualTypeOf() expectTypeOf(result.l1BatchTxIndex).toEqualTypeOf() expectTypeOf(result.logs).toEqualTypeOf() expectTypeOf(result.l2ToL1Logs).toEqualTypeOf() }) ================================================ FILE: packages/core/src/query/getTransactionReceipt.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getTransactionReceiptQueryOptions } from './getTransactionReceipt.js' test('default', () => { expect( getTransactionReceiptQueryOptions(config, { hash: '0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "getTransactionReceipt", { "hash": "0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871", }, ], } `) }) test('parameters: chainId', () => { expect( getTransactionReceiptQueryOptions(config, { chainId: chain.mainnet2.id, hash: '0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "getTransactionReceipt", { "chainId": 456, "hash": "0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871", }, ], } `) }) ================================================ FILE: packages/core/src/query/getTransactionReceipt.ts ================================================ import type { GetTransactionReceiptReturnType } from '../actions/getTransactionReceipt.js' import { type GetTransactionReceiptErrorType, type GetTransactionReceiptParameters, getTransactionReceipt, } from '../actions/getTransactionReceipt.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetTransactionReceiptOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetTransactionReceiptData, > = Compute< ExactPartial> & ScopeKeyParameter > & QueryParameter< GetTransactionReceiptQueryFnData, GetTransactionReceiptErrorType, selectData, GetTransactionReceiptQueryKey > export function getTransactionReceiptQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetTransactionReceiptData, >( config: config, options: GetTransactionReceiptOptions = {}, ): GetTransactionReceiptQueryOptions { return { ...options.query, enabled: Boolean(options.hash && (options.query?.enabled ?? true)), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.hash) throw new Error('hash is required') return getTransactionReceipt(config, { ...(parameters as any), hash: parameters.hash, }) }, queryKey: getTransactionReceiptQueryKey(options), } } export type GetTransactionReceiptQueryFnData< config extends Config, chainId extends config['chains'][number]['id'], > = GetTransactionReceiptReturnType export type GetTransactionReceiptData< config extends Config, chainId extends config['chains'][number]['id'], > = GetTransactionReceiptQueryFnData export function getTransactionReceiptQueryKey< config extends Config, chainId extends config['chains'][number]['id'], >( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['getTransactionReceipt', filterQueryOptions(options)] as const } export type GetTransactionReceiptQueryKey< config extends Config, chainId extends config['chains'][number]['id'], > = ReturnType> export type GetTransactionReceiptQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetTransactionReceiptData, > = QueryOptions< GetTransactionReceiptQueryFnData, GetTransactionReceiptErrorType, selectData, GetTransactionReceiptQueryKey > ================================================ FILE: packages/core/src/query/getWalletClient.test-d.ts ================================================ import { chain, config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { getWalletClientQueryOptions } from './getWalletClient.js' const context = {} as any test('default', async () => { const options = getWalletClientQueryOptions(config) const client = await options.queryFn(context) expectTypeOf(client.chain).toEqualTypeOf<(typeof config)['chains'][number]>() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) test('parameters: chainId', async () => { const options = getWalletClientQueryOptions(config, { chainId: chain.mainnet.id, }) const client = await options.queryFn(context) expectTypeOf(client.chain).toEqualTypeOf() expectTypeOf(client.chain).not.toEqualTypeOf() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) ================================================ FILE: packages/core/src/query/getWalletClient.test.ts ================================================ import { chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { getWalletClientQueryOptions } from './getWalletClient.js' test('default', () => { expect(getWalletClientQueryOptions(config)).toMatchInlineSnapshot(` { "enabled": false, "gcTime": 0, "queryFn": [Function], "queryKey": [ "walletClient", {}, ], "staleTime": Infinity, } `) }) test('parameters: chainId', () => { expect( getWalletClientQueryOptions(config, { chainId: chain.mainnet.id }), ).toMatchInlineSnapshot(` { "enabled": false, "gcTime": 0, "queryFn": [Function], "queryKey": [ "walletClient", { "chainId": 1, }, ], "staleTime": Infinity, } `) }) ================================================ FILE: packages/core/src/query/getWalletClient.ts ================================================ import { type GetWalletClientErrorType, type GetWalletClientParameters, type GetWalletClientReturnType, getWalletClient, } from '../actions/getWalletClient.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type GetWalletClientOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetWalletClientData, > = Compute< ExactPartial> & ScopeKeyParameter > & QueryParameter< GetWalletClientQueryFnData, GetWalletClientErrorType, selectData, GetWalletClientQueryKey > export function getWalletClientQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetWalletClientData, >( config: config, options: GetWalletClientOptions = {}, ): GetWalletClientQueryOptions { return { ...options.query, enabled: Boolean( options.connector?.getProvider && (options.query?.enabled ?? true), ), gcTime: 0, queryFn: async (context) => { if (!options.connector?.getProvider) throw new Error('connector is required') const [, { connectorUid: _, scopeKey: __, ...parameters }] = context.queryKey return getWalletClient(config, { ...parameters, connector: options.connector, }) as never }, queryKey: getWalletClientQueryKey(options), staleTime: Number.POSITIVE_INFINITY, } } export type GetWalletClientQueryFnData< config extends Config, chainId extends config['chains'][number]['id'], > = GetWalletClientReturnType export type GetWalletClientData< config extends Config, chainId extends config['chains'][number]['id'], > = GetWalletClientQueryFnData export function getWalletClientQueryKey< config extends Config, chainId extends config['chains'][number]['id'], >( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['walletClient', filterQueryOptions(options)] as const } export type GetWalletClientQueryKey< config extends Config, chainId extends config['chains'][number]['id'], > = ReturnType> export type GetWalletClientQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = GetWalletClientData, > = QueryOptions< GetWalletClientQueryFnData, GetWalletClientErrorType, selectData, GetWalletClientQueryKey > ================================================ FILE: packages/core/src/query/infiniteReadContracts.test-d.ts ================================================ import { abi, config } from '@wagmi/test' import type { MulticallResponse } from 'viem' import { expectTypeOf, test } from 'vitest' import { infiniteReadContractsQueryOptions } from './infiniteReadContracts.js' test('default', async () => { const options = infiniteReadContractsQueryOptions(config, { cacheKey: 'foo', contracts(pageParam) { expectTypeOf(pageParam).toEqualTypeOf(options.initialPageParam) return [ { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }, { address: '0x', abi: abi.wagmiMintExample, functionName: 'tokenURI', args: [123n], }, ] }, query: { initialPageParam: 0, getNextPageParam(lastPage, allPages, lastPageParam, allPageParams) { expectTypeOf(lastPage).toEqualTypeOf< [MulticallResponse, MulticallResponse] >() expectTypeOf(allPages).toEqualTypeOf< [MulticallResponse, MulticallResponse][] >() expectTypeOf(lastPageParam).toEqualTypeOf(options.initialPageParam) expectTypeOf(allPageParams).toEqualTypeOf([options.initialPageParam]) return lastPageParam + 1 }, }, }) const result = await options.queryFn({} as any) expectTypeOf(result).toEqualTypeOf< [MulticallResponse, MulticallResponse] >() }) test('allowFailure: false', async () => { const options = infiniteReadContractsQueryOptions(config, { allowFailure: false, cacheKey: 'foo', contracts(pageParam) { expectTypeOf(pageParam).toEqualTypeOf(options.initialPageParam) return [ { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }, { address: '0x', abi: abi.wagmiMintExample, functionName: 'tokenURI', args: [123n], }, ] }, query: { initialPageParam: 0, getNextPageParam(lastPage, allPages, lastPageParam, allPageParams) { expectTypeOf(lastPage).toEqualTypeOf<[bigint, string]>() expectTypeOf(allPages).toEqualTypeOf<[bigint, string][]>() expectTypeOf(lastPageParam).toEqualTypeOf(options.initialPageParam) expectTypeOf(allPageParams).toEqualTypeOf([options.initialPageParam]) return lastPageParam + 1 }, }, }) const result = await options.queryFn({} as any) expectTypeOf(result).toEqualTypeOf<[bigint, string]>() }) test('initialPageParam', async () => { const options = infiniteReadContractsQueryOptions(config, { allowFailure: false, cacheKey: 'foo', contracts(pageParam) { expectTypeOf(pageParam).toEqualTypeOf(options.initialPageParam) return [ { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }, { address: '0x', abi: abi.wagmiMintExample, functionName: 'tokenURI', args: [123n], }, ] }, query: { initialPageParam: 'bar', getNextPageParam(lastPage, allPages, lastPageParam, allPageParams) { expectTypeOf(lastPage).toEqualTypeOf<[bigint, string]>() expectTypeOf(allPages).toEqualTypeOf<[bigint, string][]>() expectTypeOf(lastPageParam).toEqualTypeOf(options.initialPageParam) expectTypeOf(allPageParams).toEqualTypeOf([options.initialPageParam]) return lastPageParam + 1 }, }, }) const result = await options.queryFn({} as any) expectTypeOf(result).toEqualTypeOf<[bigint, string]>() }) test('behavior: `contracts` after `getNextPageParam`', async () => { const options = infiniteReadContractsQueryOptions(config, { allowFailure: false, cacheKey: 'foo', query: { initialPageParam: 0, getNextPageParam(lastPage, allPages, lastPageParam, allPageParams) { expectTypeOf(lastPage).toEqualTypeOf() expectTypeOf(allPages).toEqualTypeOf() expectTypeOf(lastPageParam).toEqualTypeOf(options.initialPageParam) expectTypeOf(allPageParams).toEqualTypeOf([options.initialPageParam]) return lastPageParam + 1 }, }, contracts(pageParam) { expectTypeOf(pageParam).toEqualTypeOf(options.initialPageParam) return [ { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }, { address: '0x', abi: abi.wagmiMintExample, functionName: 'tokenURI', args: [123n], }, ] }, }) const result = await options.queryFn({} as any) expectTypeOf(result).toEqualTypeOf() }) test('overloads', async () => { const options = infiniteReadContractsQueryOptions(config, { allowFailure: false, cacheKey: 'foo', contracts(pageParam) { expectTypeOf(pageParam).toEqualTypeOf() return [ { address: '0x', abi: abi.viewOverloads, functionName: 'foo', }, { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x'], }, { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x', '0x'], }, ] }, query: { initialPageParam: 0, getNextPageParam(_, allPages) { return allPages.length + 1 }, }, }) const result = await options.queryFn({} as any) expectTypeOf(result).toEqualTypeOf< [ number, string, { foo: `0x${string}` bar: `0x${string}` }, ] >() }) ================================================ FILE: packages/core/src/query/infiniteReadContracts.test.ts ================================================ import { abi, config } from '@wagmi/test' import { expect, test } from 'vitest' import { infiniteReadContractsQueryOptions } from './infiniteReadContracts.js' test('default', () => { expect( infiniteReadContractsQueryOptions(config, { allowFailure: true, batchSize: 1024, blockNumber: 123n, blockTag: 'latest', cacheKey: 'foo', chainId: 1, multicallAddress: '0x', scopeKey: 'bar', contracts(_pageParam) { return [ { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }, { address: '0x', abi: abi.wagmiMintExample, functionName: 'tokenURI', args: [123n], }, ] }, query: { initialPageParam: 0, getNextPageParam(_lastPage, _allPages, lastPageParam, _allPageParams) { return lastPageParam + 1 }, }, }), ).toMatchInlineSnapshot(` { "getNextPageParam": [Function], "initialPageParam": 0, "queryFn": [Function], "queryKey": [ "infiniteReadContracts", { "allowFailure": true, "batchSize": 1024, "blockNumber": 123n, "blockTag": "latest", "cacheKey": "foo", "chainId": 1, "multicallAddress": "0x", "scopeKey": "bar", }, ], } `) }) ================================================ FILE: packages/core/src/query/infiniteReadContracts.ts ================================================ import type { ContractFunctionParameters } from 'viem' import { type ReadContractsErrorType, type ReadContractsParameters, type ReadContractsReturnType, readContracts, } from '../actions/readContracts.js' import type { Config } from '../createConfig.js' import type { ChainIdParameter, ScopeKeyParameter, } from '../types/properties.js' import type { StrictOmit } from '../types/utils.js' import type { InfiniteQueryOptions } from './types.js' import { filterQueryOptions } from './utils.js' export type InfiniteReadContractsOptions< contracts extends readonly unknown[], allowFailure extends boolean, pageParam, config extends Config, > = { cacheKey: string contracts( pageParam: pageParam, ): ReadContractsParameters['contracts'] } & StrictOmit< ReadContractsParameters, 'contracts' > & ScopeKeyParameter export function infiniteReadContractsQueryOptions< config extends Config, const contracts extends readonly ContractFunctionParameters[], allowFailure extends boolean = true, pageParam = unknown, >( config: config, options: InfiniteReadContractsOptions< contracts, allowFailure, pageParam, config > & ChainIdParameter & RequiredPageParamsParameters, ) { return { ...options.query, async queryFn({ pageParam, queryKey }) { const { contracts } = options const { cacheKey: _, scopeKey: _s, ...parameters } = queryKey[1] return (await readContracts(config, { ...parameters, contracts: contracts(pageParam as any), })) as ReadContractsReturnType }, queryKey: infiniteReadContractsQueryKey(options), } as const satisfies InfiniteQueryOptions< InfiniteReadContractsQueryFnData, ReadContractsErrorType, InfiniteReadContractsData, InfiniteReadContractsData, InfiniteReadContractsQueryKey, pageParam > } type RequiredPageParamsParameters< contracts extends readonly unknown[], allowFailure extends boolean, pageParam, > = { query: { initialPageParam: pageParam getNextPageParam( lastPage: InfiniteReadContractsQueryFnData, allPages: InfiniteReadContractsQueryFnData[], lastPageParam: pageParam, allPageParams: pageParam[], ): pageParam | undefined | null } } export type InfiniteReadContractsQueryFnData< contracts extends readonly unknown[], allowFailure extends boolean, > = ReadContractsReturnType export type InfiniteReadContractsData< contracts extends readonly unknown[], allowFailure extends boolean, > = InfiniteReadContractsQueryFnData export function infiniteReadContractsQueryKey< config extends Config, const contracts extends readonly unknown[], allowFailure extends boolean, pageParam, >( options: InfiniteReadContractsOptions< contracts, allowFailure, pageParam, config > & ChainIdParameter & RequiredPageParamsParameters, ) { const { contracts: _, ...parameters } = options return ['infiniteReadContracts', filterQueryOptions(parameters)] as const } export type InfiniteReadContractsQueryKey< contracts extends readonly unknown[], allowFailure extends boolean, pageParam, config extends Config, > = ReturnType< typeof infiniteReadContractsQueryKey< config, contracts, allowFailure, pageParam > > ================================================ FILE: packages/core/src/query/prepareTransactionRequest.test-d.ts ================================================ import { accounts, config } from '@wagmi/test' import { http, parseEther } from 'viem' import { celo, mainnet } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { prepareTransactionRequestQueryOptions } from './prepareTransactionRequest.js' const context = {} as any const targetAccount = accounts[1] test('default', async () => { const options = prepareTransactionRequestQueryOptions(config, { chainId: 1, to: '0x', value: parseEther('1'), }) const response = await options.queryFn(context) const { nonce: _nonce, ...request } = response request.to request.chainId expectTypeOf(response.chainId).toEqualTypeOf<1>() }) test('chain formatters', async () => { const config = createConfig({ chains: [celo, mainnet], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) { const options = prepareTransactionRequestQueryOptions(config, { to: targetAccount, value: parseEther('0.01'), feeCurrency: '0x', }) const request = await options.queryFn(context) if (request.chainId === celo.id) { expectTypeOf(request.chainId).toEqualTypeOf(celo.id) expectTypeOf(request.feeCurrency).toEqualTypeOf< `0x${string}` | undefined >() } } { const options = prepareTransactionRequestQueryOptions(config, { chainId: celo.id, to: targetAccount, value: parseEther('0.01'), feeCurrency: '0x', }) const request = await options.queryFn(context) expectTypeOf(request.chainId).toEqualTypeOf(celo.id) expectTypeOf(request.feeCurrency).toEqualTypeOf<`0x${string}` | undefined>() } { const options = prepareTransactionRequestQueryOptions(config, { chainId: mainnet.id, to: targetAccount, value: parseEther('0.01'), // @ts-expect-error feeCurrency: '0x', }) const request = await options.queryFn(context) expectTypeOf(request.chainId).toEqualTypeOf(mainnet.id) } }) ================================================ FILE: packages/core/src/query/prepareTransactionRequest.test.ts ================================================ import { accounts, chain, config } from '@wagmi/test' import { parseEther, parseGwei } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { expect, test } from 'vitest' import { prepareTransactionRequestQueryOptions } from './prepareTransactionRequest.js' const targetAccount = accounts[0] test('default', () => { expect( prepareTransactionRequestQueryOptions(config, { to: targetAccount, value: parseEther('1'), }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "prepareTransactionRequest", { "to": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "value": 1000000000000000000n, }, ], } `) }) test('parameters: account', () => { expect( prepareTransactionRequestQueryOptions(config, { account: privateKeyToAccount( '0x0123456789012345678901234567890123456789012345678901234567890123', ), to: targetAccount, value: parseEther('1'), }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "prepareTransactionRequest", { "account": { "address": "0x14791697260E4c9A71f18484C9f997B308e59325", "nonceManager": undefined, "publicKey": "0x046655feed4d214c261e0a6b554395596f1f1476a77d999560e5a8df9b8a1a3515217e88dd05e938efdd71b2cce322bf01da96cd42087b236e8f5043157a9c068e", "sign": [Function], "signAuthorization": [Function], "signMessage": [Function], "signTransaction": [Function], "signTypedData": [Function], "source": "privateKey", "type": "local", }, "to": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "value": 1000000000000000000n, }, ], } `) }) test('parameters: data', () => { expect( prepareTransactionRequestQueryOptions(config, { data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: targetAccount, value: parseEther('1'), }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "prepareTransactionRequest", { "data": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "to": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "value": 1000000000000000000n, }, ], } `) }) test('parameters: chainId', () => { expect( prepareTransactionRequestQueryOptions(config, { chainId: chain.mainnet2.id, to: targetAccount, value: parseEther('1'), }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "prepareTransactionRequest", { "chainId": 456, "to": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "value": 1000000000000000000n, }, ], } `) }) test('parameters: nonce', () => { expect( prepareTransactionRequestQueryOptions(config, { nonce: 5, to: targetAccount, value: parseEther('1'), }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "prepareTransactionRequest", { "nonce": 5, "to": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "value": 1000000000000000000n, }, ], } `) }) test('parameters: gasPrice', () => { expect( prepareTransactionRequestQueryOptions(config, { gasPrice: parseGwei('10'), to: targetAccount, value: parseEther('1'), }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "prepareTransactionRequest", { "gasPrice": 10000000000n, "to": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "value": 1000000000000000000n, }, ], } `) }) test('parameters: maxFeePerGas', () => { expect( prepareTransactionRequestQueryOptions(config, { maxFeePerGas: parseGwei('100'), to: targetAccount, value: parseEther('1'), }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "prepareTransactionRequest", { "maxFeePerGas": 100000000000n, "to": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "value": 1000000000000000000n, }, ], } `) }) test('parameters: maxPriorityFeePerGas', () => { expect( prepareTransactionRequestQueryOptions(config, { maxPriorityFeePerGas: parseGwei('5'), to: targetAccount, value: parseEther('1'), }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "prepareTransactionRequest", { "maxPriorityFeePerGas": 5000000000n, "to": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "value": 1000000000000000000n, }, ], } `) }) test('parameters: type', () => { expect( prepareTransactionRequestQueryOptions(config, { type: 'eip1559', to: targetAccount, value: parseEther('1'), }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "prepareTransactionRequest", { "to": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "type": "eip1559", "value": 1000000000000000000n, }, ], } `) }) test('parameters: parameters', () => { expect( prepareTransactionRequestQueryOptions(config, { parameters: ['gas'], to: targetAccount, value: parseEther('1'), }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "prepareTransactionRequest", { "parameters": [ "gas", ], "to": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "value": 1000000000000000000n, }, ], } `) }) ================================================ FILE: packages/core/src/query/prepareTransactionRequest.ts ================================================ import type { PrepareTransactionRequestRequest as viem_PrepareTransactionRequestRequest } from 'viem' import { type PrepareTransactionRequestErrorType, type PrepareTransactionRequestParameters, type PrepareTransactionRequestReturnType, prepareTransactionRequest, } from '../actions/prepareTransactionRequest.js' import type { Config } from '../createConfig.js' import type { SelectChains } from '../types/chain.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { UnionExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type PrepareTransactionRequestOptions< config extends Config, chainId extends config['chains'][number]['id'] | undefined, request extends viem_PrepareTransactionRequestRequest< SelectChains[0], SelectChains[0] >, selectData = PrepareTransactionRequestData, > = UnionExactPartial< PrepareTransactionRequestParameters > & ScopeKeyParameter & QueryParameter< PrepareTransactionRequestQueryFnData, PrepareTransactionRequestErrorType, selectData, PrepareTransactionRequestQueryKey > export function prepareTransactionRequestQueryOptions< config extends Config, chainId extends config['chains'][number]['id'] | undefined, request extends viem_PrepareTransactionRequestRequest< SelectChains[0], SelectChains[0] >, selectData = PrepareTransactionRequestData, >( config: config, options: PrepareTransactionRequestOptions< config, chainId, request, selectData > = {} as any, ): PrepareTransactionRequestQueryOptions { return { ...options.query, enabled: Boolean(options.to && (options.query?.enabled ?? true)), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.to) throw new Error('to is required') return prepareTransactionRequest(config, { ...(parameters as any), to: parameters.to, }) as unknown as Promise< PrepareTransactionRequestQueryFnData > }, queryKey: prepareTransactionRequestQueryKey( options, ) as PrepareTransactionRequestQueryKey, } } export type PrepareTransactionRequestQueryFnData< config extends Config, chainId extends config['chains'][number]['id'] | undefined, request extends viem_PrepareTransactionRequestRequest< SelectChains[0], SelectChains[0] >, > = PrepareTransactionRequestReturnType export type PrepareTransactionRequestData< config extends Config, chainId extends config['chains'][number]['id'] | undefined, request extends viem_PrepareTransactionRequestRequest< SelectChains[0], SelectChains[0] >, > = PrepareTransactionRequestQueryFnData export function prepareTransactionRequestQueryKey< config extends Config, chainId extends config['chains'][number]['id'] | undefined, request extends viem_PrepareTransactionRequestRequest< SelectChains[0], SelectChains[0] >, >( options: UnionExactPartial< PrepareTransactionRequestParameters > & ScopeKeyParameter = {} as any, ) { return ['prepareTransactionRequest', filterQueryOptions(options)] as const } export type PrepareTransactionRequestQueryKey< config extends Config, chainId extends config['chains'][number]['id'] | undefined, request extends viem_PrepareTransactionRequestRequest< SelectChains[0], SelectChains[0] >, > = ReturnType< typeof prepareTransactionRequestQueryKey > export type PrepareTransactionRequestQueryOptions< config extends Config, chainId extends config['chains'][number]['id'] | undefined, request extends viem_PrepareTransactionRequestRequest< SelectChains[0], SelectChains[0] >, selectData = PrepareTransactionRequestData, > = QueryOptions< PrepareTransactionRequestQueryFnData, PrepareTransactionRequestErrorType, selectData, PrepareTransactionRequestQueryKey > ================================================ FILE: packages/core/src/query/readContract.test-d.ts ================================================ import { abi, config } from '@wagmi/test' import { assertType, expectTypeOf, test } from 'vitest' import { readContractQueryOptions } from './readContract.js' const context = {} as any test('default', async () => { const options = readContractQueryOptions(config, { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }) const result = await options.queryFn(context) expectTypeOf(result).toEqualTypeOf() readContractQueryOptions(config, { address: '0x', abi: abi.erc20, // @ts-expect-error functionName: 'foo', args: ['0x'], }) }) test('overloads', async () => { { const options = readContractQueryOptions(config, { address: '0x', abi: abi.viewOverloads, functionName: 'foo', }) const result = await options.queryFn(context) assertType(result) } { const options = readContractQueryOptions(config, { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: [], }) const result = await options.queryFn(context) assertType(result) } { const options = readContractQueryOptions(config, { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x'], }) const result = await options.queryFn(context) assertType(result) } { const options = readContractQueryOptions(config, { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x', '0x'], }) const result = await options.queryFn(context) assertType<{ foo: `0x${string}` bar: `0x${string}` }>(result) } }) test('deployless read (bytecode)', async () => { const options = readContractQueryOptions(config, { code: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }) const result = await options.queryFn(context) expectTypeOf(result).toEqualTypeOf() }) test('deployless read (factory)', async () => { const options = readContractQueryOptions(config, { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], factory: '0x', factoryData: '0x', }) const result = await options.queryFn(context) expectTypeOf(result).toEqualTypeOf() }) ================================================ FILE: packages/core/src/query/readContract.test.ts ================================================ import { abi, config } from '@wagmi/test' import { expect, test } from 'vitest' import { readContractQueryOptions } from './readContract.js' test('default', () => { expect( readContractQueryOptions(config, { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "readContract", { "address": "0x", "args": [ "0x", ], "functionName": "balanceOf", }, ], "structuralSharing": [Function], } `) }) ================================================ FILE: packages/core/src/query/readContract.ts ================================================ import type { Abi, ContractFunctionArgs, ContractFunctionName } from 'viem' import { type ReadContractErrorType, type ReadContractParameters, type ReadContractReturnType, readContract, } from '../actions/readContract.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { UnionExactPartial } from '../types/utils.js' import { filterQueryOptions, structuralSharing } from './utils.js' export type ReadContractOptions< abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs, config extends Config, selectData = ReadContractData, > = UnionExactPartial> & ScopeKeyParameter & QueryParameter< ReadContractQueryFnData, ReadContractErrorType, selectData, ReadContractQueryKey > export function readContractQueryOptions< config extends Config, const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, const args extends ContractFunctionArgs, selectData = ReadContractData, >( config: config, options: ReadContractOptions = {} as any, ): ReadContractQueryOptions { return { ...options.query, enabled: Boolean( Boolean(options.address || ('code' in options && options.code)) && options.abi && options.functionName && (options.query?.enabled ?? true), ), // TODO: Support `signal` once Viem actions allow passthrough // https://tkdodo.eu/blog/why-you-want-react-query#bonus-cancellation queryFn: async (context) => { if (!options.abi) throw new Error('abi is required') const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.functionName) throw new Error('functionName is required') const result = await readContract(config, { ...(parameters as any), abi: options.abi, address: parameters.address, code: 'code' in parameters && parameters.code ? parameters.code : undefined, functionName: parameters.functionName, }) return result as ReadContractData }, queryKey: readContractQueryKey(options as any) as any, structuralSharing, } as ReadContractQueryOptions } export type ReadContractQueryFnData< abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs, > = ReadContractReturnType export type ReadContractData< abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs, > = ReadContractQueryFnData export function readContractQueryKey< config extends Config, const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs, >( options: UnionExactPartial< ReadContractParameters > & ScopeKeyParameter = {} as any, ) { return ['readContract', filterQueryOptions(options)] as const } export type ReadContractQueryKey< abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs, config extends Config, > = ReturnType> export type ReadContractQueryOptions< abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs, config extends Config, selectData = ReadContractData, > = QueryOptions< ReadContractQueryFnData, ReadContractErrorType, selectData, ReadContractQueryKey > ================================================ FILE: packages/core/src/query/readContracts.test-d.ts ================================================ import { abi, config } from '@wagmi/test' import { assertType, expectTypeOf, test } from 'vitest' import { readContractsQueryOptions } from './readContracts.js' const context = {} as any test('default', async () => { const options = readContractsQueryOptions(config, { contracts: [ { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }, { address: '0x', abi: abi.wagmiMintExample, functionName: 'tokenURI', args: [123n], }, ], }) const result = await options.queryFn({} as any) expectTypeOf(result).toEqualTypeOf< [ ( | { error: Error; result?: undefined; status: 'failure' } | { error?: undefined; result: bigint; status: 'success' } ), ( | { error: Error; result?: undefined; status: 'failure' } | { error?: undefined; result: string; status: 'success' } ), ] >() }) test('allowFailure: false', async () => { const options = readContractsQueryOptions(config, { allowFailure: false, contracts: [ { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }, { address: '0x', abi: abi.wagmiMintExample, functionName: 'tokenURI', args: [123n], }, ], }) const result = await options.queryFn({} as any) expectTypeOf(result).toEqualTypeOf<[bigint, string]>() }) test('overloads', async () => { { const options = readContractsQueryOptions(config, { allowFailure: false, contracts: [ { address: '0x', abi: abi.viewOverloads, functionName: 'foo' }, ], }) const result = await options.queryFn(context) assertType<[number]>(result) } { const options = readContractsQueryOptions(config, { allowFailure: false, contracts: [ { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: [], }, ], }) const result = await options.queryFn(context) assertType<[number]>(result) } { const options = readContractsQueryOptions(config, { allowFailure: false, contracts: [ { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x'], }, ], }) const result = await options.queryFn(context) assertType<[string]>(result) } { const options = readContractsQueryOptions(config, { allowFailure: false, contracts: [ { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x', '0x'], }, ], }) const result = await options.queryFn(context) assertType< [ { foo: `0x${string}` bar: `0x${string}` }, ] >(result) } }) ================================================ FILE: packages/core/src/query/readContracts.test.ts ================================================ import { abi, config } from '@wagmi/test' import { expect, test } from 'vitest' import { readContractsQueryKey, readContractsQueryOptions, } from './readContracts.js' test('default', () => { expect( readContractsQueryOptions(config, { contracts: [ { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }, ], }), ).toMatchInlineSnapshot(` { "queryFn": [Function], "queryKey": [ "readContracts", { "contracts": [ { "address": "0x", "args": [ "0x", ], "functionName": "balanceOf", }, ], }, ], } `) }) test('behavior: query key should not change when contracts have explicit chainIds', () => { const contracts = [ { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], chainId: 1, }, { address: '0x', abi: abi.erc20, functionName: 'totalSupply', chainId: 1, }, ] as const const queryKeyChain1 = readContractsQueryKey({ contracts, chainId: 1 }) const queryKeyChain10 = readContractsQueryKey({ contracts, chainId: 10 }) expect(queryKeyChain1).toEqual(queryKeyChain10) }) ================================================ FILE: packages/core/src/query/readContracts.ts ================================================ import type { ContractFunctionParameters, MulticallParameters as viem_MulticallParameters, } from 'viem' import { type ReadContractsErrorType, type ReadContractsReturnType, readContracts, } from '../actions/readContracts.js' import type { Config } from '../createConfig.js' import type { ChainIdParameter, ScopeKeyParameter, } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type ReadContractsOptions< contracts extends readonly unknown[], allowFailure extends boolean, config extends Config, selectData = ReadContractsData, > = ExactPartial< viem_MulticallParameters< contracts, allowFailure, { optional: true; properties: ChainIdParameter } > > & ScopeKeyParameter & QueryParameter< ReadContractsQueryFnData, ReadContractsErrorType, selectData, ReadContractsQueryKey > export function readContractsQueryOptions< config extends Config, const contracts extends readonly unknown[], allowFailure extends boolean = true, selectData = ReadContractsData, >( config: config, options: ReadContractsOptions & ChainIdParameter = {}, ): ReadContractsQueryOptions { return { ...options.query, queryFn: async (context) => { const contracts: ContractFunctionParameters[] = [] const length = context.queryKey[1].contracts.length for (let i = 0; i < length; i++) { const contract = context.queryKey[1].contracts[i]! const abi = (options.contracts?.[i] as ContractFunctionParameters).abi contracts.push({ ...contract, abi }) } const { scopeKey: _, ...parameters } = context.queryKey[1] return readContracts(config, { ...parameters, contracts, }) as Promise> }, queryKey: readContractsQueryKey(options), } } export type ReadContractsQueryFnData< contracts extends readonly unknown[], allowFailure extends boolean, > = ReadContractsReturnType export type ReadContractsData< contracts extends readonly unknown[], allowFailure extends boolean, > = ReadContractsQueryFnData export function readContractsQueryKey< config extends Config, const contracts extends readonly unknown[], allowFailure extends boolean, >( options: ExactPartial< viem_MulticallParameters< contracts, allowFailure, { optional: true; properties: ChainIdParameter } > > & ScopeKeyParameter & ChainIdParameter = {}, ) { const contracts = [] let hasContractWithoutChainId = false for (const contract of (options.contracts ?? []) as (ContractFunctionParameters & { chainId: number })[]) { const { abi: _, ...rest } = contract if (rest.chainId === undefined) hasContractWithoutChainId = true const chainId = rest.chainId ?? options.chainId contracts.push({ ...rest, ...(chainId ? { chainId } : {}) }) } const { chainId: _, ...rest } = options return [ 'readContracts', filterQueryOptions({ ...rest, ...(hasContractWithoutChainId && options.chainId ? { chainId: options.chainId } : {}), contracts, }), ] as const } export type ReadContractsQueryKey< contracts extends readonly unknown[], allowFailure extends boolean, config extends Config, > = ReturnType> export type ReadContractsQueryOptions< contracts extends readonly unknown[], allowFailure extends boolean, config extends Config, selectData = ReadContractsData, > = QueryOptions< ReadContractsQueryFnData, ReadContractsErrorType, selectData, ReadContractsQueryKey > ================================================ FILE: packages/core/src/query/reconnect.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { reconnectMutationOptions } from './reconnect.js' test('default', () => { expect(reconnectMutationOptions(config)).toMatchInlineSnapshot(` { "mutationFn": [Function], "mutationKey": [ "reconnect", ], } `) }) ================================================ FILE: packages/core/src/query/reconnect.ts ================================================ import type { MutationOptions } from '@tanstack/query-core' import { type ReconnectErrorType, type ReconnectParameters, type ReconnectReturnType, reconnect, } from '../actions/reconnect.js' import type { Config } from '../createConfig.js' import type { MutationParameter } from '../types/query.js' import type { Compute } from '../types/utils.js' import type { Mutate, MutateAsync } from './types.js' export type ReconnectOptions = MutationParameter< ReconnectData, ReconnectErrorType, ReconnectVariables, context > export function reconnectMutationOptions( config: Config, options: ReconnectOptions = {}, ): ReconnectMutationOptions { return { ...(options.mutation as any), mutationFn(variables) { return reconnect(config, variables) }, mutationKey: ['reconnect'], } } export type ReconnectMutationOptions = MutationOptions< ReconnectData, ReconnectErrorType, ReconnectVariables > export type ReconnectData = Compute export type ReconnectVariables = ReconnectParameters | undefined export type ReconnectMutate = Mutate< ReconnectData, ReconnectErrorType, ReconnectVariables, context > export type ReconnectMutateAsync = MutateAsync< ReconnectData, ReconnectErrorType, ReconnectVariables, context > ================================================ FILE: packages/core/src/query/sendCalls.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { sendCallsMutationOptions } from './sendCalls.js' test('default', () => { expect(sendCallsMutationOptions(config)).toMatchInlineSnapshot(` { "mutationFn": [Function], "mutationKey": [ "sendCalls", ], } `) }) ================================================ FILE: packages/core/src/query/sendCalls.ts ================================================ import type { MutateOptions, MutationOptions } from '@tanstack/query-core' import { type SendCallsErrorType, type SendCallsParameters, type SendCallsReturnType, sendCalls, } from '../actions/sendCalls.js' import type { Config } from '../createConfig.js' import type { MutationParameter } from '../types/query.js' import type { Compute } from '../types/utils.js' export type SendCallsOptions< config extends Config, context = unknown, > = MutationParameter< SendCallsData, SendCallsErrorType, SendCallsVariables, context > export function sendCallsMutationOptions( config: config, options: SendCallsOptions = {}, ): SendCallsMutationOptions { return { ...(options.mutation as any), mutationFn(variables) { return sendCalls(config, variables) }, mutationKey: ['sendCalls'], } } export type SendCallsMutationOptions = MutationOptions< SendCallsData, SendCallsErrorType, SendCallsVariables > export type SendCallsData = Compute export type SendCallsVariables< config extends Config, chainId extends config['chains'][number]['id'], calls extends readonly unknown[] = readonly unknown[], > = SendCallsParameters export type SendCallsMutate = < const calls extends readonly unknown[], chainId extends config['chains'][number]['id'], >( variables: SendCallsVariables, options?: | Compute< MutateOptions< SendCallsData, SendCallsErrorType, Compute>, context > > | undefined, ) => void export type SendCallsMutateAsync = < const calls extends readonly unknown[], chainId extends config['chains'][number]['id'], >( variables: SendCallsVariables, options?: | Compute< MutateOptions< SendCallsData, SendCallsErrorType, Compute>, context > > | undefined, ) => Promise ================================================ FILE: packages/core/src/query/sendCallsSync.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { sendCallsSyncMutationOptions } from './sendCallsSync.js' test('default', () => { expect(sendCallsSyncMutationOptions(config)).toMatchInlineSnapshot(` { "mutationFn": [Function], "mutationKey": [ "sendCallsSync", ], } `) }) ================================================ FILE: packages/core/src/query/sendCallsSync.ts ================================================ import type { MutateOptions, MutationOptions } from '@tanstack/query-core' import { type SendCallsSyncErrorType, type SendCallsSyncParameters, type SendCallsSyncReturnType, sendCallsSync, } from '../actions/sendCallsSync.js' import type { Config } from '../createConfig.js' import type { MutationParameter } from '../types/query.js' import type { Compute } from '../types/utils.js' export type SendCallsSyncOptions< config extends Config, context = unknown, > = MutationParameter< SendCallsSyncData, SendCallsSyncErrorType, SendCallsSyncVariables, context > export function sendCallsSyncMutationOptions( config: config, options: SendCallsSyncOptions = {}, ): SendCallsSyncMutationOptions { return { ...(options.mutation as any), mutationFn(variables) { return sendCallsSync(config, variables) }, mutationKey: ['sendCallsSync'], } } export type SendCallsSyncMutationOptions = MutationOptions< SendCallsSyncData, SendCallsSyncErrorType, SendCallsSyncVariables > export type SendCallsSyncData = Compute export type SendCallsSyncVariables< config extends Config, chainId extends config['chains'][number]['id'], calls extends readonly unknown[] = readonly unknown[], > = SendCallsSyncParameters export type SendCallsSyncMutate = < const calls extends readonly unknown[], chainId extends config['chains'][number]['id'], >( variables: SendCallsSyncVariables, options?: | Compute< MutateOptions< SendCallsSyncData, SendCallsSyncErrorType, Compute>, context > > | undefined, ) => void export type SendCallsSyncMutateAsync< config extends Config, context = unknown, > = < const calls extends readonly unknown[], chainId extends config['chains'][number]['id'], >( variables: SendCallsSyncVariables, options?: | Compute< MutateOptions< SendCallsSyncData, SendCallsSyncErrorType, Compute>, context > > | undefined, ) => Promise ================================================ FILE: packages/core/src/query/sendTransaction.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { sendTransactionMutationOptions } from './sendTransaction.js' test('default', () => { expect(sendTransactionMutationOptions(config)).toMatchInlineSnapshot(` { "mutationFn": [Function], "mutationKey": [ "sendTransaction", ], } `) }) ================================================ FILE: packages/core/src/query/sendTransaction.ts ================================================ import type { MutateOptions, MutationOptions } from '@tanstack/query-core' import { type SendTransactionErrorType, type SendTransactionParameters, type SendTransactionReturnType, sendTransaction, } from '../actions/sendTransaction.js' import type { Config } from '../createConfig.js' import type { MutationParameter } from '../types/query.js' import type { Compute } from '../types/utils.js' export type SendTransactionOptions< config extends Config, context = unknown, > = MutationParameter< SendTransactionData, SendTransactionErrorType, SendTransactionVariables, context > export function sendTransactionMutationOptions( config: config, options: SendTransactionOptions = {}, ): SendTransactionMutationOptions { return { ...(options.mutation as any), mutationFn(variables) { return sendTransaction(config, variables) }, mutationKey: ['sendTransaction'], } } export type SendTransactionMutationOptions = MutationOptions< SendTransactionData, SendTransactionErrorType, SendTransactionVariables > export type SendTransactionData = Compute export type SendTransactionVariables< config extends Config, chainId extends config['chains'][number]['id'], > = SendTransactionParameters export type SendTransactionMutate = < chainId extends config['chains'][number]['id'], >( variables: SendTransactionVariables, options?: | Compute< MutateOptions< SendTransactionData, SendTransactionErrorType, Compute>, context > > | undefined, ) => void export type SendTransactionMutateAsync< config extends Config, context = unknown, > = ( variables: SendTransactionVariables, options?: | Compute< MutateOptions< SendTransactionData, SendTransactionErrorType, Compute>, context > > | undefined, ) => Promise ================================================ FILE: packages/core/src/query/sendTransactionSync.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { sendTransactionSyncMutationOptions } from './sendTransactionSync.js' test('default', () => { expect(sendTransactionSyncMutationOptions(config)).toMatchInlineSnapshot(` { "mutationFn": [Function], "mutationKey": [ "sendTransactionSync", ], } `) }) ================================================ FILE: packages/core/src/query/sendTransactionSync.ts ================================================ import type { MutateOptions, MutationOptions } from '@tanstack/query-core' import { type SendTransactionSyncErrorType, type SendTransactionSyncParameters, type SendTransactionSyncReturnType, sendTransactionSync, } from '../actions/sendTransactionSync.js' import type { Config } from '../createConfig.js' import type { MutationParameter } from '../types/query.js' import type { Compute } from '../types/utils.js' export type SendTransactionSyncOptions< config extends Config, context = unknown, > = MutationParameter< SendTransactionSyncData, SendTransactionSyncErrorType, SendTransactionSyncVariables, context > export function sendTransactionSyncMutationOptions< config extends Config, context, >( config: config, options: SendTransactionSyncOptions = {}, ): SendTransactionSyncMutationOptions { return { ...(options.mutation as any), mutationFn(variables) { return sendTransactionSync(config, variables) }, mutationKey: ['sendTransactionSync'], } } export type SendTransactionSyncMutationOptions = MutationOptions< SendTransactionSyncData, SendTransactionSyncErrorType, SendTransactionSyncVariables > export type SendTransactionSyncData = Compute export type SendTransactionSyncVariables< config extends Config, chainId extends config['chains'][number]['id'], > = SendTransactionSyncParameters export type SendTransactionSyncMutate< config extends Config, context = unknown, > = ( variables: SendTransactionSyncVariables, options?: | Compute< MutateOptions< SendTransactionSyncData, SendTransactionSyncErrorType, Compute>, context > > | undefined, ) => void export type SendTransactionSyncMutateAsync< config extends Config, context = unknown, > = ( variables: SendTransactionSyncVariables, options?: | Compute< MutateOptions< SendTransactionSyncData, SendTransactionSyncErrorType, Compute>, context > > | undefined, ) => Promise ================================================ FILE: packages/core/src/query/showCallsStatus.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { showCallsStatusMutationOptions } from './showCallsStatus.js' test('default', () => { expect(showCallsStatusMutationOptions(config)).toMatchInlineSnapshot(` { "mutationFn": [Function], "mutationKey": [ "showCallsStatus", ], } `) }) ================================================ FILE: packages/core/src/query/showCallsStatus.ts ================================================ import type { MutateOptions, MutationOptions } from '@tanstack/query-core' import { type ShowCallsStatusErrorType, type ShowCallsStatusParameters, type ShowCallsStatusReturnType, showCallsStatus, } from '../actions/showCallsStatus.js' import type { Config } from '../createConfig.js' import type { MutationParameter } from '../types/query.js' import type { Compute } from '../types/utils.js' export type ShowCallsStatusOptions = MutationParameter< ShowCallsStatusData, ShowCallsStatusErrorType, ShowCallsStatusVariables, context > export function showCallsStatusMutationOptions( config: config, options: ShowCallsStatusOptions = {}, ): ShowCallsStatusMutationOptions { return { ...(options.mutation as any), mutationFn(variables) { return showCallsStatus(config, variables) }, mutationKey: ['showCallsStatus'], } } export type ShowCallsStatusMutationOptions = MutationOptions< ShowCallsStatusData, ShowCallsStatusErrorType, ShowCallsStatusVariables > export type ShowCallsStatusData = Compute export type ShowCallsStatusVariables = ShowCallsStatusParameters export type ShowCallsStatusMutate = ( variables: ShowCallsStatusVariables, options?: | Compute< MutateOptions< ShowCallsStatusData, ShowCallsStatusErrorType, Compute, context > > | undefined, ) => void export type ShowCallsStatusMutateAsync = ( variables: ShowCallsStatusVariables, options?: | Compute< MutateOptions< ShowCallsStatusData, ShowCallsStatusErrorType, Compute, context > > | undefined, ) => Promise ================================================ FILE: packages/core/src/query/signMessage.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { signMessageMutationOptions } from './signMessage.js' test('default', () => { expect(signMessageMutationOptions(config)).toMatchInlineSnapshot(` { "mutationFn": [Function], "mutationKey": [ "signMessage", ], } `) }) ================================================ FILE: packages/core/src/query/signMessage.ts ================================================ import type { MutationOptions } from '@tanstack/query-core' import { type SignMessageErrorType, type SignMessageParameters, type SignMessageReturnType, signMessage, } from '../actions/signMessage.js' import type { Config } from '../createConfig.js' import type { MutationParameter } from '../types/query.js' import type { Compute } from '../types/utils.js' import type { Mutate, MutateAsync } from './types.js' export type SignMessageOptions = MutationParameter< SignMessageData, SignMessageErrorType, SignMessageVariables, context > export function signMessageMutationOptions( config: Config, options: SignMessageOptions = {}, ): SignMessageMutationOptions { return { ...(options.mutation as any), mutationFn(variables) { return signMessage(config, variables) }, mutationKey: ['signMessage'], } } export type SignMessageMutationOptions = MutationOptions< SignMessageData, SignMessageErrorType, SignMessageVariables > export type SignMessageData = SignMessageReturnType export type SignMessageVariables = Compute export type SignMessageMutate = Mutate< SignMessageData, SignMessageErrorType, SignMessageVariables, context > export type SignMessageMutateAsync = MutateAsync< SignMessageData, SignMessageErrorType, SignMessageVariables, context > ================================================ FILE: packages/core/src/query/signTransaction.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { signTransactionMutationOptions } from './signTransaction.js' test('default', () => { expect(signTransactionMutationOptions(config)).toMatchInlineSnapshot(` { "mutationFn": [Function], "mutationKey": [ "signTransaction", ], } `) }) ================================================ FILE: packages/core/src/query/signTransaction.ts ================================================ import type { MutateOptions, MutationOptions } from '@tanstack/query-core' import type { SignTransactionRequest as viem_SignTransactionRequest } from 'viem' import { type SignTransactionErrorType, type SignTransactionParameters, type SignTransactionReturnType, signTransaction, } from '../actions/signTransaction.js' import type { Config } from '../createConfig.js' import type { SelectChains } from '../types/chain.js' import type { MutationParameter } from '../types/query.js' import type { Compute } from '../types/utils.js' export type SignTransactionOptions< config extends Config, chainId extends config['chains'][number]['id'], request extends viem_SignTransactionRequest< SelectChains[0], SelectChains[0] >, context = unknown, > = MutationParameter< SignTransactionData, SignTransactionErrorType, SignTransactionVariables, context > export function signTransactionMutationOptions< config extends Config, chainId extends config['chains'][number]['id'], request extends viem_SignTransactionRequest< SelectChains[0], SelectChains[0] >, context, >( config: config, options: SignTransactionOptions = {}, ): SignTransactionMutationOptions { return { ...(options.mutation as any), mutationFn(variables) { return signTransaction(config, variables as any) }, mutationKey: ['signTransaction'], } } export type SignTransactionMutationOptions< config extends Config, chainId extends config['chains'][number]['id'], request extends viem_SignTransactionRequest< SelectChains[0], SelectChains[0] >, > = MutationOptions< SignTransactionData, SignTransactionErrorType, SignTransactionVariables > export type SignTransactionData< config extends Config, chainId extends config['chains'][number]['id'], request extends viem_SignTransactionRequest< SelectChains[0], SelectChains[0] >, // > = Compute> > = SignTransactionReturnType export type SignTransactionVariables< config extends Config, chainId extends config['chains'][number]['id'], request extends viem_SignTransactionRequest< SelectChains[0], SelectChains[0] >, > = SignTransactionParameters export type SignTransactionMutate = < chainId extends config['chains'][number]['id'], const request extends viem_SignTransactionRequest< SelectChains[0], SelectChains[0] >, >( variables: SignTransactionVariables & request, options?: | Compute< MutateOptions< SignTransactionData, SignTransactionErrorType, Compute>, context > > | undefined, ) => void export type SignTransactionMutateAsync< config extends Config, context = unknown, > = < chainId extends config['chains'][number]['id'], const request extends viem_SignTransactionRequest< SelectChains[0], SelectChains[0] >, >( variables: SignTransactionVariables & request, options?: | Compute< MutateOptions< SignTransactionData, SignTransactionErrorType, Compute>, context > > | undefined, ) => Promise> ================================================ FILE: packages/core/src/query/signTypedData.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { signTypedDataMutationOptions } from './signTypedData.js' test('default', () => { expect(signTypedDataMutationOptions(config)).toMatchInlineSnapshot(` { "mutationFn": [Function], "mutationKey": [ "signTypedData", ], } `) }) ================================================ FILE: packages/core/src/query/signTypedData.ts ================================================ import type { MutateOptions, MutationOptions } from '@tanstack/query-core' import type { TypedData } from 'viem' import { type SignTypedDataErrorType, type SignTypedDataParameters, type SignTypedDataReturnType, signTypedData, } from '../actions/signTypedData.js' import type { Config } from '../createConfig.js' import type { MutationParameter } from '../types/query.js' import type { Compute } from '../types/utils.js' export type SignTypedDataOptions = MutationParameter< SignTypedDataData, SignTypedDataErrorType, SignTypedDataVariables, context > export function signTypedDataMutationOptions( config: config, options: SignTypedDataOptions = {}, ): SignTypedDataMutationOptions { return { ...(options.mutation as any), mutationFn(variables) { return signTypedData(config, variables) }, mutationKey: ['signTypedData'], } } export type SignTypedDataMutationOptions = MutationOptions< SignTypedDataData, SignTypedDataErrorType, SignTypedDataVariables > export type SignTypedDataData = Compute export type SignTypedDataVariables< typedData extends TypedData | Record = TypedData, primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData, /// primaryTypes = typedData extends TypedData ? keyof typedData : string, > = SignTypedDataParameters export type SignTypedDataMutate = < const typedData extends TypedData | Record, primaryType extends keyof typedData | 'EIP712Domain', >( variables: SignTypedDataVariables, options?: | MutateOptions< SignTypedDataData, SignTypedDataErrorType, SignTypedDataVariables< typedData, primaryType, // use `primaryType` to make sure it's not union of all possible primary types primaryType >, context > | undefined, ) => void export type SignTypedDataMutateAsync = < const typedData extends TypedData | Record, primaryType extends keyof typedData | 'EIP712Domain', >( variables: SignTypedDataVariables, options?: | MutateOptions< SignTypedDataData, SignTypedDataErrorType, SignTypedDataVariables< typedData, primaryType, // use `primaryType` to make sure it's not union of all possible primary types primaryType >, context > | undefined, ) => Promise ================================================ FILE: packages/core/src/query/simulateContract.test-d.ts ================================================ import { abi, config } from '@wagmi/test' import { type Address, http } from 'viem' import { celo, mainnet } from 'viem/chains' import { assertType, expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { type SimulateContractOptions, simulateContractQueryOptions, } from './simulateContract.js' const context = {} as any test('default', async () => { const options = simulateContractQueryOptions(config, { address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], chainId: 1, }) const response = await options.queryFn(context) expectTypeOf(response).toMatchTypeOf<{ result: boolean request: { chainId: 1 abi: readonly [ { readonly name: 'transferFrom' readonly type: 'function' readonly stateMutability: 'nonpayable' readonly inputs: readonly [ { readonly type: 'address'; readonly name: 'sender' }, { readonly type: 'address'; readonly name: 'recipient' }, { readonly type: 'uint256'; readonly name: 'amount' }, ] readonly outputs: readonly [{ type: 'bool' }] }, ] functionName: 'transferFrom' args: readonly [Address, Address, bigint] } }>() }) test('chain formatters', () => { const config = createConfig({ chains: [mainnet, celo], transports: { [celo.id]: http(), [mainnet.id]: http() }, }) type Result = SimulateContractOptions< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config, (typeof config)['chains'][number]['id'] > expectTypeOf().toMatchTypeOf<{ chainId?: typeof celo.id | typeof mainnet.id | undefined feeCurrency?: `0x${string}` | undefined }>() simulateContractQueryOptions(config, { address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], feeCurrency: '0x', }) type Result2 = SimulateContractOptions< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config, typeof celo.id > expectTypeOf().toMatchTypeOf<{ functionName?: 'approve' | 'transfer' | 'transferFrom' | undefined args?: readonly [Address, Address, bigint] | undefined feeCurrency?: `0x${string}` | undefined }>() simulateContractQueryOptions(config, { chainId: celo.id, address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], feeCurrency: '0x', }) type Result3 = SimulateContractOptions< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config, typeof mainnet.id > expectTypeOf().toMatchTypeOf<{ functionName?: 'approve' | 'transfer' | 'transferFrom' | undefined args?: readonly [Address, Address, bigint] | undefined }>() expectTypeOf().not.toMatchTypeOf<{ feeCurrency?: `0x${string}` | undefined }>() simulateContractQueryOptions(config, { chainId: mainnet.id, address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], // @ts-expect-error feeCurrency: '0x', }) }) test('overloads', async () => { { const options = simulateContractQueryOptions(config, { address: '0x', abi: abi.writeOverloads, functionName: 'foo', }) const result = await options.queryFn(context) assertType(result.result) } { const options = simulateContractQueryOptions(config, { address: '0x', abi: abi.writeOverloads, functionName: 'foo', args: [], }) const result = await options.queryFn(context) assertType(result.result) } { const options = simulateContractQueryOptions(config, { address: '0x', abi: abi.writeOverloads, functionName: 'foo', args: ['0x'], }) const result = await options.queryFn(context) assertType(result.result) } { const options = simulateContractQueryOptions(config, { address: '0x', abi: abi.writeOverloads, functionName: 'foo', args: ['0x', '0x'], //^? }) const result = await options.queryFn(context) assertType<{ foo: `0x${string}` bar: `0x${string}` }>(result.result) } }) ================================================ FILE: packages/core/src/query/simulateContract.test.ts ================================================ import { abi, config } from '@wagmi/test' import { expect, test } from 'vitest' import { simulateContractQueryOptions } from './simulateContract.js' test('default', () => { expect( simulateContractQueryOptions(config, { address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], }), ).toMatchInlineSnapshot(` { "enabled": false, "queryFn": [Function], "queryKey": [ "simulateContract", { "address": "0x", "args": [ "0x", "0x", 123n, ], "functionName": "transferFrom", }, ], } `) }) ================================================ FILE: packages/core/src/query/simulateContract.ts ================================================ import type { Abi, ContractFunctionArgs, ContractFunctionName } from 'viem' import { type SimulateContractErrorType, type SimulateContractParameters, type SimulateContractReturnType, simulateContract, } from '../actions/simulateContract.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { UnionExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type SimulateContractOptions< abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName >, config extends Config, chainId extends config['chains'][number]['id'] | undefined, selectData = SimulateContractData, > = UnionExactPartial< SimulateContractParameters > & ScopeKeyParameter & QueryParameter< SimulateContractQueryFnData, SimulateContractErrorType, selectData, SimulateContractQueryKey > export function simulateContractQueryOptions< const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, const args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName >, config extends Config, chainId extends config['chains'][number]['id'] | undefined, selectData = SimulateContractData, >( config: config, options: SimulateContractOptions< abi, functionName, args, config, chainId, selectData > = {} as any, ): SimulateContractQueryOptions< abi, functionName, args, config, chainId, selectData > { return { ...options.query, enabled: Boolean( options.abi && options.address && options.connector && options.functionName && (options.query?.enabled ?? true), ), queryFn: async (context) => { if (!options.abi) throw new Error('abi is required') if (!options.connector) throw new Error('connector is required') const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.address) throw new Error('address is required') if (!parameters.functionName) throw new Error('functionName is required') return simulateContract(config, { ...(parameters as any), abi: options.abi, address: parameters.address, connector: options.connector, functionName: parameters.functionName, }) }, queryKey: simulateContractQueryKey(options as any), } } export type SimulateContractQueryFnData< abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName >, config extends Config, chainId extends config['chains'][number]['id'] | undefined, > = SimulateContractReturnType export type SimulateContractData< abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName >, config extends Config, chainId extends config['chains'][number]['id'] | undefined, > = SimulateContractQueryFnData export function simulateContractQueryKey< abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, const args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName >, const config extends Config, chainId extends config['chains'][number]['id'] | undefined, >( options: UnionExactPartial< SimulateContractParameters > & ScopeKeyParameter = {} as any, ) { const { connector: _, ...rest } = options return ['simulateContract', filterQueryOptions(rest)] as const } export type SimulateContractQueryKey< abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName >, config extends Config, chainId extends config['chains'][number]['id'] | undefined, > = ReturnType< typeof simulateContractQueryKey > export type SimulateContractQueryOptions< abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName >, config extends Config, chainId extends config['chains'][number]['id'] | undefined, selectData = SimulateContractData, > = QueryOptions< SimulateContractQueryFnData, SimulateContractErrorType, selectData, SimulateContractQueryKey > ================================================ FILE: packages/core/src/query/switchChain.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { switchChainMutationOptions } from './switchChain.js' test('default', () => { expect(switchChainMutationOptions(config)).toMatchInlineSnapshot(` { "mutationFn": [Function], "mutationKey": [ "switchChain", ], } `) }) ================================================ FILE: packages/core/src/query/switchChain.ts ================================================ import type { MutateOptions, MutationOptions } from '@tanstack/query-core' import { type SwitchChainErrorType, type SwitchChainParameters, type SwitchChainReturnType, switchChain, } from '../actions/switchChain.js' import type { Config } from '../createConfig.js' import type { MutationParameter } from '../types/query.js' import type { Compute } from '../types/utils.js' export type SwitchChainOptions< config extends Config, context = unknown, > = MutationParameter< SwitchChainData, SwitchChainErrorType, SwitchChainVariables, context > export function switchChainMutationOptions( config: config, options: SwitchChainOptions = {}, ): SwitchChainMutationOptions { return { ...(options.mutation as any), mutationFn(variables) { return switchChain(config, variables) }, mutationKey: ['switchChain'], } } export type SwitchChainMutationOptions = MutationOptions< SwitchChainData, SwitchChainErrorType, SwitchChainVariables > export type SwitchChainData< config extends Config, chainId extends config['chains'][number]['id'], > = Compute> export type SwitchChainVariables< config extends Config, chainId extends config['chains'][number]['id'], > = Compute> export type SwitchChainMutate = < chainId extends config['chains'][number]['id'], >( variables: SwitchChainVariables, options?: | Compute< MutateOptions< SwitchChainData, SwitchChainErrorType, Compute>, context > > | undefined, ) => void export type SwitchChainMutateAsync = < chainId extends config['chains'][number]['id'], >( variables: SwitchChainVariables, options?: | Compute< MutateOptions< SwitchChainData, SwitchChainErrorType, Compute>, context > > | undefined, ) => Promise> ================================================ FILE: packages/core/src/query/switchConnection.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { switchConnectionMutationOptions } from './switchConnection.js' test('default', () => { expect(switchConnectionMutationOptions(config)).toMatchInlineSnapshot(` { "mutationFn": [Function], "mutationKey": [ "switchConnection", ], } `) }) ================================================ FILE: packages/core/src/query/switchConnection.ts ================================================ import type { MutationOptions } from '@tanstack/query-core' import { type SwitchConnectionErrorType, type SwitchConnectionParameters, type SwitchConnectionReturnType, switchConnection, } from '../actions/switchConnection.js' import type { Config } from '../createConfig.js' import type { MutationParameter } from '../types/query.js' import type { Compute } from '../types/utils.js' import type { Mutate, MutateAsync } from './types.js' export type SwitchConnectionOptions< config extends Config, context = unknown, > = MutationParameter< SwitchConnectionData, SwitchConnectionErrorType, SwitchConnectionVariables, context > export function switchConnectionMutationOptions( config: config, options: SwitchConnectionOptions = {}, ): SwitchConnectionMutationOptions { return { ...(options.mutation as any), mutationFn(variables) { return switchConnection(config, variables) }, mutationKey: ['switchConnection'], } } export type SwitchConnectionMutationOptions = MutationOptions< SwitchConnectionData, SwitchConnectionErrorType, SwitchConnectionVariables > export type SwitchConnectionData = Compute< SwitchConnectionReturnType > export type SwitchConnectionVariables = Compute export type SwitchConnectionMutate< config extends Config, context = unknown, > = Mutate< SwitchConnectionData, SwitchConnectionErrorType, SwitchConnectionVariables, context > export type SwitchConnectionMutateAsync< config extends Config, context = unknown, > = MutateAsync< SwitchConnectionData, SwitchConnectionErrorType, SwitchConnectionVariables, context > ================================================ FILE: packages/core/src/query/types.ts ================================================ import type { DefaultError, InfiniteQueryObserverOptions, MutateOptions, QueryFunction, QueryKey, } from '@tanstack/query-core' import type { Compute, StrictOmit } from '../types/utils.js' export type InfiniteQueryOptions< queryFnData = unknown, error = DefaultError, data = queryFnData, queryData = queryFnData, queryKey extends QueryKey = QueryKey, pageParam = unknown, /// options extends InfiniteQueryObserverOptions< queryFnData, error, data, queryData, queryKey, pageParam > = InfiniteQueryObserverOptions< queryFnData, error, data, queryData, queryKey, pageParam >, > = Compute< // `queryFn` doesn't pass through `pageParam` correctly StrictOmit & { queryFn?( context: QueryFunctionContext, ): options['queryFn'] extends (...args: any) => any ? ReturnType> : unknown } > // `QueryFunctionContext` not exported resulting in TS2742 error so grabbing from `QueryFunction` type QueryFunctionContext< TQueryKey extends QueryKey = QueryKey, TPageParam = never, > = Parameters>[0] export type Mutate< data = unknown, error = unknown, variables = void, context = unknown, > = ( ...args: Parameters, context>> ) => void export type MutateAsync< data = unknown, error = unknown, variables = void, context = unknown, > = MutateFn, context> type MutateFn< data = unknown, error = unknown, variables = void, context = unknown, > = undefined extends variables ? ( variables?: variables, options?: | Compute> | undefined, ) => Promise : ( variables: variables, options?: | Compute> | undefined, ) => Promise ================================================ FILE: packages/core/src/query/utils.test.ts ================================================ import { abi } from '@wagmi/test' import { expect, expectTypeOf, test } from 'vitest' import { filterQueryOptions, structuralSharing } from './utils.js' test('structuralSharing', () => { expect( structuralSharing({ foo: 'bar' }, { foo: 'bar' }), ).toMatchInlineSnapshot(` { "foo": "bar", } `) expect( structuralSharing({ foo: 'bar' }, { foo: 'baz' }), ).toMatchInlineSnapshot(` { "foo": "baz", } `) }) test('filterQueryOptions', () => { const options = filterQueryOptions({ foo: 'bar', baz: true, abi: abi.erc20, connector: undefined, }) expectTypeOf(options).toEqualTypeOf<{ foo: string baz: boolean connectorUid?: string | undefined }>() expect(options).toMatchInlineSnapshot(` { "baz": true, "foo": "bar", } `) }) ================================================ FILE: packages/core/src/query/utils.ts ================================================ import { type QueryKey, replaceEqualDeep } from '@tanstack/query-core' import type { Connector } from '../createConfig.js' import type { Compute, StrictOmit } from '../types/utils.js' export function structuralSharing( oldData: data | undefined, newData: data, ): data { return replaceEqualDeep(oldData, newData) } export function hashFn(queryKey: QueryKey): string { return JSON.stringify(queryKey, (_, value) => { if (isPlainObject(value)) return Object.keys(value) .sort() .reduce((result, key) => { result[key] = value[key] return result }, {} as any) if (typeof value === 'bigint') return value.toString() return value }) } // biome-ignore lint/complexity/noBannedTypes: using function isPlainObject(value: any): value is Object { if (!hasObjectPrototype(value)) { return false } // If has modified constructor const ctor = value.constructor if (typeof ctor === 'undefined') return true // If has modified prototype const prot = ctor.prototype if (!hasObjectPrototype(prot)) return false // If constructor does not have an Object-specific method // biome-ignore lint/suspicious/noPrototypeBuiltins: using if (!prot.hasOwnProperty('isPrototypeOf')) return false // Most likely a plain Object return true } function hasObjectPrototype(o: any): boolean { return Object.prototype.toString.call(o) === '[object Object]' } export function filterQueryOptions< type extends Record & { connector?: Connector | undefined }, >( options: type, ): Compute< StrictOmit & (type extends { connector?: Connector | undefined } ? { connectorUid?: string } : unknown) > { // destructuring is super fast // biome-ignore format: no formatting const { // import('@tanstack/query-core').QueryOptions // biome-ignore lint/correctness/noUnusedVariables: tossing _defaulted, behavior, gcTime, initialData, initialDataUpdatedAt, maxPages, meta, networkMode, queryFn, queryHash, queryKey, queryKeyHashFn, retry, retryDelay, structuralSharing, // import('@tanstack/query-core').InfiniteQueryObserverOptions // biome-ignore lint/correctness/noUnusedVariables: tossing getPreviousPageParam, getNextPageParam, initialPageParam, // import('@tanstack/react-query').UseQueryOptions // biome-ignore lint/correctness/noUnusedVariables: tossing _optimisticResults, enabled, notifyOnChangeProps, placeholderData, refetchInterval, refetchIntervalInBackground, refetchOnMount, refetchOnReconnect, refetchOnWindowFocus, retryOnMount, select, staleTime, suspense, throwOnError, //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // wagmi //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/correctness/noUnusedVariables: tossing abi, config, connector, query, watch, ...rest } = options if (connector) return { connectorUid: connector?.uid, ...rest } as never return rest as never } ================================================ FILE: packages/core/src/query/verifyMessage.test.ts ================================================ import { accounts, chain, config } from '@wagmi/test' import { expect, test } from 'vitest' import { verifyMessageQueryOptions } from './verifyMessage.js' const address = accounts[0] test('default', () => { expect( verifyMessageQueryOptions(config, { address, message: 'This is a test message for viem!', signature: '0xefd5fb29a274ea6682673d8b3caa9263e936d48d486e5df68893003e0a76496439594d12245008c6fba1c8e3ef28241cffe1bef27ff6bca487b167f261f329251c', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "verifyMessage", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "message": "This is a test message for viem!", "signature": "0xefd5fb29a274ea6682673d8b3caa9263e936d48d486e5df68893003e0a76496439594d12245008c6fba1c8e3ef28241cffe1bef27ff6bca487b167f261f329251c", }, ], } `) }) test('parameters: chainId', () => { expect( verifyMessageQueryOptions(config, { chainId: chain.mainnet2.id, address, message: 'This is a test message for viem!', signature: '0xefd5fb29a274ea6682673d8b3caa9263e936d48d486e5df68893003e0a76496439594d12245008c6fba1c8e3ef28241cffe1bef27ff6bca487b167f261f329251c', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "verifyMessage", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 456, "message": "This is a test message for viem!", "signature": "0xefd5fb29a274ea6682673d8b3caa9263e936d48d486e5df68893003e0a76496439594d12245008c6fba1c8e3ef28241cffe1bef27ff6bca487b167f261f329251c", }, ], } `) }) test('parameters: blockNumber', () => { expect( verifyMessageQueryOptions(config, { blockNumber: 1234567890n, address, message: 'This is a test message for viem!', signature: '0xefd5fb29a274ea6682673d8b3caa9263e936d48d486e5df68893003e0a76496439594d12245008c6fba1c8e3ef28241cffe1bef27ff6bca487b167f261f329251c', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "verifyMessage", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "blockNumber": 1234567890n, "message": "This is a test message for viem!", "signature": "0xefd5fb29a274ea6682673d8b3caa9263e936d48d486e5df68893003e0a76496439594d12245008c6fba1c8e3ef28241cffe1bef27ff6bca487b167f261f329251c", }, ], } `) }) test('parameters: blockTag', () => { expect( verifyMessageQueryOptions(config, { blockTag: 'safe', address, message: 'This is a test message for viem!', signature: '0xefd5fb29a274ea6682673d8b3caa9263e936d48d486e5df68893003e0a76496439594d12245008c6fba1c8e3ef28241cffe1bef27ff6bca487b167f261f329251c', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "verifyMessage", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "blockTag": "safe", "message": "This is a test message for viem!", "signature": "0xefd5fb29a274ea6682673d8b3caa9263e936d48d486e5df68893003e0a76496439594d12245008c6fba1c8e3ef28241cffe1bef27ff6bca487b167f261f329251c", }, ], } `) }) ================================================ FILE: packages/core/src/query/verifyMessage.ts ================================================ import { type VerifyMessageErrorType, type VerifyMessageParameters, type VerifyMessageReturnType, verifyMessage, } from '../actions/verifyMessage.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type VerifyMessageOptions< config extends Config, selectData = VerifyMessageData, > = Compute> & ScopeKeyParameter> & QueryParameter< VerifyMessageQueryFnData, VerifyMessageErrorType, selectData, VerifyMessageQueryKey > export function verifyMessageQueryOptions< config extends Config, selectData = VerifyMessageData, >( config: config, options: VerifyMessageOptions = {}, ): VerifyMessageQueryOptions { return { ...options.query, enabled: Boolean( options.address && options.message && options.signature && (options.query?.enabled ?? true), ), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.address) throw new Error('address is required') if (!parameters.message) throw new Error('message is required') if (!parameters.signature) throw new Error('signature is required') const verified = await verifyMessage(config, { ...parameters, address: parameters.address, message: parameters.message, signature: parameters.signature, }) return verified ?? null }, queryKey: verifyMessageQueryKey(options), } } export type VerifyMessageQueryFnData = VerifyMessageReturnType export type VerifyMessageData = VerifyMessageQueryFnData export function verifyMessageQueryKey( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { return ['verifyMessage', filterQueryOptions(options)] as const } export type VerifyMessageQueryKey = ReturnType< typeof verifyMessageQueryKey > export type VerifyMessageQueryOptions< config extends Config, selectData = VerifyMessageData, > = QueryOptions< VerifyMessageQueryFnData, VerifyMessageErrorType, selectData, VerifyMessageQueryKey > ================================================ FILE: packages/core/src/query/verifyTypedData.test-d.ts ================================================ import { config, typedData } from '@wagmi/test' import { test } from 'vitest' import { verifyTypedDataQueryOptions } from './verifyTypedData.js' test('default', async () => { verifyTypedDataQueryOptions(config, { address: '0x', ...typedData.basic, primaryType: 'Mail', signature: '0x', }) verifyTypedDataQueryOptions(config, { address: '0x', ...typedData.basic, // @ts-expect-error primaryType: 'foobarbaz', signature: '0x', }) }) ================================================ FILE: packages/core/src/query/verifyTypedData.test.ts ================================================ import { accounts, chain, config, typedData } from '@wagmi/test' import { expect, test } from 'vitest' import { verifyTypedDataQueryOptions } from './verifyTypedData.js' const address = accounts[0] test('default', () => { expect( verifyTypedDataQueryOptions(config, { address, ...typedData.basic, primaryType: 'Mail', signature: '0xefd5fb29a274ea6682673d8b3caa9263e936d48d486e5df68893003e0a76496439594d12245008c6fba1c8e3ef28241cffe1bef27ff6bca487b167f261f329251c', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "verifyTypedData", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "domain": { "chainId": 1, "name": "Ether Mail", "verifyingContract": "0x0000000000000000000000000000000000000000", "version": "1", }, "message": { "contents": "Hello, Bob!", "from": { "name": "Cow", "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", }, "to": { "name": "Bob", "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", }, }, "primaryType": "Mail", "signature": "0xefd5fb29a274ea6682673d8b3caa9263e936d48d486e5df68893003e0a76496439594d12245008c6fba1c8e3ef28241cffe1bef27ff6bca487b167f261f329251c", "types": { "Mail": [ { "name": "from", "type": "Person", }, { "name": "to", "type": "Person", }, { "name": "contents", "type": "string", }, ], "Person": [ { "name": "name", "type": "string", }, { "name": "wallet", "type": "address", }, ], }, }, ], } `) }) test('parameters: chainId', () => { expect( verifyTypedDataQueryOptions(config, { ...typedData.basic, domain: { ...typedData.basic.domain, chainId: chain.mainnet2.id, }, chainId: chain.mainnet2.id, address, primaryType: 'Mail', signature: '0xefd5fb29a274ea6682673d8b3caa9263e936d48d486e5df68893003e0a76496439594d12245008c6fba1c8e3ef28241cffe1bef27ff6bca487b167f261f329251c', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "verifyTypedData", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 456, "domain": { "chainId": 456, "name": "Ether Mail", "verifyingContract": "0x0000000000000000000000000000000000000000", "version": "1", }, "message": { "contents": "Hello, Bob!", "from": { "name": "Cow", "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", }, "to": { "name": "Bob", "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", }, }, "primaryType": "Mail", "signature": "0xefd5fb29a274ea6682673d8b3caa9263e936d48d486e5df68893003e0a76496439594d12245008c6fba1c8e3ef28241cffe1bef27ff6bca487b167f261f329251c", "types": { "Mail": [ { "name": "from", "type": "Person", }, { "name": "to", "type": "Person", }, { "name": "contents", "type": "string", }, ], "Person": [ { "name": "name", "type": "string", }, { "name": "wallet", "type": "address", }, ], }, }, ], } `) }) test('parameters: blockNumber', () => { expect( verifyTypedDataQueryOptions(config, { blockNumber: 1234567890n, address, ...typedData.basic, primaryType: 'Mail', signature: '0xefd5fb29a274ea6682673d8b3caa9263e936d48d486e5df68893003e0a76496439594d12245008c6fba1c8e3ef28241cffe1bef27ff6bca487b167f261f329251c', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "verifyTypedData", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "blockNumber": 1234567890n, "domain": { "chainId": 1, "name": "Ether Mail", "verifyingContract": "0x0000000000000000000000000000000000000000", "version": "1", }, "message": { "contents": "Hello, Bob!", "from": { "name": "Cow", "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", }, "to": { "name": "Bob", "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", }, }, "primaryType": "Mail", "signature": "0xefd5fb29a274ea6682673d8b3caa9263e936d48d486e5df68893003e0a76496439594d12245008c6fba1c8e3ef28241cffe1bef27ff6bca487b167f261f329251c", "types": { "Mail": [ { "name": "from", "type": "Person", }, { "name": "to", "type": "Person", }, { "name": "contents", "type": "string", }, ], "Person": [ { "name": "name", "type": "string", }, { "name": "wallet", "type": "address", }, ], }, }, ], } `) }) test('parameters: blockTag', () => { expect( verifyTypedDataQueryOptions(config, { blockTag: 'pending', address, ...typedData.basic, primaryType: 'Mail', signature: '0xefd5fb29a274ea6682673d8b3caa9263e936d48d486e5df68893003e0a76496439594d12245008c6fba1c8e3ef28241cffe1bef27ff6bca487b167f261f329251c', }), ).toMatchInlineSnapshot(` { "enabled": true, "queryFn": [Function], "queryKey": [ "verifyTypedData", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "blockTag": "pending", "domain": { "chainId": 1, "name": "Ether Mail", "verifyingContract": "0x0000000000000000000000000000000000000000", "version": "1", }, "message": { "contents": "Hello, Bob!", "from": { "name": "Cow", "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", }, "to": { "name": "Bob", "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", }, }, "primaryType": "Mail", "signature": "0xefd5fb29a274ea6682673d8b3caa9263e936d48d486e5df68893003e0a76496439594d12245008c6fba1c8e3ef28241cffe1bef27ff6bca487b167f261f329251c", "types": { "Mail": [ { "name": "from", "type": "Person", }, { "name": "to", "type": "Person", }, { "name": "contents", "type": "string", }, ], "Person": [ { "name": "name", "type": "string", }, { "name": "wallet", "type": "address", }, ], }, }, ], } `) }) ================================================ FILE: packages/core/src/query/verifyTypedData.ts ================================================ import type { TypedData } from 'viem' import { type VerifyTypedDataErrorType, type VerifyTypedDataParameters, type VerifyTypedDataReturnType, verifyTypedData, } from '../actions/verifyTypedData.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { UnionExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type VerifyTypedDataOptions< typedData extends TypedData | Record, primaryType extends keyof typedData | 'EIP712Domain', config extends Config, selectData = VerifyTypedDataData, > = UnionExactPartial< VerifyTypedDataParameters > & ScopeKeyParameter & QueryParameter< VerifyTypedDataQueryFnData, VerifyTypedDataErrorType, selectData, VerifyTypedDataQueryKey > export function verifyTypedDataQueryOptions< const typedData extends TypedData | Record, primaryType extends keyof typedData | 'EIP712Domain', config extends Config, selectData = VerifyTypedDataData, >( config: config, options: VerifyTypedDataOptions< typedData, primaryType, config, selectData > = {} as any, ): VerifyTypedDataQueryOptions { return { ...options.query, enabled: Boolean( options.address && options.message && options.primaryType && options.signature && options.types && (options.query?.enabled ?? true), ), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.address) throw new Error('address is required') if (!parameters.message) throw new Error('message is required') if (!parameters.primaryType) throw new Error('primaryType is required') if (!parameters.signature) throw new Error('signature is required') if (!parameters.types) throw new Error('types is required') const verified = await verifyTypedData(config, { ...(parameters as any), address: parameters.address, message: parameters.message, primaryType: parameters.primaryType, signature: parameters.signature, types: parameters.types, }) return verified ?? null }, queryKey: verifyTypedDataQueryKey(options as any) as any, } } export type VerifyTypedDataQueryFnData = VerifyTypedDataReturnType export type VerifyTypedDataData = VerifyTypedDataQueryFnData export function verifyTypedDataQueryKey< config extends Config, const typedData extends TypedData | Record, primaryType extends keyof typedData | 'EIP712Domain', >( options: UnionExactPartial< VerifyTypedDataParameters > & ScopeKeyParameter = {} as any, ) { return ['verifyTypedData', filterQueryOptions(options)] as const } export type VerifyTypedDataQueryKey< typedData extends TypedData | Record, primaryType extends keyof typedData | 'EIP712Domain', config extends Config, > = ReturnType> export type VerifyTypedDataQueryOptions< typedData extends TypedData | Record, primaryType extends keyof typedData | 'EIP712Domain', config extends Config, selectData = VerifyTypedDataData, > = QueryOptions< VerifyTypedDataQueryFnData, VerifyTypedDataErrorType, selectData, VerifyTypedDataQueryKey > ================================================ FILE: packages/core/src/query/waitForCallsStatus.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { waitForCallsStatusQueryOptions } from './waitForCallsStatus.js' test('default', () => { expect( waitForCallsStatusQueryOptions(config, { id: '0x0000000000000000000000000000000000000000', }), ).toMatchInlineSnapshot(` { "enabled": false, "queryFn": [Function], "queryKey": [ "callsStatus", { "id": "0x0000000000000000000000000000000000000000", }, ], } `) }) ================================================ FILE: packages/core/src/query/waitForCallsStatus.ts ================================================ import { type WaitForCallsStatusErrorType, type WaitForCallsStatusParameters, type WaitForCallsStatusReturnType, waitForCallsStatus, } from '../actions/waitForCallsStatus.js' import type { Config } from '../createConfig.js' import { filterQueryOptions } from '../query/utils.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' export type WaitForCallsStatusOptions = Compute & ScopeKeyParameter> & QueryParameter< WaitForCallsStatusQueryFnData, WaitForCallsStatusErrorType, selectData, WaitForCallsStatusQueryKey > export function waitForCallsStatusQueryOptions< config extends Config, selectData = WaitForCallsStatusData, >( config: config, options: WaitForCallsStatusOptions, ): WaitForCallsStatusQueryOptions { return { ...options.query, enabled: Boolean( options.id && options.connector?.getProvider && (options.query?.enabled ?? true), ), queryFn: async (context) => { if (!options.connector?.getProvider) throw new Error('connector is required') const [, { connectorUid: _, scopeKey: __, ...parameters }] = context.queryKey if (!parameters.id) throw new Error('id is required') const status = await waitForCallsStatus(config, { ...parameters, id: parameters.id, }) return status }, queryKey: waitForCallsStatusQueryKey(options), } } export type WaitForCallsStatusQueryFnData = WaitForCallsStatusReturnType export type WaitForCallsStatusData = WaitForCallsStatusQueryFnData export function waitForCallsStatusQueryKey( options: Compute< ExactPartial & ScopeKeyParameter > = {}, ) { return ['callsStatus', filterQueryOptions(options)] as const } export type WaitForCallsStatusQueryKey = ReturnType< typeof waitForCallsStatusQueryKey > export type WaitForCallsStatusQueryOptions< selectData = WaitForCallsStatusData, > = QueryOptions< WaitForCallsStatusQueryFnData, WaitForCallsStatusErrorType, selectData, WaitForCallsStatusQueryKey > ================================================ FILE: packages/core/src/query/waitForTransactionReceipt.test-d.ts ================================================ import { http } from 'viem' import { mainnet, zkSync } from 'viem/chains' import type { ZkSyncL2ToL1Log, ZkSyncLog } from 'viem/zksync' import { expectTypeOf, test } from 'vitest' import { createConfig } from '../createConfig.js' import { waitForTransactionReceiptQueryOptions } from './waitForTransactionReceipt.js' const context = {} as any test('chain formatters', async () => { const config = createConfig({ chains: [mainnet, zkSync], transports: { [mainnet.id]: http(), [zkSync.id]: http() }, }) const options = waitForTransactionReceiptQueryOptions(config, { hash: '0x123', }) const result = await options.queryFn(context) if (result.chainId === zkSync.id) { expectTypeOf(result.l1BatchNumber).toEqualTypeOf() expectTypeOf(result.l1BatchTxIndex).toEqualTypeOf() expectTypeOf(result.logs).toEqualTypeOf() expectTypeOf(result.l2ToL1Logs).toEqualTypeOf() } // @ts-expect-error result.l1BatchNumber }) test('chainId', async () => { const config = createConfig({ chains: [zkSync], transports: { [zkSync.id]: http() }, }) const options = waitForTransactionReceiptQueryOptions(config, { hash: '0x123', chainId: zkSync.id, }) const result = await options.queryFn(context) expectTypeOf(result.l1BatchNumber).toEqualTypeOf() expectTypeOf(result.l1BatchTxIndex).toEqualTypeOf() expectTypeOf(result.logs).toEqualTypeOf() expectTypeOf(result.l2ToL1Logs).toEqualTypeOf() }) ================================================ FILE: packages/core/src/query/waitForTransactionReceipt.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { waitForTransactionReceiptQueryOptions } from './waitForTransactionReceipt.js' test('default', () => { expect( waitForTransactionReceiptQueryOptions(config, {}), ).toMatchInlineSnapshot(` { "enabled": false, "queryFn": [Function], "queryKey": [ "waitForTransactionReceipt", {}, ], } `) }) ================================================ FILE: packages/core/src/query/waitForTransactionReceipt.ts ================================================ import { type WaitForTransactionReceiptErrorType, type WaitForTransactionReceiptParameters, type WaitForTransactionReceiptReturnType, waitForTransactionReceipt, } from '../actions/waitForTransactionReceipt.js' import type { Config } from '../createConfig.js' import type { ScopeKeyParameter } from '../types/properties.js' import type { QueryOptions, QueryParameter } from '../types/query.js' import type { Compute, ExactPartial } from '../types/utils.js' import { filterQueryOptions } from './utils.js' export type WaitForTransactionReceiptOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = WaitForTransactionReceiptData, > = Compute< ExactPartial> & ScopeKeyParameter > & QueryParameter< WaitForTransactionReceiptQueryFnData, WaitForTransactionReceiptErrorType, selectData, WaitForTransactionReceiptQueryKey > export function waitForTransactionReceiptQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = WaitForTransactionReceiptData, >( config: config, options: WaitForTransactionReceiptOptions = {}, ): WaitForTransactionReceiptQueryOptions { return { ...options.query, enabled: Boolean(options.hash && (options.query?.enabled ?? true)), queryFn: async (context) => { const [, { scopeKey: _, ...parameters }] = context.queryKey if (!parameters.hash) throw new Error('hash is required') return waitForTransactionReceipt(config, { ...parameters, onReplaced: options.onReplaced, hash: parameters.hash, }) as unknown as Promise< WaitForTransactionReceiptReturnType > }, queryKey: waitForTransactionReceiptQueryKey(options), } } export type WaitForTransactionReceiptQueryFnData< config extends Config, chainId extends config['chains'][number]['id'], > = WaitForTransactionReceiptReturnType export type WaitForTransactionReceiptData< config extends Config, chainId extends config['chains'][number]['id'], > = WaitForTransactionReceiptQueryFnData export function waitForTransactionReceiptQueryKey< config extends Config, chainId extends config['chains'][number]['id'], >( options: Compute< ExactPartial> & ScopeKeyParameter > = {}, ) { const { onReplaced: _, ...rest } = options return ['waitForTransactionReceipt', filterQueryOptions(rest)] as const } export type WaitForTransactionReceiptQueryKey< config extends Config, chainId extends config['chains'][number]['id'], > = ReturnType> export type WaitForTransactionReceiptQueryOptions< config extends Config, chainId extends config['chains'][number]['id'], selectData = WaitForTransactionReceiptData, > = QueryOptions< WaitForTransactionReceiptQueryFnData, WaitForTransactionReceiptErrorType, selectData, WaitForTransactionReceiptQueryKey > ================================================ FILE: packages/core/src/query/watchAsset.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { watchAssetMutationOptions } from './watchAsset.js' test('default', () => { expect(watchAssetMutationOptions(config)).toMatchInlineSnapshot(` { "mutationFn": [Function], "mutationKey": [ "watchAsset", ], } `) }) ================================================ FILE: packages/core/src/query/watchAsset.ts ================================================ import type { MutationOptions } from '@tanstack/query-core' import { type WatchAssetErrorType, type WatchAssetParameters, type WatchAssetReturnType, watchAsset, } from '../actions/watchAsset.js' import type { Config } from '../createConfig.js' import type { MutationParameter } from '../types/query.js' import type { Compute } from '../types/utils.js' import type { Mutate, MutateAsync } from './types.js' export type WatchAssetOptions = MutationParameter< WatchAssetData, WatchAssetErrorType, WatchAssetVariables, context > export function watchAssetMutationOptions( config: Config, options: WatchAssetOptions = {}, ): WatchAssetMutationOptions { return { ...(options.mutation as any), mutationFn(variables) { return watchAsset(config, variables) }, mutationKey: ['watchAsset'], } } export type WatchAssetMutationOptions = MutationOptions< WatchAssetData, WatchAssetErrorType, WatchAssetVariables > export type WatchAssetData = WatchAssetReturnType export type WatchAssetVariables = Compute export type WatchAssetMutate = Mutate< WatchAssetData, WatchAssetErrorType, WatchAssetVariables, context > export type WatchAssetMutateAsync = MutateAsync< WatchAssetData, WatchAssetErrorType, WatchAssetVariables, context > ================================================ FILE: packages/core/src/query/writeContract.test-d.ts ================================================ import { http } from 'viem' import { writeContract } from 'viem/actions' import { base } from 'viem/chains' import { test } from 'vitest' import { createConfig } from '../createConfig.js' import type { WriteContractMutate } from './writeContract.js' // https://github.com/wevm/wagmi/issues/3981 test('gh#3981', () => { const config = createConfig({ chains: [base], transports: { [base.id]: http(), }, }) const abi = [ { type: 'function', name: 'example1', inputs: [ { name: 'exampleName', type: 'address', internalType: 'address' }, ], outputs: [], stateMutability: 'payable', }, { type: 'function', name: 'example2', inputs: [ { name: 'exampleName', type: 'address', internalType: 'address' }, ], outputs: [], stateMutability: 'nonpayable', }, ] as const const write: WriteContractMutate = () => {} write({ abi, address: '0x...', functionName: 'example1', args: ['0x...'], value: 123n, }) write({ abi: [ { type: 'function', name: 'example1', inputs: [ { name: 'exampleName', type: 'address', internalType: 'address' }, ], outputs: [], stateMutability: 'payable', }, { type: 'function', name: 'example2', inputs: [ { name: 'exampleName', type: 'address', internalType: 'address' }, ], outputs: [], stateMutability: 'nonpayable', }, ] as const, address: '0x...', functionName: 'example1', args: ['0x...'], value: 123n, }) write({ abi, address: '0x...', functionName: 'example2', args: ['0x...'], // @ts-expect-error value: 123n, }) write({ abi: [ { type: 'function', name: 'example1', inputs: [ { name: 'exampleName', type: 'address', internalType: 'address' }, ], outputs: [], stateMutability: 'payable', }, { type: 'function', name: 'example2', inputs: [ { name: 'exampleName', type: 'address', internalType: 'address' }, ], outputs: [], stateMutability: 'nonpayable', }, ], address: '0x...', functionName: 'example1', args: ['0x...'], value: 123n, }) const client = config.getClient({ chainId: base.id }) writeContract(client, { abi, address: '0x...', account: '0x...', functionName: 'example1', args: ['0x...'], value: 123n, }) writeContract(client, { abi: [ { type: 'function', name: 'example1', inputs: [ { name: 'exampleName', type: 'address', internalType: 'address' }, ], outputs: [], stateMutability: 'payable', }, { type: 'function', name: 'example2', inputs: [ { name: 'exampleName', type: 'address', internalType: 'address' }, ], outputs: [], stateMutability: 'nonpayable', }, ] as const, address: '0x...', account: '0x...', functionName: 'example1', args: ['0x...'], value: 123n, }) }) ================================================ FILE: packages/core/src/query/writeContract.test.ts ================================================ import { config } from '@wagmi/test' import { expect, test } from 'vitest' import { writeContractMutationOptions } from './writeContract.js' test('default', () => { expect(writeContractMutationOptions(config)).toMatchInlineSnapshot(` { "mutationFn": [Function], "mutationKey": [ "writeContract", ], } `) }) ================================================ FILE: packages/core/src/query/writeContract.ts ================================================ import type { MutateOptions, MutationOptions } from '@tanstack/query-core' import type { Abi, ContractFunctionArgs, ContractFunctionName } from 'viem' import { type WriteContractErrorType, type WriteContractParameters, type WriteContractReturnType, writeContract, } from '../actions/writeContract.js' import type { Config } from '../createConfig.js' import type { MutationParameter } from '../types/query.js' import type { Compute } from '../types/utils.js' export type WriteContractOptions< config extends Config, context = unknown, > = MutationParameter< WriteContractData, WriteContractErrorType, WriteContractVariables< Abi, string, readonly unknown[], config, config['chains'][number]['id'] >, context > export function writeContractMutationOptions( config: config, options: WriteContractOptions = {}, ): WriteContractMutationOptions { return { ...(options.mutation as any), mutationFn(variables) { return writeContract(config, variables) }, mutationKey: ['writeContract'], } } export type WriteContractMutationOptions = MutationOptions< WriteContractData, WriteContractErrorType, WriteContractVariables< Abi, string, readonly unknown[], config, config['chains'][number]['id'] > > export type WriteContractData = Compute export type WriteContractVariables< abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName >, config extends Config, chainId extends config['chains'][number]['id'], /// allFunctionNames = ContractFunctionName, > = WriteContractParameters< abi, functionName, args, config, chainId, allFunctionNames > export type WriteContractMutate = < const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName >, chainId extends config['chains'][number]['id'], >( variables: WriteContractVariables, options?: | MutateOptions< WriteContractData, WriteContractErrorType, WriteContractVariables< abi, functionName, args, config, chainId, // use `functionName` to make sure it's not union of all possible function names functionName >, context > | undefined, ) => void export type WriteContractMutateAsync< config extends Config, context = unknown, > = < const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName >, chainId extends config['chains'][number]['id'], >( variables: WriteContractVariables, options?: | MutateOptions< WriteContractData, WriteContractErrorType, WriteContractVariables< abi, functionName, args, config, chainId, // use `functionName` to make sure it's not union of all possible function names functionName >, context > | undefined, ) => Promise ================================================ FILE: packages/core/src/query/writeContractSync.ts ================================================ import type { MutateOptions, MutationOptions } from '@tanstack/query-core' import type { Abi, ContractFunctionArgs, ContractFunctionName } from 'viem' import { type WriteContractSyncErrorType, type WriteContractSyncParameters, type WriteContractSyncReturnType, writeContractSync, } from '../actions/writeContractSync.js' import type { Config } from '../createConfig.js' import type { MutationParameter } from '../types/query.js' import type { Compute } from '../types/utils.js' export type WriteContractSyncOptions< config extends Config, context = unknown, > = MutationParameter< WriteContractSyncData, WriteContractSyncErrorType, WriteContractSyncVariables< Abi, string, readonly unknown[], config, config['chains'][number]['id'] >, context > export function writeContractSyncMutationOptions< config extends Config, context, >( config: config, options: WriteContractSyncOptions = {}, ): WriteContractSyncMutationOptions { return { ...(options.mutation as any), mutationFn(variables) { return writeContractSync(config, variables) }, mutationKey: ['writeContractSync'], } } export type WriteContractSyncMutationOptions = MutationOptions< WriteContractSyncData, WriteContractSyncErrorType, WriteContractSyncVariables< Abi, string, readonly unknown[], config, config['chains'][number]['id'] > > export type WriteContractSyncData = Compute export type WriteContractSyncVariables< abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName >, config extends Config, chainId extends config['chains'][number]['id'], > = WriteContractSyncParameters export type WriteContractSyncMutate< config extends Config, context = unknown, > = < const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName >, chainId extends config['chains'][number]['id'], >( variables: WriteContractSyncVariables< abi, functionName, args, config, chainId >, options?: | MutateOptions< WriteContractSyncData, WriteContractSyncErrorType, WriteContractSyncVariables, context > | undefined, ) => void export type WriteContractSyncMutateAsync< config extends Config, context = unknown, > = < const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName >, chainId extends config['chains'][number]['id'], >( variables: WriteContractSyncVariables< abi, functionName, args, config, chainId >, options?: | MutateOptions< WriteContractSyncData, WriteContractSyncErrorType, WriteContractSyncVariables, context > | undefined, ) => Promise ================================================ FILE: packages/core/src/tempo/AGENTS.md ================================================ # Agent Guidelines Agent guidance for `@wagmi/core/tempo`. > **Communication Style**: Be brief, concise. Maximize information density, minimize tokens. Incomplete sentences acceptable when clear. Remove filler words. Prioritize clarity over grammar. ## Code Generation ### Wagmi Actions When generating Wagmi actions (in `actions/`), follow these guidelines. An example of a generated action set can be found in `actions/fee.ts`. #### Source of Truth - **All actions must be based on their corresponding Viem actions** from `import { Actions } from viem/tempo` (local path might be `../viem/src/tempo/actions` or you can clone `gh repo clone wevm/viem`) - Wagmi actions are wrappers around Viem actions that integrate with Wagmi's config and TanStack Query #### Documentation Requirements All actions **must include comprehensive TSDoc** with: 1. **Function description** - What the action does 2. **`@example` block** - Complete working example showing: - Required imports (`createConfig`, `http`, action imports) - Config setup with chains and transports - Action usage with realistic parameters - Expected return value handling (if applicable) 3. **`@param` tags** - For each parameter (config, parameters) 4. **`@returns` tag** - Description of the return value Example: ```ts /** * Gets the user's default fee token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const token = await Actions.fee.getUserToken(config, { * account: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The user's fee token address. */ ``` #### Action Types ##### Query-based Actions (Read-Only) For read-only actions that fetch data: - Return the result from the corresponding Viem action - Parameters include `ChainIdParameter` and the Viem action's parameters - Must include query utilities for TanStack Query integration ```ts export function myAction( config: config, parameters: myAction.Parameters, ): Promise> { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return viem_Actions.myAction(client, rest) } ``` ##### Mutation-based Actions (Write) For state-changing actions, both variants must be implemented: **1. Standard Variant** - Uses `getConnectorClient` to get the wallet client - Returns the result from the corresponding Viem action - Does not wait for transaction confirmation ```ts export async function myAction( config: config, parameters: myAction.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return viem_Actions.myAction( client, parameters as viem_Actions.myAction.Parameters, ) } ``` **2. Sync Variant (`*Sync`)** - Named with `Sync` suffix (e.g., `setUserTokenSync`) - Uses `getConnectorClient` to get the wallet client - Waits for transaction inclusion on a block before returning a response - Returns both the receipt and extracted event data ```ts export async function myActionSync( config: config, parameters: myActionSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return viem_Actions.myActionSync( client, parameters as viem_Actions.myActionSync.Parameters, ) } ``` #### Namespace Properties ##### Query-based Actions All query-based actions must include the following components: - Include `enabled` logic to disable the query when required reactive parameters (e.g. addresses) are undefined - The `enabled` conditional must check ALL required reactive parameters (e.g., `account && spender` for allowance checks) - If there isn't an `ErrorType` for the Viem Action, use `import { BaseError } from 'viem'` ```ts import { filterQueryOptions } from './utils.js' import type { QueryOptions, QueryParameter } from './utils.js' export function myAction( config: config, parameters: myAction.Parameters, ): Promise { ... } export namespace myAction { export type Parameters = ChainIdParameter & viem_Actions.myAction.Parameters export type ReturnValue = viem_Actions.myAction.ReturnValue export type ErrorType = viem_Actions.myAction.ErrorType export function queryKey( parameters: Parameters, ) { return ['myAction', filterQueryOptions(parameters)] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean(rest.account && (query?.enabled ?? true)), queryKey: queryKey(rest), async queryFn(context) { const [, parameters] = context.queryKey return await myAction(config, parameters) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = myAction.ReturnValue, > = myAction.Parameters & QueryParameter< myAction.ReturnValue, myAction.ErrorType, selectData, myAction.QueryKey > export type ReturnValue< config extends Config, selectData = myAction.ReturnValue, > = QueryOptions< myAction.ReturnValue, myAction.ErrorType, selectData, myAction.QueryKey > } } ``` ##### Mutation-based Actions All mutation-based actions must include the following components: - If there isn't an `ErrorType` for the Viem Action, use `import { BaseError } from 'viem'` ```ts export async function myAction( config: config, parameters: myAction.Parameters, ): Promise { ... } export declare namespace myAction { export type Parameters = ChainIdParameter & ConnectorParameter & Omit, 'chain'> export type ReturnValue = viem_Actions.myAction.ReturnValue export type ErrorType = viem_Actions.myAction.ErrorType } export declare namespace myActionSync { export type Parameters = ChainIdParameter & ConnectorParameter & Omit, 'chain'> export type ReturnValue = viem_Actions.myActionSync.ReturnValue export type ErrorType = viem_Actions.myActionSync.ErrorType } ``` #### Testing Tests should be co-located with actions in `*action-name*.test.ts` files. **Important**: Wagmi action tests should follow the same test flows as the corresponding Viem action tests in `src/tempo/actions/`. This includes: - Setting up the same initial state (creating tokens, granting roles, minting tokens, etc.) - Testing the same behaviors and edge cases - Using the same test data and assertions where applicable The main difference is that Wagmi tests use `config` instead of `client`, and mutation actions don't require explicit `account` parameters since they use the connector's account. See `actions/token.test.ts` for a comprehensive example of test patterns and structure. ##### Test Structure Organize tests by action name with a default test case. Use namespace imports for cleaner code: ```ts import { connect } from '@wagmi/core' import { accounts, config, queryClient } from '@wagmi/test/tempo' import { describe, expect, test } from 'vitest' import * as myNamespace from './myNamespace.js' const account = accounts[0] // Query-based actions describe('myAction', () => { test('default', async () => { const result = await myNamespace.myAction(config, { // ... }) expect(result).toMatchInlineSnapshot(`...`) }) describe('queryOptions', () => { test('default', async () => { const options = myNamespace.myAction.queryOptions(config, { // ... }) expect(await queryClient.fetchQuery(options)).toMatchInlineSnapshot(`...`) }) }) }) // Mutation-based actions describe('myAction', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Include any necessary setup from the corresponding viem test // e.g., create tokens, grant roles, mint tokens, etc. const hash = await myNamespace.myAction(config, { // ... (no account parameter needed) }) expect(hash).toBeDefined() }) }) describe('myActionSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Include any necessary setup from the corresponding viem test const result = await myNamespace.myActionSync(config, { // ... (no account parameter needed) }) expect(result).toBeDefined() }) }) ``` ================================================ FILE: packages/core/src/tempo/Connectors.test.ts ================================================ /// import { createConfig, createStorage } from '@wagmi/core' import { KeyManager, webAuthn } from '@wagmi/core/tempo' import { tempoLocal } from '@wagmi/test/tempo' import { http } from 'viem' import { describe, expect, test } from 'vitest' import { cdp } from 'vitest/browser' async function setupWebAuthn() { const client = cdp() await client.send('WebAuthn.enable') const result = await client.send('WebAuthn.addVirtualAuthenticator', { options: { protocol: 'ctap2', transport: 'internal', hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true, }, }) return async () => { const client = cdp() await client.send('WebAuthn.removeVirtualAuthenticator', { authenticatorId: result.authenticatorId, }) await client.send('WebAuthn.disable') } } describe('webAuthn', () => { describe('sign-up with grantAccessKey', () => { test('passes chainId to signKeyAuthorization', async (context) => { const cleanup = await setupWebAuthn() context.onTestFinished(async () => await cleanup()) const storage = createStorage({ storage: localStorage }) const config = createConfig({ chains: [tempoLocal], connectors: [], storage, transports: { [tempoLocal.id]: http(), }, }) const connector = config._internal.connectors.setup( webAuthn({ grantAccessKey: true, keyManager: KeyManager.localStorage(), }), ) const chainId = tempoLocal.id const result = await connector.connect({ capabilities: { type: 'sign-up', label: 'ChainId Test' }, chainId, }) expect(result.chainId).toBe(chainId) // Retrieve the pending key authorization from storage to verify chainId. // The connector stores it at `pendingKeyAuthorization:
`. const address = (result.accounts as readonly string[])[0]!.toLowerCase() const keyAuth = await storage.getItem( `pendingKeyAuthorization:${address}` as any, ) expect(keyAuth).toBeDefined() // The key authorization should include the chainId passed during connect. // KeyAuthorization stores chainId as bigint. expect(BigInt((keyAuth as any).chainId)).toBe(BigInt(chainId)) }) }) }) ================================================ FILE: packages/core/src/tempo/Connectors.ts ================================================ import * as Address from 'ox/Address' import type * as Hex from 'ox/Hex' import * as PublicKey from 'ox/PublicKey' import { KeyAuthorization, SignatureEnvelope } from 'ox/tempo' import { createClient, defineChain, type EIP1193Provider, getAddress, SwitchChainError, } from 'viem' import { generatePrivateKey, type LocalAccount, privateKeyToAccount, } from 'viem/accounts' import { Account, WebAuthnP256, WebCryptoP256, walletNamespaceCompat, } from 'viem/tempo' import { createConnector } from '../connectors/createConnector.js' import { ChainNotConfiguredError } from '../errors/config.js' import type { OneOf } from '../types/utils.js' import type * as KeyManager from './KeyManager.js' /** @deprecated use `webAuthn.Parameters` instead */ export type WebAuthnParameters = webAuthn.Parameters webAuthn.type = 'webAuthn' as const /** * Connector for a WebAuthn EOA. */ export function webAuthn(options: webAuthn.Parameters) { let account: Account.RootAccount | undefined let accessKey: Account.AccessKeyAccount | undefined const defaultAccessKeyOptions = { expiry: Math.floor( (Date.now() + 24 * 60 * 60 * 1000) / 1000, // one day ), strict: false, } const accessKeyOptions = (() => { if (typeof options.grantAccessKey === 'object') return { ...defaultAccessKeyOptions, ...options.grantAccessKey } if (options.grantAccessKey === true) return defaultAccessKeyOptions return undefined })() type Properties = { // TODO(v3): Make `withCapabilities: true` default behavior connect(parameters: { chainId?: number | undefined capabilities?: | (OneOf< | { label?: string | undefined type: 'sign-up' } | { selectAccount?: boolean | undefined type: 'sign-in' } | { type?: undefined } > & { credential?: { id: string; publicKey: Hex.Hex } | undefined sign?: | { hash: Hex.Hex } | undefined }) | undefined isReconnecting?: boolean | undefined withCapabilities?: withCapabilities | boolean | undefined }): Promise<{ accounts: withCapabilities extends true ? readonly { address: Address.Address capabilities: { signature?: Hex.Hex | undefined } }[] : readonly Address.Address[] chainId: number }> } type Provider = Pick type StorageItem = { [ key: `pendingKeyAuthorization:${string}` ]: KeyAuthorization.KeyAuthorization 'webAuthn.activeCredential': WebAuthnP256.P256Credential 'webAuthn.lastActiveCredential': WebAuthnP256.P256Credential } return createConnector((config) => ({ id: 'webAuthn', name: 'EOA (WebAuthn)', type: 'webAuthn', async setup() { const credential = await config.storage?.getItem( 'webAuthn.activeCredential', ) if (!credential) return account = Account.fromWebAuthnP256(credential, { rpId: options.getOptions?.rpId ?? options.rpId, }) }, async connect(parameters = {}) { const capabilities = 'capabilities' in parameters ? (parameters.capabilities ?? {}) : {} const signHash = 'sign' in capabilities ? capabilities.sign?.hash : undefined // Fast path: if a credential is provided directly, use it. if ('credential' in capabilities && capabilities.credential) { const credential = capabilities.credential as WebAuthnP256.P256Credential config.storage?.setItem( 'webAuthn.activeCredential', normalizeValue(credential), ) config.storage?.setItem( 'webAuthn.lastActiveCredential', normalizeValue(credential), ) account = Account.fromWebAuthnP256(credential, { rpId: options.getOptions?.rpId ?? options.rpId, }) const address = getAddress(account.address) const chainId = parameters.chainId ?? config.chains[0]?.id if (!chainId) throw new ChainNotConfiguredError() return { accounts: (parameters.withCapabilities ? [{ address }] : [address]) as never, chainId, } } if ( accessKeyOptions?.strict && accessKeyOptions.expiry && accessKeyOptions.expiry < Date.now() / 1000 ) throw new Error( `\`grantAccessKey.expiry = ${accessKeyOptions.expiry}\` is in the past (${new Date(accessKeyOptions.expiry * 1000).toLocaleString()}). Please provide a valid expiry.`, ) // We are going to need to find: // - a WebAuthn `credential` to instantiate an account // - optionally, a `keyPair` to use as the access key for the account // - optionally, a signed `keyAuthorization` to provision the access key const { credential, keyAuthorization, keyPair, signature: signedHash, } = await (async () => { // If the connection type is of "sign-up", we are going to create a new credential // and provision an access key (if needed). if (capabilities.type === 'sign-up') { // Create credential (sign up) const createOptions_remote = await options.keyManager.getChallenge?.() const label = capabilities.label ?? options.createOptions?.label ?? new Date().toISOString() const rpId = createOptions_remote?.rp?.id ?? options.createOptions?.rpId ?? options.rpId const credential = await WebAuthnP256.createCredential({ ...(options.createOptions ?? {}), label, rpId, ...(createOptions_remote ?? {}), }) await options.keyManager.setPublicKey({ credential: credential.raw, publicKey: credential.publicKey, }) // Get key pair (access key) to use for the account. // Skip if signing a hash — access key provisioning is deferred. const keyPair = await (async () => { if (signHash) return undefined if (!accessKeyOptions) return undefined return await WebCryptoP256.createKeyPair() })() return { credential, keyPair, signature: undefined } } // If we are not selecting an account, we will check if an active credential is present in // storage and if so, we will use it to instantiate an account. if (!capabilities.selectAccount) { const credential = (await config.storage?.getItem( 'webAuthn.activeCredential', )) as WebAuthnP256.getCredential.ReturnValue | undefined if (credential) { // If signing a hash, skip local keypair checks and return // the stored credential — the hash will be signed via // `account.sign` since `createCredential` cannot sign. if (signHash) return { credential, keyPair: undefined, signature: undefined } // Get key pair (access key) to use for the account. const keyPair = await (async () => { if (!accessKeyOptions) return undefined const address = Address.fromPublicKey( PublicKey.fromHex(credential.publicKey), ) return await idb.get(`accessKey:${address}`) })() // If the access key provisioning is not in strict mode, return the credential and key pair (if exists). if (!accessKeyOptions?.strict) return { credential, keyPair, signature: undefined } // If a key pair is found, return the credential and key pair. if (keyPair) return { credential, keyPair, signature: undefined } // If we are reconnecting, throw an error if not found. if (parameters.isReconnecting) throw new Error('credential not found.') // Otherwise, we want to continue to sign up or register against new key pair. } } // Discover credential { // Get key pair (access key) to use for the account. // Skip if signing a hash — access key provisioning is deferred. const keyPair = await (async () => { if (signHash) return undefined if (!accessKeyOptions) return undefined return await WebCryptoP256.createKeyPair() })() // If we are provisioning an access key, we will need to sign a key authorization. // We will need the hash (digest) to sign, and the address of the access key to construct the key authorization. const { hash, keyAuthorization_unsigned } = await (async () => { const accessKeyAddress = keyPair ? Address.fromPublicKey(keyPair.publicKey) : undefined if (!accessKeyAddress) return { keyAuthorization_unsigned: undefined, hash: undefined } const chainId = parameters.chainId ?? config.chains[0]?.id const keyAuthorization_unsigned = KeyAuthorization.from({ address: accessKeyAddress, chainId: chainId ? BigInt(chainId) : undefined, expiry: accessKeyOptions?.expiry, strict: accessKeyOptions?.strict ?? false, type: 'p256', }) const hash = KeyAuthorization.getSignPayload( keyAuthorization_unsigned, ) return { keyAuthorization_unsigned, hash } })() // If no active credential, we will attempt to load the last active credential from storage. const lastActiveCredential = !capabilities.selectAccount ? await config.storage?.getItem('webAuthn.lastActiveCredential') : undefined const credential = await WebAuthnP256.getCredential({ ...(options.getOptions ?? {}), credentialId: lastActiveCredential?.id, async getPublicKey(credential) { const publicKey = await options.keyManager.getPublicKey({ credential, }) if (!publicKey) throw new Error('publicKey not found.') return publicKey }, hash: signHash ?? hash, rpId: options.getOptions?.rpId ?? options.rpId, }) const envelope = SignatureEnvelope.from({ metadata: credential.metadata, signature: credential.signature, publicKey: PublicKey.fromHex(credential.publicKey), type: 'webAuthn', }) const keyAuthorization = keyAuthorization_unsigned ? KeyAuthorization.from({ ...keyAuthorization_unsigned, signature: envelope, }) : undefined const signature = signHash && !keyAuthorization_unsigned ? SignatureEnvelope.serialize(envelope) : undefined return { credential, keyAuthorization, keyPair, signature } } })() config.storage?.setItem( 'webAuthn.lastActiveCredential', normalizeValue(credential), ) config.storage?.setItem( 'webAuthn.activeCredential', normalizeValue(credential), ) account = Account.fromWebAuthnP256(credential, { rpId: options.getOptions?.rpId ?? options.rpId, }) let signature: Hex.Hex | undefined if (signHash && !signedHash) { signature = await account.sign({ hash: signHash }) } else if (signedHash) { signature = signedHash } else if (keyPair) { accessKey = Account.fromWebCryptoP256(keyPair, { access: account, }) // If we are reconnecting, check if the access key is expired. if (parameters.isReconnecting) { if ( 'keyAuthorization' in keyPair && keyPair.keyAuthorization.expiry && keyPair.keyAuthorization.expiry < Date.now() / 1000 ) { // remove any pending key authorizations from storage. await config?.storage?.removeItem( `pendingKeyAuthorization:${account.address.toLowerCase()}`, ) const message = `Access key expired (on ${new Date(keyPair.keyAuthorization.expiry * 1000).toLocaleString()}).` accessKey = undefined // if in strict mode, disconnect and throw an error. if (accessKeyOptions?.strict) { await this.disconnect() throw new Error(message) } // otherwise, fall back to the root account. // biome-ignore lint/suspicious/noConsole: notify console.warn(`${message} Falling back to passkey.`) } } // If we are not reconnecting, orchestrate the provisioning of the access key. else { const keyAuth = keyAuthorization ?? (await account.signKeyAuthorization(accessKey, { ...accessKeyOptions, chainId: BigInt(parameters.chainId ?? config.chains[0]?.id ?? 0), } as never)) await config?.storage?.setItem( `pendingKeyAuthorization:${account.address.toLowerCase()}`, keyAuth as never, ) await idb.set(`accessKey:${account.address.toLowerCase()}`, { ...keyPair, keyAuthorization: keyAuth, }) } // If we are granting an access key and it is in strict mode, throw an error if the access key is not provisioned. } else if (accessKeyOptions?.strict) { await config.storage?.removeItem('webAuthn.activeCredential') throw new Error('access key not found') } const address = getAddress(account.address) const chainId = parameters.chainId ?? config.chains[0]?.id if (!chainId) throw new ChainNotConfiguredError() return { accounts: (parameters.withCapabilities ? [{ address, capabilities: { signature } }] : [address]) as never, chainId, } }, async disconnect() { await config.storage?.removeItem('webAuthn.activeCredential') config.emitter.emit('disconnect') account = undefined }, async getAccounts() { if (!account) return [] return [getAddress(account.address)] }, async getChainId() { return config.chains[0]?.id! }, async isAuthorized() { try { const accounts = await this.getAccounts() return !!accounts.length } catch (error) { // biome-ignore lint/suspicious/noConsole: notify console.error( 'Connector.webAuthn: Failed to check authorization', error, ) return false } }, async switchChain({ chainId }) { const chain = config.chains.find((chain) => chain.id === chainId) if (!chain) throw new SwitchChainError(new ChainNotConfiguredError()) return chain }, onAccountsChanged() {}, onChainChanged(chain) { const chainId = Number(chain) config.emitter.emit('change', { chainId }) }, async onDisconnect() { config.emitter.emit('disconnect') account = undefined }, async getClient({ chainId } = {}) { const chain = config.chains.find((x) => x.id === chainId) ?? config.chains[0] if (!chain) throw new ChainNotConfiguredError() const transports = config.transports if (!transports) throw new ChainNotConfiguredError() const transport = transports[chain.id] if (!transport) throw new ChainNotConfiguredError() const targetAccount = await (async () => { if (!accessKey) return account if (!account) throw new Error('account not found.') const item = await idb.get(`accessKey:${account.address.toLowerCase()}`) if ( item?.keyAuthorization.expiry && item.keyAuthorization.expiry < Date.now() / 1000 ) { // remove any pending key authorizations from storage. await config?.storage?.removeItem( `pendingKeyAuthorization:${account.address.toLowerCase()}`, ) const message = `Access key expired (on ${new Date(item.keyAuthorization.expiry * 1000).toLocaleString()}).` // if in strict mode, disconnect and throw an error. if (accessKeyOptions?.strict) { await this.disconnect() throw new Error(message) } // otherwise, fall back to the root account. // biome-ignore lint/suspicious/noConsole: notify console.warn(`${message} Falling back to passkey.`) return account } return accessKey })() if (!targetAccount) throw new Error('account not found.') const targetChain = defineChain({ ...chain, prepareTransactionRequest: [ async (args, { phase }) => { const keyAuthorization = await (async () => { { const keyAuthorization = ( args as { keyAuthorization?: | KeyAuthorization.KeyAuthorization | undefined } ).keyAuthorization if (keyAuthorization) return keyAuthorization } const keyAuthorization = await config.storage?.getItem( `pendingKeyAuthorization:${targetAccount?.address.toLowerCase()}`, ) await config.storage?.removeItem( `pendingKeyAuthorization:${targetAccount?.address.toLowerCase()}`, ) return keyAuthorization })() const [prepareTransactionRequestFn, options] = (() => { if (!chain.prepareTransactionRequest) return [undefined, undefined] if (typeof chain.prepareTransactionRequest === 'function') return [chain.prepareTransactionRequest, undefined] return chain.prepareTransactionRequest })() const request = await (async () => { if (!prepareTransactionRequestFn) return {} if (!options || options?.runAt?.includes(phase)) return await prepareTransactionRequestFn(args, { phase }) return {} })() return { ...args, ...request, keyAuthorization, } }, { runAt: [ 'afterFillParameters', 'beforeFillParameters', 'beforeFillTransaction', ], }, ], }) return createClient({ account: targetAccount, chain: targetChain, transport: walletNamespaceCompat(transport, { account: targetAccount, }), }) }, async getProvider({ chainId } = {}) { const { request } = await this.getClient!({ chainId }) return { request } }, })) } export namespace webAuthn { export type Parameters = { /** Options for WebAuthn registration. */ createOptions?: | Pick< WebAuthnP256.createCredential.Parameters, 'createFn' | 'label' | 'rpId' | 'userId' | 'timeout' > | undefined /** Options for WebAuthn authentication. */ getOptions?: | Pick | undefined /** * Whether or not to grant an access key upon connection, and optionally, expiry + limits to assign to the key. */ grantAccessKey?: | boolean | (Pick & { /** Whether or not to throw an error and disconnect if the access key is not provisioned or is expired. */ strict?: boolean | undefined }) /** Public key manager. */ keyManager: KeyManager.KeyManager /** The RP ID to use for WebAuthn. */ rpId?: string | undefined } } /** * Normalizes a value into a structured-clone compatible format. * * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/structuredClone */ function normalizeValue(value: type): type { if (Array.isArray(value)) return value.map(normalizeValue) as never if (typeof value === 'function') return undefined as never if (typeof value !== 'object' || value === null) return value if (Object.getPrototypeOf(value) !== Object.prototype) try { return structuredClone(value) } catch { return undefined as never } const normalized: Record = {} for (const [k, v] of Object.entries(value)) normalized[k] = normalizeValue(v) return normalized as never } // Based on `idb-keyval` // https://github.com/jakearchibald/idb-keyval let defaultGetStoreFunc: | (( txMode: IDBTransactionMode, callback: (store: IDBObjectStore) => type | PromiseLike, ) => Promise) | undefined const idb = { /** * Get a value by its key. * * @param key * @param customStore Method to get a custom store. Use with caution (see the docs). */ get(key: IDBValidKey): Promise { return this.defaultGetStore()('readonly', (store) => this.promisifyRequest(store.get(key)), ) }, /** * Set a value with a key. * * @param key * @param value * @param customStore Method to get a custom store. Use with caution (see the docs). */ set(key: IDBValidKey, value: any): Promise { return this.defaultGetStore()('readwrite', (store) => { store.put(value, key) return this.promisifyRequest(store.transaction) }) }, defaultGetStore() { if (!defaultGetStoreFunc) defaultGetStoreFunc = this.createStore('keyval-store', 'keyval') return defaultGetStoreFunc }, createStore( dbName: string, storeName: string, ): NonNullable { let dbp: Promise | undefined const getDB = () => { if (dbp) return dbp const request = indexedDB.open(dbName) request.onupgradeneeded = () => request.result.createObjectStore(storeName) dbp = this.promisifyRequest(request) dbp.then( (db) => { // It seems like Safari sometimes likes to just close the connection. // It's supposed to fire this event when that happens. Let's hope it does! db.onclose = () => { dbp = undefined } }, () => {}, ) return dbp } return (txMode, callback) => getDB().then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)), ) }, promisifyRequest( request: IDBRequest | IDBTransaction, ): Promise { return new Promise((resolve, reject) => { // @ts-ignore - file size hacks request.oncomplete = request.onsuccess = () => resolve(request.result) // @ts-ignore - file size hacks request.onabort = request.onerror = () => reject(request.error) }) }, } /** @deprecated use `dangerous_secp256k1.Parameters` instead */ export type Dangerous_Secp256k1Parameters = dangerous_secp256k1.Parameters dangerous_secp256k1.type = 'dangerous_secp256k1' as const /** * Connector for a Secp256k1 EOA. * * WARNING: NOT RECOMMENDED FOR PRODUCTION USAGE. * This connector stores private keys in clear text, and are bound to the session * length of the storage used. */ export function dangerous_secp256k1( options: dangerous_secp256k1.Parameters = {}, ) { let account: LocalAccount | undefined type Properties = { // TODO(v3): Make `withCapabilities: true` default behavior connect(parameters: { capabilities?: { type?: 'sign-up' | undefined } | undefined chainId?: number | undefined isReconnecting?: boolean | undefined withCapabilities?: withCapabilities | boolean | undefined }): Promise<{ accounts: readonly Address.Address[] chainId: number }> } type Provider = Pick type StorageItem = { 'secp256k1.activeAddress': Address.Address 'secp256k1.lastActiveAddress': Address.Address [key: `secp256k1.${string}.privateKey`]: Hex.Hex } return createConnector((config) => ({ id: 'secp256k1', name: 'EOA (Secp256k1)', type: 'secp256k1', async setup() { const address = await config.storage?.getItem('secp256k1.activeAddress') const privateKey = await config.storage?.getItem( `secp256k1.${address}.privateKey`, ) if (privateKey) account = privateKeyToAccount(privateKey) else if ( address && options.account && Address.isEqual(address, options.account.address) ) account = options.account }, async connect(parameters = {}) { const address = await (async () => { if ( 'capabilities' in parameters && parameters.capabilities?.type === 'sign-up' ) { const privateKey = generatePrivateKey() const account = privateKeyToAccount(privateKey) const address = account.address await config.storage?.setItem( `secp256k1.${address}.privateKey`, privateKey, ) await config.storage?.setItem('secp256k1.activeAddress', address) await config.storage?.setItem('secp256k1.lastActiveAddress', address) return address } const address = await config.storage?.getItem( 'secp256k1.lastActiveAddress', ) const privateKey = await config.storage?.getItem( `secp256k1.${address}.privateKey`, ) if (privateKey) account = privateKeyToAccount(privateKey) else if (options.account) { account = options.account await config.storage?.setItem( 'secp256k1.lastActiveAddress', account.address, ) } if (!account) throw new Error('account not found.') await config.storage?.setItem( 'secp256k1.activeAddress', account.address, ) return account.address })() const chainId = parameters.chainId ?? config.chains[0]?.id if (!chainId) throw new ChainNotConfiguredError() return { accounts: (parameters.withCapabilities ? [{ address }] : [address]) as never, chainId, } }, async disconnect() { await config.storage?.removeItem('secp256k1.activeAddress') account = undefined }, async getAccounts() { if (!account) return [] return [getAddress(account.address)] }, async getChainId() { return config.chains[0]?.id! }, async isAuthorized() { try { const accounts = await this.getAccounts() return !!accounts.length } catch (error) { // biome-ignore lint/suspicious/noConsole: notify console.error( 'Connector.secp256k1: Failed to check authorization', error, ) return false } }, async switchChain({ chainId }) { const chain = config.chains.find((chain) => chain.id === chainId) if (!chain) throw new SwitchChainError(new ChainNotConfiguredError()) return chain }, onAccountsChanged() {}, onChainChanged(chain) { const chainId = Number(chain) config.emitter.emit('change', { chainId }) }, async onDisconnect() { config.emitter.emit('disconnect') account = undefined }, async getClient({ chainId } = {}) { const chain = config.chains.find((x) => x.id === chainId) ?? config.chains[0] if (!chain) throw new ChainNotConfiguredError() const transports = config.transports if (!transports) throw new ChainNotConfiguredError() const transport = transports[chain.id] if (!transport) throw new ChainNotConfiguredError() if (!account) throw new Error('account not found.') return createClient({ account, chain, transport: walletNamespaceCompat(transport, { account, }), }) }, async getProvider({ chainId } = {}) { const { request } = await this.getClient!({ chainId }) return { request } }, })) } export declare namespace dangerous_secp256k1 { export type Parameters = { account?: LocalAccount | undefined } } ================================================ FILE: packages/core/src/tempo/KeyManager.ts ================================================ import type { WebAuthnP256 } from 'ox' import * as Base64 from 'ox/Base64' import type * as Hex from 'ox/Hex' import * as Json from 'ox/Json' import { type CreateStorageParameters, createStorage, type Storage, } from '../createStorage.js' export type KeyManager = { /** Function to fetch create options for WebAuthn. */ getChallenge?: | (() => Promise<{ challenge: Hex.Hex rp?: { id: string; name: string } | undefined }>) | undefined /** Function to fetch the public key for a credential. */ getPublicKey: (parameters: { credential: WebAuthnP256.P256Credential['raw'] }) => Promise /** Function to set the public key for a credential. */ setPublicKey: (parameters: { credential: WebAuthnP256.P256Credential['raw'] publicKey: Hex.Hex }) => Promise } /** Instantiates a key manager. */ export function from(manager: manager): manager { return manager } /** Instantiates a key manager from a Storage instance. */ export function fromStorage(storage: Storage): KeyManager { return from({ async getPublicKey(parameters) { const publicKey = await storage.getItem(parameters.credential.id) if (!publicKey) throw new Error('publicKey not found.') return publicKey as Hex.Hex }, async setPublicKey(parameters) { await storage.setItem(parameters.credential.id, parameters.publicKey) }, }) } /** * Instantiates a key manager from a localStorage instance. * * WARNING: Do not use this in production. * This is because we are unable to extract a user's public key after the registration * process. If a user clears their storage, or visits the website on a different device, * they will not be able to access their account. * * Instead, we recommend to set up a remote store such as [`KeyManager.http`](#http) to register * public keys against their WebAuthn credential. * * @see {@link http} * * @deprecated */ export function localStorage(options: localStorage.Options = {}) { const { key = 'wagmi.keyManager' } = options const storage = createStorage({ ...options, key, storage: typeof window !== 'undefined' ? window.localStorage : undefined, }) return fromStorage(storage) } export namespace localStorage { export type Options = Omit } /** * Instantiates a key manager that uses HTTP endpoints for credential management. * * @example * ```tsx * import { KeyManager } from '@wagmi/core/tempo' * * const keyManager = KeyManager.http('https://api.example.com') * ``` * * @param url - The URL to use for the HTTP endpoints. * @param options - Configuration options for HTTP endpoints. * @returns A KeyManager instance that uses HTTP for credential operations. */ export function http( url: | string | { getChallenge?: string | Request | undefined getPublicKey?: string | Request | undefined setPublicKey?: string | Request | undefined }, options: http.Options = {}, ): KeyManager { const { fetch: fetchFn = globalThis.fetch } = options const { getChallenge, getPublicKey, setPublicKey } = (() => { const base = typeof url === 'string' ? url : '' const urls = typeof url === 'object' ? url : {} return { getChallenge: urls.getChallenge ?? `${base}/challenge`, getPublicKey: urls.getPublicKey ?? `${base}/:credentialId`, setPublicKey: urls.setPublicKey ?? `${base}/:credentialId`, } })() return from({ async getChallenge() { const request = getChallenge instanceof Request ? getChallenge : new Request(getChallenge) const response = await fetchFn(request) if (!response.ok) throw new Error(`Failed to get create options: ${response.statusText}`) return await response.json() }, async getPublicKey(parameters) { const request = getPublicKey instanceof Request ? getPublicKey : new Request(getPublicKey) const response = await fetchFn( new Request( request.url.replace(':credentialId', parameters.credential.id), request, ), ) if (!response.ok) throw new Error(`Failed to get public key: ${response.statusText}`) const data = await response.json() return data.publicKey as Hex.Hex }, async setPublicKey(parameters) { const request = setPublicKey instanceof Request ? setPublicKey : new Request(setPublicKey) const response = await fetchFn( new Request( request.url.replace(':credentialId', parameters.credential.id), request, ), { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: Json.stringify({ ...parameters, credential: serializeCredential(parameters.credential), }), }, ) if (!response.ok) throw new Error(`Failed to set public key: ${response.statusText}`) }, }) } export namespace http { export type Options = { /** Custom fetch function. @default `globalThis.fetch`. */ fetch?: typeof fetch | undefined } } /** * Serializes a WebAuthn credential for JSON transmission. * @internal */ function serializeCredential( credential: WebAuthnP256.P256Credential['raw'], ): Record { const response = credential.response return { ...credential, rawId: Base64.fromBytes(new Uint8Array(credential.rawId)), response: { clientDataJSON: Base64.fromBytes(new Uint8Array(response.clientDataJSON)), ...('attestationObject' in response && { attestationObject: Base64.fromBytes( new Uint8Array(response.attestationObject as ArrayBuffer), ), }), ...('getAuthenticatorData' in response && typeof response.getAuthenticatorData === 'function' && { authenticatorData: Base64.fromBytes( new Uint8Array( response.getAuthenticatorData.call(response) as ArrayBuffer, ), ), }), ...('getPublicKey' in response && typeof response.getPublicKey === 'function' && { publicKey: Base64.fromBytes( new Uint8Array(response.getPublicKey.call(response) as ArrayBuffer), ), }), ...('getPublicKeyAlgorithm' in response && typeof response.getPublicKeyAlgorithm === 'function' && { publicKeyAlgorithm: response.getPublicKeyAlgorithm.call(response), }), ...('getTransports' in response && typeof response.getTransports === 'function' && { transports: response.getTransports.call(response), }), ...('authenticatorData' in response && { authenticatorData: Base64.fromBytes( new Uint8Array(response.authenticatorData as ArrayBuffer), ), }), ...('signature' in response && { signature: Base64.fromBytes( new Uint8Array(response.signature as ArrayBuffer), ), }), ...('userHandle' in response && response.userHandle ? { userHandle: Base64.fromBytes( new Uint8Array(response.userHandle as ArrayBuffer), ), } : {}), }, } } ================================================ FILE: packages/core/src/tempo/actions/amm.test.ts ================================================ import { connect, getConnectorClient } from '@wagmi/core' import { accounts, addresses, config, queryClient, viem_setupPoolWithLiquidity, } from '@wagmi/test/tempo' import { parseUnits } from 'viem' import { describe, expect, test } from 'vitest' import * as ammActions from './amm.js' import * as tokenActions from './token.js' const account = accounts[0] describe('getPool', () => { test('default', async () => { const pool = await ammActions.getPool(config, { userToken: addresses.alphaUsd, validatorToken: '0x20c0000000000000000000000000000000000001', }) expect(pool).toMatchInlineSnapshot(` { "reserveUserToken": 0n, "reserveValidatorToken": 0n, "totalSupply": 0n, } `) }) describe('queryOptions', () => { test('default', async () => { const options = ammActions.getPool.queryOptions(config, { userToken: addresses.alphaUsd, validatorToken: '0x20c0000000000000000000000000000000000001', }) const pool = await queryClient.fetchQuery(options) expect(pool).toMatchInlineSnapshot(` { "reserveUserToken": 0n, "reserveValidatorToken": 0n, "totalSupply": 0n, } `) }) }) }) describe('getLiquidityBalance', () => { test('default', async () => { const balance = await ammActions.getLiquidityBalance(config, { userToken: addresses.alphaUsd, validatorToken: '0x20c0000000000000000000000000000000000001', address: account.address, }) expect(balance).toMatchInlineSnapshot('0n') }) describe('queryOptions', () => { test('default', async () => { const options = ammActions.getLiquidityBalance.queryOptions(config, { userToken: addresses.alphaUsd, validatorToken: '0x20c0000000000000000000000000000000000001', address: account.address, }) const balance = await queryClient.fetchQuery(options) expect(balance).toMatchInlineSnapshot('0n') }) }) }) describe('mintSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token for testing const { token } = await tokenActions.createSync(config, { name: 'Test Token', symbol: 'TEST', currency: 'USD', }) // Grant issuer role to mint tokens await tokenActions.grantRolesSync(config, { token, roles: ['issuer'], to: account.address, }) // Mint some tokens to account await tokenActions.mintSync(config, { to: account.address, amount: parseUnits('1000', 6), token, }) // Add liquidity to pool const { receipt: mintReceipt, ...mintResult } = await ammActions.mintSync( config, { userTokenAddress: token, validatorTokenAddress: addresses.alphaUsd, validatorTokenAmount: parseUnits('100', 6), to: account.address, }, ) expect(mintReceipt).toBeDefined() expect(mintResult.amountValidatorToken).toBe(100000000n) expect(mintResult.liquidity).toBe(49999000n) expect(mintResult.sender).toBe(account.address) expect(mintResult.to).toBe(account.address) expect(mintResult.validatorToken.toLowerCase()).toBe( addresses.alphaUsd.toLowerCase(), ) }) }) describe.skip('burnSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) const client = await getConnectorClient(config) const { tokenAddress } = await viem_setupPoolWithLiquidity(client) const account2 = accounts[1] // Get LP balance before burn const lpBalanceBefore = await ammActions.getLiquidityBalance(config, { userToken: tokenAddress, validatorToken: addresses.alphaUsd, address: account.address, }) // TODO(TEMPO-1183): Remove this janky fix to get some user token in the pool await tokenActions.transferSync(config, { to: account2.address, amount: 600n, token: tokenAddress, feeToken: tokenAddress, }) // Burn half of LP tokens const { receipt: burnReceipt, ...burnResult } = await ammActions.burnSync( config, { userToken: tokenAddress, validatorToken: addresses.alphaUsd, liquidity: lpBalanceBefore / 2n, to: account.address, }, ) expect(burnReceipt).toBeDefined() expect(burnResult).toMatchInlineSnapshot(` { "amountUserToken": 337n, "amountValidatorToken": 49998664n, "liquidity": 24999500n, "sender": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", "to": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", "userToken": "0x20c0000000000000000000000000000000000005", "validatorToken": "0x20C0000000000000000000000000000000000001", } `) }) }) describe.skip('rebalanceSwapSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) const client = await getConnectorClient(config) const { tokenAddress } = await viem_setupPoolWithLiquidity(client) const account2 = accounts[1] // TODO(TEMPO-1183): Remove this janky fix to get some user token in the pool await tokenActions.transferSync(config, { to: account2.address, amount: 600n, token: tokenAddress, feeToken: tokenAddress, }) // Perform rebalance swap const { receipt: swapReceipt, ...swapResult } = await ammActions.rebalanceSwapSync(config, { userToken: tokenAddress, validatorToken: addresses.alphaUsd, amountOut: 100n, to: account2.address, }) expect(swapReceipt).toBeDefined() expect(swapResult).toMatchInlineSnapshot(` { "amountIn": 100n, "amountOut": 100n, "swapper": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", "userToken": "0x20C0000000000000000000000000000000000006", "validatorToken": "0x20C0000000000000000000000000000000000001", } `) }) }) ================================================ FILE: packages/core/src/tempo/actions/amm.ts ================================================ import type { Account, BaseErrorType } from 'viem' import { Actions } from 'viem/tempo' import { getConnectorClient } from '../../actions/getConnectorClient.js' import type { Config } from '../../createConfig.js' import type { ChainIdParameter, ConnectorParameter, } from '../../types/properties.js' import type { UnionLooseOmit } from '../../types/utils.js' import type { QueryOptions, QueryParameter } from './utils.js' import { filterQueryOptions } from './utils.js' /** * Gets the reserves for a liquidity pool. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const pool = await Actions.amm.getPool(config, { * userToken: '0x...', * validatorToken: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The pool reserves. */ export function getPool( config: config, parameters: getPool.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.amm.getPool(client, rest) } export namespace getPool { export type Parameters = ChainIdParameter & Actions.amm.getPool.Parameters export type ReturnValue = Actions.amm.getPool.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: Parameters, ) { return ['getPool', filterQueryOptions(parameters)] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean( rest.userToken && rest.validatorToken && (query?.enabled ?? true), ), queryKey: queryKey(rest), async queryFn({ queryKey }) { const [, parameters] = queryKey return await getPool(config, parameters) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = getPool.ReturnValue, > = getPool.Parameters & QueryParameter< getPool.ReturnValue, getPool.ErrorType, selectData, getPool.QueryKey > export type ReturnValue< config extends Config, selectData = getPool.ReturnValue, > = QueryOptions< getPool.ReturnValue, getPool.ErrorType, selectData, getPool.QueryKey > } } /** * Gets the LP token balance for an account in a specific pool. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const poolId = await Actions.amm.getPoolId(config, { * userToken: '0x...', * validatorToken: '0x...', * }) * * const balance = await Actions.amm.getLiquidityBalance(config, { * poolId, * address: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The LP token balance. */ export function getLiquidityBalance( config: config, parameters: getLiquidityBalance.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.amm.getLiquidityBalance(client, rest) } export namespace getLiquidityBalance { export type Parameters = ChainIdParameter & Actions.amm.getLiquidityBalance.Parameters export type ReturnValue = Actions.amm.getLiquidityBalance.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: Parameters, ) { return ['getLiquidityBalance', filterQueryOptions(parameters)] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean( rest.address && (rest.poolId || (rest.userToken !== undefined && rest.validatorToken !== undefined)) && (query?.enabled ?? true), ), queryKey: queryKey(rest), async queryFn({ queryKey }) { const [, parameters] = queryKey return await getLiquidityBalance(config, parameters as any) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = getLiquidityBalance.ReturnValue, > = getLiquidityBalance.Parameters & QueryParameter< getLiquidityBalance.ReturnValue, getLiquidityBalance.ErrorType, selectData, getLiquidityBalance.QueryKey > export type ReturnValue< config extends Config, selectData = getLiquidityBalance.ReturnValue, > = QueryOptions< getLiquidityBalance.ReturnValue, getLiquidityBalance.ErrorType, selectData, getLiquidityBalance.QueryKey > } } /** * Performs a rebalance swap from validator token to user token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.amm.rebalanceSwap(config, { * userToken: '0x...', * validatorToken: '0x...', * amountOut: 100n, * to: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction hash. */ export async function rebalanceSwap( config: config, parameters: rebalanceSwap.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.amm.rebalanceSwap(client, parameters as never) } export declare namespace rebalanceSwap { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.amm.rebalanceSwap.Parameters, 'chain' > export type ReturnValue = Actions.amm.rebalanceSwap.ReturnValue export type ErrorType = BaseErrorType } /** * Performs a rebalance swap from validator token to user token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.amm.rebalanceSwapSync(config, { * userToken: '0x...', * validatorToken: '0x...', * amountOut: 100n, * to: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function rebalanceSwapSync( config: config, parameters: rebalanceSwapSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.amm.rebalanceSwapSync(client, parameters as never) } export declare namespace rebalanceSwapSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.amm.rebalanceSwapSync.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.amm.rebalanceSwapSync.ReturnValue export type ErrorType = BaseErrorType } /** * Adds liquidity to a pool. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.amm.mint(config, { * userTokenAddress: '0x20c0...beef', * validatorTokenAddress: '0x20c0...babe', * validatorTokenAmount: 100n, * to: '0xfeed...fede', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction hash. */ export async function mint( config: config, parameters: mint.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.amm.mint(client, parameters as never) } export declare namespace mint { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.amm.mint.Parameters, 'chain' > export type ReturnValue = Actions.amm.mint.ReturnValue export type ErrorType = BaseErrorType } /** * Adds liquidity to a pool. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.amm.mintSync(config, { * userTokenAddress: '0x20c0...beef', * validatorTokenAddress: '0x20c0...babe', * validatorTokenAmount: 100n, * to: '0xfeed...fede', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function mintSync( config: config, parameters: mintSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.amm.mintSync(client, parameters as never) } export declare namespace mintSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.amm.mintSync.Parameters, 'chain' > export type ReturnValue = Actions.amm.mintSync.ReturnValue export type ErrorType = BaseErrorType } /** * Removes liquidity from a pool. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.amm.burn(config, { * userToken: '0x20c0...beef', * validatorToken: '0x20c0...babe', * liquidity: 50n, * to: '0xfeed...fede', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction hash. */ export async function burn( config: config, parameters: burn.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.amm.burn(client, parameters as never) } export declare namespace burn { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.amm.burn.Parameters, 'chain' > export type ReturnValue = Actions.amm.burn.ReturnValue export type ErrorType = BaseErrorType } /** * Removes liquidity from a pool. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.amm.burnSync(config, { * userToken: '0x20c0...beef', * validatorToken: '0x20c0...babe', * liquidity: 50n, * to: '0xfeed...fede', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function burnSync( config: config, parameters: burnSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.amm.burnSync(client, parameters as never) } export declare namespace burnSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.amm.burnSync.Parameters, 'chain' > export type ReturnValue = Actions.amm.burnSync.ReturnValue export type ErrorType = BaseErrorType } /** * Watches for rebalance swap events. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.amm.watchRebalanceSwap(config, { * onRebalanceSwap: (args, log) => { * console.log('Rebalance swap:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchRebalanceSwap( config: config, parameters: watchRebalanceSwap.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.amm.watchRebalanceSwap(client, rest) } export declare namespace watchRebalanceSwap { export type Parameters = ChainIdParameter & Actions.amm.watchRebalanceSwap.Parameters } /** * Watches for liquidity mint events. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.amm.watchMint(config, { * onMint: (args, log) => { * console.log('Liquidity added:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchMint( config: config, parameters: watchMint.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.amm.watchMint(client, rest) } export declare namespace watchMint { export type Parameters = ChainIdParameter & Actions.amm.watchMint.Parameters } /** * Watches for liquidity burn events. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.amm.watchBurn(config, { * onBurn: (args, log) => { * console.log('Liquidity removed:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchBurn( config: config, parameters: watchBurn.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.amm.watchBurn(client, rest) } export declare namespace watchBurn { export type Parameters = ChainIdParameter & Actions.amm.watchBurn.Parameters } ================================================ FILE: packages/core/src/tempo/actions/dex.test.ts ================================================ import { connect } from '@wagmi/core' import { accounts, addresses, config, setupTokenPair } from '@wagmi/test/tempo' import { isAddress, parseUnits } from 'viem' import { Tick } from 'viem/tempo' import { describe, expect, test, vi } from 'vitest' import * as dex from './dex.js' import * as token from './token.js' const account = accounts[0] const account2 = accounts[1] describe('buy', () => { test('default', async () => { const { base, quote } = await setupTokenPair() // Place ask order to create liquidity await dex.placeSync(config, { token: base, amount: parseUnits('500', 6), type: 'sell', tick: Tick.fromPrice('1.001'), }) // Get initial balances const baseBalanceBefore = await token.getBalance(config, { token: base, account: account.address, }) // Buy base tokens with quote tokens const { receipt } = await dex.buySync(config, { tokenIn: quote, tokenOut: base, amountOut: parseUnits('100', 6), maxAmountIn: parseUnits('150', 6), }) expect(receipt).toBeDefined() expect(receipt.status).toBe('success') // Verify balances changed const baseBalanceAfter = await token.getBalance(config, { token: base, account: account.address, }) // Should have received base tokens expect(baseBalanceAfter).toBeGreaterThan(baseBalanceBefore) }) test('behavior: respects maxAmountIn', async () => { const { base, quote } = await setupTokenPair() // Place ask order at high price await dex.placeSync(config, { token: base, amount: parseUnits('500', 6), type: 'sell', tick: Tick.fromPrice('1.01'), // 1% above peg }) // Try to buy with insufficient maxAmountIn - should fail await expect( dex.buySync(config, { tokenIn: quote, tokenOut: base, amountOut: parseUnits('100', 6), maxAmountIn: parseUnits('50', 6), // Way too low for 1% premium }), ).rejects.toThrow('The contract function "swapExactAmountOut" reverted') }) test('behavior: fails with insufficient liquidity', async () => { const { base, quote } = await setupTokenPair() // Don't place any orders - no liquidity // Try to buy - should fail due to no liquidity await expect( dex.buySync(config, { tokenIn: quote, tokenOut: base, amountOut: parseUnits('100', 6), maxAmountIn: parseUnits('150', 6), }), ).rejects.toThrow('The contract function "swapExactAmountOut" reverted') }) }) describe('cancel', () => { test('default', async () => { const { base, quote } = await setupTokenPair() // Place a bid order const { orderId } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) // Check initial DEX balance (should be 0) const dexBalanceBefore = await dex.getBalance(config, { account: account.address, token: quote, }) expect(dexBalanceBefore).toBe(0n) // Cancel the order const { receipt, ...result } = await dex.cancelSync(config, { orderId, }) expect(receipt).toBeDefined() expect(receipt.status).toBe('success') expect(result.orderId).toBe(orderId) // Check DEX balance after cancel - tokens should be refunded to internal balance const dexBalanceAfter = await dex.getBalance(config, { account: account.address, token: quote, }) expect(dexBalanceAfter).toBeGreaterThan(0n) }) test('behavior: only maker can cancel', async () => { const { base } = await setupTokenPair() // Account places order const { orderId } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) // Transfer gas to account2 await token.transferSync(config, { to: account2.address, amount: parseUnits('1', 6), token: addresses.alphaUsd, }) // Use a different account via the connector await connect(config, { connector: config.connectors[1]!, }) // Account2 tries to cancel - should fail await expect( dex.cancelSync(config, { orderId, }), ).rejects.toThrow('The contract function "cancel" reverted') }) test('behavior: cannot cancel non-existent order', async () => { await setupTokenPair() // Try to cancel an order that doesn't exist await expect( dex.cancelSync(config, { orderId: 999n, }), ).rejects.toThrow('The contract function "cancel" reverted') }) }) describe('createPair', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) const { token: baseToken } = await token.createSync(config, { name: 'Test Base Token', symbol: 'BASE', currency: 'USD', admin: account, }) const { receipt, ...result } = await dex.createPairSync(config, { base: baseToken, }) expect(receipt).toBeDefined() expect(receipt.status).toBe('success') const { key, ...rest } = result expect(key).toBeDefined() expect(rest).toEqual( expect.objectContaining({ base: expect.toSatisfy(isAddress), quote: expect.toSatisfy(isAddress), }), ) }) }) describe('getBalance', () => { test('default', async () => { const { base, quote } = await setupTokenPair() // Initial balance should be 0 const initialBalance = await dex.getBalance(config, { account: account.address, token: quote, }) expect(initialBalance).toBe(0n) // Place and cancel order to create internal balance const { orderId } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.0005'), }) await dex.cancelSync(config, { orderId, }) // Now balance should be > 0 (refunded quote tokens) const balance = await dex.getBalance(config, { account: account.address, token: quote, }) expect(balance).toBeGreaterThan(0n) }) test('behavior: check different account', async () => { const { quote } = await setupTokenPair() // Check account2's balance (should be 0) const balance = await dex.getBalance(config, { account: account2.address, token: quote, }) expect(balance).toBe(0n) }) test('behavior: balances are per-token', async () => { const { base, quote } = await setupTokenPair() // Create balance in quote token const { orderId } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) await dex.cancelSync(config, { orderId }) // Check quote balance (should have refunded tokens) const quoteBalance = await dex.getBalance(config, { account: account.address, token: quote, }) expect(quoteBalance).toBeGreaterThan(0n) // Check base balance (should still be 0) const baseBalance = await dex.getBalance(config, { account: account.address, token: base, }) expect(baseBalance).toBe(0n) }) }) describe('getBuyQuote', () => { test('default', async () => { const { base, quote } = await setupTokenPair() // Place ask orders to create liquidity await dex.placeSync(config, { token: base, amount: parseUnits('500', 6), type: 'sell', tick: Tick.fromPrice('1.001'), }) // Get quote for buying base tokens const amountIn = await dex.getBuyQuote(config, { tokenIn: quote, tokenOut: base, amountOut: parseUnits('100', 6), }) expect(amountIn).toBeGreaterThan(0n) // Should be approximately 100 * 1.001 = 100.1 expect(amountIn).toBeGreaterThan(parseUnits('100', 6)) }) test('behavior: fails with no liquidity', async () => { const { base, quote } = await setupTokenPair() // No orders placed - no liquidity // Quote should fail await expect( dex.getBuyQuote(config, { tokenIn: quote, tokenOut: base, amountOut: parseUnits('100', 6), }), ).rejects.toThrow( 'The contract function "quoteSwapExactAmountOut" reverted', ) }) }) describe('getOrder', () => { test('default', async () => { const { base } = await setupTokenPair() // Place an order to get an order ID const { orderId } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) // Get the order details const order = await dex.getOrder(config, { orderId, }) expect(order).toBeDefined() expect(order.maker).toBe(account.address) expect(order.isBid).toBe(true) expect(order.tick).toBe(Tick.fromPrice('1.001')) expect(order.amount).toBe(parseUnits('100', 6)) expect(order.remaining).toBe(parseUnits('100', 6)) expect(order.isFlip).toBe(false) }) test('behavior: returns flip order details', async () => { const { base } = await setupTokenPair() // Place a flip order const { orderId } = await dex.placeFlipSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), flipTick: Tick.fromPrice('1.002'), }) // Get the order details const order = await dex.getOrder(config, { orderId, }) expect(order).toBeDefined() expect(order.maker).toBe(account.address) expect(order.isBid).toBe(true) expect(order.tick).toBe(Tick.fromPrice('1.001')) expect(order.amount).toBe(parseUnits('100', 6)) expect(order.isFlip).toBe(true) expect(order.flipTick).toBe(Tick.fromPrice('1.002')) }) test('behavior: fails for non-existent order', async () => { await setupTokenPair() // Try to get an order that doesn't exist await expect( dex.getOrder(config, { orderId: 999n, }), ).rejects.toThrow('The contract function "getOrder" reverted') }) test('behavior: reflects order state after partial fill', async () => { const { base, quote } = await setupTokenPair() // Place a large sell order const { orderId } = await dex.placeSync(config, { token: base, amount: parseUnits('500', 6), type: 'sell', tick: Tick.fromPrice('1.001'), }) // Get initial order state const orderBefore = await dex.getOrder(config, { orderId, }) expect(orderBefore.amount).toBe(parseUnits('500', 6)) expect(orderBefore.remaining).toBe(parseUnits('500', 6)) // Partially fill the order with a buy await dex.buySync(config, { tokenIn: quote, tokenOut: base, amountOut: parseUnits('100', 6), maxAmountIn: parseUnits('150', 6), }) // Get order state after partial fill const orderAfter = await dex.getOrder(config, { orderId, }) expect(orderAfter.amount).toBe(parseUnits('500', 6)) // amount unchanged expect(orderAfter.remaining).toBeLessThan(parseUnits('500', 6)) // remaining decreased }) test('behavior: linked list pointers for multiple orders at same tick', async () => { const { base } = await setupTokenPair() const tick = Tick.fromPrice('1.001') // Place first order const { orderId: orderId1 } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick, }) // Place second order at same tick const { orderId: orderId2 } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick, }) // Get first order const order1 = await dex.getOrder(config, { orderId: orderId1, }) expect(order1.prev).toBe(0n) // should be 0 as it's first expect(order1.next).toBe(orderId2) // should point to second order // Get second order const order2 = await dex.getOrder(config, { orderId: orderId2, }) expect(order2.prev).toBe(orderId1) // should point to first order expect(order2.next).toBe(0n) // should be 0 as it's last }) }) describe('getOrderbook', () => { test('default', async () => { const { base, quote } = await setupTokenPair() // Get orderbook information const book = await dex.getOrderbook(config, { base, quote, }) expect(book).toBeDefined() expect(book.base).toBe(base) expect(book.quote).toBe(quote) expect(book.bestBidTick).toBeDefined() expect(book.bestAskTick).toBeDefined() }) test('behavior: shows best bid and ask after orders placed', async () => { const { base, quote } = await setupTokenPair() const bidTick = Tick.fromPrice('0.999') const askTick = Tick.fromPrice('1.001') // Place a bid order await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: bidTick, }) // Place an ask order await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'sell', tick: askTick, }) // Get orderbook const book = await dex.getOrderbook(config, { base, quote, }) expect(book.bestBidTick).toBe(bidTick) expect(book.bestAskTick).toBe(askTick) }) test('behavior: best ticks update after better orders placed', async () => { const { base, quote } = await setupTokenPair() // Place initial bid at 0.999 await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('0.999'), }) // Get orderbook const bookBefore = await dex.getOrderbook(config, { base, quote, }) expect(bookBefore.bestBidTick).toBe(Tick.fromPrice('0.999')) // Place better bid at 1.0 await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.0'), }) // Get orderbook again const bookAfter = await dex.getOrderbook(config, { base, quote, }) expect(bookAfter.bestBidTick).toBe(Tick.fromPrice('1.0')) }) test.todo('behavior: best ticks update after order cancellation') test('behavior: multiple pairs have independent orderbooks', async () => { const { base: base1, quote: quote1 } = await setupTokenPair() const { base: base2, quote: quote2 } = await setupTokenPair() // Place order on first pair await dex.placeSync(config, { token: base1, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) // Place order on second pair at different tick await dex.placeSync(config, { token: base2, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('0.999'), }) // Get orderbooks const book1 = await dex.getOrderbook(config, { base: base1, quote: quote1, }) const book2 = await dex.getOrderbook(config, { base: base2, quote: quote2, }) // Each pair should have its own best tick expect(book1.bestBidTick).toBe(Tick.fromPrice('1.001')) expect(book2.bestBidTick).toBe(Tick.fromPrice('0.999')) }) }) describe('getTickLevel', () => { test('default', async () => { const { base } = await setupTokenPair() const tick = Tick.fromPrice('1.001') // Place an order to create liquidity at this tick const { orderId } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick, }) // Get the price level const level = await dex.getTickLevel(config, { base, tick, isBid: true, }) expect(level).toBeDefined() expect(level.head).toBe(orderId) // head should be our order expect(level.tail).toBe(orderId) // tail should also be our order (only one) expect(level.totalLiquidity).toBeGreaterThan(0n) }) test('behavior: empty price level', async () => { const { base } = await setupTokenPair() const tick = Tick.fromPrice('1.001') // Query a tick with no orders const level = await dex.getTickLevel(config, { base, tick, isBid: true, }) expect(level).toBeDefined() expect(level.head).toBe(0n) expect(level.tail).toBe(0n) expect(level.totalLiquidity).toBe(0n) }) test('behavior: multiple orders at same tick', async () => { const { base } = await setupTokenPair() const tick = Tick.fromPrice('1.001') // Place first order const { orderId: orderId1 } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick, }) // Place second order at same tick const { orderId: orderId2 } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick, }) // Get the price level const level = await dex.getTickLevel(config, { base, tick, isBid: true, }) expect(level.head).toBe(orderId1) // head should be first order expect(level.tail).toBe(orderId2) // tail should be last order // Total liquidity should be sum of both orders (approximately) expect(level.totalLiquidity).toBeGreaterThan(parseUnits('145', 6)) }) test('behavior: bid vs ask sides', async () => { const { base } = await setupTokenPair() const tick = Tick.fromPrice('1.001') // Place a buy order (bid) await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick, }) // Place a sell order (ask) at same tick await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'sell', tick, }) // Get bid side const bidLevel = await dex.getTickLevel(config, { base, tick, isBid: true, }) // Get ask side const askLevel = await dex.getTickLevel(config, { base, tick, isBid: false, }) // Both should have liquidity but different amounts expect(bidLevel.totalLiquidity).toBeGreaterThan(0n) expect(askLevel.totalLiquidity).toBeGreaterThan(0n) expect(bidLevel.head).not.toBe(askLevel.head) }) test('behavior: liquidity changes after order cancellation', async () => { const { base } = await setupTokenPair() const tick = Tick.fromPrice('1.001') // Place orders const { orderId: orderId1 } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick, }) await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick, }) // Get level before cancellation const levelBefore = await dex.getTickLevel(config, { base, tick, isBid: true, }) // Cancel first order await dex.cancelSync(config, { orderId: orderId1, }) // Get level after cancellation const levelAfter = await dex.getTickLevel(config, { base, tick, isBid: true, }) // Total liquidity should decrease expect(levelAfter.totalLiquidity).toBeLessThan(levelBefore.totalLiquidity) }) test('behavior: liquidity changes after partial fill', async () => { const { base, quote } = await setupTokenPair() const tick = Tick.fromPrice('1.001') // Place sell order await dex.placeSync(config, { token: base, amount: parseUnits('500', 6), type: 'sell', tick, }) // Get level before fill const levelBefore = await dex.getTickLevel(config, { base, tick, isBid: false, }) // Partially fill the order await dex.buySync(config, { tokenIn: quote, tokenOut: base, amountOut: parseUnits('100', 6), maxAmountIn: parseUnits('150', 6), }) // Get level after fill const levelAfter = await dex.getTickLevel(config, { base, tick, isBid: false, }) // Total liquidity should decrease expect(levelAfter.totalLiquidity).toBeLessThan(levelBefore.totalLiquidity) }) test('behavior: tick at boundaries', async () => { const { base } = await setupTokenPair() // Place order at min tick await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'sell', tick: Tick.minTick, }) // Query min tick const minLevel = await dex.getTickLevel(config, { base, tick: Tick.minTick, isBid: false, }) expect(minLevel.totalLiquidity).toBeGreaterThan(0n) // Place order at max tick await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.maxTick, }) // Query max tick const maxLevel = await dex.getTickLevel(config, { base, tick: Tick.maxTick, isBid: true, }) expect(maxLevel.totalLiquidity).toBeGreaterThan(0n) }) }) describe('getSellQuote', () => { test('default', async () => { const { base, quote } = await setupTokenPair() // Place bid orders to create liquidity await dex.placeSync(config, { token: base, amount: parseUnits('500', 6), type: 'buy', tick: Tick.fromPrice('0.999'), }) // Get quote for selling base tokens const amountOut = await dex.getSellQuote(config, { tokenIn: base, tokenOut: quote, amountIn: parseUnits('100', 6), }) expect(amountOut).toBeGreaterThan(0n) // Should be approximately 100 * 0.999 = 99.9 expect(amountOut).toBeLessThan(parseUnits('100', 6)) }) test('behavior: fails with no liquidity', async () => { const { base, quote } = await setupTokenPair() // Quote should fail with no liquidity await expect( dex.getSellQuote(config, { tokenIn: base, tokenOut: quote, amountIn: parseUnits('100', 6), }), ).rejects.toThrow('The contract function "quoteSwapExactAmountIn" reverted') }) }) describe('place', () => { test('default', async () => { // Setup token pair const { base } = await setupTokenPair() // Place a sell order const { receipt, orderId, token, ...result } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'sell', tick: Tick.fromPrice('1.001'), }) expect(receipt).toBeDefined() expect(receipt.status).toBe('success') expect(orderId).toBeGreaterThan(0n) expect(token).toBe(base) expect(result).toMatchInlineSnapshot(` { "amount": 100000000n, "flipTick": 0, "isBid": false, "isFlipOrder": false, "maker": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", "tick": 100, } `) // Place a buy order const { receipt: receipt2, orderId: orderId2, token: token2, ...result2 } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) expect(receipt2.status).toBe('success') expect(orderId2).toBeGreaterThan(0n) expect(token2).toBe(base) expect(result2).toMatchInlineSnapshot(` { "amount": 100000000n, "flipTick": 0, "isBid": true, "isFlipOrder": false, "maker": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", "tick": 100, } `) }) test('behavior: tick at boundaries', async () => { const { base } = await setupTokenPair() // Test at min tick (-2000) const { receipt: receipt1, ...result1 } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'sell', tick: Tick.minTick, }) expect(receipt1.status).toBe('success') expect(result1.tick).toBe(-2000) // Test at max tick (2000) const { receipt: receipt2, ...result2 } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.maxTick, }) expect(receipt2.status).toBe('success') expect(result2.tick).toBe(2000) }) test('behavior: tick validation fails outside bounds', async () => { const { base } = await setupTokenPair() // Test tick above max tick should fail await expect( dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.maxTick + 1, }), ).rejects.toThrow('The contract function "place" reverted') // Test tick below min tick should fail await expect( dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'sell', tick: Tick.minTick - 1, }), ).rejects.toThrow('The contract function "place" reverted') }) test('behavior: transfers from wallet', async () => { const { base, quote } = await setupTokenPair() // Get balances before placing order const baseBalanceBefore = await token.getBalance(config, { token: base, account: account.address, }) const quoteBalanceBefore = await token.getBalance(config, { token: quote, account: account.address, }) // Place a buy order - should transfer quote tokens to escrow const orderAmount = parseUnits('100', 6) const tick = Tick.fromPrice('1.001') await dex.placeSync(config, { token: base, amount: orderAmount, type: 'buy', tick, }) // Get balances after placing order const baseBalanceAfter = await token.getBalance(config, { token: base, account: account.address, }) const quoteBalanceAfter = await token.getBalance(config, { token: quote, account: account.address, }) // Base token balance should be unchanged (we're buying base, not selling) expect(baseBalanceAfter).toBe(baseBalanceBefore) // Quote token balance should decrease (escrowed for the bid) // Amount = orderAmount * (1 + tick/1000) for bids const expectedQuoteEscrowed = (orderAmount * BigInt(100000 + tick)) / BigInt(100000) expect(quoteBalanceBefore - quoteBalanceAfter).toBeGreaterThanOrEqual( expectedQuoteEscrowed, ) }) test('behavior: multiple orders at same tick', async () => { const { base } = await setupTokenPair() const tick = Tick.fromPrice('1.0005') // Place first order const { orderId: orderId1 } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick, }) // Place second order at same tick const { orderId: orderId2 } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick, }) // Order IDs should be different and sequential expect(orderId2).toBeGreaterThan(orderId1) }) }) describe('placeFlip', () => { test('default', async () => { const { base } = await setupTokenPair() // Place a flip bid order const { receipt, orderId, token, ...result } = await dex.placeFlipSync( config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), flipTick: Tick.fromPrice('1.002'), }, ) expect(receipt).toBeDefined() expect(receipt.status).toBe('success') expect(orderId).toBeGreaterThan(0n) expect(token).toBe(base) expect(result.flipTick).toBe(Tick.fromPrice('1.002')) expect(result).toMatchInlineSnapshot(` { "amount": 100000000n, "flipTick": 200, "isBid": true, "isFlipOrder": true, "maker": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", "tick": 100, } `) }) test('behavior: flip bid requires flipTick > tick', async () => { const { base } = await setupTokenPair() // Valid: flipTick > tick for bid const { receipt: receipt1 } = await dex.placeFlipSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.0005'), flipTick: Tick.fromPrice('1.001'), }) expect(receipt1.status).toBe('success') // Invalid: flipTick <= tick for bid should fail await expect( dex.placeFlipSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), flipTick: Tick.fromPrice('1.001'), // Equal }), ).rejects.toThrow('The contract function "placeFlip" reverted') await expect( dex.placeFlipSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), flipTick: Tick.fromPrice('1.0005'), // Less than }), ).rejects.toThrow('The contract function "placeFlip" reverted') }) test('behavior: flip ask requires flipTick < tick', async () => { const { base } = await setupTokenPair() // Valid: flipTick < tick for ask const { receipt: receipt1 } = await dex.placeFlipSync(config, { token: base, amount: parseUnits('100', 6), type: 'sell', tick: Tick.fromPrice('1.001'), flipTick: Tick.fromPrice('1.0005'), }) expect(receipt1.status).toBe('success') // Invalid: flipTick >= tick for ask should fail await expect( dex.placeFlipSync(config, { token: base, amount: parseUnits('100', 6), type: 'sell', tick: Tick.fromPrice('1.0005'), flipTick: Tick.fromPrice('1.0005'), // Equal }), ).rejects.toThrow('The contract function "placeFlip" reverted') await expect( dex.placeFlipSync(config, { token: base, amount: parseUnits('100', 6), type: 'sell', tick: Tick.fromPrice('1.0005'), flipTick: Tick.fromPrice('1.001'), // Greater than }), ).rejects.toThrow('The contract function "placeFlip" reverted') }) test('behavior: flip ticks at boundaries', async () => { const { base } = await setupTokenPair() // Flip order with ticks at extreme boundaries const { receipt } = await dex.placeFlipSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.minTick, flipTick: Tick.maxTick, }) expect(receipt.status).toBe('success') }) }) describe('sell', () => { test('default', async () => { const { base, quote } = await setupTokenPair() // Place bid order to create liquidity await dex.placeSync(config, { token: base, amount: parseUnits('500', 6), type: 'buy', tick: Tick.fromPrice('0.999'), }) // Sell base tokens const { receipt } = await dex.sellSync(config, { tokenIn: base, tokenOut: quote, amountIn: parseUnits('100', 6), minAmountOut: parseUnits('50', 6), }) expect(receipt).toBeDefined() expect(receipt.status).toBe('success') }) test('behavior: respects minAmountOut', async () => { const { base, quote } = await setupTokenPair() // Place bid order at low price await dex.placeSync(config, { token: base, amount: parseUnits('500', 6), type: 'buy', tick: Tick.fromPrice('0.99'), // 1% below peg }) // Try to sell with too high minAmountOut - should fail await expect( dex.sellSync(config, { tokenIn: base, tokenOut: quote, amountIn: parseUnits('100', 6), minAmountOut: parseUnits('150', 6), // Way too high }), ).rejects.toThrow('The contract function "swapExactAmountIn" reverted') }) test('behavior: fails with insufficient liquidity', async () => { const { base, quote } = await setupTokenPair() // No orders - no liquidity // Try to sell - should fail await expect( dex.sellSync(config, { tokenIn: base, tokenOut: quote, amountIn: parseUnits('100', 6), minAmountOut: parseUnits('50', 6), }), ).rejects.toThrow('The contract function "swapExactAmountIn" reverted') }) }) describe('watchFlipOrderPlaced', () => { test('default', async () => { const { base } = await setupTokenPair() const receivedOrders: Array<{ args: dex.watchFlipOrderPlaced.Args log: dex.watchFlipOrderPlaced.Log }> = [] const unwatch = dex.watchFlipOrderPlaced(config, { onFlipOrderPlaced: (args, log) => { receivedOrders.push({ args, log }) }, }) try { // Place flip order await dex.placeFlipSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), flipTick: Tick.fromPrice('1.002'), }) await vi.waitFor(() => { expect(receivedOrders).toHaveLength(1) }) expect(receivedOrders[0]?.args.flipTick).toBe(Tick.fromPrice('1.002')) expect(receivedOrders[0]?.args.tick).toBe(Tick.fromPrice('1.001')) } finally { unwatch() } }) }) describe('watchOrderCancelled', () => { test('default', async () => { const { base } = await setupTokenPair() const receivedCancellations: Array<{ args: dex.watchOrderCancelled.Args log: dex.watchOrderCancelled.Log }> = [] const unwatch = dex.watchOrderCancelled(config, { onOrderCancelled: (args, log) => { receivedCancellations.push({ args, log }) }, }) try { // Place order const { orderId } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) // Cancel order await dex.cancelSync(config, { orderId, }) await vi.waitFor(() => { expect(receivedCancellations).toHaveLength(1) }) expect(receivedCancellations[0]?.args.orderId).toBe(orderId) } finally { unwatch() } }) test('behavior: filter by orderId', async () => { const { base } = await setupTokenPair() // Place two orders const { orderId: orderId1 } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) const { orderId: orderId2 } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) const receivedCancellations: Array<{ args: dex.watchOrderCancelled.Args log: dex.watchOrderCancelled.Log }> = [] // Watch only for cancellation of orderId1 const unwatch = dex.watchOrderCancelled(config, { orderId: orderId1, onOrderCancelled: (args, log) => { receivedCancellations.push({ args, log }) }, }) try { // Cancel orderId1 (should be captured) await dex.cancelSync(config, { orderId: orderId1, }) // Cancel orderId2 (should NOT be captured) await dex.cancelSync(config, { orderId: orderId2, }) await vi.waitFor(() => { expect(receivedCancellations).toHaveLength(1) }) expect(receivedCancellations[0]?.args.orderId).toBe(orderId1) } finally { unwatch() } }) }) describe('watchOrderFilled', () => { test('default', async () => { const { base, quote } = await setupTokenPair() // Place a sell order to create liquidity const { orderId } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'sell', tick: Tick.fromPrice('1.001'), }) const receivedFills: Array<{ args: dex.watchOrderFilled.Args log: dex.watchOrderFilled.Log }> = [] const unwatch = dex.watchOrderFilled(config, { onOrderFilled: (args, log) => { receivedFills.push({ args, log }) }, }) try { // Buy from the order to trigger a fill await dex.buySync(config, { tokenIn: quote, tokenOut: base, amountOut: parseUnits('50', 6), maxAmountIn: parseUnits('100', 6), }) await vi.waitFor(() => { expect(receivedFills.length).toBeGreaterThanOrEqual(1) }) expect(receivedFills[0]?.args.orderId).toBe(orderId) expect(receivedFills[0]?.args.maker).toBe(account.address) expect(receivedFills[0]?.args.taker).toBe(account.address) expect(receivedFills[0]?.args.amountFilled).toBeGreaterThan(0n) } finally { unwatch() } }) test('behavior: filter by orderId', async () => { const { base, quote } = await setupTokenPair() // Place two sell orders const { orderId: orderId1 } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'sell', tick: Tick.fromPrice('1.001'), }) const { orderId: orderId2 } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'sell', tick: Tick.fromPrice('1.002'), }) const receivedFills: Array<{ args: dex.watchOrderFilled.Args log: dex.watchOrderFilled.Log }> = [] // Watch only for fills on orderId1 const unwatch = dex.watchOrderFilled(config, { orderId: orderId1, onOrderFilled: (args, log) => { receivedFills.push({ args, log }) }, }) try { // Buy enough to fill orderId1 only (cheaper price first) await dex.buySync(config, { tokenIn: quote, tokenOut: base, amountOut: parseUnits('50', 6), maxAmountIn: parseUnits('100', 6), }) await vi.waitFor(() => { expect(receivedFills.length).toBeGreaterThanOrEqual(1) }) expect(receivedFills[0]?.args.orderId).toBe(orderId1) // Suppress unused variable warning void orderId2 } finally { unwatch() } }) }) describe('watchOrderPlaced', () => { test('default', async () => { const { base } = await setupTokenPair() const receivedOrders: Array<{ args: dex.watchOrderPlaced.Args log: dex.watchOrderPlaced.Log }> = [] const unwatch = dex.watchOrderPlaced(config, { onOrderPlaced: (args, log) => { receivedOrders.push({ args, log }) }, }) try { // Place first order await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) // Place second order await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'sell', tick: Tick.fromPrice('0.999'), }) await vi.waitFor(() => { expect(receivedOrders).toHaveLength(2) }) expect(receivedOrders[0]?.args.isBid).toBe(true) expect(receivedOrders[0]?.args.amount).toBe(parseUnits('100', 6)) expect(receivedOrders[1]?.args.isBid).toBe(false) expect(receivedOrders[1]?.args.amount).toBe(parseUnits('100', 6)) } finally { unwatch() } }) test('behavior: filter by token', async () => { const { base } = await setupTokenPair() const { base: base2 } = await setupTokenPair() const receivedOrders: Array<{ args: dex.watchOrderPlaced.Args log: dex.watchOrderPlaced.Log }> = [] // Watch only for orders on base const unwatch = dex.watchOrderPlaced(config, { token: base, onOrderPlaced: (args, log) => { receivedOrders.push({ args, log }) }, }) try { // Place order on base (should be captured) await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) // Place order on base2 (should NOT be captured) await dex.placeSync(config, { token: base2, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) await vi.waitFor(() => { expect(receivedOrders).toHaveLength(1) }) expect(receivedOrders[0]?.args.token.toLowerCase()).toBe( base.toLowerCase(), ) } finally { unwatch() } }) }) describe('withdraw', () => { test('default', async () => { const { base, quote } = await setupTokenPair() // Create internal balance const { orderId } = await dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) await dex.cancelSync(config, { orderId }) // Get DEX balance const dexBalance = await dex.getBalance(config, { account: account.address, token: quote, }) expect(dexBalance).toBeGreaterThan(0n) // Get wallet balance before withdraw const walletBalanceBefore = await token.getBalance(config, { token: quote, account: account.address, }) // Withdraw from DEX const { receipt } = await dex.withdrawSync(config, { token: quote, amount: dexBalance, }) expect(receipt).toBeDefined() expect(receipt.status).toBe('success') // Check DEX balance is now 0 const dexBalanceAfter = await dex.getBalance(config, { account: account.address, token: quote, }) expect(dexBalanceAfter).toBe(0n) // Check wallet balance increased const walletBalanceAfter = await token.getBalance(config, { token: quote, account: account.address, }) expect(walletBalanceAfter).toBeGreaterThan(walletBalanceBefore) }) }) ================================================ FILE: packages/core/src/tempo/actions/dex.ts ================================================ import type { Account, BaseErrorType } from 'viem' import { Actions } from 'viem/tempo' import { getConnectorClient } from '../../actions/getConnectorClient.js' import type { Config } from '../../createConfig.js' import type { ChainIdParameter, ConnectorParameter, } from '../../types/properties.js' import type { PartialBy, UnionLooseOmit } from '../../types/utils.js' import type { QueryOptions, QueryParameter } from './utils.js' /** * Buys a specific amount of tokens. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.dex.buy(config, { * tokenIn: '0x20c...11', * tokenOut: '0x20c...20', * amountOut: parseUnits('100', 6), * maxAmountIn: parseUnits('105', 6), * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction hash. */ export async function buy( config: config, parameters: buy.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.dex.buy(client, parameters as never) } export declare namespace buy { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.dex.buy.Parameters, 'chain' > export type ReturnValue = Actions.dex.buy.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.dex.buy.ErrorType } /** * Buys a specific amount of tokens. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.dex.buySync(config, { * tokenIn: '0x20c...11', * tokenOut: '0x20c...20', * amountOut: parseUnits('100', 6), * maxAmountIn: parseUnits('105', 6), * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt. */ export async function buySync( config: config, parameters: buySync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.dex.buySync(client, parameters as never) } export declare namespace buySync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.dex.buySync.Parameters, 'chain' > export type ReturnValue = Actions.dex.buySync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.dex.buySync.ErrorType } /** * Cancels an order from the orderbook. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.dex.cancel(config, { * orderId: 123n, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction hash. */ export async function cancel( config: config, parameters: cancel.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.dex.cancel(client, parameters as never) } export declare namespace cancel { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.dex.cancel.Parameters, 'chain' > export type ReturnValue = Actions.dex.cancel.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.dex.cancel.ErrorType } /** * Cancels an order from the orderbook. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.dex.cancelSync(config, { * orderId: 123n, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function cancelSync( config: config, parameters: cancelSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.dex.cancelSync(client, parameters as never) } export declare namespace cancelSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.dex.cancelSync.Parameters, 'chain' > export type ReturnValue = Actions.dex.cancelSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.dex.cancelSync.ErrorType } /** * Cancels a stale order from the orderbook. * * A stale order is one where the owner's balance or allowance has dropped * below the order amount. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.dex.cancelStale(config, { * orderId: 123n, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction hash. */ export async function cancelStale( config: config, parameters: cancelStale.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.dex.cancelStale(client, parameters as never) } export declare namespace cancelStale { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.dex.cancelStale.Parameters, 'chain' > export type ReturnValue = Actions.dex.cancelStale.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.dex.cancelStale.ErrorType } /** * Cancels a stale order from the orderbook and waits for confirmation. * * A stale order is one where the owner's balance or allowance has dropped * below the order amount. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.dex.cancelStaleSync(config, { * orderId: 123n, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function cancelStaleSync( config: config, parameters: cancelStaleSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.dex.cancelStaleSync(client, parameters as never) } export declare namespace cancelStaleSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.dex.cancelStaleSync.Parameters, 'chain' > export type ReturnValue = Actions.dex.cancelStaleSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.dex.cancelStaleSync.ErrorType } /** * Creates a new trading pair on the DEX. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.dex.createPair(config, { * base: '0x20c...11', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction hash. */ export async function createPair( config: config, parameters: createPair.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.dex.createPair(client, parameters as never) } export declare namespace createPair { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.dex.createPair.Parameters, 'chain' > export type ReturnValue = Actions.dex.createPair.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.dex.createPair.ErrorType } /** * Creates a new trading pair on the DEX. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.dex.createPairSync(config, { * base: '0x20c...11', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function createPairSync( config: config, parameters: createPairSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.dex.createPairSync(client, parameters as never) } export declare namespace createPairSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.dex.createPairSync.Parameters, 'chain' > export type ReturnValue = Actions.dex.createPairSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.dex.createPairSync.ErrorType } /** * Gets a user's token balance on the DEX. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const balance = await Actions.dex.getBalance(config, { * account: '0x...', * token: '0x20c...11', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The user's token balance on the DEX. */ export function getBalance( config: config, parameters: getBalance.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.dex.getBalance(client, rest) } export namespace getBalance { export type Parameters = ChainIdParameter & Actions.dex.getBalance.Parameters export type ReturnValue = Actions.dex.getBalance.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: PartialBy, 'account'>, ) { return ['getBalance', parameters] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean(rest.account && (query?.enabled ?? true)), queryKey: queryKey(rest), async queryFn({ queryKey }) { const [, { account, ...parameters }] = queryKey if (!account) throw new Error('account is required.') return await getBalance(config, { account, ...parameters }) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = getBalance.ReturnValue, > = PartialBy, 'account'> & QueryParameter< getBalance.ReturnValue, getBalance.ErrorType, selectData, getBalance.QueryKey > export type ReturnValue< config extends Config, selectData = getBalance.ReturnValue, > = QueryOptions< getBalance.ReturnValue, getBalance.ErrorType, selectData, getBalance.QueryKey > } } /** * Gets the quote for buying a specific amount of tokens. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const amountIn = await Actions.dex.getBuyQuote(config, { * amountOut: parseUnits('100', 6), * tokenIn: '0x20c...11', * tokenOut: '0x20c...20', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The amount of tokenIn needed to buy the specified amountOut. */ export function getBuyQuote( config: config, parameters: getBuyQuote.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.dex.getBuyQuote(client, rest) } export namespace getBuyQuote { export type Parameters = ChainIdParameter & Actions.dex.getBuyQuote.Parameters export type ReturnValue = Actions.dex.getBuyQuote.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: Parameters, ) { return ['getBuyQuote', parameters] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean( rest.tokenIn && rest.tokenOut && rest.amountOut && (query?.enabled ?? true), ), queryKey: queryKey(rest), async queryFn({ queryKey }) { const [, parameters] = queryKey return await getBuyQuote(config, parameters) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = getBuyQuote.ReturnValue, > = getBuyQuote.Parameters & QueryParameter< getBuyQuote.ReturnValue, getBuyQuote.ErrorType, selectData, getBuyQuote.QueryKey > export type ReturnValue< config extends Config, selectData = getBuyQuote.ReturnValue, > = QueryOptions< getBuyQuote.ReturnValue, getBuyQuote.ErrorType, selectData, getBuyQuote.QueryKey > } } /** * Gets an order's details from the orderbook. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const order = await Actions.dex.getOrder(config, { * orderId: 123n, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The order details. */ export function getOrder( config: config, parameters: getOrder.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.dex.getOrder(client, rest) } export namespace getOrder { export type Parameters = ChainIdParameter & Actions.dex.getOrder.Parameters export type ReturnValue = Actions.dex.getOrder.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: Parameters, ) { return ['getOrder', parameters] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean(rest.orderId !== undefined && (query?.enabled ?? true)), queryKey: queryKey(rest), async queryFn({ queryKey }) { const [, parameters] = queryKey return await getOrder(config, parameters) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = getOrder.ReturnValue, > = getOrder.Parameters & QueryParameter< getOrder.ReturnValue, getOrder.ErrorType, selectData, getOrder.QueryKey > export type ReturnValue< config extends Config, selectData = getOrder.ReturnValue, > = QueryOptions< getOrder.ReturnValue, getOrder.ErrorType, selectData, getOrder.QueryKey > } } /** * Gets orderbook information for a trading pair. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const book = await Actions.dex.getOrderbook(config, { * base: '0x20c...11', * quote: '0x20c...20', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The orderbook information. */ export function getOrderbook( config: config, parameters: getOrderbook.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.dex.getOrderbook(client, rest) } export namespace getOrderbook { export type Parameters = ChainIdParameter & Actions.dex.getOrderbook.Parameters export type ReturnValue = Actions.dex.getOrderbook.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: Parameters, ) { return ['getOrderbook', parameters] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean(rest.base && rest.quote && (query?.enabled ?? true)), queryKey: queryKey(rest), async queryFn({ queryKey }) { const [, parameters] = queryKey return await getOrderbook(config, parameters) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = getOrderbook.ReturnValue, > = getOrderbook.Parameters & QueryParameter< getOrderbook.ReturnValue, getOrderbook.ErrorType, selectData, getOrderbook.QueryKey > export type ReturnValue< config extends Config, selectData = getOrderbook.ReturnValue, > = QueryOptions< getOrderbook.ReturnValue, getOrderbook.ErrorType, selectData, getOrderbook.QueryKey > } } /** * Gets the price level information at a specific tick. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions, Tick } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const level = await Actions.dex.getTickLevel(config, { * base: '0x20c...11', * tick: Tick.fromPrice('1.001'), * isBid: true, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The price level information. */ export function getTickLevel( config: config, parameters: getTickLevel.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.dex.getTickLevel(client, rest) } export namespace getTickLevel { export type Parameters = ChainIdParameter & Actions.dex.getTickLevel.Parameters export type ReturnValue = Actions.dex.getTickLevel.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: Parameters, ) { return ['getTickLevel', parameters] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean( rest.base && rest.tick !== undefined && rest.isBid !== undefined && (query?.enabled ?? true), ), queryKey: queryKey(rest), async queryFn({ queryKey }) { const [, parameters] = queryKey return await getTickLevel(config, parameters) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = getTickLevel.ReturnValue, > = getTickLevel.Parameters & QueryParameter< getTickLevel.ReturnValue, getTickLevel.ErrorType, selectData, getTickLevel.QueryKey > export type ReturnValue< config extends Config, selectData = getTickLevel.ReturnValue, > = QueryOptions< getTickLevel.ReturnValue, getTickLevel.ErrorType, selectData, getTickLevel.QueryKey > } } /** * Gets the quote for selling a specific amount of tokens. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const amountOut = await Actions.dex.getSellQuote(config, { * amountIn: parseUnits('100', 6), * tokenIn: '0x20c...11', * tokenOut: '0x20c...20', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The amount of tokenOut received for selling the specified amountIn. */ export function getSellQuote( config: config, parameters: getSellQuote.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.dex.getSellQuote(client, rest) } export namespace getSellQuote { export type Parameters = ChainIdParameter & Actions.dex.getSellQuote.Parameters export type ReturnValue = Actions.dex.getSellQuote.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: Parameters, ) { return ['getSellQuote', parameters] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean( rest.tokenIn && rest.tokenOut && rest.amountIn && (query?.enabled ?? true), ), queryKey: queryKey(rest), async queryFn({ queryKey }) { const [, parameters] = queryKey return await getSellQuote(config, parameters) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = getSellQuote.ReturnValue, > = getSellQuote.Parameters & QueryParameter< getSellQuote.ReturnValue, getSellQuote.ErrorType, selectData, getSellQuote.QueryKey > export type ReturnValue< config extends Config, selectData = getSellQuote.ReturnValue, > = QueryOptions< getSellQuote.ReturnValue, getSellQuote.ErrorType, selectData, getSellQuote.QueryKey > } } /** * Places a limit order on the orderbook. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.dex.place(config, { * amount: parseUnits('100', 6), * tick: Tick.fromPrice('0.99'), * token: '0x20c...11', * type: 'buy', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction hash. */ export async function place( config: config, parameters: place.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.dex.place(client, parameters as never) } export declare namespace place { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.dex.place.Parameters, 'chain' > export type ReturnValue = Actions.dex.place.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.dex.place.ErrorType } /** * Places a flip order that automatically flips when filled. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.dex.placeFlip(config, { * amount: parseUnits('100', 6), * flipTick: Tick.fromPrice('1.01'), * tick: Tick.fromPrice('0.99'), * token: '0x20c...11', * type: 'buy', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction hash. */ export async function placeFlip( config: config, parameters: placeFlip.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.dex.placeFlip(client, parameters as never) } export declare namespace placeFlip { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.dex.placeFlip.Parameters, 'chain' > export type ReturnValue = Actions.dex.placeFlip.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.dex.placeFlip.ErrorType } /** * Places a flip order that automatically flips when filled. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.dex.placeFlipSync(config, { * amount: parseUnits('100', 6), * flipTick: Tick.fromPrice('1.01'), * tick: Tick.fromPrice('0.99'), * token: '0x20c...11', * type: 'buy', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function placeFlipSync( config: config, parameters: placeFlipSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.dex.placeFlipSync(client, parameters as never) } export declare namespace placeFlipSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.dex.placeFlipSync.Parameters, 'chain' > export type ReturnValue = Actions.dex.placeFlipSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.dex.placeFlipSync.ErrorType } /** * Places a limit order on the orderbook. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.dex.placeSync(config, { * amount: parseUnits('100', 6), * tick: Tick.fromPrice('0.99'), * token: '0x20c...11', * type: 'buy', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function placeSync( config: config, parameters: placeSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.dex.placeSync(client, parameters as never) } export declare namespace placeSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.dex.placeSync.Parameters, 'chain' > export type ReturnValue = Actions.dex.placeSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.dex.placeSync.ErrorType } /** * Sells a specific amount of tokens. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.dex.sell(config, { * amountIn: parseUnits('100', 6), * minAmountOut: parseUnits('95', 6), * tokenIn: '0x20c...11', * tokenOut: '0x20c...20', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction hash. */ export async function sell( config: config, parameters: sell.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.dex.sell(client, parameters as never) } export declare namespace sell { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.dex.sell.Parameters, 'chain' > export type ReturnValue = Actions.dex.sell.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.dex.sell.ErrorType } /** * Sells a specific amount of tokens. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.dex.sellSync(config, { * amountIn: parseUnits('100', 6), * minAmountOut: parseUnits('95', 6), * tokenIn: '0x20c...11', * tokenOut: '0x20c...20', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt. */ export async function sellSync( config: config, parameters: sellSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.dex.sellSync(client, parameters as never) } export declare namespace sellSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.dex.sellSync.Parameters, 'chain' > export type ReturnValue = Actions.dex.sellSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.dex.sellSync.ErrorType } /** * Watches for flip order placement events on the DEX. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.dex.watchFlipOrderPlaced(config, { * onFlipOrderPlaced: (args, log) => { * console.log('Flip order placed:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchFlipOrderPlaced( config: config, parameters: watchFlipOrderPlaced.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.dex.watchFlipOrderPlaced(client, rest) } export declare namespace watchFlipOrderPlaced { export type Parameters = ChainIdParameter & Actions.dex.watchFlipOrderPlaced.Parameters export type Args = Actions.dex.watchFlipOrderPlaced.Args export type Log = Actions.dex.watchFlipOrderPlaced.Log } /** * Watches for order cancellation events on the DEX. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.dex.watchOrderCancelled(config, { * onOrderCancelled: (args, log) => { * console.log('Order cancelled:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchOrderCancelled( config: config, parameters: watchOrderCancelled.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.dex.watchOrderCancelled(client, rest) } export declare namespace watchOrderCancelled { export type Parameters = ChainIdParameter & Actions.dex.watchOrderCancelled.Parameters export type Args = Actions.dex.watchOrderCancelled.Args export type Log = Actions.dex.watchOrderCancelled.Log } /** * Watches for order filled events on the DEX. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.dex.watchOrderFilled(config, { * onOrderFilled: (args, log) => { * console.log('Order filled:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchOrderFilled( config: config, parameters: watchOrderFilled.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.dex.watchOrderFilled(client, rest) } export declare namespace watchOrderFilled { export type Parameters = ChainIdParameter & Actions.dex.watchOrderFilled.Parameters export type Args = Actions.dex.watchOrderFilled.Args export type Log = Actions.dex.watchOrderFilled.Log } /** * Watches for order placement events on the DEX. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.dex.watchOrderPlaced(config, { * onOrderPlaced: (args, log) => { * console.log('Order placed:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchOrderPlaced( config: config, parameters: watchOrderPlaced.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.dex.watchOrderPlaced(client, rest) } export declare namespace watchOrderPlaced { export type Parameters = ChainIdParameter & Actions.dex.watchOrderPlaced.Parameters export type Args = Actions.dex.watchOrderPlaced.Args export type Log = Actions.dex.watchOrderPlaced.Log } /** * Withdraws tokens from the DEX to the caller's wallet. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.dex.withdraw(config, { * amount: 100n, * token: '0x20c...11', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction hash. */ export async function withdraw( config: config, parameters: withdraw.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.dex.withdraw(client, parameters as never) } export declare namespace withdraw { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.dex.withdraw.Parameters, 'chain' > export type ReturnValue = Actions.dex.withdraw.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.dex.withdraw.ErrorType } /** * Withdraws tokens from the DEX to the caller's wallet. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.dex.withdrawSync(config, { * amount: 100n, * token: '0x20c...11', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function withdrawSync( config: config, parameters: withdrawSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.dex.withdrawSync(client, parameters as never) } export declare namespace withdrawSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.dex.withdrawSync.Parameters, 'chain' > export type ReturnValue = Actions.dex.withdrawSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.dex.withdrawSync.ErrorType } ================================================ FILE: packages/core/src/tempo/actions/faucet.ts ================================================ import type { BaseErrorType } from 'viem' import { Actions } from 'viem/tempo' import type { Config } from '../../createConfig.js' import type { ChainIdParameter } from '../../types/properties.js' import type { UnionCompute } from '../../types/utils.js' /** * Funds an account with an initial amount of set token(s) * on Tempo's testnet. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const hashes = await Actions.faucet.fund(config, { * account: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction hashes. */ export async function fund( config: config, parameters: fund.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.faucet.fund(client, rest) } export declare namespace fund { export type Parameters = UnionCompute< ChainIdParameter & Actions.faucet.fund.Parameters > export type ReturnValue = Actions.faucet.fund.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.faucet.fund.ErrorType } /** * Funds an account with an initial amount of set token(s) * on Tempo's testnet. Returns with the transaction receipts. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const receipts = await Actions.faucet.fundSync(config, { * account: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction hashes. */ export async function fundSync( config: config, parameters: fundSync.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.faucet.fundSync(client, rest) } export declare namespace fundSync { export type Parameters = UnionCompute< ChainIdParameter & Actions.faucet.fundSync.Parameters > export type ReturnValue = Actions.faucet.fundSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.faucet.fundSync.ErrorType } ================================================ FILE: packages/core/src/tempo/actions/fee.test.ts ================================================ import { connect } from '@wagmi/core' import { accounts, config, queryClient } from '@wagmi/test/tempo' import { describe, expect, test } from 'vitest' import { getUserToken, setUserToken, setUserTokenSync } from './fee.js' const account = accounts[0] describe('getUserToken', () => { test('default', async () => { const result = await getUserToken(config, { account, }) expect(result).toMatchInlineSnapshot(` { "address": "0x20C0000000000000000000000000000000000001", "id": 1n, } `) }) describe('queryOptions', () => { test('default', async () => { const options = getUserToken.queryOptions(config, { account, }) expect(await queryClient.fetchQuery(options)).toMatchInlineSnapshot( ` { "address": "0x20C0000000000000000000000000000000000001", "id": 1n, } `, ) }) }) }) describe('setUserToken', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) const hash = await setUserToken(config, { account, token: '0x20C0000000000000000000000000000000000001', }) expect(hash).toBeDefined() }) }) describe('setUserTokenSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) const result = await setUserTokenSync(config, { account, token: '0x20C0000000000000000000000000000000000001', }) expect(result).toBeDefined() }) }) ================================================ FILE: packages/core/src/tempo/actions/fee.ts ================================================ import type { Account, BaseErrorType } from 'viem' import { Actions } from 'viem/tempo' import { getConnectorClient } from '../../actions/getConnectorClient.js' import type { Config } from '../../createConfig.js' import type { ChainIdParameter, ConnectorParameter, } from '../../types/properties.js' import type { PartialBy, UnionLooseOmit } from '../../types/utils.js' import type { QueryOptions, QueryParameter } from './utils.js' import { filterQueryOptions } from './utils.js' /** * Gets the user's default fee token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.fee.getUserToken(config, { * account: '0x20c...0055', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export function getUserToken( config: config, parameters: getUserToken.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.fee.getUserToken(client, rest) } export namespace getUserToken { export type Parameters = ChainIdParameter & Actions.fee.getUserToken.Parameters export type ReturnValue = Actions.fee.getUserToken.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: PartialBy, 'account'>, ) { return ['getUserToken', filterQueryOptions(parameters)] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean(rest.account && (query?.enabled ?? true)), queryKey: queryKey(rest), async queryFn(context) { const [, { account, ...parameters }] = context.queryKey if (!account) throw new Error('account is required.') return await getUserToken(config, { account, ...parameters }) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = getUserToken.ReturnValue, > = PartialBy, 'account'> & QueryParameter< getUserToken.ReturnValue, getUserToken.ErrorType, selectData, getUserToken.QueryKey > export type ReturnValue< config extends Config, selectData = getUserToken.ReturnValue, > = QueryOptions< getUserToken.ReturnValue, getUserToken.ErrorType, selectData, getUserToken.QueryKey > } } /** * Sets the user's default fee token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.fee.setUserToken(config, { * token: '0x20c...0055', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function setUserToken( config: config, parameters: setUserToken.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.fee.setUserToken(client, parameters as never) } export declare namespace setUserToken { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.fee.setUserToken.Parameters, 'chain' > export type ReturnValue = Actions.fee.setUserToken.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.fee.setUserToken.ErrorType } /** * Sets the user's default fee token. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.fee.setUserTokenSync(config, { * token: '0x20c...0055', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function setUserTokenSync( config: config, parameters: setUserTokenSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.fee.setUserTokenSync(client, parameters as never) } export declare namespace setUserTokenSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.fee.setUserTokenSync.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.fee.setUserTokenSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.fee.setUserTokenSync.ErrorType } /** * Watches for user token set events on the Fee Manager. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.fee.watchSetUserToken(config, { * onUserTokenSet: (args, log) => { * console.log('User token set:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchSetUserToken( config: config, parameters: watchSetUserToken.Parameters, ): () => void { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.fee.watchSetUserToken(client, rest) } export declare namespace watchSetUserToken { export type Parameters = ChainIdParameter & Actions.fee.watchSetUserToken.Parameters } ================================================ FILE: packages/core/src/tempo/actions/index.ts ================================================ /** biome-ignore-all lint/performance/noReExportAll: entrypoint */ // biome-ignore lint/performance/noBarrelFile: stable export * as amm from './amm.js' export * as dex from './dex.js' export * as faucet from './faucet.js' export * as fee from './fee.js' export * as nonce from './nonce.js' export * as policy from './policy.js' export * as reward from './reward.js' export * as token from './token.js' ================================================ FILE: packages/core/src/tempo/actions/nonce.test.ts ================================================ import { accounts, config, queryClient, restart } from '@wagmi/test/tempo' import { beforeEach, describe, expect, test, vi } from 'vitest' import * as nonce from './nonce.js' import * as token from './token.js' const account = accounts[0] const account2 = accounts[1] beforeEach(async () => { await restart() }) describe('getNonce', () => { test('default', async () => { const result = await nonce.getNonce(config, { account: account.address, nonceKey: 1n, }) expect(result).toBe(0n) }) test('queryOptions', async () => { const options = nonce.getNonce.queryOptions(config, { account: account.address, nonceKey: 1n, }) const result = await queryClient.fetchQuery(options) expect(result).toBe(0n) }) }) test('watchNonceIncremented', async () => { const events: any[] = [] const unwatch = nonce.watchNonceIncremented(config, { onNonceIncremented: (args) => { events.push(args) }, args: { account: account.address, nonceKey: 5n, }, }) // Have to manually set nonce because eth_FillTransaction does not support nonce keys await token.transferSync(config, { to: account2.address, amount: 1n, token: 1n, nonceKey: 5n, nonce: 0, }) await token.transferSync(config, { to: account2.address, amount: 1n, token: 1n, nonceKey: 5n, nonce: 1, }) await vi.waitFor(() => { expect(events).toHaveLength(2) }) unwatch() expect(events[0]?.account).toBe(account.address) expect(events[0]?.nonceKey).toBe(5n) expect(events[0]?.newNonce).toBe(1n) expect(events[1]?.newNonce).toBe(2n) }) ================================================ FILE: packages/core/src/tempo/actions/nonce.ts ================================================ import type { BaseErrorType } from 'viem' import { Actions } from 'viem/tempo' import type { Config } from '../../createConfig.js' import type { ChainIdParameter } from '../../types/properties.js' import type { PartialBy } from '../../types/utils.js' import type { QueryOptions, QueryParameter } from './utils.js' import { filterQueryOptions } from './utils.js' /** * Gets the nonce for an account and nonce key. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const nonce = await Actions.nonce.getNonce(config, { * account: '0x...', * nonceKey: 1n, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The nonce value. */ export function getNonce( config: config, parameters: getNonce.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.nonce.getNonce(client, rest) } export namespace getNonce { export type Parameters = ChainIdParameter & Actions.nonce.getNonce.Parameters export type ReturnValue = Actions.nonce.getNonce.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: PartialBy, 'account' | 'nonceKey'>, ) { return ['getNonce', filterQueryOptions(parameters)] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean( rest.account && rest.nonceKey !== undefined && (query?.enabled ?? true), ), queryKey: queryKey(rest), async queryFn(context) { const [, { account, nonceKey, ...parameters }] = context.queryKey if (!account) throw new Error('account is required.') if (nonceKey === undefined) throw new Error('nonceKey is required.') return await getNonce(config, { account, nonceKey, ...parameters }) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = getNonce.ReturnValue, > = PartialBy, 'account' | 'nonceKey'> & QueryParameter< getNonce.ReturnValue, getNonce.ErrorType, selectData, getNonce.QueryKey > export type ReturnValue< config extends Config, selectData = getNonce.ReturnValue, > = QueryOptions< getNonce.ReturnValue, getNonce.ErrorType, selectData, getNonce.QueryKey > } } /** * Watches for nonce incremented events. * * @deprecated This function has been deprecated post-AllegroModerato. It will be removed in a future version. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.nonce.watchNonceIncremented(config, { * onNonceIncremented: (args, log) => { * console.log('Nonce incremented:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchNonceIncremented( config: config, parameters: watchNonceIncremented.Parameters, ): () => void { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.nonce.watchNonceIncremented(client, rest) } export declare namespace watchNonceIncremented { export type Parameters = ChainIdParameter & Actions.nonce.watchNonceIncremented.Parameters } ================================================ FILE: packages/core/src/tempo/actions/policy.test.ts ================================================ import { connect } from '@wagmi/core' import { accounts, config, queryClient } from '@wagmi/test/tempo' import { describe, expect, test, vi } from 'vitest' import * as policy from './policy.js' const account = accounts[0] const account2 = accounts[1] describe('create', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) const result = await policy.createSync(config, { type: 'whitelist', }) expect(result.receipt).toBeDefined() expect(result.policyId).toBeDefined() expect(result.policyType).toBe(0) expect(result.updater).toBe(account.address) // verify policy was created const data = await policy.getData(config, { policyId: result.policyId, }) expect(data.admin).toBe(account.address) expect(data.type).toBe('whitelist') }) test('behavior: blacklist', async () => { await connect(config, { connector: config.connectors[0]!, }) const result = await policy.createSync(config, { type: 'blacklist', }) expect(result.receipt).toBeDefined() expect(result.policyId).toBeDefined() expect(result.policyType).toBe(1) expect(result.updater).toBe(account.address) // verify policy was created const data = await policy.getData(config, { policyId: result.policyId, }) expect(data.admin).toBe(account.address) expect(data.type).toBe('blacklist') }) }) describe('setAdmin', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // create policy const { policyId } = await policy.createSync(config, { type: 'whitelist', }) // set new admin const { receipt: setAdminReceipt, ...setAdminResult } = await policy.setAdminSync(config, { policyId, admin: account2.address, }) expect(setAdminReceipt).toBeDefined() expect(setAdminResult.policyId).toBe(policyId) expect(setAdminResult.admin).toBe(account2.address) expect(setAdminResult.updater).toBe(account.address) { // verify new admin const data = await policy.getData(config, { policyId, }) expect(data.admin).toBe(account2.address) } }) }) describe('modifyWhitelist', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // create whitelist policy const { policyId } = await policy.createSync(config, { type: 'whitelist', }) // verify account2 is not authorized { const isAuthorized = await policy.isAuthorized(config, { policyId, user: account2.address, }) expect(isAuthorized).toBe(false) } // add account2 to whitelist const addResult = await policy.modifyWhitelistSync(config, { policyId, address: account2.address, allowed: true, }) expect(addResult.receipt).toBeDefined() expect(addResult.policyId).toBe(policyId) expect(addResult.account).toBe(account2.address) expect(addResult.allowed).toBe(true) expect(addResult.updater).toBe(account.address) // verify account2 is authorized { const isAuthorized = await policy.isAuthorized(config, { policyId, user: account2.address, }) expect(isAuthorized).toBe(true) } // remove account2 from whitelist const removeResult = await policy.modifyWhitelistSync(config, { policyId, address: account2.address, allowed: false, }) expect(removeResult.receipt).toBeDefined() expect(removeResult.policyId).toBe(policyId) expect(removeResult.account).toBe(account2.address) expect(removeResult.allowed).toBe(false) expect(removeResult.updater).toBe(account.address) // verify account2 is no longer authorized { const isAuthorized = await policy.isAuthorized(config, { policyId, user: account2.address, }) expect(isAuthorized).toBe(false) } }) }) describe('modifyBlacklist', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // create blacklist policy const { policyId } = await policy.createSync(config, { type: 'blacklist', }) // verify account2 is authorized (not blacklisted) { const isAuthorized = await policy.isAuthorized(config, { policyId, user: account2.address, }) expect(isAuthorized).toBe(true) } // add account2 to blacklist const addResult = await policy.modifyBlacklistSync(config, { policyId, address: account2.address, restricted: true, }) expect(addResult.receipt).toBeDefined() expect(addResult.policyId).toBe(policyId) expect(addResult.account).toBe(account2.address) expect(addResult.restricted).toBe(true) expect(addResult.updater).toBe(account.address) // verify account2 is not authorized (blacklisted) { const isAuthorized = await policy.isAuthorized(config, { policyId, user: account2.address, }) expect(isAuthorized).toBe(false) } // remove account2 from blacklist const removeResult = await policy.modifyBlacklistSync(config, { policyId, address: account2.address, restricted: false, }) expect(removeResult.receipt).toBeDefined() expect(removeResult.policyId).toBe(policyId) expect(removeResult.account).toBe(account2.address) expect(removeResult.restricted).toBe(false) expect(removeResult.updater).toBe(account.address) // verify account2 is authorized again { const isAuthorized = await policy.isAuthorized(config, { policyId, user: account2.address, }) expect(isAuthorized).toBe(true) } }) }) describe('getData', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // create policy const { policyId } = await policy.createSync(config, { type: 'whitelist', }) { // get policy data const data = await policy.getData(config, { policyId, }) expect(data.admin).toBe(account.address) expect(data.type).toBe('whitelist') } }) test('behavior: blacklist', async () => { await connect(config, { connector: config.connectors[0]!, }) // create blacklist policy const { policyId } = await policy.createSync(config, { type: 'blacklist', }) { // get policy data const data = await policy.getData(config, { policyId, }) expect(data.admin).toBe(account.address) expect(data.type).toBe('blacklist') } }) describe('queryOptions', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // create policy const { policyId } = await policy.createSync(config, { type: 'whitelist', }) const options = policy.getData.queryOptions(config, { policyId, }) const data = await queryClient.fetchQuery(options) expect(data.admin).toBe(account.address) expect(data.type).toBe('whitelist') }) }) }) describe('isAuthorized', () => { test('special policy: always-reject (policyId 0)', async () => { const isAuthorized = await policy.isAuthorized(config, { policyId: 0n, user: account.address, }) expect(isAuthorized).toBe(false) }) test('special policy: always-allow (policyId 1)', async () => { const isAuthorized = await policy.isAuthorized(config, { policyId: 1n, user: account.address, }) expect(isAuthorized).toBe(true) }) describe('queryOptions', () => { test('default', async () => { const options = policy.isAuthorized.queryOptions(config, { policyId: 1n, user: account.address, }) const isAuthorized = await queryClient.fetchQuery(options) expect(isAuthorized).toBe(true) }) }) }) describe('watchCreate', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) const events: any[] = [] const unwatch = policy.watchCreate(config, { onPolicyCreated: (args, log) => { events.push({ args, log }) }, }) // create policy await policy.createSync(config, { type: 'whitelist', }) await vi.waitFor(() => { expect(events.length).toBeGreaterThanOrEqual(1) }) unwatch() expect(events[0].args.policyId).toBeDefined() expect(events[0].args.updater).toBe(account.address) expect(events[0].args.type).toBe('whitelist') }) }) describe('watchAdminUpdated', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // create policy const { policyId } = await policy.createSync(config, { type: 'whitelist', }) const events: any[] = [] const unwatch = policy.watchAdminUpdated(config, { onAdminUpdated: (args, log) => { events.push({ args, log }) }, }) // set new admin await policy.setAdminSync(config, { policyId, admin: account2.address, }) await vi.waitFor(() => { const event = events.find((e) => e.args.admin === account2.address) expect(event).toBeDefined() }) unwatch() const event = events.find((e) => e.args.admin === account2.address) expect(event.args.policyId).toBe(policyId) expect(event.args.updater).toBe(account.address) }) }) describe('watchWhitelistUpdated', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // create whitelist policy const { policyId } = await policy.createSync(config, { type: 'whitelist', }) const events: any[] = [] const unwatch = policy.watchWhitelistUpdated(config, { onWhitelistUpdated: (args, log) => { events.push({ args, log }) }, }) // add address to whitelist await policy.modifyWhitelistSync(config, { policyId, address: account2.address, allowed: true, }) // remove address from whitelist await policy.modifyWhitelistSync(config, { policyId, address: account2.address, allowed: false, }) await vi.waitFor(() => { expect(events.length).toBeGreaterThanOrEqual(2) }) unwatch() expect(events[0].args.policyId).toBe(policyId) expect(events[0].args.updater).toBe(account.address) expect(events[0].args.account).toBe(account2.address) expect(events[0].args.allowed).toBe(true) expect(events[1].args.allowed).toBe(false) }) }) describe('watchBlacklistUpdated', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // create blacklist policy const { policyId } = await policy.createSync(config, { type: 'blacklist', }) const events: any[] = [] const unwatch = policy.watchBlacklistUpdated(config, { onBlacklistUpdated: (args, log) => { events.push({ args, log }) }, }) // add address to blacklist await policy.modifyBlacklistSync(config, { policyId, address: account2.address, restricted: true, }) // remove address from blacklist await policy.modifyBlacklistSync(config, { policyId, address: account2.address, restricted: false, }) await vi.waitFor(() => { expect(events.length).toBeGreaterThanOrEqual(2) }) unwatch() expect(events[0].args.policyId).toBe(policyId) expect(events[0].args.updater).toBe(account.address) expect(events[0].args.account).toBe(account2.address) expect(events[0].args.restricted).toBe(true) expect(events[1].args.restricted).toBe(false) }) }) ================================================ FILE: packages/core/src/tempo/actions/policy.ts ================================================ import type { Account, BaseErrorType } from 'viem' import { Actions } from 'viem/tempo' import { getConnectorClient } from '../../actions/getConnectorClient.js' import type { Config } from '../../createConfig.js' import type { ChainIdParameter, ConnectorParameter, } from '../../types/properties.js' import type { UnionLooseOmit } from '../../types/utils.js' import type { QueryOptions, QueryParameter } from './utils.js' /** * Creates a new policy. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.policy.create(config, { * type: 'whitelist', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function create( config: config, parameters: create.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.policy.create(client, parameters as never) } export declare namespace create { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.policy.create.Parameters, 'chain' | 'admin' > export type ReturnValue = Actions.policy.create.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.policy.create.ErrorType } /** * Creates a new policy. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.policy.createSync(config, { * type: 'whitelist', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function createSync( config: config, parameters: createSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.policy.createSync(client, parameters as never) } export declare namespace createSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.policy.createSync.Parameters, 'chain' | 'admin' > export type ReturnValue = Actions.policy.createSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.policy.createSync.ErrorType } /** * Sets the admin for a policy. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.policy.setAdmin(config, { * policyId: 2n, * admin: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function setAdmin( config: config, parameters: setAdmin.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.policy.setAdmin(client, parameters as never) } export declare namespace setAdmin { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.policy.setAdmin.Parameters, 'chain' > export type ReturnValue = Actions.policy.setAdmin.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.policy.setAdmin.ErrorType } /** * Sets the admin for a policy. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.policy.setAdminSync(config, { * policyId: 2n, * admin: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function setAdminSync( config: config, parameters: setAdminSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.policy.setAdminSync(client, parameters as never) } export declare namespace setAdminSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.policy.setAdminSync.Parameters, 'chain' > export type ReturnValue = Actions.policy.setAdminSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.policy.setAdminSync.ErrorType } /** * Modifies a policy whitelist. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.policy.modifyWhitelist(config, { * policyId: 2n, * address: '0x...', * allowed: true, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function modifyWhitelist( config: config, parameters: modifyWhitelist.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.policy.modifyWhitelist(client, parameters as never) } export declare namespace modifyWhitelist { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.policy.modifyWhitelist.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.policy.modifyWhitelist.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.policy.modifyWhitelist.ErrorType } /** * Modifies a policy whitelist. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.policy.modifyWhitelistSync(config, { * policyId: 2n, * address: '0x...', * allowed: true, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function modifyWhitelistSync( config: config, parameters: modifyWhitelistSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.policy.modifyWhitelistSync(client, parameters as never) } export declare namespace modifyWhitelistSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.policy.modifyWhitelistSync.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.policy.modifyWhitelistSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.policy.modifyWhitelistSync.ErrorType } /** * Modifies a policy blacklist. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.policy.modifyBlacklist(config, { * policyId: 2n, * address: '0x...', * restricted: true, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function modifyBlacklist( config: config, parameters: modifyBlacklist.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.policy.modifyBlacklist(client, parameters as never) } export declare namespace modifyBlacklist { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.policy.modifyBlacklist.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.policy.modifyBlacklist.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.policy.modifyBlacklist.ErrorType } /** * Modifies a policy blacklist. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.policy.modifyBlacklistSync(config, { * policyId: 2n, * address: '0x...', * restricted: true, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function modifyBlacklistSync( config: config, parameters: modifyBlacklistSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.policy.modifyBlacklistSync(client, parameters as never) } export declare namespace modifyBlacklistSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.policy.modifyBlacklistSync.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.policy.modifyBlacklistSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.policy.modifyBlacklistSync.ErrorType } /** * Gets policy data. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const data = await Actions.policy.getData(config, { * policyId: 2n, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The policy data. */ export function getData( config: config, parameters: getData.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.policy.getData(client, rest) } export namespace getData { export type Parameters = ChainIdParameter & Actions.policy.getData.Parameters export type ReturnValue = Actions.policy.getData.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: Parameters, ) { return ['getData', parameters] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean(rest.policyId !== undefined && (query?.enabled ?? true)), queryKey: queryKey(rest), async queryFn({ queryKey }) { const [, parameters] = queryKey return await getData(config, parameters) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = getData.ReturnValue, > = getData.Parameters & QueryParameter< getData.ReturnValue, getData.ErrorType, selectData, getData.QueryKey > export type ReturnValue< config extends Config, selectData = getData.ReturnValue, > = QueryOptions< getData.ReturnValue, getData.ErrorType, selectData, getData.QueryKey > } } /** * Checks if a user is authorized by a policy. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const authorized = await Actions.policy.isAuthorized(config, { * policyId: 2n, * user: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Whether the user is authorized. */ export function isAuthorized( config: config, parameters: isAuthorized.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.policy.isAuthorized(client, rest) } export namespace isAuthorized { export type Parameters = ChainIdParameter & Actions.policy.isAuthorized.Parameters export type ReturnValue = Actions.policy.isAuthorized.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: Parameters, ) { return ['isAuthorized', parameters] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean( rest.policyId !== undefined && rest.user && (query?.enabled ?? true), ), queryKey: queryKey(rest), async queryFn({ queryKey }) { const [, parameters] = queryKey return await isAuthorized(config, parameters) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = isAuthorized.ReturnValue, > = isAuthorized.Parameters & QueryParameter< isAuthorized.ReturnValue, isAuthorized.ErrorType, selectData, isAuthorized.QueryKey > export type ReturnValue< config extends Config, selectData = isAuthorized.ReturnValue, > = QueryOptions< isAuthorized.ReturnValue, isAuthorized.ErrorType, selectData, isAuthorized.QueryKey > } } /** * Watches for policy creation events. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.policy.watchCreate(config, { * onPolicyCreated: (args, log) => { * console.log('Policy created:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchCreate( config: config, parameters: watchCreate.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.policy.watchCreate(client, rest) } export declare namespace watchCreate { export type Parameters = ChainIdParameter & Actions.policy.watchCreate.Parameters } /** * Watches for policy admin update events. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.policy.watchAdminUpdated(config, { * onAdminUpdated: (args, log) => { * console.log('Policy admin updated:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchAdminUpdated( config: config, parameters: watchAdminUpdated.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.policy.watchAdminUpdated(client, rest) } export declare namespace watchAdminUpdated { export type Parameters = ChainIdParameter & Actions.policy.watchAdminUpdated.Parameters } /** * Watches for whitelist update events. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.policy.watchWhitelistUpdated(config, { * onWhitelistUpdated: (args, log) => { * console.log('Whitelist updated:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchWhitelistUpdated( config: config, parameters: watchWhitelistUpdated.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.policy.watchWhitelistUpdated(client, rest) } export declare namespace watchWhitelistUpdated { export type Parameters = ChainIdParameter & Actions.policy.watchWhitelistUpdated.Parameters } /** * Watches for blacklist update events. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.policy.watchBlacklistUpdated(config, { * onBlacklistUpdated: (args, log) => { * console.log('Blacklist updated:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchBlacklistUpdated( config: config, parameters: watchBlacklistUpdated.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.policy.watchBlacklistUpdated(client, rest) } export declare namespace watchBlacklistUpdated { export type Parameters = ChainIdParameter & Actions.policy.watchBlacklistUpdated.Parameters } ================================================ FILE: packages/core/src/tempo/actions/reward.test.ts ================================================ import { getConnection } from '@wagmi/core' import { config, queryClient, setupToken } from '@wagmi/test/tempo' import { parseUnits } from 'viem' import { describe, expect, test, vi } from 'vitest' import * as actions from './reward.js' import * as tokenActions from './token.js' describe('claimSync', () => { test('default', async () => { const { token } = await setupToken() const connection = getConnection(config) const balanceBefore = await tokenActions.getBalance(config, { account: connection.address!, token, }) // Opt in to rewards await actions.setRecipientSync(config, { recipient: connection.address!, token, }) // Mint reward tokens const rewardAmount = parseUnits('100', 6) await tokenActions.mintSync(config, { amount: rewardAmount, to: connection.address!, token, }) // Start immediate reward await actions.distributeSync(config, { amount: rewardAmount, token, }) // Trigger reward accrual by transferring await tokenActions.transferSync(config, { amount: 1n, to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', token, }) // Claim rewards const { receipt } = await actions.claimSync(config, { token, }) expect(receipt).toBeDefined() const balanceAfter = await tokenActions.getBalance(config, { account: connection.address!, token, }) // Balance should have increased due to claimed rewards expect(balanceAfter).toBeGreaterThan( balanceBefore + rewardAmount - parseUnits('1', 6), ) }) }) describe('getGlobalRewardPerToken', () => { test('default', async () => { const { token } = await setupToken() const rate = await actions.getGlobalRewardPerToken(config, { token, }) expect(rate).toBe(0n) }) describe('queryOptions', () => { test('default', async () => { const { token } = await setupToken() const options = actions.getGlobalRewardPerToken.queryOptions(config, { token, }) const rate = await queryClient.fetchQuery(options) expect(rate).toBe(0n) }) }) }) describe('getUserRewardInfo', () => { test('default', async () => { const { token } = await setupToken() const connection = getConnection(config) const info = await actions.getUserRewardInfo(config, { token, account: connection.address!, }) expect(info.rewardRecipient).toBeDefined() expect(info.rewardPerToken).toBeDefined() expect(info.rewardBalance).toBeDefined() }) describe('queryOptions', () => { test('default', async () => { const { token } = await setupToken() const connection = getConnection(config) const options = actions.getUserRewardInfo.queryOptions(config, { token, account: connection.address!, }) const info = await queryClient.fetchQuery(options) expect(info.rewardRecipient).toBeDefined() expect(info.rewardPerToken).toBeDefined() expect(info.rewardBalance).toBeDefined() }) }) }) describe('setRecipientSync', () => { test('default', async () => { const { token } = await setupToken() const connection = getConnection(config) // Set reward recipient const { holder, receipt, recipient } = await actions.setRecipientSync( config, { recipient: connection.address!, token, }, ) expect(receipt).toBeDefined() expect(holder).toBe(connection.address) expect(recipient).toBe(connection.address) }) }) describe('watchRewardDistributed', () => { test('default', async () => { const { token } = await setupToken() const connection = getConnection(config) // Setup rewards await actions.setRecipientSync(config, { recipient: connection.address!, token, }) const rewardAmount = parseUnits('100', 6) await tokenActions.mintSync(config, { amount: rewardAmount, to: connection.address!, token, }) const events: any[] = [] const unwatch = actions.watchRewardDistributed(config, { token, onRewardDistributed: (args) => { events.push(args) }, }) await actions.distributeSync(config, { amount: rewardAmount, token, }) await vi.waitFor(() => { expect(events.length).toBeGreaterThan(0) }) unwatch() expect(events[0]?.amount).toBe(rewardAmount) expect(events[0]?.funder).toBe(connection.address) }) }) describe('watchRewardRecipientSet', () => { test('default', async () => { const { token } = await setupToken() const account = getConnection(config) const events: any[] = [] const unwatch = actions.watchRewardRecipientSet(config, { token, onRewardRecipientSet: (args) => { events.push(args) }, }) await actions.setRecipientSync(config, { recipient: account.address!, token, }) await vi.waitFor(() => { expect(events.length).toBeGreaterThan(0) }) unwatch() expect(events[0]?.holder).toBe(account.address) expect(events[0]?.recipient).toBe(account.address) }) }) ================================================ FILE: packages/core/src/tempo/actions/reward.ts ================================================ import type { Account, BaseErrorType } from 'viem' import { Actions } from 'viem/tempo' import { getConnectorClient } from '../../actions/getConnectorClient.js' import type { Config } from '../../createConfig.js' import type { ChainIdParameter, ConnectorParameter, } from '../../types/properties.js' import type { UnionLooseOmit } from '../../types/utils.js' import type { QueryOptions, QueryParameter } from './utils.js' /** * Claims accumulated rewards for a recipient. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoTestnet], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.reward.claim(config, { * token: '0x20c0000000000000000000000000000000000001', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction hash. */ export async function claim( config: config, parameters: claim.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.reward.claim(client, parameters as never) } export declare namespace claim { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.reward.claim.Parameters, 'chain' > export type ReturnValue = Actions.reward.claim.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.reward.claim.ErrorType } /** * Claims accumulated rewards for a recipient and waits for confirmation. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoTestnet], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.reward.claimSync(config, { * token: '0x20c0000000000000000000000000000000000001', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt. */ export async function claimSync( config: config, parameters: claimSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.reward.claimSync(client, parameters as never) } export declare namespace claimSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.reward.claimSync.Parameters, 'chain' > export type ReturnValue = Actions.reward.claimSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.reward.claimSync.ErrorType } /** * Gets the global reward per token value for a token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoModerato], * transports: { * [tempo.id]: http(), * }, * }) * * const value = await Actions.reward.getGlobalRewardPerToken(config, { * token: '0x20c0000000000000000000000000000000000001', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The global reward per token value (scaled by 1e18). */ export function getGlobalRewardPerToken( config: config, parameters: getGlobalRewardPerToken.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.reward.getGlobalRewardPerToken(client, rest) } export namespace getGlobalRewardPerToken { export type Parameters = ChainIdParameter & Actions.reward.getGlobalRewardPerToken.Parameters export type ReturnValue = Actions.reward.getGlobalRewardPerToken.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: Parameters, ) { return ['getGlobalRewardPerToken', parameters] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean(rest.token && (query?.enabled ?? true)), queryKey: queryKey(rest), async queryFn({ queryKey }) { const [, parameters] = queryKey return await getGlobalRewardPerToken(config, parameters) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = getGlobalRewardPerToken.ReturnValue, > = getGlobalRewardPerToken.Parameters & QueryParameter< getGlobalRewardPerToken.ReturnValue, getGlobalRewardPerToken.ErrorType, selectData, getGlobalRewardPerToken.QueryKey > export type ReturnValue< config extends Config, selectData = getGlobalRewardPerToken.ReturnValue, > = QueryOptions< getGlobalRewardPerToken.ReturnValue, getGlobalRewardPerToken.ErrorType, selectData, getGlobalRewardPerToken.QueryKey > } } /** * Gets the reward information for a specific account. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoTestnet], * transports: { * [tempo.id]: http(), * }, * }) * * const info = await Actions.reward.getUserRewardInfo(config, { * token: '0x20c0000000000000000000000000000000000001', * account: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The user's reward information (recipient, rewardPerToken, rewardBalance). */ export function getUserRewardInfo( config: config, parameters: getUserRewardInfo.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.reward.getUserRewardInfo(client, rest) } export namespace getUserRewardInfo { export type Parameters = ChainIdParameter & Actions.reward.getUserRewardInfo.Parameters export type ReturnValue = Actions.reward.getUserRewardInfo.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: Parameters, ) { return ['getUserRewardInfo', parameters] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean(rest.token && rest.account && (query?.enabled ?? true)), queryKey: queryKey(rest), async queryFn({ queryKey }) { const [, parameters] = queryKey return await getUserRewardInfo(config, parameters) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = getUserRewardInfo.ReturnValue, > = getUserRewardInfo.Parameters & QueryParameter< getUserRewardInfo.ReturnValue, getUserRewardInfo.ErrorType, selectData, getUserRewardInfo.QueryKey > export type ReturnValue< config extends Config, selectData = getUserRewardInfo.ReturnValue, > = QueryOptions< getUserRewardInfo.ReturnValue, getUserRewardInfo.ErrorType, selectData, getUserRewardInfo.QueryKey > } } /** * Sets or changes the reward recipient for a token holder. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoTestnet], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.reward.setRecipient(config, { * recipient: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', * token: '0x20c0000000000000000000000000000000000001', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction hash. */ export async function setRecipient( config: config, parameters: setRecipient.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.reward.setRecipient(client, parameters as never) } export declare namespace setRecipient { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.reward.setRecipient.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.reward.setRecipient.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.reward.setRecipient.ErrorType } /** * Sets or changes the reward recipient for a token holder and waits for confirmation. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoTestnet], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.reward.setRecipientSync(config, { * recipient: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', * token: '0x20c0000000000000000000000000000000000001', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function setRecipientSync( config: config, parameters: setRecipientSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.reward.setRecipientSync(client, parameters as never) } export declare namespace setRecipientSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.reward.setRecipientSync.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.reward.setRecipientSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.reward.setRecipientSync.ErrorType } /** * Distributes tokens to opted-in holders. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoTestnet], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.reward.distribute(config, { * amount: 100000000000000000000n, * seconds: 86400, * token: '0x20c0000000000000000000000000000000000001', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction hash. */ export async function distribute( config: config, parameters: distribute.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.reward.distribute(client, parameters as never) } export declare namespace distribute { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.reward.distribute.Parameters, 'chain' > export type ReturnValue = Actions.reward.distribute.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.reward.distribute.ErrorType } /** * Distributes tokens to opted-in holders and waits for confirmation. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoTestnet], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.reward.distributeSync(config, { * amount: 100000000000000000000n, * seconds: 86400, * token: '0x20c0000000000000000000000000000000000001', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function distributeSync( config: config, parameters: distributeSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.reward.distributeSync(client, parameters as never) } export declare namespace distributeSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.reward.distributeSync.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.reward.distributeSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.reward.distributeSync.ErrorType } /** * Watches for reward distributed events. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoTestnet], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.reward.watchRewardDistributed(config, { * token: '0x20c0000000000000000000000000000000000001', * onRewardDistributed: (args, log) => { * console.log('Reward distributed:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchRewardDistributed( config: config, parameters: watchRewardDistributed.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.reward.watchRewardDistributed(client, rest) } export declare namespace watchRewardDistributed { export type Parameters = ChainIdParameter & Actions.reward.watchRewardDistributed.Parameters } /** * Watches for reward recipient set events. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempoTestnet], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.reward.watchRewardRecipientSet(config, { * token: '0x20c0000000000000000000000000000000000001', * onRewardRecipientSet: (args, log) => { * console.log('Reward recipient set:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchRewardRecipientSet( config: config, parameters: watchRewardRecipientSet.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.reward.watchRewardRecipientSet(client, rest) } export declare namespace watchRewardRecipientSet { export type Parameters = ChainIdParameter & Actions.reward.watchRewardRecipientSet.Parameters } ================================================ FILE: packages/core/src/tempo/actions/token.test.ts ================================================ import { connect } from '@wagmi/core' import { accounts, addresses, config, queryClient } from '@wagmi/test/tempo' import { parseUnits } from 'viem' import { describe, expect, test, vi } from 'vitest' import * as token from './token.js' const account = accounts[0] const account2 = accounts[1] describe('getAllowance', () => { test('default', async () => { const allowance = await token.getAllowance(config, { account: account.address, spender: account2.address, token: addresses.alphaUsd, }) expect(allowance).toBeDefined() expect(typeof allowance).toBe('bigint') }) describe('queryOptions', () => { test('default', async () => { const options = token.getAllowance.queryOptions(config, { account: account.address, spender: account2.address, token: addresses.alphaUsd, }) const allowance = await queryClient.fetchQuery(options) expect(allowance).toBeDefined() expect(typeof allowance).toBe('bigint') }) }) }) describe('getBalance', () => { test('default', async () => { const balance = await token.getBalance(config, { account: account.address, token: addresses.alphaUsd, }) expect(balance).toBeDefined() expect(typeof balance).toBe('bigint') expect(balance).toBeGreaterThan(0n) }) describe('queryOptions', () => { test('default', async () => { const options = token.getBalance.queryOptions(config, { account: account.address, token: addresses.alphaUsd, }) const balance = await queryClient.fetchQuery(options) expect(balance).toBeDefined() expect(typeof balance).toBe('bigint') expect(balance).toBeGreaterThan(0n) }) }) }) describe('getMetadata', () => { test('default', async () => { const metadata = await token.getMetadata(config, { token: addresses.alphaUsd, }) expect(metadata).toBeDefined() expect(metadata).toMatchInlineSnapshot(` { "currency": "USD", "decimals": 6, "name": "AlphaUSD", "paused": false, "quoteToken": "0x20C0000000000000000000000000000000000000", "supplyCap": 340282366920938463463374607431768211455n, "symbol": "AlphaUSD", "totalSupply": 202914184810805067765n, "transferPolicyId": 1n, } `) }) describe('queryOptions', () => { test('default', async () => { const options = token.getMetadata.queryOptions(config, { token: addresses.alphaUsd, }) const metadata = await queryClient.fetchQuery(options) expect(metadata).toBeDefined() expect(metadata).toMatchInlineSnapshot(` { "currency": "USD", "decimals": 6, "name": "AlphaUSD", "paused": false, "quoteToken": "0x20C0000000000000000000000000000000000000", "supplyCap": 340282366920938463463374607431768211455n, "symbol": "AlphaUSD", "totalSupply": 202914184810805067765n, "transferPolicyId": 1n, } `) }) }) }) describe('getRoleAdmin', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a token where we're the admin const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'GetRoleAdmin Test', symbol: 'GRATEST', }) const adminRole = await token.getRoleAdmin(config, { token: tokenAddr, role: 'issuer', }) expect(adminRole).toBeDefined() expect(typeof adminRole).toBe('string') expect(adminRole).toBe( '0x0000000000000000000000000000000000000000000000000000000000000000', ) }) describe('queryOptions', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a token where we're the admin const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'GetRoleAdmin Query Test', symbol: 'GRAQTEST', }) const options = token.getRoleAdmin.queryOptions(config, { token: tokenAddr, role: 'issuer', }) const adminRole = await queryClient.fetchQuery(options) expect(adminRole).toBeDefined() expect(typeof adminRole).toBe('string') expect(adminRole).toBe( '0x0000000000000000000000000000000000000000000000000000000000000000', ) }) }) }) describe('hasRole', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a token where we're the admin const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'HasRole Test', symbol: 'HRTEST', }) const result = await token.hasRole(config, { token: tokenAddr, account: account.address, role: 'defaultAdmin', }) expect(result).toBeDefined() expect(typeof result).toBe('boolean') expect(result).toBe(true) }) describe('queryOptions', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a token where we're the admin const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'HasRole Query Test', symbol: 'HRQTEST', }) const options = token.hasRole.queryOptions(config, { token: tokenAddr, account: account.address, role: 'defaultAdmin', }) const result = await queryClient.fetchQuery(options) expect(result).toBeDefined() expect(typeof result).toBe('boolean') expect(result).toBe(true) }) }) }) describe('approve', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) const hash = await token.approve(config, { amount: parseUnits('100', 6), spender: account2.address, token: addresses.alphaUsd, }) expect(hash).toBeDefined() expect(typeof hash).toBe('string') }) }) describe('approveSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) const { receipt, ...result } = await token.approveSync(config, { amount: parseUnits('100', 6), spender: account2.address, token: addresses.alphaUsd, }) expect(receipt).toBeDefined() expect(result).toMatchInlineSnapshot(` { "amount": 100000000n, "owner": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", "spender": "0x8C8d35429F74ec245F8Ef2f4Fd1e551cFF97d650", } `) }) }) describe('transfer', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) const hash = await token.transfer(config, { amount: parseUnits('1', 6), to: account2.address, token: addresses.alphaUsd, }) expect(hash).toBeDefined() expect(typeof hash).toBe('string') }) }) describe('transferSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) const { receipt, ...result } = await token.transferSync(config, { amount: parseUnits('1', 6), to: account2.address, token: addresses.alphaUsd, }) expect(receipt).toBeDefined() expect(result).toMatchInlineSnapshot(` { "amount": 1000000n, "from": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", "to": "0x8C8d35429F74ec245F8Ef2f4Fd1e551cFF97d650", } `) }) }) describe('mint', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token where we're the admin const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Mintable Token', symbol: 'MINT', }) // Grant issuer role await token.grantRolesSync(config, { token: tokenAddr, roles: ['issuer'], to: account.address, }) const hash = await token.mint(config, { token: tokenAddr, to: account.address, amount: parseUnits('100', 6), }) expect(hash).toBeDefined() expect(typeof hash).toBe('string') }) }) describe('mintSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token where we're the admin const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Mintable Token Sync', symbol: 'MINTSYNC', }) // Grant issuer role await token.grantRolesSync(config, { token: tokenAddr, roles: ['issuer'], to: account.address, }) const { receipt, ...result } = await token.mintSync(config, { token: tokenAddr, to: account.address, amount: parseUnits('100', 6), }) expect(receipt).toBeDefined() expect(result).toMatchInlineSnapshot(` { "amount": 100000000n, "to": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", } `) }) }) describe('burn', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token where we're the admin const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Burnable Token', symbol: 'BURN', }) // Grant issuer role await token.grantRolesSync(config, { token: tokenAddr, roles: ['issuer'], to: account.address, }) // Mint some tokens first await token.mintSync(config, { token: tokenAddr, to: account.address, amount: parseUnits('1000', 6), }) const hash = await token.burn(config, { token: tokenAddr, amount: parseUnits('1', 6), }) expect(hash).toBeDefined() expect(typeof hash).toBe('string') }) }) describe('burnSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token where we're the admin const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Burnable Token Sync', symbol: 'BURNSYNC', }) // Grant issuer role await token.grantRolesSync(config, { token: tokenAddr, roles: ['issuer'], to: account.address, }) // Mint some tokens first await token.mintSync(config, { token: tokenAddr, to: account.address, amount: parseUnits('1000', 6), }) const { receipt, ...result } = await token.burnSync(config, { token: tokenAddr, amount: parseUnits('1', 6), }) expect(receipt).toBeDefined() expect(result).toMatchInlineSnapshot(` { "amount": 1000000n, "from": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", } `) }) }) describe('create', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) const hash = await token.create(config, { name: 'Test Token', symbol: 'TEST', currency: 'USD', }) expect(hash).toBeDefined() expect(typeof hash).toBe('string') }) }) describe('createSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) const { receipt, ...result } = await token.createSync(config, { name: 'Test Token', symbol: 'TEST', currency: 'USD', }) expect(receipt).toBeDefined() expect(result.token).toBeDefined() expect(result.tokenId).toBeDefined() expect(result.name).toBe('Test Token') expect(result.symbol).toBe('TEST') expect(result.currency).toBe('USD') expect(result.admin).toBe(account.address) }) }) describe.todo('burnBlocked') describe.todo('burnBlockedSync') describe('changeTransferPolicy', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Policy Token', symbol: 'POLICY', }) const hash = await token.changeTransferPolicy(config, { token: tokenAddr, policyId: 0n, }) expect(hash).toBeDefined() expect(typeof hash).toBe('string') }) }) describe('changeTransferPolicySync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Policy Token Sync', symbol: 'POLICYSYNC', }) const { receipt, ...result } = await token.changeTransferPolicySync( config, { token: tokenAddr, policyId: 0n, }, ) expect(receipt).toBeDefined() expect(result).toMatchInlineSnapshot(` { "newPolicyId": 0n, "updater": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", } `) }) }) describe('grantRoles', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Grant Roles Token', symbol: 'GRANT', }) const hash = await token.grantRoles(config, { token: tokenAddr, roles: ['issuer'], to: account2.address, }) expect(hash).toBeDefined() expect(typeof hash).toBe('string') }) }) describe('grantRolesSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Grant Roles Token Sync', symbol: 'GRANTSYNC', }) const { receipt, value } = await token.grantRolesSync(config, { token: tokenAddr, roles: ['issuer'], to: account2.address, }) expect(receipt).toBeDefined() expect(value).toBeDefined() expect(value.length).toBe(1) expect(value[0]?.account).toBe(account2.address) expect(value[0]?.hasRole).toBe(true) }) }) describe('pause', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Pausable Token', symbol: 'PAUSE', }) // Grant pause role await token.grantRolesSync(config, { token: tokenAddr, roles: ['pause'], to: account.address, }) const hash = await token.pause(config, { token: tokenAddr, }) expect(hash).toBeDefined() expect(typeof hash).toBe('string') }) }) describe('pauseSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Pausable Token Sync', symbol: 'PAUSESYNC', }) // Grant pause role await token.grantRolesSync(config, { token: tokenAddr, roles: ['pause'], to: account.address, }) const { receipt, ...result } = await token.pauseSync(config, { token: tokenAddr, }) expect(receipt).toBeDefined() expect(result).toMatchInlineSnapshot(` { "isPaused": true, "updater": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", } `) }) }) describe('unpause', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Unpausable Token', symbol: 'UNPAUSE', }) // Grant pause and unpause roles await token.grantRolesSync(config, { token: tokenAddr, roles: ['pause', 'unpause'], to: account.address, }) // First pause it await token.pauseSync(config, { token: tokenAddr, }) const hash = await token.unpause(config, { token: tokenAddr, }) expect(hash).toBeDefined() expect(typeof hash).toBe('string') }) }) describe('unpauseSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Unpausable Token Sync', symbol: 'UNPAUSESYNC', }) // Grant pause and unpause roles await token.grantRolesSync(config, { token: tokenAddr, roles: ['pause', 'unpause'], to: account.address, }) // First pause it await token.pauseSync(config, { token: tokenAddr, }) const { receipt, ...result } = await token.unpauseSync(config, { token: tokenAddr, }) expect(receipt).toBeDefined() expect(result).toMatchInlineSnapshot(` { "isPaused": false, "updater": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", } `) }) }) describe('revokeRoles', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Revoke Roles Token', symbol: 'REVOKE', }) // Grant issuer role to account2 await token.grantRolesSync(config, { token: tokenAddr, roles: ['issuer'], to: account2.address, }) const hash = await token.revokeRoles(config, { token: tokenAddr, roles: ['issuer'], from: account2.address, }) expect(hash).toBeDefined() expect(typeof hash).toBe('string') }) }) describe('revokeRolesSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Revoke Roles Token Sync', symbol: 'REVOKESYNC', }) // Grant issuer role to account2 await token.grantRolesSync(config, { token: tokenAddr, roles: ['issuer'], to: account2.address, }) const { receipt, value } = await token.revokeRolesSync(config, { token: tokenAddr, roles: ['issuer'], from: account2.address, }) expect(receipt).toBeDefined() expect(value).toBeDefined() expect(value.length).toBe(1) expect(value[0]?.account).toBe(account2.address) expect(value[0]?.hasRole).toBe(false) }) }) describe('renounceRoles', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Renounce Roles Token', symbol: 'RENOUNCE', }) // Grant issuer role to ourselves await token.grantRolesSync(config, { token: tokenAddr, roles: ['issuer'], to: account.address, }) const hash = await token.renounceRoles(config, { token: tokenAddr, roles: ['issuer'], }) expect(hash).toBeDefined() expect(typeof hash).toBe('string') }) }) describe('renounceRolesSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Renounce Roles Token Sync', symbol: 'RENOUNCESYNC', }) // Grant issuer role to ourselves await token.grantRolesSync(config, { token: tokenAddr, roles: ['issuer'], to: account.address, }) const { receipt, value } = await token.renounceRolesSync(config, { token: tokenAddr, roles: ['issuer'], }) expect(receipt).toBeDefined() expect(value).toBeDefined() expect(value.length).toBe(1) expect(value[0]?.account).toBe(account.address) expect(value[0]?.hasRole).toBe(false) }) }) describe('setRoleAdmin', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Role Admin Token', symbol: 'ROLEADMIN', }) const hash = await token.setRoleAdmin(config, { token: tokenAddr, role: 'issuer', adminRole: 'pause', }) expect(hash).toBeDefined() expect(typeof hash).toBe('string') }) }) describe('setRoleAdminSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Role Admin Token Sync', symbol: 'ROLEADMINSYNC', }) const { receipt, ...result } = await token.setRoleAdminSync(config, { token: tokenAddr, role: 'issuer', adminRole: 'pause', }) expect(receipt).toBeDefined() expect(result.role).toBeDefined() expect(result.newAdminRole).toBeDefined() expect(result.sender).toBe(account.address) }) }) describe('setSupplyCap', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Supply Cap Token', symbol: 'SUPPLYCAP', }) const hash = await token.setSupplyCap(config, { token: tokenAddr, supplyCap: parseUnits('1000000', 6), }) expect(hash).toBeDefined() expect(typeof hash).toBe('string') }) }) describe('setSupplyCapSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Supply Cap Token Sync', symbol: 'SUPPLYCAPSYNC', }) const { receipt, ...result } = await token.setSupplyCapSync(config, { token: tokenAddr, supplyCap: parseUnits('1000000', 6), }) expect(receipt).toBeDefined() expect(result.newSupplyCap).toBe(parseUnits('1000000', 6)) expect(result.updater).toBe(account.address) }) }) describe('prepareUpdateQuoteToken', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create quote token const { token: quoteToken } = await token.createSync(config, { currency: 'USD', name: 'Quote Token', symbol: 'QUOTE', }) // Create main token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Main Token', symbol: 'MAIN', }) const hash = await token.prepareUpdateQuoteToken(config, { token: tokenAddr, quoteToken, }) expect(hash).toBeDefined() expect(typeof hash).toBe('string') }) }) describe('prepareUpdateQuoteTokenSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create quote token const { token: quoteToken } = await token.createSync(config, { currency: 'USD', name: 'Quote Token Sync', symbol: 'QUOTESYNC', }) // Create main token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Main Token Sync', symbol: 'MAINSYNC', }) const { receipt, ...result } = await token.prepareUpdateQuoteTokenSync( config, { token: tokenAddr, quoteToken, }, ) expect(receipt).toBeDefined() expect(result.nextQuoteToken).toBe(quoteToken) expect(result.updater).toBe(account.address) }) }) describe('updateQuoteToken', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create quote token const { token: quoteToken } = await token.createSync(config, { currency: 'USD', name: 'Quote Token Finalize', symbol: 'QUOTEFINAL', }) // Create main token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Main Token Finalize', symbol: 'MAINFINAL', }) // Prepare quote token update first await token.prepareUpdateQuoteTokenSync(config, { token: tokenAddr, quoteToken, }) const hash = await token.updateQuoteToken(config, { token: tokenAddr, }) expect(hash).toBeDefined() expect(typeof hash).toBe('string') }) }) describe('updateQuoteTokenSync', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create quote token const { token: quoteToken } = await token.createSync(config, { currency: 'USD', name: 'Quote Token Finalize Sync', symbol: 'QUOTEFINALSYNC', }) // Create main token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Main Token Finalize Sync', symbol: 'MAINFINALSYNC', }) // Prepare quote token update first await token.prepareUpdateQuoteTokenSync(config, { token: tokenAddr, quoteToken, }) const { receipt, ...result } = await token.updateQuoteTokenSync(config, { token: tokenAddr, }) expect(receipt).toBeDefined() expect(result.newQuoteToken).toBe(quoteToken) expect(result.updater).toBe(account.address) }) }) describe.todo('permit') describe.todo('permitSync') describe('watchAdminRole', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Watch Admin Role Token', symbol: 'WATCHADMIN', }) const events: any[] = [] const unwatch = token.watchAdminRole(config, { token: tokenAddr, onRoleAdminUpdated: (args) => { events.push(args) }, }) // Trigger event by setting a role admin await token.setRoleAdminSync(config, { token: tokenAddr, role: 'issuer', adminRole: 'pause', }) await vi.waitFor(() => { expect(events.length).toBeGreaterThan(0) }) unwatch() expect(events[0]).toBeDefined() }) }) describe('watchApprove', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) const events: any[] = [] const unwatch = token.watchApprove(config, { onApproval: (args) => { events.push(args) }, token: addresses.alphaUsd, }) // Trigger approval event await token.approveSync(config, { amount: parseUnits('50', 6), spender: account2.address, token: addresses.alphaUsd, }) await vi.waitFor(() => { expect(events.length).toBeGreaterThan(0) }) unwatch() expect(events[0]?.owner).toBe(account.address) expect(events[0]?.spender).toBe(account2.address) expect(events[0]?.amount).toBe(parseUnits('50', 6)) }) }) describe('watchBurn', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Watch Burn Token', symbol: 'WATCHBURN', }) // Grant issuer role and mint tokens await token.grantRolesSync(config, { token: tokenAddr, roles: ['issuer'], to: account.address, }) await token.mintSync(config, { token: tokenAddr, to: account.address, amount: parseUnits('1000', 6), }) const events: any[] = [] const unwatch = token.watchBurn(config, { token: tokenAddr, onBurn: (args) => { events.push(args) }, }) // Trigger burn event await token.burnSync(config, { token: tokenAddr, amount: parseUnits('10', 6), }) await vi.waitFor(() => { expect(events.length).toBeGreaterThan(0) }) unwatch() expect(events[0]?.from).toBe(account.address) expect(events[0]?.amount).toBe(parseUnits('10', 6)) }) }) describe('watchCreate', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) const events: any[] = [] const unwatch = token.watchCreate(config, { onTokenCreated: (args) => { events.push(args) }, }) // Trigger token creation event await token.createSync(config, { name: 'Watch Create Token', symbol: 'WATCHCREATE', currency: 'USD', }) await vi.waitFor(() => { expect(events.length).toBeGreaterThan(0) }) unwatch() expect(events[0]?.name).toBe('Watch Create Token') expect(events[0]?.symbol).toBe('WATCHCREATE') expect(events[0]?.currency).toBe('USD') expect(events[0]?.admin).toBe(account.address) }) }) describe('watchMint', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Watch Mint Token', symbol: 'WATCHMINT', }) // Grant issuer role await token.grantRolesSync(config, { token: tokenAddr, roles: ['issuer'], to: account.address, }) const events: any[] = [] const unwatch = token.watchMint(config, { token: tokenAddr, onMint: (args) => { events.push(args) }, }) // Trigger mint event await token.mintSync(config, { token: tokenAddr, to: account.address, amount: parseUnits('100', 6), }) await vi.waitFor(() => { expect(events.length).toBeGreaterThan(0) }) unwatch() expect(events[0]?.to).toBe(account.address) expect(events[0]?.amount).toBe(parseUnits('100', 6)) }) }) describe('watchRole', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await token.createSync(config, { currency: 'USD', name: 'Watch Role Token', symbol: 'WATCHROLE', }) const events: any[] = [] const unwatch = token.watchRole(config, { token: tokenAddr, onRoleUpdated: (args) => { events.push(args) }, }) // Trigger role update event by granting a role await token.grantRolesSync(config, { token: tokenAddr, roles: ['issuer'], to: account2.address, }) await vi.waitFor(() => { expect(events.find((e) => e.account === account2.address)).toBeDefined() }) unwatch() const event = events.find((e) => e.account === account2.address) expect(event?.hasRole).toBe(true) expect(event?.type).toBe('granted') }) }) describe('watchTransfer', () => { test('default', async () => { await connect(config, { connector: config.connectors[0]!, }) const events: any[] = [] const unwatch = token.watchTransfer(config, { token: addresses.alphaUsd, onTransfer: (args) => { events.push(args) }, }) // Trigger transfer event await token.transferSync(config, { amount: parseUnits('5', 6), to: account2.address, token: addresses.alphaUsd, }) await vi.waitFor(() => { expect(events.length).toBeGreaterThan(0) }) unwatch() expect(events[0]?.from).toBe(account.address) expect(events[0]?.to).toBe(account2.address) expect(events[0]?.amount).toBe(parseUnits('5', 6)) }) }) ================================================ FILE: packages/core/src/tempo/actions/token.ts ================================================ import type { Account, BaseErrorType } from 'viem' import { Actions } from 'viem/tempo' import { getConnectorClient } from '../../actions/getConnectorClient.js' import type { Config } from '../../createConfig.js' import type { ChainIdParameter, ConnectorParameter, } from '../../types/properties.js' import type { UnionLooseOmit } from '../../types/utils.js' import type { QueryOptions, QueryParameter } from './utils.js' /** * Approves a spender to transfer TIP20 tokens on behalf of the caller. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { Actions } from '@wagmi/core/tempo' * import { tempo } from '@wagmi/core/chains' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.token.approve(config, { * spender: '0x...', * amount: 100n, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function approve( config: config, parameters: approve.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.approve(client, parameters as never) } export declare namespace approve { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.approve.Parameters, 'chain' > export type ReturnValue = Actions.token.approve.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.approve.ErrorType } /** * Approves a spender to transfer TIP20 tokens on behalf of the caller. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.token.approveSync(config, { * spender: '0x...', * amount: 100n, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function approveSync( config: config, parameters: approveSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.approveSync(client, parameters as never) } export declare namespace approveSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.approveSync.Parameters, 'chain' > export type ReturnValue = Actions.token.approveSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.approveSync.ErrorType } /** * Burns TIP20 tokens from the caller's balance. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.token.burn(config, { * amount: 100n, * token: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function burn( config: config, parameters: burn.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.burn(client, parameters as never) } export declare namespace burn { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.burn.Parameters, 'chain' > export type ReturnValue = Actions.token.burn.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.burn.ErrorType } /** * Burns TIP20 tokens from a blocked address. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.token.burnBlocked(config, { * from: '0x...', * amount: 100n, * token: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function burnBlocked( config: config, parameters: burnBlocked.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return await Actions.token.burnBlocked(client, parameters as never) } export declare namespace burnBlocked { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.burnBlocked.Parameters, 'chain' > export type ReturnValue = Actions.token.burnBlocked.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.burnBlocked.ErrorType } /** * Burns TIP20 tokens from a blocked address. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.token.burnBlockedSync(config, { * from: '0x...', * amount: 100n, * token: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function burnBlockedSync( config: config, parameters: burnBlockedSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.burnBlockedSync(client, parameters as never) } export declare namespace burnBlockedSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.burnBlockedSync.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.token.burnBlockedSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.burnBlockedSync.ErrorType } /** * Burns TIP20 tokens from the caller's balance. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.token.burnSync(config, { * amount: 100n, * token: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function burnSync( config: config, parameters: burnSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.burnSync(client, parameters as never) } export declare namespace burnSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.burnSync.Parameters, 'chain' > export type ReturnValue = Actions.token.burnSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.burnSync.ErrorType } /** * Changes the transfer policy ID for a TIP20 token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.token.changeTransferPolicy(config, { * token: '0x...', * policyId: 1n, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function changeTransferPolicy( config: config, parameters: changeTransferPolicy.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.changeTransferPolicy(client, parameters as never) } export declare namespace changeTransferPolicy { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.changeTransferPolicy.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.token.changeTransferPolicy.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.changeTransferPolicy.ErrorType } /** * Changes the transfer policy ID for a TIP20 token. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.token.changeTransferPolicySync(config, { * token: '0x...', * policyId: 1n, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function changeTransferPolicySync( config: config, parameters: changeTransferPolicySync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.changeTransferPolicySync(client, parameters as never) } export declare namespace changeTransferPolicySync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.changeTransferPolicySync.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.token.changeTransferPolicySync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.changeTransferPolicySync.ErrorType } /** * Creates a new TIP20 token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.token.create(config, { * name: 'My Token', * symbol: 'MTK', * currency: 'USD', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function create( config: config, parameters: create.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.create(client, parameters as never) } export declare namespace create { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.create.Parameters, 'chain' > export type ReturnValue = Actions.token.create.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.create.ErrorType } /** * Creates a new TIP20 token. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.token.createSync(config, { * name: 'My Token', * symbol: 'MTK', * currency: 'USD', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function createSync( config: config, parameters: createSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.createSync(client, parameters as never) } export declare namespace createSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.createSync.Parameters, 'chain' > export type ReturnValue = Actions.token.createSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.createSync.ErrorType } /** * Updates the quote token for a TIP20 token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.token.updateQuoteToken(config, { * token: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function updateQuoteToken( config: config, parameters: updateQuoteToken.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.updateQuoteToken(client, parameters as never) } export declare namespace updateQuoteToken { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.updateQuoteToken.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.token.updateQuoteToken.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.updateQuoteToken.ErrorType } /** * Updates the quote token for a TIP20 token. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.token.updateQuoteTokenSync(config, { * token: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function updateQuoteTokenSync( config: config, parameters: updateQuoteTokenSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.updateQuoteTokenSync(client, parameters as never) } export declare namespace updateQuoteTokenSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.updateQuoteTokenSync.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.token.updateQuoteTokenSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.updateQuoteTokenSync.ErrorType } /** * Gets TIP20 token allowance. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const allowance = await Actions.token.getAllowance(config, { * account: '0x...', * spender: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The token allowance. */ export function getAllowance( config: config, parameters: getAllowance.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.token.getAllowance(client, rest) } export namespace getAllowance { export type Parameters = ChainIdParameter & Actions.token.getAllowance.Parameters export type ReturnValue = Actions.token.getAllowance.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: Parameters, ) { return ['getAllowance', parameters] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean( rest.account && rest.spender && rest.token && (query?.enabled ?? true), ), queryKey: queryKey(rest), async queryFn(context) { const [, parameters] = context.queryKey return await getAllowance(config, parameters) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = getAllowance.ReturnValue, > = getAllowance.Parameters & QueryParameter< getAllowance.ReturnValue, getAllowance.ErrorType, selectData, getAllowance.QueryKey > export type ReturnValue< config extends Config, selectData = getAllowance.ReturnValue, > = QueryOptions< getAllowance.ReturnValue, getAllowance.ErrorType, selectData, getAllowance.QueryKey > } } /** * Gets TIP20 token balance for an address. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const balance = await Actions.token.getBalance(config, { * account: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The token balance. */ export function getBalance( config: config, parameters: getBalance.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.token.getBalance(client, rest as never) } export namespace getBalance { export type Parameters = ChainIdParameter & Actions.token.getBalance.Parameters export type ReturnValue = Actions.token.getBalance.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: Parameters, ) { return ['getBalance', parameters] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean(rest.account && rest.token && (query?.enabled ?? true)), queryKey: queryKey(rest), async queryFn(context) { const [, parameters] = context.queryKey return (await getBalance(config, parameters)) ?? null }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = getBalance.ReturnValue, > = getBalance.Parameters & QueryParameter< getBalance.ReturnValue, getBalance.ErrorType, selectData, getBalance.QueryKey > export type ReturnValue< config extends Config, selectData = getBalance.ReturnValue, > = QueryOptions< getBalance.ReturnValue, getBalance.ErrorType, selectData, getBalance.QueryKey > } } /** * Gets TIP20 token metadata. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const metadata = await Actions.token.getMetadata(config, { * token: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The token metadata. */ export function getMetadata( config: config, parameters: getMetadata.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.token.getMetadata(client, rest) } export namespace getMetadata { export type Parameters = ChainIdParameter & Actions.token.getMetadata.Parameters export type ReturnValue = Actions.token.getMetadata.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: Parameters, ) { return ['getMetadata', parameters] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean(rest.token && (query?.enabled ?? true)), queryKey: queryKey(rest), async queryFn(context) { const [, parameters] = context.queryKey return await getMetadata(config, parameters) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = getMetadata.ReturnValue, > = getMetadata.Parameters & QueryParameter< getMetadata.ReturnValue, getMetadata.ErrorType, selectData, getMetadata.QueryKey > export type ReturnValue< config extends Config, selectData = getMetadata.ReturnValue, > = QueryOptions< getMetadata.ReturnValue, getMetadata.ErrorType, selectData, getMetadata.QueryKey > } } /** * Gets the admin role for a specific role in a TIP20 token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const adminRole = await Actions.token.getRoleAdmin(config, { * role: 'issuer', * token: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The admin role hash. */ export function getRoleAdmin( config: config, parameters: getRoleAdmin.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.token.getRoleAdmin(client, rest) } export namespace getRoleAdmin { export type Parameters = ChainIdParameter & Actions.token.getRoleAdmin.Parameters export type ReturnValue = Actions.token.getRoleAdmin.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: Parameters, ) { return ['getRoleAdmin', parameters] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean(rest.token && rest.role && (query?.enabled ?? true)), queryKey: queryKey(rest), async queryFn(context) { const [, parameters] = context.queryKey return await getRoleAdmin(config, parameters) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = getRoleAdmin.ReturnValue, > = getRoleAdmin.Parameters & QueryParameter< getRoleAdmin.ReturnValue, getRoleAdmin.ErrorType, selectData, getRoleAdmin.QueryKey > export type ReturnValue< config extends Config, selectData = getRoleAdmin.ReturnValue, > = QueryOptions< getRoleAdmin.ReturnValue, getRoleAdmin.ErrorType, selectData, getRoleAdmin.QueryKey > } } /** * Grants a role for a TIP20 token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.token.grantRoles(config, { * token: '0x...', * to: '0x...', * roles: ['issuer'], * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function grantRoles( config: config, parameters: grantRoles.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.grantRoles(client, parameters as never) } export declare namespace grantRoles { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.grantRoles.Parameters, 'chain' > export type ReturnValue = Actions.token.grantRoles.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.grantRoles.ErrorType } /** * Grants a role for a TIP20 token. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.token.grantRolesSync(config, { * token: '0x...', * to: '0x...', * roles: ['issuer'], * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function grantRolesSync( config: config, parameters: grantRolesSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.grantRolesSync(client, parameters as never) } export declare namespace grantRolesSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.grantRolesSync.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.token.grantRolesSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.grantRolesSync.ErrorType } /** * Checks if an account has a specific role for a TIP20 token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const hasRole = await Actions.token.hasRole(config, { * account: '0x...', * role: 'issuer', * token: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Whether the account has the role. */ export function hasRole( config: config, parameters: hasRole.Parameters, ): Promise { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.token.hasRole(client, rest) } export namespace hasRole { export type Parameters = ChainIdParameter & Actions.token.hasRole.Parameters export type ReturnValue = Actions.token.hasRole.ReturnValue export type ErrorType = BaseErrorType export function queryKey( parameters: Parameters, ) { return ['hasRole', parameters] as const } export type QueryKey = ReturnType< typeof queryKey > export function queryOptions( config: Config, parameters: queryOptions.Parameters, ): queryOptions.ReturnValue { const { query, ...rest } = parameters return { ...query, enabled: Boolean( rest.token && rest.role && rest.account && (query?.enabled ?? true), ), queryKey: queryKey(rest), async queryFn(context) { const [, parameters] = context.queryKey return await hasRole(config, parameters) }, } } export declare namespace queryOptions { export type Parameters< config extends Config, selectData = hasRole.ReturnValue, > = hasRole.Parameters & QueryParameter< hasRole.ReturnValue, hasRole.ErrorType, selectData, hasRole.QueryKey > export type ReturnValue< config extends Config, selectData = hasRole.ReturnValue, > = QueryOptions< hasRole.ReturnValue, hasRole.ErrorType, selectData, hasRole.QueryKey > } } /** * Mints TIP20 tokens to an address. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.token.mint(config, { * to: '0x...', * amount: 100n, * token: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function mint( config: config, parameters: mint.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.mint(client, parameters as never) } export declare namespace mint { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.mint.Parameters, 'chain' > export type ReturnValue = Actions.token.mint.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.mint.ErrorType } /** * Mints TIP20 tokens to an address. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.token.mintSync(config, { * to: '0x...', * amount: 100n, * token: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function mintSync( config: config, parameters: mintSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.mintSync(client, parameters as never) } export declare namespace mintSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.mintSync.Parameters, 'chain' > export type ReturnValue = Actions.token.mintSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.mintSync.ErrorType } /** * Pauses a TIP20 token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.token.pause(config, { * token: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function pause( config: config, parameters: pause.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.pause(client, parameters as never) } export declare namespace pause { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.pause.Parameters, 'chain' > export type ReturnValue = Actions.token.pause.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.pause.ErrorType } /** * Pauses a TIP20 token. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.token.pauseSync(config, { * token: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function pauseSync( config: config, parameters: pauseSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.pauseSync(client, parameters as never) } export declare namespace pauseSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.pauseSync.Parameters, 'chain' > export type ReturnValue = Actions.token.pauseSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.pauseSync.ErrorType } /** * Renounces a role for a TIP20 token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.token.renounceRoles(config, { * token: '0x...', * roles: ['issuer'], * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function renounceRoles( config: config, parameters: renounceRoles.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.renounceRoles(client, parameters as never) } export declare namespace renounceRoles { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.renounceRoles.Parameters, 'chain' > export type ReturnValue = Actions.token.renounceRoles.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.renounceRoles.ErrorType } /** * Renounces a role for a TIP20 token. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.token.renounceRolesSync(config, { * token: '0x...', * roles: ['issuer'], * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function renounceRolesSync( config: config, parameters: renounceRolesSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.renounceRolesSync(client, parameters as never) } export declare namespace renounceRolesSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.renounceRolesSync.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.token.renounceRolesSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.renounceRolesSync.ErrorType } /** * Revokes a role for a TIP20 token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.token.revokeRoles(config, { * token: '0x...', * from: '0x...', * roles: ['issuer'], * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function revokeRoles( config: config, parameters: revokeRoles.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.revokeRoles(client, parameters as never) } export declare namespace revokeRoles { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.revokeRoles.Parameters, 'chain' > export type ReturnValue = Actions.token.revokeRoles.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.revokeRoles.ErrorType } /** * Revokes a role for a TIP20 token. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.token.revokeRolesSync(config, { * token: '0x...', * from: '0x...', * roles: ['issuer'], * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function revokeRolesSync( config: config, parameters: revokeRolesSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.revokeRolesSync(client, parameters as never) } export declare namespace revokeRolesSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.revokeRolesSync.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.token.revokeRolesSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.revokeRolesSync.ErrorType } /** * Sets the admin role for a specific role in a TIP20 token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.token.setRoleAdmin(config, { * token: '0x...', * role: 'issuer', * adminRole: 'pause', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function setRoleAdmin( config: config, parameters: setRoleAdmin.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.setRoleAdmin(client, parameters as never) } export declare namespace setRoleAdmin { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.setRoleAdmin.Parameters, 'chain' > export type ReturnValue = Actions.token.setRoleAdmin.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.setRoleAdmin.ErrorType } /** * Sets the admin role for a specific role in a TIP20 token. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.token.setRoleAdminSync(config, { * token: '0x...', * role: 'issuer', * adminRole: 'pause', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function setRoleAdminSync( config: config, parameters: setRoleAdminSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.setRoleAdminSync(client, parameters as never) } export declare namespace setRoleAdminSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.setRoleAdminSync.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.token.setRoleAdminSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.setRoleAdminSync.ErrorType } /** * Sets the supply cap for a TIP20 token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.token.setSupplyCap(config, { * token: '0x...', * supplyCap: 1000000n, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function setSupplyCap( config: config, parameters: setSupplyCap.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.setSupplyCap(client, parameters as never) } export declare namespace setSupplyCap { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.setSupplyCap.Parameters, 'chain' > export type ReturnValue = Actions.token.setSupplyCap.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.setSupplyCap.ErrorType } /** * Sets the supply cap for a TIP20 token. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.token.setSupplyCapSync(config, { * token: '0x...', * supplyCap: 1000000n, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function setSupplyCapSync( config: config, parameters: setSupplyCapSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.setSupplyCapSync(client, parameters as never) } export declare namespace setSupplyCapSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.setSupplyCapSync.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.token.setSupplyCapSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.setSupplyCapSync.ErrorType } /** * Transfers TIP20 tokens to another address. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.token.transfer(config, { * to: '0x...', * amount: 100n, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function transfer( config: config, parameters: transfer.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.transfer(client, parameters as never) } export declare namespace transfer { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.transfer.Parameters, 'chain' > export type ReturnValue = Actions.token.transfer.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.transfer.ErrorType } /** * Transfers TIP20 tokens to another address. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.token.transferSync(config, { * to: '0x...', * amount: 100n, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function transferSync( config: config, parameters: transferSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.transferSync(client, parameters as never) } export declare namespace transferSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.transferSync.Parameters, 'chain' > export type ReturnValue = Actions.token.transferSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.transferSync.ErrorType } /** * Unpauses a TIP20 token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.token.unpause(config, { * token: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function unpause( config: config, parameters: unpause.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.unpause(client, parameters as never) } export declare namespace unpause { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.unpause.Parameters, 'chain' > export type ReturnValue = Actions.token.unpause.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.unpause.ErrorType } /** * Unpauses a TIP20 token. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.token.unpauseSync(config, { * token: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function unpauseSync( config: config, parameters: unpauseSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.unpauseSync(client, parameters as never) } export declare namespace unpauseSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.unpauseSync.Parameters, 'chain' > export type ReturnValue = Actions.token.unpauseSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.unpauseSync.ErrorType } /** * Prepares the quote token update for a TIP20 token. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const hash = await Actions.token.prepareUpdateQuoteToken(config, { * token: '0x...', * quoteToken: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns Transaction hash. */ export async function prepareUpdateQuoteToken( config: config, parameters: prepareUpdateQuoteToken.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.prepareUpdateQuoteToken(client, parameters as never) } export declare namespace prepareUpdateQuoteToken { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.prepareUpdateQuoteToken.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.token.prepareUpdateQuoteToken.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.prepareUpdateQuoteToken.ErrorType } /** * Prepares the quote token update for a TIP20 token. * * Note: This is a synchronous action that waits for the transaction to * be included on a block before returning a response. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const result = await Actions.token.prepareUpdateQuoteTokenSync(config, { * token: '0x...', * quoteToken: '0x...', * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns The transaction receipt and event data. */ export async function prepareUpdateQuoteTokenSync( config: config, parameters: prepareUpdateQuoteTokenSync.Parameters, ): Promise { const { account, chainId, connector } = parameters const client = await getConnectorClient(config, { account, assertChainId: false, chainId, connector, }) return Actions.token.prepareUpdateQuoteTokenSync(client, parameters as never) } export declare namespace prepareUpdateQuoteTokenSync { export type Parameters = ChainIdParameter & ConnectorParameter & UnionLooseOmit< Actions.token.prepareUpdateQuoteTokenSync.Parameters< config['chains'][number], Account >, 'chain' > export type ReturnValue = Actions.token.prepareUpdateQuoteTokenSync.ReturnValue export type ErrorType = BaseErrorType // TODO: Actions.token.prepareUpdateQuoteTokenSync.ErrorType } /** * Watches for TIP20 token role admin updates. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.token.watchAdminRole(config, { * onRoleAdminUpdated: (args, log) => { * console.log('Role admin updated:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchAdminRole( config: config, parameters: watchAdminRole.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.token.watchAdminRole(client, rest) } export declare namespace watchAdminRole { export type Parameters = ChainIdParameter & Actions.token.watchAdminRole.Parameters } /** * Watches for TIP20 token approval events. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.token.watchApprove(config, { * onApproval: (args, log) => { * console.log('Approval:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchApprove( config: config, parameters: watchApprove.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.token.watchApprove(client, rest) } export declare namespace watchApprove { export type Parameters = ChainIdParameter & Actions.token.watchApprove.Parameters } /** * Watches for TIP20 token burn events. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.token.watchBurn(config, { * onBurn: (args, log) => { * console.log('Burn:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchBurn( config: config, parameters: watchBurn.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.token.watchBurn(client, rest) } export declare namespace watchBurn { export type Parameters = ChainIdParameter & Actions.token.watchBurn.Parameters } /** * Watches for new TIP20 tokens created. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.token.watchCreate(config, { * onTokenCreated: (args, log) => { * console.log('Token created:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchCreate( config: config, parameters: watchCreate.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.token.watchCreate(client, rest) } export declare namespace watchCreate { export type Parameters = ChainIdParameter & Actions.token.watchCreate.Parameters } /** * Watches for TIP20 token mint events. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.token.watchMint(config, { * onMint: (args, log) => { * console.log('Mint:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchMint( config: config, parameters: watchMint.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.token.watchMint(client, rest) } export declare namespace watchMint { export type Parameters = ChainIdParameter & Actions.token.watchMint.Parameters export type ReturnValue = Actions.token.watchMint.ReturnValue } /** * Watches for TIP20 token role membership updates. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.token.watchRole(config, { * onRoleUpdated: (args, log) => { * console.log('Role updated:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchRole( config: config, parameters: watchRole.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.token.watchRole(client, rest) } export declare namespace watchRole { export type Parameters = ChainIdParameter & Actions.token.watchRole.Parameters } /** * Watches for TIP20 token transfer events. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.token.watchTransfer(config, { * onTransfer: (args, log) => { * console.log('Transfer:', args) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchTransfer( config: config, parameters: watchTransfer.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.token.watchTransfer(client, rest) } export declare namespace watchTransfer { export type Parameters = ChainIdParameter & Actions.token.watchTransfer.Parameters } /** * Watches for TIP20 token quote token update events. * * @example * ```ts * import { createConfig, http } from '@wagmi/core' * import { tempo } from '@wagmi/core/chains' * import { Actions } from '@wagmi/core/tempo' * * const config = createConfig({ * chains: [tempo], * transports: { * [tempo.id]: http(), * }, * }) * * const unwatch = Actions.token.watchUpdateQuoteToken(config, { * onUpdateQuoteToken: (args, log) => { * if (args.completed) * console.log('quote token update completed:', args.newQuoteToken) * else * console.log('quote token update proposed:', args.newQuoteToken) * }, * }) * ``` * * @param config - Config. * @param parameters - Parameters. * @returns A function to unsubscribe from the event. */ export function watchUpdateQuoteToken( config: config, parameters: watchUpdateQuoteToken.Parameters, ) { const { chainId, ...rest } = parameters const client = config.getClient({ chainId }) return Actions.token.watchUpdateQuoteToken(client, rest) } export declare namespace watchUpdateQuoteToken { export type Parameters = ChainIdParameter & Actions.token.watchUpdateQuoteToken.Parameters } ================================================ FILE: packages/core/src/tempo/actions/utils.ts ================================================ import type * as Query from '@tanstack/query-core' import type { RequiredBy, UnionLooseOmit } from '../../types/utils.js' export type QueryParameter< queryFnData = unknown, error = Query.DefaultError, data = queryFnData, queryKey extends Query.QueryKey = Query.QueryKey, > = { query?: | UnionLooseOmit< QueryOptions, 'queryKey' | 'queryFn' > | undefined } export type QueryOptions< queryFnData = unknown, error = Query.DefaultError, data = queryFnData, queryKey extends Query.QueryKey = Query.QueryKey, > = RequiredBy< Query.QueryOptions, 'queryKey' | 'queryFn' > & { enabled: boolean } export function filterQueryOptions>( options: type, ): type { // biome-ignore format: no formatting const { // import('@tanstack/query-core').QueryOptions // biome-ignore lint/correctness/noUnusedVariables: tossing _defaulted, behavior, gcTime, initialData, initialDataUpdatedAt, maxPages, meta, networkMode, queryFn, queryHash, queryKey, queryKeyHashFn, retry, retryDelay, structuralSharing, // import('@tanstack/query-core').InfiniteQueryObserverOptions // biome-ignore lint/correctness/noUnusedVariables: tossing getPreviousPageParam, getNextPageParam, initialPageParam, // import('@tanstack/react-query').UseQueryOptions // biome-ignore lint/correctness/noUnusedVariables: tossing _optimisticResults, enabled, notifyOnChangeProps, placeholderData, refetchInterval, refetchIntervalInBackground, refetchOnMount, refetchOnReconnect, refetchOnWindowFocus, retryOnMount, select, staleTime, suspense, throwOnError, // wagmi // biome-ignore lint/correctness/noUnusedVariables: tossing config, connector, query, ...rest } = options return rest as type } ================================================ FILE: packages/core/src/transports/connector.test.ts ================================================ import { config } from '@wagmi/test' import { optimism } from 'viem/chains' import { expect, test } from 'vitest' import { createStore } from 'zustand' import { injected } from '../connectors/injected.js' import { mock } from '../connectors/mock.js' import { unstable_connector } from './connector.js' const connector = config.connectors[0]! test('setup', () => { expect(unstable_connector(injected)({})).toMatchInlineSnapshot(` { "config": { "key": "connector", "methods": undefined, "name": "Connector", "request": [Function], "retryCount": 3, "retryDelay": 150, "timeout": undefined, "type": "connector", }, "request": [Function], "value": undefined, } `) }) test('behavior: connector type not found', async () => { const transport = unstable_connector({ type: 'foo' })({}) await expect(() => transport.request({ method: 'eth_chainId' }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ProviderDisconnectedError: The Provider is disconnected from all chains. Details: Could not find connector of type "foo" in \`connectors\` passed to \`createConfig\`. Version: viem@2.47.5] `) }) test('behavior: provider is disconnected', async () => { const transport = unstable_connector(mock)({ connectors: createStore(() => [ { ...connector, async getProvider() { return undefined }, }, ]), }) await expect(() => transport.request({ method: 'eth_chainId' }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ProviderDisconnectedError: The Provider is disconnected from all chains. Details: Provider is disconnected. Version: viem@2.47.5] `) }) test('behavior: chainId mismatch', async () => { const transport = unstable_connector(mock)({ chain: optimism, connectors: createStore(() => [ { ...connector, async getProvider(options = {}) { if (options.chainId === optimism.id) return connector.getProvider() return undefined }, }, ]), }) await expect(() => transport.request({ method: 'eth_chainId' }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [ChainDisconnectedError: The Provider is not connected to the requested chain. Details: The current chain of the connector (id: 1) does not match the target chain for the request (id: 10 – OP Mainnet). Version: viem@2.47.5] `) }) test('behavior: request', async () => { const transport = unstable_connector(mock)({ connectors: createStore(() => [connector]), }) await expect( transport.request({ method: 'eth_chainId' }), ).resolves.toThrowErrorMatchingInlineSnapshot(`"0x1"`) }) ================================================ FILE: packages/core/src/transports/connector.ts ================================================ import { ChainDisconnectedError, createTransport, type EIP1193Parameters, type EIP1193Provider, type EIP1193RequestFn, hexToNumber, ProviderDisconnectedError, type TransportConfig, type WalletRpcSchema, withRetry, withTimeout, } from 'viem' import type { Connector, Transport } from '../createConfig.js' export type ConnectorTransportConfig = { /** The key of the transport. */ key?: TransportConfig['key'] | undefined /** The name of the transport. */ name?: TransportConfig['name'] | undefined /** The max number of times to retry. */ retryCount?: TransportConfig['retryCount'] | undefined /** The base delay (in ms) between retries. */ retryDelay?: TransportConfig['retryDelay'] | undefined } export type ConnectorTransport = Transport export function unstable_connector( connector: Pick, config: ConnectorTransportConfig = {}, ): Transport<'connector'> { const { type } = connector const { key = 'connector', name = 'Connector', retryDelay } = config return (parameters) => { const { chain, connectors } = parameters const retryCount = config.retryCount ?? parameters.retryCount const request: EIP1193RequestFn = async ({ method, params }) => { const connector = connectors?.getState().find((c) => c.type === type) if (!connector) throw new ProviderDisconnectedError( new Error( `Could not find connector of type "${type}" in \`connectors\` passed to \`createConfig\`.`, ), ) const provider = (await connector.getProvider({ chainId: chain?.id, })) as EIP1193Provider | undefined if (!provider) throw new ProviderDisconnectedError( new Error('Provider is disconnected.'), ) // We are applying a retry & timeout strategy here as some injected wallets (e.g. MetaMask) fail to // immediately resolve a JSON-RPC request on page load. const chainId = hexToNumber( await withRetry(() => withTimeout(() => provider.request({ method: 'eth_chainId' }), { timeout: 100, }), ), ) if (chain && chainId !== chain.id) throw new ChainDisconnectedError( new Error( `The current chain of the connector (id: ${chainId}) does not match the target chain for the request (id: ${chain.id} – ${chain.name}).`, ), ) const body = { method, params } as EIP1193Parameters return provider.request(body) } return createTransport({ key, name, request, retryCount, retryDelay, type: 'connector', }) } } ================================================ FILE: packages/core/src/transports/fallback.test.ts ================================================ import { http } from 'viem' import { expect, test } from 'vitest' import { unstable_connector } from './connector.js' import { fallback } from './fallback.js' test('setup', () => { expect( fallback([ unstable_connector({ type: 'injected' }), http('https://example.com'), ])({}), ).toMatchInlineSnapshot(` { "config": { "key": "fallback", "methods": undefined, "name": "Fallback", "request": [Function], "retryCount": 3, "retryDelay": 150, "timeout": undefined, "type": "fallback", }, "request": [Function], "value": { "onResponse": [Function], "transports": [ { "config": { "key": "connector", "methods": undefined, "name": "Connector", "request": [Function], "retryCount": 0, "retryDelay": 150, "timeout": undefined, "type": "connector", }, "request": [Function], "value": undefined, }, { "config": { "key": "http", "methods": undefined, "name": "HTTP JSON-RPC", "request": [Function], "retryCount": 0, "retryDelay": 150, "timeout": 10000, "type": "http", }, "request": [Function], "value": { "fetchOptions": undefined, "url": "https://example.com", }, }, ], }, } `) }) ================================================ FILE: packages/core/src/transports/fallback.ts ================================================ import { fallback as viem_fallback } from 'viem' import type { Transport } from '../createConfig.js' export function fallback( transports: Transport[], config?: Parameters[1], ) { return viem_fallback(transports, config) } ================================================ FILE: packages/core/src/types/chain.test-d.ts ================================================ import type { Chain, mainnet, optimism, sepolia } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import type { Config } from '../createConfig.js' import type { SelectChains } from './chain.js' import type { Merge } from './utils.js' test('not narrowable', () => { type Result = SelectChains expectTypeOf().toEqualTypeOf() }) test('chainId', () => { type Result = SelectChains< Config, 1 > expectTypeOf().toEqualTypeOf() }) test('at least one chain has formatters', () => { type Result = SelectChains> expectTypeOf().toEqualTypeOf< readonly [typeof mainnet, typeof optimism] >() }) test('no formatters', () => { type Result = SelectChains> expectTypeOf().toEqualTypeOf< readonly [Merge] >() }) ================================================ FILE: packages/core/src/types/chain.ts ================================================ import type { Chain, ChainFormatters } from 'viem' import type { Config } from '../createConfig.js' import type { IsNarrowable, Merge } from './utils.js' /** Filters {@link Config} chains by {@link chainId} or simplifies if no `ChainFormatters` are present. */ export type SelectChains< config extends Config, chainId extends config['chains'][number]['id'] | undefined = undefined, > = Config extends config ? readonly [Chain] // chains not inferrable, return default : IsNarrowable extends true ? readonly [Extract] // select specific chain : HasFormatter extends true ? config['chains'] // return all chains since one has formatter : // return default chain with ID set to union (allows for more simple type since the only thing that is different is the chain ID for each chain) readonly [Merge] type HasFormatter = chains extends readonly [ infer head extends Chain, ...infer tail extends readonly Chain[], ] ? IsNarrowable extends true ? true : HasFormatter : false ================================================ FILE: packages/core/src/types/properties.ts ================================================ import type { Config, Connector } from '../createConfig.js' export type ChainIdParameter< config extends Config, chainId extends | config['chains'][number]['id'] | undefined = config['chains'][number]['id'], > = { chainId?: | (chainId extends config['chains'][number]['id'] ? chainId : undefined) | config['chains'][number]['id'] | undefined } export type ConfigParameter = { config?: Config | config | undefined } export type ConnectorParameter = { connector?: Connector | undefined } export type EnabledParameter = { enabled?: boolean | undefined } export type ScopeKeyParameter = { scopeKey?: string | undefined } export type SyncConnectedChainParameter = { syncConnectedChain?: boolean | undefined } ================================================ FILE: packages/core/src/types/query.ts ================================================ import type * as Query from '@tanstack/query-core' import type { Compute, LooseOmit, RequiredBy, UnionLooseOmit } from './utils.js' export type MutationParameter< data = unknown, error = Error, variables = void, context = unknown, > = { mutation?: | LooseOmit< Query.MutationOptions, context>, 'mutationFn' | 'mutationKey' | 'throwOnError' > | undefined } export type QueryParameter< queryFnData = unknown, error = Query.DefaultError, data = queryFnData, queryKey extends Query.QueryKey = Query.QueryKey, > = { query?: | UnionLooseOmit< QueryOptions, 'queryKey' | 'queryFn' > | undefined } export type QueryOptions< queryFnData = unknown, error = Query.DefaultError, data = queryFnData, queryKey extends Query.QueryKey = Query.QueryKey, > = Omit< RequiredBy< Query.QueryObserverOptions, 'queryKey' >, 'queryFn' | 'queryHash' | 'queryKeyHashFn' | 'throwOnError' > & { queryFn: Exclude< Query.QueryObserverOptions< queryFnData, error, data, queryFnData, queryKey >['queryFn'], typeof Query.skipToken | undefined > } ================================================ FILE: packages/core/src/types/register.ts ================================================ import type { Config } from '../createConfig.js' // biome-ignore lint/suspicious/noEmptyInterface: using export interface Register {} export type ResolvedRegister = { config: Register extends { config: infer config extends Config } ? config : Config } ================================================ FILE: packages/core/src/types/utils.test-d.ts ================================================ import { assertType, expectTypeOf, test } from 'vitest' import type { Compute, ExactPartial, IsNever, Mutable, OneOf, PartialBy, } from './utils.js' test('ExactPartial', () => { expectTypeOf>().toEqualTypeOf<{ foo?: boolean | undefined bar?: boolean | undefined }>() }) test('IsNever', () => { expectTypeOf>().toEqualTypeOf() }) test('Mutable', () => { expectTypeOf< Mutable<{ foo: boolean; readonly bar: boolean }> >().toEqualTypeOf<{ foo: boolean; bar: boolean }>() }) test('OneOf', () => { assertType>({ foo: false }) assertType>({ bar: false }) }) test('PartialBy', () => { type Result = Compute> expectTypeOf().toEqualTypeOf<{ foo?: string | undefined bar: number }>() }) ================================================ FILE: packages/core/src/types/utils.ts ================================================ /** Combines members of an intersection into a readable type. */ // https://twitter.com/mattpocockuk/status/1622730173446557697?s=20&t=NdpAcmEFXY01xkqU3KO0Mg export type Compute = { [key in keyof type]: type[key] } & unknown /** * Makes all properties of an object optional. * * Compatible with [`exactOptionalPropertyTypes`](https://www.typescriptlang.org/tsconfig#exactOptionalPropertyTypes). */ export type ExactPartial = { [key in keyof type]?: type[key] | undefined } /** * Creates a fixed array of `count` elements of type `type`. * * @example * ```ts * type Result = FixedArray * // ^? type Result = readonly [string, string, string] * ``` */ export type FixedArray< type, count extends number, result extends readonly type[] = [], > = result['length'] extends count ? result : FixedArray /** Checks if {@link type} can be narrowed further than {@link type2} */ export type IsNarrowable = IsUnknown extends true ? false : undefined extends type ? false : IsNever< (type extends type2 ? true : false) & (type2 extends type ? false : true) > extends true ? false : true /** * @internal * Checks if {@link type} is `never` */ export type IsNever = [type] extends [never] ? true : false /** * @internal * Checks if {@link type} is `unknown` */ export type IsUnknown = unknown extends type ? true : false /** Merges two object types into new type */ export type Merge = Compute< LooseOmit & obj2 > /** Removes `readonly` from all properties of an object. */ export type Mutable = { -readonly [key in keyof type]: type[key] } /** Strict version of built-in Omit type */ export type StrictOmit = Pick< type, Exclude > /** Makes objects destructurable. */ export type OneOf< union extends object, /// keys extends KeyofUnion = KeyofUnion, > = union extends infer Item ? Compute]?: undefined }> : never type KeyofUnion = type extends type ? keyof type : never /** Makes {@link key} optional in {@link type} while preserving type inference. */ // s/o trpc (https://github.com/trpc/trpc/blob/main/packages/server/src/types.ts#L6) export type PartialBy = ExactPartial< Pick > & StrictOmit /* Removes `undefined` from object property */ export type RemoveUndefined = { [key in keyof type]: NonNullable } /** * Creates a type that is {@link type} with the required keys {@link key}. * * @example * ```ts * RequiredBy<{ a?: string, b: number }, 'a'> * // { a: string, b: number } * ``` * * @internal */ export type RequiredBy = Omit & ExactRequired> /** @internal */ export type ExactRequired = { [key in keyof type]-?: Exclude } /////////////////////////////////////////////////////////////////////////// // Loose types /** Loose version of {@link StrictOmit} */ export type LooseOmit = Pick< type, Exclude > /////////////////////////////////////////////////////////////////////////// // Union types export type UnionCompute = type extends object ? Compute : type export type UnionLooseOmit = type extends any ? LooseOmit : never export type UnionStrictOmit = type extends any ? StrictOmit : never export type UnionExactPartial = type extends object ? ExactPartial : type ================================================ FILE: packages/core/src/utils/cookie.test.ts ================================================ import { http } from 'viem' import { mainnet } from 'viem/chains' import { expect, test } from 'vitest' import { createConfig } from '../createConfig.js' import { createStorage } from '../createStorage.js' import { cookieStorage, cookieToInitialState, parseCookie } from './cookie.js' test('cookieStorage', () => { expect(cookieStorage.getItem('recentConnectorId')).toMatchInlineSnapshot( 'null', ) cookieStorage.setItem('recentConnectorId', 'foo') expect(cookieStorage.getItem('recentConnectorId')).toMatchInlineSnapshot( `"foo"`, ) cookieStorage.removeItem('recentConnectorId') expect(cookieStorage.getItem('recentConnectorId')).toMatchInlineSnapshot( 'null', ) }) test('cookieToInitialState', () => { const config = createConfig({ chains: [mainnet], transports: { [mainnet.id]: http() }, storage: createStorage({ storage: cookieStorage }), }) expect( cookieToInitialState( config, 'wagmi.store={"state":{"connections":{"__type":"Map","value":[]},"chainId":1,"current":null},"version":2}; ', ), ).toMatchInlineSnapshot(` { "chainId": 1, "connections": Map {}, "current": null, } `) expect(cookieToInitialState(config)).toMatchInlineSnapshot('undefined') expect(cookieToInitialState(config), 'foo').toMatchInlineSnapshot('undefined') }) test('parseCookie', () => { expect( parseCookie( 'wagmi.store={"state":{"connections":{"__type":"Map","value":[]},"chainId":1,"current":null},"version":2}; ', 'wagmi.store', ), ).toMatchInlineSnapshot( `"{"state":{"connections":{"__type":"Map","value":[]},"chainId":1,"current":null},"version":2}"`, ) expect( parseCookie( 'foo="bar"; wagmi.store={"state":{"connections":{"__type":"Map","value":[]},"chainId":1,"current":null},"version":2}; ', 'wagmi.store', ), ).toMatchInlineSnapshot( `"{"state":{"connections":{"__type":"Map","value":[]},"chainId":1,"current":null},"version":2}"`, ) expect(parseCookie('foo="bar"; ', 'wagmi.store')).toMatchInlineSnapshot( 'undefined', ) }) ================================================ FILE: packages/core/src/utils/cookie.ts ================================================ import type { Config, State } from '../createConfig.js' import type { BaseStorage } from '../createStorage.js' import { deserialize } from './deserialize.js' export const cookieStorage = { getItem(key) { if (typeof window === 'undefined') return null const value = parseCookie(document.cookie, key) return value ?? null }, setItem(key, value) { if (typeof window === 'undefined') return // biome-ignore lint/suspicious/noDocumentCookie: using document.cookie = `${key}=${value};path=/;samesite=Lax` }, removeItem(key) { if (typeof window === 'undefined') return // biome-ignore lint/suspicious/noDocumentCookie: using document.cookie = `${key}=;max-age=-1;path=/` }, } satisfies BaseStorage export function cookieToInitialState(config: Config, cookie?: string | null) { if (!cookie) return undefined const key = `${config.storage?.key}.store` const parsed = parseCookie(cookie, key) if (!parsed) return undefined return deserialize<{ state: State }>(parsed).state } export function parseCookie(cookie: string, key: string) { const keyValue = cookie.split('; ').find((x) => x.startsWith(`${key}=`)) if (!keyValue) return undefined return keyValue.substring(key.length + 1) } ================================================ FILE: packages/core/src/utils/deepEqual.test.ts ================================================ import { expect, test } from 'vitest' import { deepEqual } from './deepEqual.js' test('compares primitive values', () => { expect(deepEqual(true, true)).toBe(true) expect(deepEqual(true, false)).toBe(false) expect(deepEqual(1, 1)).toBe(true) expect(deepEqual(1, 2)).toBe(false) expect(deepEqual('zustand', 'zustand')).toBe(true) expect(deepEqual('zustand', 'redux')).toBe(false) }) test('compares objects', () => { expect(deepEqual({ foo: 'bar', asd: 123 }, { foo: 'bar', asd: 123 })).toBe( true, ) expect( deepEqual({ foo: 'bar', asd: 123 }, { foo: 'bar', foobar: true }), ).toBe(false) expect( deepEqual({ foo: 'bar', asd: 123 }, { foo: 'bar', asd: 123, foobar: true }), ).toBe(false) }) test('compares arrays', () => { expect(deepEqual([1, 2, 3], [1, 2, 3])).toBe(true) expect(deepEqual([1, 2, 3], [2, 3, 4])).toBe(false) expect( deepEqual([{ foo: 'bar' }, { asd: 123 }], [{ foo: 'bar' }, { asd: 123 }]), ).toBe(true) expect(deepEqual([{ foo: 'bar' }], [{ foo: 'bar', asd: 123 }])).toBe(false) }) ================================================ FILE: packages/core/src/utils/deepEqual.ts ================================================ /** Forked from https://github.com/epoberezkin/fast-deep-equal */ export function deepEqual(a: any, b: any) { if (a === b) return true if (a && b && typeof a === 'object' && typeof b === 'object') { if (a.constructor !== b.constructor) return false let length: number let i: number if (Array.isArray(a) && Array.isArray(b)) { length = a.length if (length !== b.length) return false for (i = length; i-- !== 0; ) if (!deepEqual(a[i], b[i])) return false return true } if ( typeof a.valueOf === 'function' && a.valueOf !== Object.prototype.valueOf ) return a.valueOf() === b.valueOf() if ( typeof a.toString === 'function' && a.toString !== Object.prototype.toString ) return a.toString() === b.toString() const keys = Object.keys(a) length = keys.length if (length !== Object.keys(b).length) return false for (i = length; i-- !== 0; ) if (!Object.hasOwn(b, keys[i]!)) return false for (i = length; i-- !== 0; ) { const key = keys[i] if (key && !deepEqual(a[key], b[key])) return false } return true } // true if both NaN, false otherwise // biome-ignore lint/suspicious/noSelfCompare: using return a !== a && b !== b } ================================================ FILE: packages/core/src/utils/deserialize.test.ts ================================================ import { expect, test } from 'vitest' import { deserialize } from './deserialize.js' import { serialize } from './serialize.js' test('deserializes', () => { const deserializedCache = deserialize( serialize({ some: 'complex', object: { that: 'has', many: [ { many: 'many', manymany: 'many' }, { many: 'many' }, { many: 'many' }, { many: { properties: { ones: { that: { have: { functions: () => null, }, }, }, }, }, }, ], }, and: { ones: { that: { have: { bigints: 123456789012345678901234567890n, }, }, }, }, also: { ones: { that: { have: { proxies: new Proxy({ lol: 'nice' }, {}), }, }, }, }, }), ) expect(deserializedCache).toMatchInlineSnapshot(` { "also": { "ones": { "that": { "have": { "proxies": { "lol": "nice", }, }, }, }, }, "and": { "ones": { "that": { "have": { "bigints": 123456789012345678901234567890n, }, }, }, }, "object": { "many": [ { "many": "many", "manymany": "many", }, { "many": "many", }, { "many": "many", }, { "many": { "properties": { "ones": { "that": { "have": {}, }, }, }, }, }, ], "that": "has", }, "some": "complex", } `) }) test('Map', () => { const map = new Map().set('foo', { bar: 'baz' }) const deserializedCache = deserialize(serialize({ map })) expect(deserializedCache).toEqual({ map }) }) test('bigint', () => { const bigint = 123n const deserializedCache = deserialize(serialize({ bigint })) expect(deserializedCache).toEqual({ bigint }) }) ================================================ FILE: packages/core/src/utils/deserialize.ts ================================================ type Reviver = (key: string, value: any) => any export function deserialize(value: string, reviver?: Reviver): type { return JSON.parse(value, (key, value_) => { let value = value_ if (value?.__type === 'bigint') value = BigInt(value.value) if (value?.__type === 'Map') value = new Map(value.value) return reviver?.(key, value) ?? value }) } ================================================ FILE: packages/core/src/utils/extractRpcUrls.test.ts ================================================ import { http } from 'viem' import { mainnet, optimism, sepolia } from 'viem/chains' import { expect, test } from 'vitest' import { injected } from '../connectors/injected.js' import { unstable_connector } from '../transports/connector.js' import { fallback } from '../transports/fallback.js' import { extractRpcUrls } from './extractRpcUrls.js' test('default', () => { expect( extractRpcUrls({ chain: mainnet, transports: { [mainnet.id]: fallback([ http('https://wagmi.com'), http('https://lol.com'), ]), [sepolia.id]: http('https://sepoliarocks.com'), [optimism.id]: http(), }, }), ).toMatchInlineSnapshot(` [ "https://wagmi.com", "https://lol.com", ] `) expect( extractRpcUrls({ chain: sepolia, transports: { [mainnet.id]: fallback([ http('https://wagmi.com'), http('https://lol.com'), ]), [sepolia.id]: http('https://sepoliarocks.com'), [optimism.id]: http(), }, }), ).toMatchInlineSnapshot(` [ "https://sepoliarocks.com", ] `) expect( extractRpcUrls({ chain: optimism, transports: { [mainnet.id]: fallback([ http('https://wagmi.com'), http('https://lol.com'), ]), [sepolia.id]: http('https://sepoliarocks.com'), [optimism.id]: http(), }, }), ).toMatchInlineSnapshot(` [ "https://mainnet.optimism.io", ] `) expect( extractRpcUrls({ chain: mainnet, }), ).toMatchInlineSnapshot(` [ "https://eth.merkle.io", ] `) expect( extractRpcUrls({ chain: mainnet, transports: { [mainnet.id]: fallback([ unstable_connector(injected), http('https://lol.com'), ]), }, }), ).toMatchInlineSnapshot(` [ "https://eth.merkle.io", "https://lol.com", ] `) }) ================================================ FILE: packages/core/src/utils/extractRpcUrls.ts ================================================ import type { Chain, Transport } from 'viem' type ExtractRpcUrlsParameters = { transports?: Record | undefined chain: Chain } export function extractRpcUrls(parameters: ExtractRpcUrlsParameters) { const { chain } = parameters const fallbackUrl = chain.rpcUrls.default.http[0] if (!parameters.transports) return [fallbackUrl] const transport = parameters.transports?.[chain.id]?.({ chain }) const transports = (transport?.value?.transports as NonNullable< typeof transport >[]) || [transport] return transports.map(({ value }) => value?.url || fallbackUrl) } ================================================ FILE: packages/core/src/utils/getAction.test.ts ================================================ import { abi, address, config } from '@wagmi/test' import * as viem_actions from 'viem/actions' import { expect, test, vi } from 'vitest' import { getAction } from './getAction.js' test('uses tree-shakable action', async () => { const client = config.getClient({ chainId: 1 }) const name = 'getBlockNumber' const actions = { ...viem_actions } const spy = vi.spyOn(actions, name) const action = getAction(client, actions[name], name) await action({}) expect(spy).toBeCalledWith(client, {}) }) test('uses client action', async () => { const client = config .getClient({ chainId: 1 }) .extend(() => ({ getBlockNumber: async () => 69n })) const name = 'getBlockNumber' const spy = vi.spyOn(client, name) const action = getAction(client, client[name], name) await action({}) expect(spy).toBeCalledWith({}) }) test('internal call', async () => { const client = config.getClient({ chainId: 1 }).extend(() => ({ async call() { return { data: '0x0000000000000000000000000000000000000000000000000000000000000045', } }, })) await expect( viem_actions.readContract(client, { address: address.wagmiMintExample, abi: abi.erc20, functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }), ).resolves.toEqual(69n) }) ================================================ FILE: packages/core/src/utils/getAction.ts ================================================ import type { Account, Chain, Client, PublicActions, RpcSchema, Transport, WalletActions, } from 'viem' /** * Retrieves and returns an action from the client (if exists), and falls * back to the tree-shakable action. * * Useful for extracting overridden actions from a client (ie. if a consumer * wants to override the `sendTransaction` implementation). */ export function getAction< transport extends Transport, chain extends Chain | undefined, account extends Account | undefined, rpcSchema extends RpcSchema | undefined, extended extends { [key: string]: unknown }, client extends Client, parameters, returnType, >( client: client, actionFn: (_: any, parameters: parameters) => returnType, // Some minifiers drop `Function.prototype.name`, or replace it with short letters, // meaning that `actionFn.name` will not always work. For that case, the consumer // needs to pass the name explicitly. name: keyof PublicActions | keyof WalletActions, ): (parameters: parameters) => returnType { const action_implicit = client[actionFn.name] if (typeof action_implicit === 'function') return action_implicit as (params: parameters) => returnType const action_explicit = client[name] if (typeof action_explicit === 'function') return action_explicit as (params: parameters) => returnType return (params) => actionFn(client, params) } ================================================ FILE: packages/core/src/utils/getVersion.test.ts ================================================ import { expect, test } from 'vitest' import { getVersion } from './getVersion.js' test('default', () => { expect(getVersion()).toMatchInlineSnapshot(`"@wagmi/core@x.y.z"`) }) ================================================ FILE: packages/core/src/utils/getVersion.ts ================================================ import { version } from '../version.js' export const getVersion = () => `@wagmi/core@${version}` ================================================ FILE: packages/core/src/utils/serialize.test.ts ================================================ import { describe, expect, it } from 'vitest' import { serialize } from './serialize.js' class Foo { value: string constructor(value: string) { this.value = value } } const simpleObject = { boolean: true, fn() { return 'foo' }, nan: Number.NaN, nil: null, number: 123, string: 'foo', undef: undefined, [Symbol('key')]: 'value', } const bigintObject = Object.assign({}, simpleObject, { bigint: 123n, nested: { bigint: { value: 69n, }, }, }) const bufferString = 'this is a test buffer' const complexObject = Object.assign({}, simpleObject, { array: ['foo', { bar: 'baz' }], buffer: Buffer.alloc(bufferString.length, bufferString), error: new Error('boom'), foo: new Foo('value'), map: new Map().set('foo', { bar: 'baz' }), object: { foo: { bar: 'baz' } }, promise: Promise.resolve('foo'), regexp: /foo/, set: new Set().add('foo').add({ bar: 'baz' }), weakmap: new WeakMap([ [{}, 'foo'], [{}, 'bar'], ]), weakset: new WeakSet([{}, {}]), }) const circularObject = Object.assign( {}, complexObject, { map: { __type: 'Map', value: [['foo', { bar: 'baz' }]] }, }, { deeply: { nested: { reference: {}, }, }, }, ) circularObject.deeply.nested.reference = circularObject describe('stringify', () => { describe('handling of object types', () => { it('should handle simple objects', () => { const result = serialize(simpleObject) expect(result).toMatchInlineSnapshot( `"{"boolean":true,"nan":null,"nil":null,"number":123,"string":"foo"}"`, ) }) it('should handle objects with bigints', () => { const result = serialize(bigintObject) expect(result).toMatchInlineSnapshot( `"{"boolean":true,"nan":null,"nil":null,"number":123,"string":"foo","bigint":{"__type":"bigint","value":"123"},"nested":{"bigint":{"value":{"__type":"bigint","value":"69"}}}}"`, ) }) it('should handle simple objects with a custom replacer', () => { const replacer = (_key: string, value: any) => value && typeof value === 'object' ? value : `primitive-${value}` const result = serialize(simpleObject, replacer) expect(result).toMatchInlineSnapshot( `"{"boolean":"primitive-true","fn":"primitive-fn() {\\n return \\"foo\\";\\n }","nan":"primitive-NaN","nil":"primitive-null","number":"primitive-123","string":"primitive-foo","undef":"primitive-undefined"}"`, ) }) it('should handle simple objects with indentation', () => { const result = serialize(simpleObject, null, 2) expect(result).toMatchInlineSnapshot(` "{ "boolean": true, "nan": null, "nil": null, "number": 123, "string": "foo" }" `) }) it('should handle bigint objects with indentation', () => { const result = serialize(bigintObject, null, 2) expect(result).toMatchInlineSnapshot(` "{ "boolean": true, "nan": null, "nil": null, "number": 123, "string": "foo", "bigint": { "__type": "bigint", "value": "123" }, "nested": { "bigint": { "value": { "__type": "bigint", "value": "69" } } } }" `) }) it('should handle complex objects', () => { const result = serialize(complexObject) expect(result).toMatchInlineSnapshot( `"{"boolean":true,"nan":null,"nil":null,"number":123,"string":"foo","array":["foo",{"bar":"baz"}],"buffer":{"type":"Buffer","data":[116,104,105,115,32,105,115,32,97,32,116,101,115,116,32,98,117,102,102,101,114]},"error":{},"foo":{"value":"value"},"map":{"__type":"Map","value":[["foo",{"bar":"baz"}]]},"object":{"foo":{"bar":"baz"}},"promise":{},"regexp":{},"set":{},"weakmap":{},"weakset":{}}"`, ) }) it('should handle complex objects with a custom replacer', () => { const replacer = (_key: string, value: any) => value && typeof value === 'object' ? value : `primitive-${value}` const result = serialize(complexObject, replacer) expect(result).toMatchInlineSnapshot( `"{"boolean":"primitive-true","fn":"primitive-fn() {\\n return \\"foo\\";\\n }","nan":"primitive-NaN","nil":"primitive-null","number":"primitive-123","string":"primitive-foo","undef":"primitive-undefined","array":["primitive-foo",{"bar":"primitive-baz"}],"buffer":{"type":"primitive-Buffer","data":["primitive-116","primitive-104","primitive-105","primitive-115","primitive-32","primitive-105","primitive-115","primitive-32","primitive-97","primitive-32","primitive-116","primitive-101","primitive-115","primitive-116","primitive-32","primitive-98","primitive-117","primitive-102","primitive-102","primitive-101","primitive-114"]},"error":{},"foo":{"value":"primitive-value"},"map":{"__type":"primitive-Map","value":[["primitive-foo",{"bar":"primitive-baz"}]]},"object":{"foo":{"bar":"primitive-baz"}},"promise":{},"regexp":{},"set":{},"weakmap":{},"weakset":{}}"`, ) }) it('should handle circular objects', () => { const result = serialize(circularObject) expect(result).toEqual( JSON.stringify( circularObject, (() => { const cache: any[] = [] return (_key, value) => { if (value && typeof value === 'object' && ~cache.indexOf(value)) { return '[ref=.]' } cache.push(value) return value } })(), ), ) }) it('should handle circular objects with a custom circular replacer', () => { const result = serialize( circularObject, null, null, (_key: string, _value: string, referenceKey: string) => referenceKey, ) const circularReplacer = (() => { const cache: any[] = [] return (_key: string, value: any) => { if (value && typeof value === 'object' && ~cache.indexOf(value)) { return '.' } cache.push(value) return value } })() expect(result).toEqual(JSON.stringify(circularObject, circularReplacer)) }) }) describe('key references', () => { it('should point to the top level object when it is referenced', () => { const object = { foo: 'bar', deeply: { recursive: { object: {}, }, }, } object.deeply.recursive.object = object expect(serialize(object)).toEqual( `{"foo":"bar","deeply":{"recursive":{"object":"[ref=.]"}}}`, ) }) it('should point to the nested object when it is referenced', () => { const object = { foo: 'bar', deeply: { recursive: { object: {}, }, }, } object.deeply.recursive.object = object.deeply.recursive expect(serialize(object)).toEqual( `{"foo":"bar","deeply":{"recursive":{"object":"[ref=.deeply.recursive]"}}}`, ) }) }) }) ================================================ FILE: packages/core/src/utils/serialize.ts ================================================ /** * Get the reference key for the circular value * * @param keys the keys to build the reference key from * @param cutoff the maximum number of keys to include * @returns the reference key */ function getReferenceKey(keys: string[], cutoff: number) { return keys.slice(0, cutoff).join('.') || '.' } /** * Faster `Array.prototype.indexOf` implementation build for slicing / splicing * * @param array the array to match the value in * @param value the value to match * @returns the matching index, or -1 */ function getCutoff(array: any[], value: any) { const { length } = array for (let index = 0; index < length; ++index) { if (array[index] === value) { return index + 1 } } return 0 } type StandardReplacer = (key: string, value: any) => any type CircularReplacer = (key: string, value: any, referenceKey: string) => any /** * Create a replacer method that handles circular values * * @param [replacer] a custom replacer to use for non-circular values * @param [circularReplacer] a custom replacer to use for circular methods * @returns the value to stringify */ function createReplacer( replacer?: StandardReplacer | null | undefined, circularReplacer?: CircularReplacer | null | undefined, ): StandardReplacer { const hasReplacer = typeof replacer === 'function' const hasCircularReplacer = typeof circularReplacer === 'function' const cache: any[] = [] const keys: string[] = [] return function replace(this: any, key: string, value: any) { if (typeof value === 'object') { if (cache.length) { const thisCutoff = getCutoff(cache, this) if (thisCutoff === 0) { cache[cache.length] = this } else { cache.splice(thisCutoff) keys.splice(thisCutoff) } keys[keys.length] = key const valueCutoff = getCutoff(cache, value) if (valueCutoff !== 0) { return hasCircularReplacer ? circularReplacer.call( this, key, value, getReferenceKey(keys, valueCutoff), ) : `[ref=${getReferenceKey(keys, valueCutoff)}]` } } else { cache[0] = value keys[0] = key } } return hasReplacer ? replacer.call(this, key, value) : value } } /** * Stringifier that handles circular values * * Forked from https://github.com/planttheidea/fast-stringify * * @param value to stringify * @param [replacer] a custom replacer function for handling standard values * @param [indent] the number of spaces to indent the output by * @param [circularReplacer] a custom replacer function for handling circular values * @returns the stringified output */ export function serialize( value: any, replacer?: StandardReplacer | null | undefined, indent?: number | null | undefined, circularReplacer?: CircularReplacer | null | undefined, ) { return JSON.stringify( value, createReplacer((key, value_) => { let value = value_ if (typeof value === 'bigint') value = { __type: 'bigint', value: value_.toString() } if (value instanceof Map) value = { __type: 'Map', value: Array.from(value_.entries()) } return replacer?.(key, value) ?? value }, circularReplacer), indent ?? undefined, ) } ================================================ FILE: packages/core/src/utils/uid.ts ================================================ const size = 256 let index = size let buffer: string export function uid(length = 11) { if (!buffer || index + length > size * 2) { buffer = '' index = 0 for (let i = 0; i < size; i++) { buffer += ((256 + Math.random() * 256) | 0).toString(16).substring(1) } } return buffer.substring(index, index++ + length) } ================================================ FILE: packages/core/src/version.ts ================================================ export const version = '3.4.0' ================================================ FILE: packages/core/test/setup.ts ================================================ import { vi } from 'vitest' vi.mock('../src/version.ts', () => { return { version: 'x.y.z' } }) ================================================ FILE: packages/core/tsconfig.build.json ================================================ { "extends": "../../tsconfig.base.json", "include": ["src/**/*.ts"], "exclude": ["src/**/*.bench-d.ts", "src/**/*.test.ts", "src/**/*.test-d.ts"], "compilerOptions": { "sourceMap": true } } ================================================ FILE: packages/core/tsconfig.json ================================================ { "extends": "./tsconfig.build.json", "include": ["src/**/*.ts", "test/**/*.ts"], "exclude": [], "compilerOptions": { "resolveJsonModule": true } } ================================================ FILE: packages/create-wagmi/CHANGELOG.md ================================================ # create-wagmi ## 2.0.19 ### Patch Changes - Fixed Vite React template build by removing global Buffer patch ([#4900](https://github.com/wevm/wagmi/pull/4900)) ## 2.0.18 ### Patch Changes - Bumped next.js template dependencies ([`d717d86`](https://github.com/wevm/wagmi/commit/d717d86962a6335d9c23e7fe530f17bae16f4e10)) ## 2.0.17 ### Patch Changes - Bumped next.js template dependencies ([`99c7e2f`](https://github.com/wevm/wagmi/commit/99c7e2f096ef3fc277b3f517c0ddd983bd920880)) ## 2.0.16 ### Patch Changes - Bumped Wagmi version ([`0112d33`](https://github.com/wevm/wagmi/commit/0112d33a20340f37b3b19538f55e1f32cb24c5f1)) ## 2.0.15 ### Patch Changes - [#4673](https://github.com/wevm/wagmi/pull/4673) [`c49866724e182920e369193201d1308259c3968e`](https://github.com/wevm/wagmi/commit/c49866724e182920e369193201d1308259c3968e) Thanks [@imaksp](https://github.com/imaksp)! - Fixed Next.js template type error ## 2.0.14 ### Patch Changes - [#4450](https://github.com/wevm/wagmi/pull/4450) [`7b9a6bb35881b657a00bdd7ccd7edea32660f5bf`](https://github.com/wevm/wagmi/commit/7b9a6bb35881b657a00bdd7ccd7edea32660f5bf) Thanks [@tmm](https://github.com/tmm)! - Removed internal usage of `fs-extra`. ## 2.0.13 ### Patch Changes - [#4060](https://github.com/wevm/wagmi/pull/4060) [`95965c1f19d480b97f2b297a077a9e607dee32ad`](https://github.com/wevm/wagmi/commit/95965c1f19d480b97f2b297a077a9e607dee32ad) Thanks [@dalechyn](https://github.com/dalechyn)! - Bumped Tanstack Query dependencies to fix typing issues between exported Wagmi query options and TanStack Query suspense query methods (due to [`direction` property in `QueryFunctionContext` being deprecated](https://github.com/TanStack/query/pull/7410)). ## 2.0.12 ### Patch Changes - [`c00303d0c5909680b3124f92c0a2d2f31ea30405`](https://github.com/wevm/wagmi/commit/c00303d0c5909680b3124f92c0a2d2f31ea30405) Thanks [@tmm](https://github.com/tmm)! - Bumped Next.js version ## 2.0.11 ### Patch Changes - [#3871](https://github.com/wevm/wagmi/pull/3871) [`0e6bd286`](https://github.com/wevm/wagmi/commit/0e6bd286ca2572d2bfbe206db460528b7c2ebc63) Thanks [@jxom](https://github.com/jxom)! - Added `.npmrc` with `legacy-peer-deps = true` to templates. ## 2.0.10 ### Patch Changes - [`3f8203bd`](https://github.com/wevm/wagmi/commit/3f8203bd77fcf6b6756640b5971d09741ae3853d) Thanks [@tmm](https://github.com/tmm)! - Set Wagmi-related package versions to latest. ## 2.0.9 ### Patch Changes - [#3518](https://github.com/wevm/wagmi/pull/3518) [`338e857d`](https://github.com/wevm/wagmi/commit/338e857d8cb2fe85e13d9207bef14cada1c1962d) Thanks [@tmm](https://github.com/tmm)! - Bumped dependencies. ## 2.0.8 ### Patch Changes - [#3510](https://github.com/wevm/wagmi/pull/3510) [`660ff80d`](https://github.com/wevm/wagmi/commit/660ff80d5b046967a446eba43ee54b8359a37d0d) Thanks [@tmm](https://github.com/tmm)! - Fixed issue where connectors returning multiple addresses didn't checksum correctly. ## 2.0.7 ### Patch Changes - [#3496](https://github.com/wevm/wagmi/pull/3496) [`ba7f8a75`](https://github.com/wevm/wagmi/commit/ba7f8a758efb07664c6e401b5e7e325e7c62341b) Thanks [@tmm](https://github.com/tmm)! - Bumped dependencies. ## 2.0.6 ### Patch Changes - [#3427](https://github.com/wevm/wagmi/pull/3427) [`370f1b4a`](https://github.com/wevm/wagmi/commit/370f1b4a3f154d181acf381c31c2e7862e22c0e4) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Bumped dependencies. ## 2.0.5 ### Patch Changes - [#3459](https://github.com/wevm/wagmi/pull/3459) [`d950b666`](https://github.com/wevm/wagmi/commit/d950b666b56700ca039ce16cdfdf34564991e7f5) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Bumped dependencies ## 2.0.4 ### Patch Changes - [#3443](https://github.com/wevm/wagmi/pull/3443) [`007024a6`](https://github.com/wevm/wagmi/commit/007024a684ddbecf924cdc06dd6a8854fc3d5eeb) Thanks [@jmrossy](https://github.com/jmrossy)! - Bumped dependencies. - [#3447](https://github.com/wevm/wagmi/pull/3447) [`a02a26ad`](https://github.com/wevm/wagmi/commit/a02a26ad030d3afb78f744377d61b5c60b65d97a) Thanks [@tmm](https://github.com/tmm)! - Bumped dependencies. ## 2.0.3 ### Patch Changes - [`ec0d8b41`](https://github.com/wevm/wagmi/commit/ec0d8b4112181fefb11025e436a94a6114761d37) Thanks [@tmm](https://github.com/tmm)! - Added note to `metaMask` connector. ## 2.0.2 ### Patch Changes - [#3384](https://github.com/wevm/wagmi/pull/3384) [`ee868c33`](https://github.com/wevm/wagmi/commit/ee868c3385dae511230b6ddcb5627c1293cc1844) Thanks [@tmm](https://github.com/tmm)! - Fixed connectors not bubbling error when connecting with `chainId` and subsequent user rejection. ## 2.0.1 ### Major Changes - [#3333](https://github.com/wevm/wagmi/pull/3333) [`b3a0baaa`](https://github.com/wevm/wagmi/commit/b3a0baaaee7decf750d376aab2502cd33ca4825a) Thanks [@tmm](https://github.com/tmm)! - Added support for Wagmi 2.0. ## 1.0.5 ### Patch Changes - 6ba996f: Fixed optional WalletConnect Cloud Project ID prompt ## 1.0.4 ### Patch Changes - eb8dd9d: Updated wagmi & viem. Added ConnectKit template back in. ## 1.0.3 ### Patch Changes - 00d9080: Added RainbowKit & Web3Modal wagmi v1 templates ## 1.0.2 ### Patch Changes - 3c65f77: Fixed Next.js default template title ## 1.0.0 ### Major Changes - affc13e: Updated to wagmi v1. ## 0.1.19 ### Patch Changes - 1282f0e: Updated templates to use WalletConnect v2 by default ## 0.1.18 ### Patch Changes - 12dcfe0: Updated wagmi to 0.12 in ConnectKit templates. ## 0.1.17 ### Patch Changes - 6eba01a: Updated wagmi to 0.12. - 3a0ab8c: Added .env to .gitignore in templates. ## 0.1.16 ### Patch Changes - 7ad50f1: Upgraded `@wagmi/cli` ## 0.1.15 ### Patch Changes - 6e30599: Added `test` config to `foundry.toml` on the Foundry templates. ## 0.1.14 ### Patch Changes - 19f3675: Bumped `wagmi` to `~0.11.0`. ## 0.1.13 ### Patch Changes - c1ab75c: Bump @wagmi/cli ## 0.1.12 ### Patch Changes - af6e551: Added templates for `@wagmi/cli`: - `@wagmi/cli (Mint NFT Example)` - `@wagmi/cli + ERC20` - `@wagmi/cli + Etherscan (Mint NFT Example)` - `@wagmi/cli + Foundry (Counter.sol Example)` ## 0.1.11 ### Patch Changes - cc638dd: Fixed an issue where Vite projects used `process.env` instead of `import.meta.env`. - 75d1c2d: Updated `wagmi` to `~0.10.0`. ## 0.1.10 ### Patch Changes - 9cd7140: Amend gitignore files for Vite templates ## 0.1.9 ### Patch Changes - 904a2e1: Fixed import env variables in Vite (React) templates ## 0.1.8 ### Patch Changes - 65cc841: Update RainbowKit & ConnectKit templates to `wagmi@~0.9.0` ## 0.1.7 ### Patch Changes - a59d9c5: Upgrade `default` & `web3modal` templates to `wagmi@0.9` ## 0.1.6 ### Patch Changes - b544457: Updated `connectkit` to `1.1.0` in the ConnectKit templates ## 0.1.5 ### Patch Changes - 6bd6c74: Updated repo link in package.json ## 0.1.4 ### Patch Changes - c39666b: Added ability to select providers - 37708ed: **Added ability to select frameworks.** Each directory in `templates/` now mirrors a "framework", where its child directories mirror a "template" for that framework. Example: ``` templates/ next/ connectkit/ default/ rainbowkit/ web3modal vite-react/ connectkit/ default/ rainbowkit/ web3modal/ ``` - 399d2b9: Moved template configuration to the template level + added hooks ## 0.1.3 ### Patch Changes - 353332a: Added Web3Modal template - dd95b14: **next-with-connectkit**: Update `connectkit` to `^1.0.0` ## 0.1.2 ### Patch Changes - 34f666b: Fixed issue where package manager install process would not log error ## 0.1.1 ### Patch Changes - 900cbdc: Updated `@rainbow-me/rainbowkit` dependency in Next + RainbowKit template ## 0.1.0 ### Minor Changes - 23993d2: ## 🎉 Initial release 🎉 Get up and running quickly with wagmi by using the `create-wagmi` CLI. This tool interactively scaffolds a new wagmi project for you so you can start building instantly without the hassle of setting up `git`, installing packages, worrying about TypeScript configuration, etc. To get started, `create-wagmi` can be instantiated with one of your favorite package managers: ```bash npm init wagmi # or pnpm create wagmi # or yarn create wagmi ``` ================================================ FILE: packages/create-wagmi/README.md ================================================ # create-wagmi Get up and running quickly with [Wagmi](https://wagmi.sh) by using the `create-wagmi` CLI. ## Installation ```bash npm create wagmi # or pnpm create wagmi # or yarn create wagmi ``` ## Documentation For documentation and guides, visit [wagmi.sh](https://wagmi.sh/cli/create-wagmi). ================================================ FILE: packages/create-wagmi/package.json ================================================ { "name": "create-wagmi", "description": "Create Wagmi apps with one command", "version": "2.0.19", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/wevm/wagmi.git", "directory": "packages/create-wagmi" }, "scripts": { "build": "pnpm run build:esm+types", "build:esm+types": "tsc --project tsconfig.build.json --outDir ./dist/esm --declaration --declarationMap --declarationDir ./dist/types", "check:types": "tsc --noEmit", "clean": "rm -rf dist tsconfig.tsbuildinfo", "dev": "bun src/cli.ts", "test:build": "publint --strict" }, "files": [ "dist/**", "!dist/**/*.tsbuildinfo", "src/**/*.ts", "!src/**/*.test.ts", "!src/**/*.test-d.ts", "templates/**" ], "bin": { "wagmi": "./dist/esm/cli.js" }, "sideEffects": false, "type": "module", "exports": { "./package.json": "./package.json" }, "dependencies": { "cac": "^6.7.14", "cross-spawn": "^7.0.3", "picocolors": "^1.0.0", "prompts": "^2.4.2" }, "devDependencies": { "@types/cross-spawn": "^6.0.6", "@types/node": "^24.5.1", "@types/prompts": "^2.4.9" }, "contributors": [ "awkweb.eth ", "jxom.eth " ], "funding": "https://github.com/sponsors/wevm", "keywords": [ "wagmi", "eth", "ethereum", "dapps", "wallet", "web3", "cli" ] } ================================================ FILE: packages/create-wagmi/src/cli.test.ts ================================================ import { type ExecSyncOptionsWithStringEncoding, execSync, } from 'node:child_process' import { mkdirSync, readdirSync, writeFileSync } from 'node:fs' import { rm } from 'node:fs/promises' import { join } from 'node:path' import pc from 'picocolors' import { afterEach, beforeAll, expect, test } from 'vitest' import { version } from './version.js' const cliPath = join(__dirname, '../dist/esm/cli.js') const projectName = 'test-app' const genPath = join(__dirname, projectName) function run( args: string[], options: ExecSyncOptionsWithStringEncoding = { encoding: 'utf8' }, ): string { return execSync(`node ${cliPath} ${args.join(' ')}`, options) } function createNonEmptyDir() { mkdirSync(genPath, { recursive: true }) const file = join(genPath, 'foo') writeFileSync(file, 'bar') } beforeAll(async () => { execSync('pnpm --filter create-wagmi build') await rm(genPath, { recursive: true, force: true }) }) afterEach(async () => { await rm(genPath, { recursive: true, force: true }) }) test('prompts for the project name if none supplied', () => { const stdout = run([]) expect(stdout).toContain('Project name:') }) test('prompts for the framework if none supplied when target dir is current directory', () => { mkdirSync(genPath) const stdout = run(['.'], { cwd: genPath, encoding: 'utf8' }) expect(stdout).toContain('Select a framework:') }) test('prompts for the framework if none supplied', () => { const stdout = run([projectName]) expect(stdout).toContain('Select a framework:') }) test('prompts for the framework on not supplying a value for --template', () => { const stdout = run([projectName, '--template']) expect(stdout).toContain('Select a framework:') }) test('prompts for the framework on supplying an invalid template', () => { const stdout = run([projectName, '--template', 'unknown']) expect(stdout).toContain( `"unknown" isn't a valid template. Please choose from below:`, ) }) test('asks to overwrite non-empty target directory', () => { createNonEmptyDir() const stdout = run([projectName], { cwd: __dirname, encoding: 'utf8' }) expect(stdout).toContain(`Target directory "${projectName}" is not empty.`) }) test('asks to overwrite non-empty current directory', () => { createNonEmptyDir() const stdout = run(['.'], { cwd: genPath, encoding: 'utf8' }) expect(stdout).toContain('Current directory is not empty.') }) const templateFiles = readdirSync( join(cliPath, '../../../templates/vite-react'), ) .map((filePath) => { if (filePath === '_gitignore') return '.gitignore' if (filePath === '_env.local') return '.env.local' if (filePath === '_npmrc') return '.npmrc' return filePath }) .sort() test('successfully scaffolds a project based on vite-react starter template', () => { mkdirSync(genPath, { recursive: true }) const stdout = run([projectName, '--template', 'vite-react'], { cwd: __dirname, encoding: 'utf8', }) const generatedFiles = readdirSync(genPath).sort() expect(stdout).toContain(`Scaffolding project in ${genPath}`) expect(templateFiles).toEqual(generatedFiles) }) test('works with the -t alias', () => { mkdirSync(genPath, { recursive: true }) const stdout = run([projectName, '-t', 'vite-react'], { cwd: __dirname, encoding: 'utf8', }) const generatedFiles = readdirSync(genPath).sort() expect(stdout).toContain(`Scaffolding project in ${genPath}`) expect(templateFiles).toEqual(generatedFiles) }) test('uses different package manager', () => { mkdirSync(genPath, { recursive: true }) const stdout = run([projectName, '--bun', '-t', 'vite-react'], { cwd: __dirname, encoding: 'utf8', }) expect(stdout).toContain('bun install') }) test('shows help', () => { const stdout = run(['--help']) expect( stdout .replace(version, 'x.y.z') .replace(pc.green(''), ''), ).toMatchInlineSnapshot(` "create-wagmi/x.y.z Usage: $ create-wagmi [options] Options: -t, --template [name] Template to bootstrap with. Available: vite-react, next, vite-vue, nuxt, vite-vanilla --bun Use bun as your package manager --npm Use npm as your package manager --pnpm Use pnpm as your package manager --yarn Use yarn as your package manager -h, --help Display this message -v, --version Display version number " `) }) test('shows version', () => { const stdout = run(['--version']) expect(stdout).toContain(`create-wagmi/${version} `) }) ================================================ FILE: packages/create-wagmi/src/cli.ts ================================================ #!/usr/bin/env node import * as fs from 'node:fs' import * as path from 'node:path' import { fileURLToPath } from 'node:url' import { cac } from 'cac' import spawn from 'cross-spawn' import pc from 'picocolors' import prompts from 'prompts' import { type Framework, frameworks } from './frameworks.js' import { copy, emptyDir, formatTargetDir, isEmpty, isValidPackageName, pkgFromUserAgent, toValidPackageName, } from './utils.js' import { version } from './version.js' const templates = frameworks .map((f) => f.variants?.map((v) => v.name) || [f.name]) .reduce((a, b) => a.concat(b), []) const cli = cac('create-wagmi') cli .usage(`${pc.green('')} [options]`) .option( '-t, --template [name]', `Template to bootstrap with. Available: ${templates .sort((a, b) => (a && !b ? -1 : 1)) .join(', ')}`, ) .option('--bun', 'Use bun as your package manager') .option('--npm', 'Use npm as your package manager') .option('--pnpm', 'Use pnpm as your package manager') .option('--yarn', 'Use yarn as your package manager') cli.help() cli.version(version) const cwd = process.cwd() const renameFiles: Record = { '_env.local': '.env.local', // https://github.com/npm/npm/issues/1862 _gitignore: '.gitignore', _npmrc: '.npmrc', } const defaultTargetDir = 'wagmi-project' async function init() { const { args, options } = cli.parse(process.argv) if (options.help) return if (options.version) return const argTargetDir = formatTargetDir(args[0]) const argTemplate = options.template || options.t let targetDir = argTargetDir || defaultTargetDir function getProjectName() { return targetDir === '.' ? path.basename(path.resolve()) : targetDir } let result: prompts.Answers< 'framework' | 'overwrite' | 'packageName' | 'projectName' | 'variant' > try { result = await prompts( [ { type: argTargetDir ? null : 'text', name: 'projectName', message: pc.reset('Project name:'), initial: defaultTargetDir, onState(state) { targetDir = formatTargetDir(state.value) || defaultTargetDir }, }, { type() { return !fs.existsSync(targetDir) || isEmpty(targetDir) ? null : 'confirm' }, name: 'overwrite', message() { return `${ targetDir === '.' ? 'Current directory' : `Target directory "${targetDir}"` } is not empty. Remove existing files and continue?` }, }, { type(_, { overwrite }: { overwrite?: boolean }) { if (overwrite === false) throw new Error(`${pc.red('×')} Operation cancelled`) return null }, name: 'overwriteChecker', }, { type() { return isValidPackageName(getProjectName()) ? null : 'text' }, name: 'packageName', message: pc.reset('Package name:'), initial() { return toValidPackageName(getProjectName()) }, validate(dir) { return isValidPackageName(dir) || 'Invalid package.json name' }, }, { type: argTemplate && templates.includes(argTemplate) ? null : 'select', name: 'framework', message: typeof argTemplate === 'string' && !templates.includes(argTemplate) ? pc.reset( `"${argTemplate}" isn't a valid template. Please choose from below: `, ) : pc.reset('Select a framework:'), initial: 0, choices: frameworks.map((framework) => { const frameworkColor = framework.color return { title: frameworkColor(framework.display || framework.name), value: framework, } }), }, { type(framework: Framework) { return framework?.variants?.length > 1 ? 'select' : null }, name: 'variant', message: pc.reset('Select a variant:'), choices(framework: Framework) { return framework.variants.map((variant) => { const variantColor = variant.color return { title: variantColor(variant.display || variant.name), value: variant.name, } }) }, }, ], { onCancel() { throw new Error(`${pc.red('×')} Operation cancelled`) }, }, ) } catch (error) { console.log((error as Error).message) return } // user choice associated with prompts const { framework, overwrite, packageName, variant = framework?.variants[0]?.name, } = result const root = path.join(cwd, targetDir) if (overwrite) emptyDir(root) else if (!fs.existsSync(root)) fs.mkdirSync(root, { recursive: true }) // determine template const template: string = variant || framework?.name || argTemplate const pkgInfo = pkgFromUserAgent(process.env.npm_config_user_agent) type PkgManager = 'bun' | 'npm' | 'pnpm' | 'yarn' let pkgManager: PkgManager if (options.bun) pkgManager = 'bun' else if (options.npm) pkgManager = 'npm' else if (options.pnpm) pkgManager = 'pnpm' else if (options.yarn) pkgManager = 'yarn' else pkgManager = pkgInfo ? (pkgInfo.name as PkgManager) : 'npm' const isYarn1 = pkgManager === 'yarn' && pkgInfo?.version?.startsWith('1.') const { customCommand } = frameworks.flatMap((f) => f.variants).find((v) => v.name === template) ?? {} if (customCommand) { const fullCustomCommand = customCommand .replace(/^npm create /, () => { // `bun create` uses it's own set of templates, // the closest alternative is using `bun x` directly on the package if (pkgManager === 'bun') return 'bun x create-' return `${pkgManager} create ` }) // Only Yarn 1.x doesn't support `@version` in the `create` command .replace('@latest', () => (isYarn1 ? '' : '@latest')) .replace(/^npm exec/, () => { // Prefer `pnpm dlx`, `yarn dlx`, or `bun x` if (pkgManager === 'pnpm') return 'pnpm dlx' if (pkgManager === 'yarn' && !isYarn1) return 'yarn dlx' if (pkgManager === 'bun') return 'bun x' // Use `npm exec` in all other cases, // including Yarn 1.x and other custom npm clients. return 'npm exec' }) const [command, ...args] = fullCustomCommand.split(' ') // we replace TARGET_DIR here because targetDir may include a space const replacedArgs = args.map((arg) => arg.replace('TARGET_DIR', targetDir)) const { status } = spawn.sync(command!, replacedArgs, { stdio: 'inherit', }) process.exit(status ?? 0) } console.log(`\nScaffolding project in ${root}...`) const templateDir = path.resolve( fileURLToPath(import.meta.url), '../../../templates', template, ) function write(file: string, content?: string) { const targetPath = path.join(root, renameFiles[file] ?? file) if (content) fs.writeFileSync(targetPath, content) else copy(path.join(templateDir, file), targetPath) } const files = fs.readdirSync(templateDir) for (const file of files.filter((f) => f !== 'package.json')) { write(file) } const pkg = JSON.parse( fs.readFileSync(path.join(templateDir, 'package.json'), 'utf-8'), ) pkg.name = packageName || getProjectName() write('package.json', `${JSON.stringify(pkg, null, 2)}\n`) const cdProjectName = path.relative(cwd, root) console.log('\nDone. Now run:\n') if (root !== cwd) console.log( ` cd ${ cdProjectName.includes(' ') ? `"${cdProjectName}"` : cdProjectName }`, ) switch (pkgManager) { case 'yarn': console.log(' yarn') console.log(' yarn dev') break default: console.log(` ${pkgManager} install`) console.log(` ${pkgManager} run dev`) break } console.log() } init().catch((e) => { // biome-ignore lint/suspicious/noConsole: logging error console.error(e) }) ================================================ FILE: packages/create-wagmi/src/frameworks.ts ================================================ import pc from 'picocolors' type ColorFunc = (str: string | number) => string type FrameworkVariant = { name: string display: string color: ColorFunc customCommand?: string } export type Framework = { name: string display: string color: ColorFunc variants: readonly FrameworkVariant[] } export const frameworks: readonly Framework[] = [ { name: 'react', display: 'React', color: pc.cyan, variants: [ { name: 'vite-react', display: 'Vite', color: pc.blue, }, { name: 'next', display: 'Next', color: pc.yellow, }, ], }, { name: 'vue', display: 'Vue', color: pc.green, variants: [ { name: 'vite-vue', display: 'Vite', color: pc.blue, }, { name: 'nuxt', display: 'Nuxt', color: pc.yellow, }, ], }, { name: 'vanilla', display: 'Vanilla', color: pc.magenta, variants: [ { name: 'vite-vanilla', display: 'Vite', color: pc.blue, }, ], }, ] ================================================ FILE: packages/create-wagmi/src/index.test-d.ts ================================================ import { expectTypeOf } from 'vitest' // noop test because vitest typecheck fails unless each workspace project has type test expectTypeOf(1).toEqualTypeOf() ================================================ FILE: packages/create-wagmi/src/utils.ts ================================================ import * as fs from 'node:fs' import * as path from 'node:path' export function formatTargetDir(targetDir: string | undefined) { return targetDir?.trim().replace(/\/+$/g, '') } export function copy(src: string, dest: string) { const stat = fs.statSync(src) if (stat.isDirectory()) copyDir(src, dest) else fs.copyFileSync(src, dest) } function copyDir(srcDir: string, destDir: string) { fs.mkdirSync(destDir, { recursive: true }) for (const file of fs.readdirSync(srcDir)) { const srcFile = path.resolve(srcDir, file) const destFile = path.resolve(destDir, file) copy(srcFile, destFile) } } export function isValidPackageName(projectName: string) { return /^(?:@[a-z\d\-*~][a-z\d\-*._~]*\/)?[a-z\d\-~][a-z\d\-._~]*$/.test( projectName, ) } export function toValidPackageName(projectName: string) { return projectName .trim() .toLowerCase() .replace(/\s+/g, '-') .replace(/^[._]/, '') .replace(/[^a-z\d\-~]+/g, '-') } export function isEmpty(path: string) { const files = fs.readdirSync(path) return files.length === 0 || (files.length === 1 && files[0] === '.git') } export function emptyDir(dir: string) { if (!fs.existsSync(dir)) return for (const file of fs.readdirSync(dir)) { if (file === '.git') continue fs.rmSync(path.resolve(dir, file), { recursive: true, force: true }) } } export function pkgFromUserAgent(userAgent: string | undefined) { if (!userAgent) return undefined const pkgSpec = userAgent.split(' ')[0]! const pkgSpecArr = pkgSpec.split('/') return { name: pkgSpecArr[0], version: pkgSpecArr[1], } } // function setupReactSwc(root: string, isTs: boolean) { // editFile(path.resolve(root, 'package.json'), (content) => { // return content.replace( // /"@vitejs\/plugin-react": ".+?"/, // `"@vitejs/plugin-react-swc": "^3.3.2"`, // ) // }) // editFile( // path.resolve(root, `vite.config.${isTs ? 'ts' : 'js'}`), // (content) => { // return content.replace('@vitejs/plugin-react', '@vitejs/plugin-react-swc') // }, // ) // } // function editFile(file: string, callback: (content: string) => string) { // const content = fs.readFileSync(file, 'utf-8') // fs.writeFileSync(file, callback(content), 'utf-8') // } ================================================ FILE: packages/create-wagmi/src/version.ts ================================================ export const version = '2.0.19' ================================================ FILE: packages/create-wagmi/templates/next/README.md ================================================ This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-wagmi`](https://github.com/wevm/wagmi/tree/main/packages/create-wagmi). ================================================ FILE: packages/create-wagmi/templates/next/_env.local ================================================ NEXT_TELEMETRY_DISABLED=1 ================================================ FILE: packages/create-wagmi/templates/next/_gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # next.js /.next/ /out/ # production /build # misc .DS_Store *.pem # debug npm-debug.log* yarn-debug.log* yarn-error.log* # local env files .env*.local # vercel .vercel # typescript *.tsbuildinfo next-env.d.ts ================================================ FILE: packages/create-wagmi/templates/next/_npmrc ================================================ legacy-peer-deps = true ================================================ FILE: packages/create-wagmi/templates/next/next-env.d.ts ================================================ /// /// // NOTE: This file should not be edited // see https://nextjs.org/docs/basic-features/typescript for more information. ================================================ FILE: packages/create-wagmi/templates/next/next.config.ts ================================================ import type { NextConfig } from 'next' const nextConfig: NextConfig = {} export default nextConfig ================================================ FILE: packages/create-wagmi/templates/next/package.json ================================================ { "name": "wagmi-next-starter", "private": true, "type": "module", "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "@tanstack/react-query": "latest", "next": "latest", "react": "latest", "react-dom": "latest", "viem": "latest", "wagmi": "latest" }, "devDependencies": { "@types/node": "^24.10.1", "@types/react": "latest", "@types/react-dom": "latest", "@wagmi/cli": "latest", "typescript": "latest" } } ================================================ FILE: packages/create-wagmi/templates/next/src/app/globals.css ================================================ :root { background-color: #181818; color: rgba(255, 255, 255, 0.87); color-scheme: light dark; font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; font-synthesis: none; font-weight: 400; line-height: 1.5; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-text-size-adjust: 100%; } @media (prefers-color-scheme: light) { :root { background-color: #f8f8f8; color: #181818; } } ================================================ FILE: packages/create-wagmi/templates/next/src/app/layout.tsx ================================================ import './globals.css' import type { Metadata } from 'next' import { Inter } from 'next/font/google' import { headers } from 'next/headers' import { type ReactNode } from 'react' import { cookieToInitialState } from 'wagmi' import { getConfig } from '../wagmi' import { Providers } from './providers' const inter = Inter({ subsets: ['latin'] }) export const metadata: Metadata = { title: 'Create Wagmi', description: 'Generated by create-wagmi', } export default async function RootLayout(props: { children: ReactNode }) { const initialState = cookieToInitialState( getConfig(), (await headers()).get('cookie'), ) return ( {props.children} ) } ================================================ FILE: packages/create-wagmi/templates/next/src/app/page.tsx ================================================ 'use client' import { useConnect, useConnection, useConnectors, useDisconnect } from 'wagmi' function App() { const connection = useConnection() const { connect, status, error } = useConnect() const connectors = useConnectors() const { disconnect } = useDisconnect() return ( <>

Connection

status: {connection.status}
addresses: {JSON.stringify(connection.addresses)}
chainId: {connection.chainId}
{connection.status === 'connected' && ( )}

Connect

{connectors.map((connector) => ( ))}
{status}
{error?.message}
) } export default App ================================================ FILE: packages/create-wagmi/templates/next/src/app/providers.tsx ================================================ 'use client' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { type ReactNode, useState } from 'react' import { type State, WagmiProvider } from 'wagmi' import { getConfig } from '@/wagmi' export function Providers(props: { children: ReactNode initialState?: State }) { const [config] = useState(() => getConfig()) const [queryClient] = useState(() => new QueryClient()) return ( {props.children} ) } ================================================ FILE: packages/create-wagmi/templates/next/src/wagmi.ts ================================================ import { cookieStorage, createConfig, createStorage, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export function getConfig() { return createConfig({ chains: [mainnet, sepolia], storage: createStorage({ storage: cookieStorage, }), ssr: true, transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) } declare module 'wagmi' { interface Register { config: ReturnType } } ================================================ FILE: packages/create-wagmi/templates/next/tsconfig.json ================================================ { "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "react-jsx", "incremental": true, "plugins": [ { "name": "next" } ], "paths": { "@/*": ["./src/*"] } }, "include": [ "next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/dev/types/**/*.ts", ".next/types/**/*.ts" ], "exclude": ["node_modules"] } ================================================ FILE: packages/create-wagmi/templates/nuxt/_env.local ================================================ NUXT_TELEMETRY_DISABLED=1 ================================================ FILE: packages/create-wagmi/templates/nuxt/_gitignore ================================================ # Nuxt dev/build outputs .output .data .nuxt .nitro .cache dist # Node dependencies node_modules # Logs logs *.log # Misc .DS_Store .fleet .idea # Local env files .env .env.* !.env.example ================================================ FILE: packages/create-wagmi/templates/nuxt/_npmrc ================================================ legacy-peer-deps = true ================================================ FILE: packages/create-wagmi/templates/nuxt/app.vue ================================================ ================================================ FILE: packages/create-wagmi/templates/nuxt/components/Connect.vue ================================================ ================================================ FILE: packages/create-wagmi/templates/nuxt/components/Connection.vue ================================================ ================================================ FILE: packages/create-wagmi/templates/nuxt/nuxt.config.ts ================================================ import { defineNuxtConfig } from 'nuxt/config' // https://nuxt.com/docs/api/configuration/nuxt-config export default defineNuxtConfig({ devtools: { enabled: true }, modules: ['@wagmi/vue/nuxt'], }) ================================================ FILE: packages/create-wagmi/templates/nuxt/package.json ================================================ { "name": "nuxt-app", "private": true, "type": "module", "scripts": { "build": "nuxt typecheck && nuxt build", "dev": "nuxt dev", "generate": "nuxt generate", "preview": "nuxt preview", "postinstall": "nuxt prepare" }, "dependencies": { "@tanstack/vue-query": "latest", "@wagmi/vue": "latest", "nuxt": "latest", "viem": "latest", "vue": "latest", "vue-router": "latest" }, "devDependencies": { "typescript": "latest", "vue-tsc": "latest" } } ================================================ FILE: packages/create-wagmi/templates/nuxt/plugins/wagmi.ts ================================================ import { VueQueryPlugin } from '@tanstack/vue-query' import { WagmiPlugin } from '@wagmi/vue' import { defineNuxtPlugin } from 'nuxt/app' import { config } from '../wagmi' // TODO: Move to @wagmi/vue/nuxt nitro plugin export default defineNuxtPlugin((nuxtApp) => { nuxtApp.vueApp.use(WagmiPlugin, { config }).use(VueQueryPlugin, {}) }) ================================================ FILE: packages/create-wagmi/templates/nuxt/server/tsconfig.json ================================================ { "extends": "../.nuxt/tsconfig.server.json" } ================================================ FILE: packages/create-wagmi/templates/nuxt/tsconfig.json ================================================ { // https://nuxt.com/docs/guide/concepts/typescript "extends": "./.nuxt/tsconfig.json" } ================================================ FILE: packages/create-wagmi/templates/nuxt/wagmi.ts ================================================ import { cookieStorage, createConfig, createStorage, http } from '@wagmi/vue' import { mainnet, optimism, sepolia } from '@wagmi/vue/chains' export const config = createConfig({ chains: [mainnet, sepolia, optimism], storage: createStorage({ storage: cookieStorage, }), ssr: true, transports: { [mainnet.id]: http(), [sepolia.id]: http(), [optimism.id]: http(), }, }) declare module '@wagmi/vue' { interface Register { config: typeof config } } ================================================ FILE: packages/create-wagmi/templates/vite-react/README.md ================================================ This is a [Vite](https://vitejs.dev) project bootstrapped with [`create-wagmi`](https://github.com/wevm/wagmi/tree/main/packages/create-wagmi). ================================================ FILE: packages/create-wagmi/templates/vite-react/_gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: packages/create-wagmi/templates/vite-react/_npmrc ================================================ legacy-peer-deps = true ================================================ FILE: packages/create-wagmi/templates/vite-react/index.html ================================================ Create Wagmi
================================================ FILE: packages/create-wagmi/templates/vite-react/package.json ================================================ { "name": "wagmi-vite-starter", "private": true, "type": "module", "scripts": { "dev": "vite", "build": "tsc && vite build", "preview": "vite preview" }, "dependencies": { "@tanstack/react-query": "latest", "react": "latest", "react-dom": "latest", "viem": "latest", "wagmi": "latest" }, "devDependencies": { "@types/react": "latest", "@types/react-dom": "latest", "@vitejs/plugin-react": "latest", "@wagmi/cli": "latest", "typescript": "latest", "vite": "latest" } } ================================================ FILE: packages/create-wagmi/templates/vite-react/src/App.tsx ================================================ import { useConnect, useConnection, useConnectors, useDisconnect } from 'wagmi' function App() { const connection = useConnection() const { connect, status, error } = useConnect() const connectors = useConnectors() const { disconnect } = useDisconnect() return ( <>

Connection

status: {connection.status}
addresses: {JSON.stringify(connection.addresses)}
chainId: {connection.chainId}
{connection.status === 'connected' && ( )}

Connect

{connectors.map((connector) => ( ))}
{status}
{error?.message}
) } export default App ================================================ FILE: packages/create-wagmi/templates/vite-react/src/index.css ================================================ :root { background-color: #181818; color: rgba(255, 255, 255, 0.87); color-scheme: light dark; font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; font-synthesis: none; font-weight: 400; line-height: 1.5; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-text-size-adjust: 100%; } @media (prefers-color-scheme: light) { :root { background-color: #f8f8f8; color: #181818; } } ================================================ FILE: packages/create-wagmi/templates/vite-react/src/main.tsx ================================================ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import React from 'react' import ReactDOM from 'react-dom/client' import { WagmiProvider } from 'wagmi' import App from './App.tsx' import { config } from './wagmi.ts' import './index.css' const queryClient = new QueryClient() ReactDOM.createRoot(document.getElementById('root')!).render( , ) ================================================ FILE: packages/create-wagmi/templates/vite-react/src/vite-env.d.ts ================================================ /// ================================================ FILE: packages/create-wagmi/templates/vite-react/src/wagmi.ts ================================================ import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) declare module 'wagmi' { interface Register { config: typeof config } } ================================================ FILE: packages/create-wagmi/templates/vite-react/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], "module": "ESNext", "skipLibCheck": true, /* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", /* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] } ================================================ FILE: packages/create-wagmi/templates/vite-react/tsconfig.node.json ================================================ { "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true }, "include": ["vite.config.ts"] } ================================================ FILE: packages/create-wagmi/templates/vite-react/vite.config.ts ================================================ import react from '@vitejs/plugin-react' import { defineConfig } from 'vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], }) ================================================ FILE: packages/create-wagmi/templates/vite-vanilla/_gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: packages/create-wagmi/templates/vite-vanilla/_npmrc ================================================ legacy-peer-deps = true ================================================ FILE: packages/create-wagmi/templates/vite-vanilla/index.html ================================================ Create Wagmi
================================================ FILE: packages/create-wagmi/templates/vite-vanilla/package.json ================================================ { "name": "wagmi-core-vanilla-starter", "private": true, "type": "module", "scripts": { "dev": "vite", "build": "tsc && vite build", "preview": "vite preview" }, "dependencies": { "@wagmi/connectors": "latest", "@wagmi/core": "latest", "react": "latest", "react-dom": "latest", "viem": "latest" }, "devDependencies": { "@wagmi/cli": "latest", "typescript": "latest", "vite": "latest" } } ================================================ FILE: packages/create-wagmi/templates/vite-vanilla/src/main.ts ================================================ import { connect, disconnect, reconnect, watchConnection } from '@wagmi/core' import { Buffer } from 'buffer' import './style.css' import { config } from './wagmi' globalThis.Buffer = Buffer document.querySelector('#app')!.innerHTML = `

Connection

status:
addresses:
chainId:

Connect

${config.connectors .map( (connector) => ``, ) .join('')}
` setupApp(document.querySelector('#app')!) function setupApp(element: HTMLDivElement) { const connectElement = element.querySelector('#connect') const buttons = element.querySelectorAll('.connect') for (const button of buttons) { const connector = config.connectors.find( (connector) => connector.uid === button.id, )! button.addEventListener('click', async () => { try { const errorElement = element.querySelector('#error') if (errorElement) errorElement.remove() await connect(config, { connector }) } catch (error) { const errorElement = document.createElement('div') errorElement.id = 'error' errorElement.innerText = (error as Error).message connectElement?.appendChild(errorElement) } }) } watchConnection(config, { onChange(connection) { const connectionElement = element.querySelector('#connection')! connectionElement.innerHTML = `

Connection

status: ${connection.status}
addresses: ${ connection.addresses ? JSON.stringify(connection.addresses) : '' }
chainId: ${connection.chainId ?? ''}
${ connection.status === 'connected' ? `` : '' } ` const disconnectButton = element.querySelector('#disconnect') if (disconnectButton) disconnectButton.addEventListener('click', () => disconnect(config)) }, }) reconnect(config) .then(() => {}) .catch(() => {}) } ================================================ FILE: packages/create-wagmi/templates/vite-vanilla/src/style.css ================================================ :root { background-color: #181818; color: rgba(255, 255, 255, 0.87); color-scheme: light dark; font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; font-synthesis: none; font-weight: 400; line-height: 1.5; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-text-size-adjust: 100%; } @media (prefers-color-scheme: light) { :root { background-color: #f8f8f8; color: #181818; } } ================================================ FILE: packages/create-wagmi/templates/vite-vanilla/src/vite-env.d.ts ================================================ /// ================================================ FILE: packages/create-wagmi/templates/vite-vanilla/src/wagmi.ts ================================================ import { createConfig, http } from '@wagmi/core' import { mainnet, sepolia } from '@wagmi/core/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ================================================ FILE: packages/create-wagmi/templates/vite-vanilla/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "module": "ESNext", "lib": ["ES2020", "DOM", "DOM.Iterable"], "skipLibCheck": true, /* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, /* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true }, "include": ["src"] } ================================================ FILE: packages/create-wagmi/templates/vite-vue/README.md ================================================ This is a [Vite](https://vitejs.dev) project bootstrapped with [`create-wagmi`](https://github.com/wevm/wagmi/tree/main/packages/create-wagmi). ================================================ FILE: packages/create-wagmi/templates/vite-vue/_gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: packages/create-wagmi/templates/vite-vue/_npmrc ================================================ legacy-peer-deps = true ================================================ FILE: packages/create-wagmi/templates/vite-vue/index.html ================================================ Create Wagmi
================================================ FILE: packages/create-wagmi/templates/vite-vue/package.json ================================================ { "name": "wagmi-vue-vite-starter", "private": true, "type": "module", "scripts": { "dev": "vite", "build": "vue-tsc && vite build", "preview": "vite preview" }, "dependencies": { "@tanstack/vue-query": "latest", "@wagmi/vue": "latest", "viem": "latest", "vue": "latest" }, "devDependencies": { "@vitejs/plugin-vue": "latest", "vite": "latest", "vue-tsc": "latest" } } ================================================ FILE: packages/create-wagmi/templates/vite-vue/src/App.vue ================================================ ================================================ FILE: packages/create-wagmi/templates/vite-vue/src/components/Connect.vue ================================================ ================================================ FILE: packages/create-wagmi/templates/vite-vue/src/components/Connection.vue ================================================ ================================================ FILE: packages/create-wagmi/templates/vite-vue/src/main.ts ================================================ import { VueQueryPlugin } from '@tanstack/vue-query' import { WagmiPlugin } from '@wagmi/vue' import { Buffer } from 'buffer' import { createApp } from 'vue' // `@coinbase-wallet/sdk` uses `Buffer` globalThis.Buffer = Buffer import App from './App.vue' import './style.css' import { config } from './wagmi' const app = createApp(App) app.use(WagmiPlugin, { config }).use(VueQueryPlugin, {}) app.mount('#app') ================================================ FILE: packages/create-wagmi/templates/vite-vue/src/style.css ================================================ :root { background-color: #181818; color: rgba(255, 255, 255, 0.87); color-scheme: light dark; font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; font-synthesis: none; font-weight: 400; line-height: 1.5; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-text-size-adjust: 100%; } @media (prefers-color-scheme: light) { :root { background-color: #f8f8f8; color: #181818; } } ================================================ FILE: packages/create-wagmi/templates/vite-vue/src/vite-env.d.ts ================================================ /// ================================================ FILE: packages/create-wagmi/templates/vite-vue/src/wagmi.ts ================================================ import { createConfig, createStorage, http } from '@wagmi/vue' import { mainnet, optimism, sepolia } from '@wagmi/vue/chains' export const config = createConfig({ chains: [mainnet, sepolia, optimism], storage: createStorage({ storage: localStorage, key: 'vite-vue' }), transports: { [mainnet.id]: http(), [sepolia.id]: http(), [optimism.id]: http(), }, }) declare module '@wagmi/vue' { interface Register { config: typeof config } } ================================================ FILE: packages/create-wagmi/templates/vite-vue/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "module": "ESNext", "lib": ["ES2020", "DOM", "DOM.Iterable"], "skipLibCheck": true, /* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "preserve", /* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true }, "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"], "references": [{ "path": "./tsconfig.node.json" }] } ================================================ FILE: packages/create-wagmi/templates/vite-vue/tsconfig.node.json ================================================ { "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true, "strict": true }, "include": ["vite.config.ts"] } ================================================ FILE: packages/create-wagmi/templates/vite-vue/vite.config.ts ================================================ import vue from '@vitejs/plugin-vue' import { defineConfig } from 'vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [vue()], }) ================================================ FILE: packages/create-wagmi/tsconfig.build.json ================================================ { "extends": "../../tsconfig.base.json", "include": ["src/**/*.ts"], "exclude": ["src/**/*.test.ts"], "compilerOptions": { "sourceMap": true } } ================================================ FILE: packages/create-wagmi/tsconfig.json ================================================ { "extends": "./tsconfig.build.json", "include": ["src/**/*.ts"], "exclude": [] } ================================================ FILE: packages/react/CHANGELOG.md ================================================ # wagmi ## 3.5.0 ### Minor Changes - Added `useSignTransaction` ([#4995](https://github.com/wevm/wagmi/pull/4995)) ### Patch Changes - Updated dependencies [[`8b96e2f`](https://github.com/wevm/wagmi/commit/8b96e2f46d9b3441d3b499b03924700ac0629be6)]: - @wagmi/core@3.4.0 - @wagmi/connectors@7.2.1 ## 3.4.4 ### Patch Changes - Updated dependencies [[`c1dedd9`](https://github.com/wevm/wagmi/commit/c1dedd99c0a1878d7cd48476946868636ac81dd8), [`9dbdd82`](https://github.com/wevm/wagmi/commit/9dbdd8277808eb361fe7fe01ea34e4c6bb85c7a5)]: - @wagmi/core@3.3.4 - @wagmi/connectors@7.2.0 ## 3.4.3 ### Patch Changes - Added ability to sign arbitrary `hash` on `webAuthn#connect`. ([#4994](https://github.com/wevm/wagmi/pull/4994)) - Updated dependencies [[`4b3f5a3`](https://github.com/wevm/wagmi/commit/4b3f5a3f7b3f242e8fbc1f08ae2f81ae13c5e09f)]: - @wagmi/core@3.3.3 - @wagmi/connectors@7.1.7 ## 3.4.2 ### Patch Changes - Updated dependencies [[`68e17db`](https://github.com/wevm/wagmi/commit/68e17db7ff84982db8f52f54e6f047c5efab62ab)]: - @wagmi/core@3.3.2 - @wagmi/connectors@7.1.6 ## 3.4.1 ### Patch Changes - Updated dependencies [[`7f756bd`](https://github.com/wevm/wagmi/commit/7f756bda12cd332016f0bb3a2f20307c37499309)]: - @wagmi/core@3.3.1 - @wagmi/connectors@7.1.5 ## 3.4.0 ### Minor Changes - Added `useContractEvents` hook. ([#4905](https://github.com/wevm/wagmi/pull/4905)) - Added `useBlobBaseFee` and `useWriteContractSync` hooks. ([`dfe7904`](https://github.com/wevm/wagmi/commit/dfe790426d5ac24d55eacdf8d0193292de801911)) ### Patch Changes - Fixed `createUseWriteContract` not returning `mutate`/`mutateAsyc` with `abi` injected. ([#4967](https://github.com/wevm/wagmi/pull/4967)) - Fixed re-subscribe every render for `useWatchBlockNumber`, `useWatchBlocks`, `useWatchContractEvent`, `useWatchPendingTransactions`. ([`b5d6911`](https://github.com/wevm/wagmi/commit/b5d6911a863e35d677374acd744c054daacd663a)) - Updated dependencies [[`dfe7904`](https://github.com/wevm/wagmi/commit/dfe790426d5ac24d55eacdf8d0193292de801911), [`d503a2c`](https://github.com/wevm/wagmi/commit/d503a2cb6ef96018669a66d03f72a2b2b06dc0fb), [`5399840`](https://github.com/wevm/wagmi/commit/53998407645edd95d85e50a931acaed87c05e256), [`5978cc5`](https://github.com/wevm/wagmi/commit/5978cc508ac837be88ed84c15ea5aa805f59005a), [`67612ed`](https://github.com/wevm/wagmi/commit/67612edfbcb971b71c86964aae72ff3ef80bbe10), [`dbe9484`](https://github.com/wevm/wagmi/commit/dbe9484c1a635c3fc9b658a7d8e34ccc0a82ed1d)]: - @wagmi/core@3.3.0 - @wagmi/connectors@7.1.4 ## 3.3.4 ### Patch Changes - Fixed issue where `wagmi/tempo` hooks were not propagating `UseQueryOptions`. ([#4955](https://github.com/wevm/wagmi/pull/4955)) ## 3.3.3 ### Patch Changes - Updated dependencies [[`979fe26`](https://github.com/wevm/wagmi/commit/979fe265e5273a8b49a4469ffab88b1a18b1aeaa), [`979fe26`](https://github.com/wevm/wagmi/commit/979fe265e5273a8b49a4469ffab88b1a18b1aeaa), [`e4541de`](https://github.com/wevm/wagmi/commit/e4541def76a1744dc36c188453265cc6e9d83722)]: - @wagmi/core@3.2.3 - @wagmi/connectors@7.1.3 ## 3.3.2 ### Patch Changes - Updated query internals. ([`4fefa57`](https://github.com/wevm/wagmi/commit/4fefa576014820b454344b579282ddecde5c7994)) - Updated dependencies [[`4fefa57`](https://github.com/wevm/wagmi/commit/4fefa576014820b454344b579282ddecde5c7994)]: - @wagmi/core@3.2.2 - @wagmi/connectors@7.1.2 ## 3.3.1 ### Patch Changes - Updated dependencies [[`a373b50`](https://github.com/wevm/wagmi/commit/a373b504f2ba199ca63ec0da6138ad1aa12a3a8f)]: - @wagmi/core@3.2.1 - @wagmi/connectors@7.1.1 ## 3.3.0 ### Minor Changes - Updated to `viem@2.44.0` with Tempo Moderato support. ([#4940](https://github.com/wevm/wagmi/pull/4940)) **Breaking Changes (Tempo)** - Renamed `reward.useStart` → `reward.useDistribute` - Renamed `reward.useStartSync` → `reward.useDistributeSync` - Renamed `reward.useGetTotalPerSecond` → `reward.useGetGlobalRewardPerToken` - Renamed `reward.useWatchRewardScheduled` → `reward.useWatchRewardDistributed` - Removed `nonce.useNonceKeyCount` - Removed `nonce.useWatchActiveKeyCountChanged` - Removed `amm.useWatchFeeSwap` **New Features (Tempo)** - Added `dex.useCancelStale` hook - Added `dex.useCancelStaleSync` hook ### Patch Changes - Updated dependencies [[`2ee3f55`](https://github.com/wevm/wagmi/commit/2ee3f559a2637c7aab3fca6c7d196cf238ecd63d)]: - @wagmi/core@3.2.0 - @wagmi/connectors@7.1.3 ## 3.2.0 ### Minor Changes - Added first-class support and extension for [Tempo](https://docs.tempo.xyz) via `/tempo` entrypoint. ([#4922](https://github.com/wevm/wagmi/pull/4922)) ### Patch Changes - Updated dependencies [[`14989e4`](https://github.com/wevm/wagmi/commit/14989e425a36b765a6a24e5abf1782c2a26c70db)]: - @wagmi/core@3.1.0 - @wagmi/connectors@7.1.2 ## 3.1.4 ### Patch Changes - Updated dependencies [[`a5c4381`](https://github.com/wevm/wagmi/commit/a5c4381563374018dca0074017b21181ac027e9a)]: - @wagmi/core@3.0.2 - @wagmi/connectors@7.0.6 ## 3.1.3 ### Patch Changes - Fixed published exports. ([`ed86500`](https://github.com/wevm/wagmi/commit/ed86500fbd56e5f543cb04e990b2dadc08d8b3b5)) - Updated dependencies [[`ed86500`](https://github.com/wevm/wagmi/commit/ed86500fbd56e5f543cb04e990b2dadc08d8b3b5)]: - @wagmi/connectors@7.0.5 ## 3.1.2 ### Patch Changes - Updated dependencies [[`9bbf13e`](https://github.com/wevm/wagmi/commit/9bbf13eac895669e70b233de767c8731d221f16e)]: - @wagmi/connectors@7.0.4 ## 3.1.1 ### Patch Changes - Fixed `useReadContract` return type inference for ABI function overloads. ([`058c8c1`](https://github.com/wevm/wagmi/commit/058c8c18459a69a4aa2141e34640273a06a819f4)) - Updated dependencies [[`058c8c1`](https://github.com/wevm/wagmi/commit/058c8c18459a69a4aa2141e34640273a06a819f4)]: - @wagmi/core@3.0.1 - @wagmi/connectors@7.0.3 ## 3.1.0 ### Minor Changes - Deprecated custom mutate function names and renamed to `mutate`/`mutateAsync` to reduce destructure key renaming fatigue and align with TanStack Query terminology. ([#4878](https://github.com/wevm/wagmi/pull/4878)) **Before** Had to destructure hook result and often rename keys when using multiple of the same hook. Could decide not to destructure, but syntax becomes awkward for mutate functions (e.g. `connect.connect` or `connect.connectAsync`). ```ts const { connect, isPending: connectIsPending } = useConnect(); const { writeContract: transfer, error: transferError, isPending: transferIsPending, } = useWriteContract(); const { writeContract: approve, error: approveError } = useWriteContract(); ``` **After** Allows you to name the hook result whatever you want and not worry about also renaming properties. ```ts const connect = useConnect(); // connect.isPending const transfer = useWriteContract(); // transfer.mutate, transfer.error, transfer.isPending const approve = useWriteContract(); // approve.mutate, approve.error ``` ## 3.0.2 ### Patch Changes - Updated dependencies [[`0a46561`](https://github.com/wevm/wagmi/commit/0a4656137e1f9ed101dd1f79545d516aba32a92e)]: - @wagmi/connectors@7.0.2 ## 3.0.1 ### Patch Changes - Updated dependencies [[`856548a`](https://github.com/wevm/wagmi/commit/856548a5ae23c8771e3a51a919e1e978b83c4b00)]: - @wagmi/connectors@7.0.1 ## 3.0.0 ### Major Changes - All connector dependencies are now optional peer dependencies. This means that if you want to use a specific connector, you need to install its required dependencies. ([#4857](https://github.com/wevm/wagmi/pull/4857)) #### baseAccount [`baseAccount`](https://wagmi.sh/react/api/connectors/baseAccount) requires `@base-org/account` ``` pnpm add @base-org/account@~2.4.0 ``` #### coinbaseWallet [`coinbaseWallet`](https://wagmi.sh/react/api/connectors/coinbaseWallet) requires `@coinbase/wallet-sdk` ``` pnpm add @coinbase/wallet-sdk@~4.3.6 ``` #### gemini [`gemini`](https://wagmi.sh/react/api/connectors/gemini) requires `@gemini-wallet/core` ``` pnpm add @gemini-wallet/core@~0.3.1 ``` #### metaMask [`metaMask`](https://wagmi.sh/react/api/connectors/metaMask) requires `@metamask/sdk` ``` pnpm add @metamask/sdk@~0.33.1 ``` #### porto [`porto`](https://wagmi.sh/react/api/connectors/porto) requires `porto` ``` pnpm add porto@~0.2.35 ``` #### safe [`safe`](https://wagmi.sh/react/api/connectors/safe) requires `@safe-global/safe-apps-provider` and `@safe-global/safe-apps-sdk` ``` pnpm add @safe-global/safe-apps-provider@~0.18.6 @safe-global/safe-apps-sdk@~9.1.0 ``` #### walletConnect [`walletConnect`](https://wagmi.sh/react/api/connectors/walletConnect) requires `walletconnect/ethereum-provider` ``` pnpm add @walletconnect/ethereum-provider@~2.21.1 ``` ### Patch Changes - Updated dependencies [[`73e7326`](https://github.com/wevm/wagmi/commit/73e7326ac21303d7790765c78a7076b319b2ad26)]: - @wagmi/connectors@7.0.0 - @wagmi/core@3.0.0 ## 2.19.5 ### Patch Changes - Updated dependencies [[`5388de5`](https://github.com/wevm/wagmi/commit/5388de593847b23368c42646c27ee5438260062d)]: - @wagmi/connectors@6.2.0 ## 2.19.4 ### Patch Changes - Optimized internal `chainId` computation for `useReadContracts` to reduce unnecessary query invalidations. ([#4872](https://github.com/wevm/wagmi/pull/4872)) ## 2.19.3 ### Patch Changes - Updated dependencies [[`2ddb506`](https://github.com/wevm/wagmi/commit/2ddb506b67fcb2abb464765d2af88df2eb58de60)]: - @wagmi/connectors@6.1.4 ## 2.19.2 ### Patch Changes - Updated dependencies [[`65cf154`](https://github.com/wevm/wagmi/commit/65cf1544d65bfb1fb830c405a371e8cd3c3fb73e)]: - @wagmi/connectors@6.1.3 ## 2.19.1 ### Patch Changes - Updated dependencies [[`faf3eed`](https://github.com/wevm/wagmi/commit/faf3eeddb97c300f971083f8ee9b02a29ad23cbb)]: - @wagmi/connectors@6.1.2 ## 2.19.0 ### Minor Changes - Exported internal types ([`3e634b7`](https://github.com/wevm/wagmi/commit/3e634b7bcf0bd0e67e59fcb74ad89dfb56e4eae9)) ### Patch Changes - Updated dependencies [[`990dd23`](https://github.com/wevm/wagmi/commit/990dd2339e96b302931056e0fb898bd2dd42a04d)]: - @wagmi/connectors@6.1.1 ## 2.18.2 ### Patch Changes - Updated dependencies [[`ae31a8d`](https://github.com/wevm/wagmi/commit/ae31a8d3d0b436841d6546ab2565dee624204aca)]: - @wagmi/connectors@6.1.0 ## 2.18.1 ### Patch Changes - Updated dependencies [[`74100b0`](https://github.com/wevm/wagmi/commit/74100b0dea2dfe7b057fdbe1660596554c70642e)]: - @wagmi/core@2.22.1 - @wagmi/connectors@6.0.1 ## 2.18.0 ### Minor Changes - Added `useSendTransactionSync` and `useSendCallsSync` Hooks. ([#4823](https://github.com/wevm/wagmi/pull/4823)) ### Patch Changes - Updated dependencies [[`ebb2352`](https://github.com/wevm/wagmi/commit/ebb2352375e05e52d0bcf6ae1a60ac4e798bf29f)]: - @wagmi/core@2.22.0 - @wagmi/connectors@6.0.0 ## 2.17.5 ### Patch Changes - Updated dependencies [[`2f0db95`](https://github.com/wevm/wagmi/commit/2f0db9553d30dd95b3245c44dafec4fa1a758397), [`866aeb0`](https://github.com/wevm/wagmi/commit/866aeb0e6361ef9114246e50149c1077bc05bf10)]: - @wagmi/connectors@5.11.2 - @wagmi/core@2.21.2 ## 2.17.4 ### Patch Changes - Updated dependencies [[`41eb70e`](https://github.com/wevm/wagmi/commit/41eb70e072774b282053a5e98669a7d01c0e2438), [`9a00e42`](https://github.com/wevm/wagmi/commit/9a00e423d52df9478681df743f00429717ffc584)]: - @wagmi/connectors@5.11.1 ## 2.17.3 ### Patch Changes - Updated dependencies [[`f05c075`](https://github.com/wevm/wagmi/commit/f05c075365a737d870a657f2db9220eb93ad0ac1)]: - @wagmi/connectors@5.11.0 ## 2.17.2 ### Patch Changes - Updated dependencies [[`72b703a`](https://github.com/wevm/wagmi/commit/72b703ab379c74ecf88f637cf47f31786c823a48)]: - @wagmi/core@2.21.1 - @wagmi/connectors@5.10.2 ## 2.17.1 ### Patch Changes - Updated dependencies [[`5937456`](https://github.com/wevm/wagmi/commit/59374562f2c3a41245687eb1c29ee8023737c7cc)]: - @wagmi/connectors@5.10.1 ## 2.17.0 ### Minor Changes - [#4784](https://github.com/wevm/wagmi/pull/4784) [`8736133a13eb82099e20468b735525a266fdfd6c`](https://github.com/wevm/wagmi/commit/8736133a13eb82099e20468b735525a266fdfd6c) Thanks [@tmm](https://github.com/tmm)! - Added `withCapabilities` option to `connect` for exposing response capabilities. ### Patch Changes - Updated dependencies [[`8736133a13eb82099e20468b735525a266fdfd6c`](https://github.com/wevm/wagmi/commit/8736133a13eb82099e20468b735525a266fdfd6c)]: - @wagmi/connectors@5.10.0 - @wagmi/core@2.21.0 ## 2.16.9 ### Patch Changes - Updated dependencies [[`ce06e137e7bfaf000464b1cecd6c86e19a66ebcf`](https://github.com/wevm/wagmi/commit/ce06e137e7bfaf000464b1cecd6c86e19a66ebcf)]: - @wagmi/core@2.20.3 - @wagmi/connectors@5.9.9 ## 2.16.8 ### Patch Changes - Updated dependencies [[`a03da817a388646c9b4885792101a67eef3616e7`](https://github.com/wevm/wagmi/commit/a03da817a388646c9b4885792101a67eef3616e7)]: - @wagmi/connectors@5.9.8 ## 2.16.7 ### Patch Changes - Updated dependencies [[`986b96427a4bb743d2673dfbc7e8cb5041316db3`](https://github.com/wevm/wagmi/commit/986b96427a4bb743d2673dfbc7e8cb5041316db3)]: - @wagmi/core@2.20.2 - @wagmi/connectors@5.9.7 ## 2.16.6 ### Patch Changes - [#4773](https://github.com/wevm/wagmi/pull/4773) [`d4c367ca46c508598c997cf229a31593a1e2b8b8`](https://github.com/wevm/wagmi/commit/d4c367ca46c508598c997cf229a31593a1e2b8b8) Thanks [@tmm](https://github.com/tmm)! - Fixed issue with codegen actions/hooks, where `syncConnectedChain: false` did not work as intended. - Updated dependencies [[`d4c367ca46c508598c997cf229a31593a1e2b8b8`](https://github.com/wevm/wagmi/commit/d4c367ca46c508598c997cf229a31593a1e2b8b8)]: - @wagmi/core@2.20.1 - @wagmi/connectors@5.9.6 ## 2.16.5 ### Patch Changes - Updated dependencies [[`a13aa2b68890f180f6ac3f741cbb9817494cb66c`](https://github.com/wevm/wagmi/commit/a13aa2b68890f180f6ac3f741cbb9817494cb66c)]: - @wagmi/core@2.20.0 - @wagmi/connectors@5.9.5 ## 2.16.4 ### Patch Changes - Updated dependencies [[`f4039419b83b52b2984de149db85c11f503ffe39`](https://github.com/wevm/wagmi/commit/f4039419b83b52b2984de149db85c11f503ffe39)]: - @wagmi/connectors@5.9.4 ## 2.16.3 ### Patch Changes - Updated dependencies [[`909324d28c81e15c9df312b277dcff1983fbae4d`](https://github.com/wevm/wagmi/commit/909324d28c81e15c9df312b277dcff1983fbae4d)]: - @wagmi/connectors@5.9.3 ## 2.16.2 ### Patch Changes - Updated dependencies [[`b5f017dbc707729eb0b36d617352be224d1139d4`](https://github.com/wevm/wagmi/commit/b5f017dbc707729eb0b36d617352be224d1139d4)]: - @wagmi/core@2.19.0 - @wagmi/connectors@5.9.2 ## 2.16.1 ### Patch Changes - Updated dependencies [[`6fbafd425e488dbeee8404162dbeb3c737eeb8cf`](https://github.com/wevm/wagmi/commit/6fbafd425e488dbeee8404162dbeb3c737eeb8cf), [`6514ba29a5acb918773235fed0238d7d679d06d5`](https://github.com/wevm/wagmi/commit/6514ba29a5acb918773235fed0238d7d679d06d5)]: - @wagmi/connectors@5.9.1 - @wagmi/core@2.18.1 ## 2.16.0 ### Minor Changes - [#4734](https://github.com/wevm/wagmi/pull/4734) [`eac550ae5b49f96a7e3404a6d88adc62d3889013`](https://github.com/wevm/wagmi/commit/eac550ae5b49f96a7e3404a6d88adc62d3889013) Thanks [@jxom](https://github.com/jxom)! - Added `baseAccount` connector. ### Patch Changes - Updated dependencies [[`eac550ae5b49f96a7e3404a6d88adc62d3889013`](https://github.com/wevm/wagmi/commit/eac550ae5b49f96a7e3404a6d88adc62d3889013)]: - @wagmi/connectors@6.0.0 - @wagmi/core@2.18.0 ## 2.15.7 ### Patch Changes - Updated dependencies [[`e75bd89406e9b6ff5b7d3a7148ab34140fe6352a`](https://github.com/wevm/wagmi/commit/e75bd89406e9b6ff5b7d3a7148ab34140fe6352a)]: - @wagmi/connectors@5.8.6 ## 2.15.6 ### Patch Changes - Updated dependencies [[`7ce242b549d8cc78e6c319d9ee419693da36704c`](https://github.com/wevm/wagmi/commit/7ce242b549d8cc78e6c319d9ee419693da36704c)]: - @wagmi/core@2.17.3 - @wagmi/connectors@5.8.5 ## 2.15.5 ### Patch Changes - Updated dependencies [[`3a90f358820444a85bb727742b0a16eb943fc361`](https://github.com/wevm/wagmi/commit/3a90f358820444a85bb727742b0a16eb943fc361)]: - @wagmi/connectors@5.8.4 ## 2.15.4 ### Patch Changes - Updated dependencies [[`42b1fed58e9ac09da0f8ebf3e9271f98a707aaac`](https://github.com/wevm/wagmi/commit/42b1fed58e9ac09da0f8ebf3e9271f98a707aaac)]: - @wagmi/connectors@5.8.3 ## 2.15.3 ### Patch Changes - Updated dependencies [[`29297a48af72b537173d948ccd2fe37d39914c66`](https://github.com/wevm/wagmi/commit/29297a48af72b537173d948ccd2fe37d39914c66), [`07370106d5fb6b8fe300992d93abf25b3d0eaf57`](https://github.com/wevm/wagmi/commit/07370106d5fb6b8fe300992d93abf25b3d0eaf57)]: - @wagmi/core@2.17.2 - @wagmi/connectors@5.8.2 ## 2.15.2 ### Patch Changes - [#4649](https://github.com/wevm/wagmi/pull/4649) [`01f64e64fa4f85cdd30023903f972f4f9023681f`](https://github.com/wevm/wagmi/commit/01f64e64fa4f85cdd30023903f972f4f9023681f) Thanks [@jxom](https://github.com/jxom)! - Added `chainId` parameter to `getCapabilities`/`useCapabilities`. - Updated dependencies [[`01f64e64fa4f85cdd30023903f972f4f9023681f`](https://github.com/wevm/wagmi/commit/01f64e64fa4f85cdd30023903f972f4f9023681f)]: - @wagmi/core@2.17.1 - @wagmi/connectors@5.8.1 ## 2.15.1 ### Patch Changes - Updated dependencies [[`cc5517ff6880bb630f1b201930acc20dd1a0b451`](https://github.com/wevm/wagmi/commit/cc5517ff6880bb630f1b201930acc20dd1a0b451)]: - @wagmi/connectors@5.8.0 ## 2.15.0 ### Minor Changes - [#4638](https://github.com/wevm/wagmi/pull/4638) [`799ee4d4b23c2ecd64e3f3668e67634e81939719`](https://github.com/wevm/wagmi/commit/799ee4d4b23c2ecd64e3f3668e67634e81939719) Thanks [@jxom](https://github.com/jxom)! - Stabilized EIP-5792 Actions & Hooks. ### Patch Changes - Updated dependencies [[`88427b2bcd13ec375ef519e9ad1ccffef9f02a7b`](https://github.com/wevm/wagmi/commit/88427b2bcd13ec375ef519e9ad1ccffef9f02a7b), [`799ee4d4b23c2ecd64e3f3668e67634e81939719`](https://github.com/wevm/wagmi/commit/799ee4d4b23c2ecd64e3f3668e67634e81939719), [`3f8b2edc4f237cccff1009bcef03d51ca27a7324`](https://github.com/wevm/wagmi/commit/3f8b2edc4f237cccff1009bcef03d51ca27a7324)]: - @wagmi/connectors@6.0.0 - @wagmi/core@2.17.0 ## 2.14.16 ### Patch Changes - Updated dependencies [[`b59c024b23c69f5459b17390531207cfdf126ce4`](https://github.com/wevm/wagmi/commit/b59c024b23c69f5459b17390531207cfdf126ce4)]: - @wagmi/connectors@5.7.12 ## 2.14.15 ### Patch Changes - [`a4bd0623eed28e3761a27295831a60ad835f0ee0`](https://github.com/wevm/wagmi/commit/a4bd0623eed28e3761a27295831a60ad835f0ee0) Thanks [@jxom](https://github.com/jxom)! - **Experimental (EIP-5792):** Updated `id` parameter to be optional on `useWaitForCallsStatus`. - Updated dependencies [[`a4bd0623eed28e3761a27295831a60ad835f0ee0`](https://github.com/wevm/wagmi/commit/a4bd0623eed28e3761a27295831a60ad835f0ee0)]: - @wagmi/core@2.16.7 - @wagmi/connectors@5.7.11 ## 2.14.14 ### Patch Changes - [#4586](https://github.com/wevm/wagmi/pull/4586) [`edf47477b2f6385a1c3ae01d36a8498c47f30a0b`](https://github.com/wevm/wagmi/commit/edf47477b2f6385a1c3ae01d36a8498c47f30a0b) Thanks [@jxom](https://github.com/jxom)! - **Experimental (EIP-5792):** Added `waitForCallsStatus` + `useWaitForCallsStatus`. - Updated dependencies [[`edf47477b2f6385a1c3ae01d36a8498c47f30a0b`](https://github.com/wevm/wagmi/commit/edf47477b2f6385a1c3ae01d36a8498c47f30a0b), [`e944812ebc234a72c1417b77cff341166f5e0fef`](https://github.com/wevm/wagmi/commit/e944812ebc234a72c1417b77cff341166f5e0fef)]: - @wagmi/core@2.16.6 - @wagmi/connectors@5.7.10 ## 2.14.13 ### Patch Changes - Updated dependencies [[`5b7101fddb61df56e34b2e02b46bc409e496eaf9`](https://github.com/wevm/wagmi/commit/5b7101fddb61df56e34b2e02b46bc409e496eaf9)]: - @wagmi/connectors@5.7.9 ## 2.14.12 ### Patch Changes - [`d0c9a86921a4e939373cc6e763284e53f2a2e93c`](https://github.com/wevm/wagmi/commit/d0c9a86921a4e939373cc6e763284e53f2a2e93c) Thanks [@jxom](https://github.com/jxom)! - **Experimental (ERC-5792)**: Added support for `account: null` in `sendCalls` to cater for sending calls without a connected account (account will be filled by the wallet). - Updated dependencies [[`d0c9a86921a4e939373cc6e763284e53f2a2e93c`](https://github.com/wevm/wagmi/commit/d0c9a86921a4e939373cc6e763284e53f2a2e93c)]: - @wagmi/core@2.16.5 - @wagmi/connectors@5.7.8 ## 2.14.11 ### Patch Changes - [`507f864d91238bfd423d0e36d3619eb9f6e52eec`](https://github.com/wevm/wagmi/commit/507f864d91238bfd423d0e36d3619eb9f6e52eec) Thanks [@jxom](https://github.com/jxom)! - Updated `@coinbase/wallet-sdk`. - Updated dependencies [[`507f864d91238bfd423d0e36d3619eb9f6e52eec`](https://github.com/wevm/wagmi/commit/507f864d91238bfd423d0e36d3619eb9f6e52eec)]: - @wagmi/connectors@5.7.7 - @wagmi/core@2.16.4 ## 2.14.10 ### Patch Changes - Updated dependencies [[`639952c97f0fe3927106f42d3c9f7f366cdf7f7a`](https://github.com/wevm/wagmi/commit/639952c97f0fe3927106f42d3c9f7f366cdf7f7a), [`5aa2c095f7bfb6dfcf91c6945c3e1f9c9dd05766`](https://github.com/wevm/wagmi/commit/5aa2c095f7bfb6dfcf91c6945c3e1f9c9dd05766)]: - @wagmi/connectors@5.7.6 ## 2.14.9 ### Patch Changes - Updated dependencies [[`a257e8d4f97431a4af872cda1817b4ae17c7bbed`](https://github.com/wevm/wagmi/commit/a257e8d4f97431a4af872cda1817b4ae17c7bbed)]: - @wagmi/connectors@5.7.5 ## 2.14.8 ### Patch Changes - Updated dependencies [[`c8a257e0f6d2ece013b873895c35769a8a804fdc`](https://github.com/wevm/wagmi/commit/c8a257e0f6d2ece013b873895c35769a8a804fdc)]: - @wagmi/connectors@5.7.4 ## 2.14.7 ### Patch Changes - [#4497](https://github.com/wevm/wagmi/pull/4497) [`00c144b21bac3f0797b683d8a4a81f7399c6e042`](https://github.com/wevm/wagmi/commit/00c144b21bac3f0797b683d8a4a81f7399c6e042) Thanks [@tmm](https://github.com/tmm)! - Bumped `use-sync-external-store` version for React 19. ## 2.14.6 ### Patch Changes - [#4480](https://github.com/wevm/wagmi/pull/4480) [`384a1d91597622eb59e1c05dc13ce25017c5b6d8`](https://github.com/wevm/wagmi/commit/384a1d91597622eb59e1c05dc13ce25017c5b6d8) Thanks [@RodeRickIsWatching](https://github.com/RodeRickIsWatching)! - Fixed invocation of default storage. - Updated dependencies [[`384a1d91597622eb59e1c05dc13ce25017c5b6d8`](https://github.com/wevm/wagmi/commit/384a1d91597622eb59e1c05dc13ce25017c5b6d8)]: - @wagmi/core@2.16.3 - @wagmi/connectors@5.7.3 ## 2.14.5 ### Patch Changes - [`012907032b532a438fce48f407470250cbc8f0c6`](https://github.com/wevm/wagmi/commit/012907032b532a438fce48f407470250cbc8f0c6) Thanks [@jxom](https://github.com/jxom)! - Fixed assignment in `getDefaultStorage`. - Updated dependencies [[`012907032b532a438fce48f407470250cbc8f0c6`](https://github.com/wevm/wagmi/commit/012907032b532a438fce48f407470250cbc8f0c6)]: - @wagmi/core@2.16.2 - @wagmi/connectors@5.7.2 ## 2.14.4 ### Patch Changes - Updated dependencies [[`9c8c35a3b829f2c58edcd3a29e2dcd99974d7470`](https://github.com/wevm/wagmi/commit/9c8c35a3b829f2c58edcd3a29e2dcd99974d7470), [`3892ebd21c06beef4b28ece4e70d2a38807bce6f`](https://github.com/wevm/wagmi/commit/3892ebd21c06beef4b28ece4e70d2a38807bce6f)]: - @wagmi/connectors@5.7.1 - @wagmi/core@2.16.1 ## 2.14.3 ### Patch Changes - Updated dependencies [[`e3f63a02c1f7d80481804584f262bc98dab0400d`](https://github.com/wevm/wagmi/commit/e3f63a02c1f7d80481804584f262bc98dab0400d)]: - @wagmi/connectors@5.7.0 ## 2.14.2 ### Patch Changes - Updated dependencies [[`adf2253b10c6d4fc583e4bc9f01a8ef5ca267c85`](https://github.com/wevm/wagmi/commit/adf2253b10c6d4fc583e4bc9f01a8ef5ca267c85)]: - @wagmi/connectors@5.6.2 ## 2.14.1 ### Patch Changes - Updated dependencies [[`987404f590c1d29ebb3cb68928f5e54aa032793d`](https://github.com/wevm/wagmi/commit/987404f590c1d29ebb3cb68928f5e54aa032793d)]: - @wagmi/connectors@5.6.1 ## 2.14.0 ### Minor Changes - [#4453](https://github.com/wevm/wagmi/pull/4453) [`070e48480194c8d7f45bda1d7dd1346e6f5d7227`](https://github.com/wevm/wagmi/commit/070e48480194c8d7f45bda1d7dd1346e6f5d7227) Thanks [@tmm](https://github.com/tmm)! - Added support to `useConnect` for custom `connector.connect` parameters. ### Patch Changes - Updated dependencies [[`afea6b67822a7a2b96901ec851441d27ee0f7a52`](https://github.com/wevm/wagmi/commit/afea6b67822a7a2b96901ec851441d27ee0f7a52), [`070e48480194c8d7f45bda1d7dd1346e6f5d7227`](https://github.com/wevm/wagmi/commit/070e48480194c8d7f45bda1d7dd1346e6f5d7227), [`8b0726c1106fce88b782e676498eabf0718b2619`](https://github.com/wevm/wagmi/commit/8b0726c1106fce88b782e676498eabf0718b2619)]: - @wagmi/connectors@5.6.0 - @wagmi/core@2.16.0 ## 2.13.5 ### Patch Changes - [#4447](https://github.com/wevm/wagmi/pull/4447) [`244f7777d9d227b3134d4cb9b9dda64f50cbddd3`](https://github.com/wevm/wagmi/commit/244f7777d9d227b3134d4cb9b9dda64f50cbddd3) Thanks [@Aerilym](https://github.com/Aerilym)! - Fixed config parameter passing in useSimulateContract and useEstimateGas ## 2.13.4 ### Patch Changes - [`2f79a3da4872d6158569017b1927a07a1ff5e7ba`](https://github.com/wevm/wagmi/commit/2f79a3da4872d6158569017b1927a07a1ff5e7ba) Thanks [@tmm](https://github.com/tmm)! - Exported `injected` and `mock`. ## 2.13.3 ### Patch Changes - [#4433](https://github.com/wevm/wagmi/pull/4433) [`06e186cd679b27fe195309110e766fcf46d4efbc`](https://github.com/wevm/wagmi/commit/06e186cd679b27fe195309110e766fcf46d4efbc) Thanks [@Aerilym](https://github.com/Aerilym)! - Bumped Metamask SDK version to `0.31.1`. - Updated dependencies [[`06e186cd679b27fe195309110e766fcf46d4efbc`](https://github.com/wevm/wagmi/commit/06e186cd679b27fe195309110e766fcf46d4efbc)]: - @wagmi/connectors@5.5.3 - @wagmi/core@2.15.2 ## 2.13.2 ### Patch Changes - Updated dependencies [[`e563ef69130a511fd6f3f72ed4cd4fbe1390541f`](https://github.com/wevm/wagmi/commit/e563ef69130a511fd6f3f72ed4cd4fbe1390541f)]: - @wagmi/connectors@5.5.2 ## 2.13.1 ### Patch Changes - [`b8bbb409f4934538e3dd6cac5aaf7346292d0693`](https://github.com/wevm/wagmi/commit/b8bbb409f4934538e3dd6cac5aaf7346292d0693) Thanks [@jxom](https://github.com/jxom)! - Fixed issue where `null` gas would accidentally pass through. - Updated dependencies [[`b8bbb409f4934538e3dd6cac5aaf7346292d0693`](https://github.com/wevm/wagmi/commit/b8bbb409f4934538e3dd6cac5aaf7346292d0693)]: - @wagmi/core@2.15.1 - @wagmi/connectors@5.5.1 ## 2.13.0 ### Minor Changes - [#4417](https://github.com/wevm/wagmi/pull/4417) [`42e65ea4fea99c639817088bba915e0933d17141`](https://github.com/wevm/wagmi/commit/42e65ea4fea99c639817088bba915e0933d17141) Thanks [@jxom](https://github.com/jxom)! - Removed simulation in `writeContract` & `sendTransaction`. ### Patch Changes - Updated dependencies [[`42e65ea4fea99c639817088bba915e0933d17141`](https://github.com/wevm/wagmi/commit/42e65ea4fea99c639817088bba915e0933d17141)]: - @wagmi/connectors@6.0.0 - @wagmi/core@2.15.0 ## 2.12.33 ### Patch Changes - Updated dependencies [[`7ca62b44cd997d48f92c2b81343726a5908aa00b`](https://github.com/wevm/wagmi/commit/7ca62b44cd997d48f92c2b81343726a5908aa00b)]: - @wagmi/connectors@5.4.0 ## 2.12.32 ### Patch Changes - Updated dependencies [[`a13aa8d7c38eb3cc8171a02d6302e6d12cf6bcb3`](https://github.com/wevm/wagmi/commit/a13aa8d7c38eb3cc8171a02d6302e6d12cf6bcb3), [`a13aa8d7c38eb3cc8171a02d6302e6d12cf6bcb3`](https://github.com/wevm/wagmi/commit/a13aa8d7c38eb3cc8171a02d6302e6d12cf6bcb3)]: - @wagmi/core@2.14.6 - @wagmi/connectors@5.3.10 ## 2.12.31 ### Patch Changes - Updated dependencies [[`b12a04eeec985c48d2feac94b011d41fb29ca23e`](https://github.com/wevm/wagmi/commit/b12a04eeec985c48d2feac94b011d41fb29ca23e)]: - @wagmi/connectors@5.3.9 ## 2.12.30 ### Patch Changes - Updated dependencies [[`6b9bbacdc7bffd44fc2165362a5e65fd434e7646`](https://github.com/wevm/wagmi/commit/6b9bbacdc7bffd44fc2165362a5e65fd434e7646), [`dac62dc99a0679fa632a0fae49873d6053d06b35`](https://github.com/wevm/wagmi/commit/dac62dc99a0679fa632a0fae49873d6053d06b35)]: - @wagmi/core@2.14.5 - @wagmi/connectors@5.3.8 ## 2.12.29 ### Patch Changes - Updated dependencies [[`e08681c81fbdf475213e2d0f4c5517d0abf4e743`](https://github.com/wevm/wagmi/commit/e08681c81fbdf475213e2d0f4c5517d0abf4e743)]: - @wagmi/core@2.14.4 - @wagmi/connectors@5.3.7 ## 2.12.28 ### Patch Changes - Updated dependencies [[`7558ff3133c11bc4c49473d08ee9a47eaa12df5b`](https://github.com/wevm/wagmi/commit/7558ff3133c11bc4c49473d08ee9a47eaa12df5b)]: - @wagmi/connectors@5.3.6 ## 2.12.27 ### Patch Changes - Updated dependencies [[`cb7dd2ebb871d0be8f1a11a8cd8ce592cd74b7c7`](https://github.com/wevm/wagmi/commit/cb7dd2ebb871d0be8f1a11a8cd8ce592cd74b7c7), [`7fe78f2d09778fc01fd0cffe85ba198e64999275`](https://github.com/wevm/wagmi/commit/7fe78f2d09778fc01fd0cffe85ba198e64999275)]: - @wagmi/core@2.14.3 - @wagmi/connectors@5.3.5 ## 2.12.26 ### Patch Changes - Updated dependencies [[`b6861a4c378dab78d8751ae0ac2aa425f3c24b8f`](https://github.com/wevm/wagmi/commit/b6861a4c378dab78d8751ae0ac2aa425f3c24b8f), [`d0d0963bb5904a15cf0355862d62dd141ce0c31c`](https://github.com/wevm/wagmi/commit/d0d0963bb5904a15cf0355862d62dd141ce0c31c), [`ecac0ba36243d94c9199d0bd21937104c835d9a0`](https://github.com/wevm/wagmi/commit/ecac0ba36243d94c9199d0bd21937104c835d9a0)]: - @wagmi/connectors@5.3.4 - @wagmi/core@2.14.2 ## 2.12.25 ### Patch Changes - Updated dependencies [[`83c6d16b7d6dddfa6bda036e04f00ec313c6248c`](https://github.com/wevm/wagmi/commit/83c6d16b7d6dddfa6bda036e04f00ec313c6248c)]: - @wagmi/connectors@5.3.3 ## 2.12.24 ### Patch Changes - [`a4c5389c1a299bd7acf9df4a0d607e2ced709280`](https://github.com/wevm/wagmi/commit/a4c5389c1a299bd7acf9df4a0d607e2ced709280) Thanks [@jxom](https://github.com/jxom)! - Exported `Transport` type (for inference). ## 2.12.23 ### Patch Changes - Updated dependencies [[`8970cc51398e1ac713435533096215c6d31ffdf9`](https://github.com/wevm/wagmi/commit/8970cc51398e1ac713435533096215c6d31ffdf9)]: - @wagmi/connectors@5.3.2 ## 2.12.22 ### Patch Changes - Updated dependencies [[`052e72e1f8c1c14fcbdce04a9f8fa7ec28d83702`](https://github.com/wevm/wagmi/commit/052e72e1f8c1c14fcbdce04a9f8fa7ec28d83702), [`b250fc21ee577b2a75c5a34ff684f62fb4ad771a`](https://github.com/wevm/wagmi/commit/b250fc21ee577b2a75c5a34ff684f62fb4ad771a)]: - @wagmi/core@2.14.1 - @wagmi/connectors@5.3.1 ## 2.12.21 ### Patch Changes - Updated dependencies [[`f43e074f473820b208a6295d7c97f847332f1a1d`](https://github.com/wevm/wagmi/commit/f43e074f473820b208a6295d7c97f847332f1a1d)]: - @wagmi/connectors@6.0.0 - @wagmi/core@2.14.0 ## 2.12.20 ### Patch Changes - Updated dependencies [[`c05caabc20c3ced9682cfc7ba1f3f7dcfece0703`](https://github.com/wevm/wagmi/commit/c05caabc20c3ced9682cfc7ba1f3f7dcfece0703), [`5ae49af590ff168426c9c283d54c34ae5148fcd9`](https://github.com/wevm/wagmi/commit/5ae49af590ff168426c9c283d54c34ae5148fcd9), [`f3182b22e6e454d9bd74f1b940ef34431fd9555d`](https://github.com/wevm/wagmi/commit/f3182b22e6e454d9bd74f1b940ef34431fd9555d)]: - @wagmi/core@2.13.9 - @wagmi/connectors@5.2.2 ## 2.12.19 ### Patch Changes - Updated dependencies [[`91a40f2db08e3a91db421b8732a5511a1e6c88fd`](https://github.com/wevm/wagmi/commit/91a40f2db08e3a91db421b8732a5511a1e6c88fd)]: - @wagmi/connectors@5.2.1 ## 2.12.18 ### Patch Changes - Updated dependencies [[`34a0c3b7eea778aee7c27f7ace5e4b2be4e8a0a4`](https://github.com/wevm/wagmi/commit/34a0c3b7eea778aee7c27f7ace5e4b2be4e8a0a4)]: - @wagmi/connectors@5.2.0 ## 2.12.17 ### Patch Changes - Updated dependencies [[`3b2123664b7ac66848390739e855c3b9702ab60c`](https://github.com/wevm/wagmi/commit/3b2123664b7ac66848390739e855c3b9702ab60c)]: - @wagmi/connectors@5.1.15 ## 2.12.16 ### Patch Changes - Updated dependencies [[`56f2482508f2ba71bd6b0295c70c6abca7101e57`](https://github.com/wevm/wagmi/commit/56f2482508f2ba71bd6b0295c70c6abca7101e57)]: - @wagmi/connectors@5.1.14 - @wagmi/core@2.13.8 ## 2.12.15 ### Patch Changes - [#4229](https://github.com/wevm/wagmi/pull/4229) [`c6b8efd26254c8e692b2b67286ed538fc183b992`](https://github.com/wevm/wagmi/commit/c6b8efd26254c8e692b2b67286ed538fc183b992) Thanks [@weilliao05621](https://github.com/weilliao05621)! - Stabilized `useAccount` return type object reference. ## 2.12.14 ### Patch Changes - Updated dependencies [[`be75c2d4ef636d7362420ab0a106bfdf63f5d1e6`](https://github.com/wevm/wagmi/commit/be75c2d4ef636d7362420ab0a106bfdf63f5d1e6)]: - @wagmi/core@2.13.7 - @wagmi/connectors@5.1.13 ## 2.12.13 ### Patch Changes - Updated dependencies [[`edcbf5d6fbe92f639bead800502edda9e0aa39f1`](https://github.com/wevm/wagmi/commit/edcbf5d6fbe92f639bead800502edda9e0aa39f1)]: - @wagmi/core@2.13.6 - @wagmi/connectors@5.1.12 ## 2.12.12 ### Patch Changes - Updated dependencies [[`82404c960e04c83e0bae6e1e12459ef9debf9554`](https://github.com/wevm/wagmi/commit/82404c960e04c83e0bae6e1e12459ef9debf9554), [`d07ad7f63a018256908a673d078aaf79e47ac703`](https://github.com/wevm/wagmi/commit/d07ad7f63a018256908a673d078aaf79e47ac703)]: - @wagmi/connectors@5.1.11 ## 2.12.11 ### Patch Changes - [#4262](https://github.com/wevm/wagmi/pull/4262) [`8531f83db3a1fbb8202c3e426b7f85679f587a52`](https://github.com/wevm/wagmi/commit/8531f83db3a1fbb8202c3e426b7f85679f587a52) Thanks [@nezouse](https://github.com/nezouse)! - Added experimental actions entrypoint. ## 2.12.10 ### Patch Changes - [#4260](https://github.com/wevm/wagmi/pull/4260) [`969a208a110b760a13fd7263360320f52440a9b6`](https://github.com/wevm/wagmi/commit/969a208a110b760a13fd7263360320f52440a9b6) Thanks [@tmm](https://github.com/tmm)! - Fixed `useReadContract` deployless reads support. - [#4259](https://github.com/wevm/wagmi/pull/4259) [`f47ce8f6d263e49fdff90b8edb3190142d2657bb`](https://github.com/wevm/wagmi/commit/f47ce8f6d263e49fdff90b8edb3190142d2657bb) Thanks [@tmm](https://github.com/tmm)! - Disabled `useConnectorClient` and `useWalletClient` during reconnection if connector is not fully restored. - Updated dependencies [[`81de006e66121a18c61945c1f9b8426c83a5713c`](https://github.com/wevm/wagmi/commit/81de006e66121a18c61945c1f9b8426c83a5713c), [`f47ce8f6d263e49fdff90b8edb3190142d2657bb`](https://github.com/wevm/wagmi/commit/f47ce8f6d263e49fdff90b8edb3190142d2657bb)]: - @wagmi/connectors@5.1.10 - @wagmi/core@2.13.5 ## 2.12.9 ### Patch Changes - Updated dependencies [[`21bd0e473d374cbbd7a01bececa6022d529026ba`](https://github.com/wevm/wagmi/commit/21bd0e473d374cbbd7a01bececa6022d529026ba), [`5c89c6853e616437a3be2b019db895451fecfb3c`](https://github.com/wevm/wagmi/commit/5c89c6853e616437a3be2b019db895451fecfb3c)]: - @wagmi/connectors@5.1.9 ## 2.12.8 ### Patch Changes - Updated dependencies [[`b580ad4edff1721e0b9d138cf5ae2ec74d2374c7`](https://github.com/wevm/wagmi/commit/b580ad4edff1721e0b9d138cf5ae2ec74d2374c7)]: - @wagmi/connectors@5.1.8 ## 2.12.7 ### Patch Changes - Updated dependencies [[`91fd81a068789c5020e891f539bcad8f54a7a52f`](https://github.com/wevm/wagmi/commit/91fd81a068789c5020e891f539bcad8f54a7a52f)]: - @wagmi/connectors@5.1.7 ## 2.12.6 ### Patch Changes - Updated dependencies [[`3168616298cbb6135d0ffda771cba4126e83eba8`](https://github.com/wevm/wagmi/commit/3168616298cbb6135d0ffda771cba4126e83eba8), [`d7608ef9a79459465dc8c06a2ab740465c881907`](https://github.com/wevm/wagmi/commit/d7608ef9a79459465dc8c06a2ab740465c881907)]: - @wagmi/connectors@5.1.6 ## 2.12.5 ### Patch Changes - Updated dependencies [[`b4c8971788c70b09479946ecfa998cff2f1b3953`](https://github.com/wevm/wagmi/commit/b4c8971788c70b09479946ecfa998cff2f1b3953)]: - @wagmi/core@2.13.4 - @wagmi/connectors@5.1.5 ## 2.12.4 ### Patch Changes - Updated dependencies [[`871dbdbfe59ac8ad01d1ec6150ea7b091b7b7de4`](https://github.com/wevm/wagmi/commit/871dbdbfe59ac8ad01d1ec6150ea7b091b7b7de4)]: - @wagmi/core@2.13.3 - @wagmi/connectors@5.1.4 ## 2.12.3 ### Patch Changes - Updated dependencies [[`1b9b523fa9b9dfe839aecdf4b40caa9547d7e594`](https://github.com/wevm/wagmi/commit/1b9b523fa9b9dfe839aecdf4b40caa9547d7e594)]: - @wagmi/core@2.13.2 - @wagmi/connectors@5.1.3 ## 2.12.2 ### Patch Changes - Updated dependencies [[`abb490dac4f0f02f46cb0878e7ca9a0db6aada56`](https://github.com/wevm/wagmi/commit/abb490dac4f0f02f46cb0878e7ca9a0db6aada56), [`28e0e5c9a4f856583f9d36a807502bd51a0c6ec2`](https://github.com/wevm/wagmi/commit/28e0e5c9a4f856583f9d36a807502bd51a0c6ec2)]: - @wagmi/connectors@5.1.2 ## 2.12.1 ### Patch Changes - Updated dependencies [[`07c1227f306d0efb9421d4bb77a774f92f5fcf45`](https://github.com/wevm/wagmi/commit/07c1227f306d0efb9421d4bb77a774f92f5fcf45)]: - @wagmi/core@2.13.1 - @wagmi/connectors@5.1.1 ## 2.12.0 ### Minor Changes - [#4162](https://github.com/wevm/wagmi/pull/4162) [`a73a7737b756886b388f120ae423e72cca53e8a0`](https://github.com/wevm/wagmi/commit/a73a7737b756886b388f120ae423e72cca53e8a0) Thanks [@jxom](https://github.com/jxom)! - Added functionality for consumer-defined RPC URLs (`config.transports`) to be propagated to the WalletConnect & MetaMask Connectors. ### Patch Changes - Updated dependencies [[`a73a7737b756886b388f120ae423e72cca53e8a0`](https://github.com/wevm/wagmi/commit/a73a7737b756886b388f120ae423e72cca53e8a0)]: - @wagmi/connectors@6.0.0 - @wagmi/core@2.13.0 ## 2.11.3 ### Patch Changes - [#4124](https://github.com/wevm/wagmi/pull/4124) [`26616462db2e0140025f22c505c4541cfecb9308`](https://github.com/wevm/wagmi/commit/26616462db2e0140025f22c505c4541cfecb9308) Thanks [@t0rbik](https://github.com/t0rbik)! - Updated `useConnectorClient` to be enabled when status is `'reconnecting'` or `'connected'` (previously was also enabled when status was `'connecting'`). ## 2.11.2 ### Patch Changes - Updated dependencies [[`5bc8c8877810b2eec24a829df87dce40a51e6f20`](https://github.com/wevm/wagmi/commit/5bc8c8877810b2eec24a829df87dce40a51e6f20), [`8d81df5cc884d0a210dedd3c1ea0e2e9e52b83c5`](https://github.com/wevm/wagmi/commit/8d81df5cc884d0a210dedd3c1ea0e2e9e52b83c5)]: - @wagmi/core@2.12.2 - @wagmi/connectors@5.0.26 ## 2.11.1 ### Patch Changes - [#4146](https://github.com/wevm/wagmi/pull/4146) [`cc996e08e930c9e88cf753a1e874652059e81a3b`](https://github.com/wevm/wagmi/commit/cc996e08e930c9e88cf753a1e874652059e81a3b) Thanks [@jxom](https://github.com/jxom)! - Updated `@safe-global/safe-apps-sdk` + `@safe-global/safe-apps-provider` dependencies. - Updated dependencies [[`cc996e08e930c9e88cf753a1e874652059e81a3b`](https://github.com/wevm/wagmi/commit/cc996e08e930c9e88cf753a1e874652059e81a3b)]: - @wagmi/connectors@5.0.25 - @wagmi/core@2.12.1 ## 2.11.0 ### Minor Changes - [#4128](https://github.com/wevm/wagmi/pull/4128) [`5581a810ef70308e99c6f8b630cd4bca59f64afc`](https://github.com/wevm/wagmi/commit/5581a810ef70308e99c6f8b630cd4bca59f64afc) Thanks [@dalechyn](https://github.com/dalechyn)! - Added `useWatchAsset` hook. ### Patch Changes - Updated dependencies [[`5581a810ef70308e99c6f8b630cd4bca59f64afc`](https://github.com/wevm/wagmi/commit/5581a810ef70308e99c6f8b630cd4bca59f64afc)]: - @wagmi/core@2.12.0 - @wagmi/connectors@6.0.0 ## 2.10.11 ### Patch Changes - [`d3814ab4b88f9f0e052b53bc3d458df87b43f01d`](https://github.com/wevm/wagmi/commit/d3814ab4b88f9f0e052b53bc3d458df87b43f01d) Thanks [@jxom](https://github.com/jxom)! - Updated `mipd` dependency. - Updated dependencies [[`b08013eaa9ce97c02f8a7128ea400e3da7ef74bb`](https://github.com/wevm/wagmi/commit/b08013eaa9ce97c02f8a7128ea400e3da7ef74bb), [`d3814ab4b88f9f0e052b53bc3d458df87b43f01d`](https://github.com/wevm/wagmi/commit/d3814ab4b88f9f0e052b53bc3d458df87b43f01d)]: - @wagmi/core@2.11.8 - @wagmi/connectors@5.0.23 ## 2.10.10 ### Patch Changes - Updated dependencies [[`0bb8b562ae04ecfeb2d6b2f1b980ebae31dc127e`](https://github.com/wevm/wagmi/commit/0bb8b562ae04ecfeb2d6b2f1b980ebae31dc127e)]: - @wagmi/connectors@5.0.22 - @wagmi/core@2.11.7 ## 2.10.9 ### Patch Changes - [#4060](https://github.com/wevm/wagmi/pull/4060) [`95965c1f19d480b97f2b297a077a9e607dee32ad`](https://github.com/wevm/wagmi/commit/95965c1f19d480b97f2b297a077a9e607dee32ad) Thanks [@dalechyn](https://github.com/dalechyn)! - Bumped Tanstack Query dependencies to fix typing issues between exported Wagmi query options and TanStack Query suspense query methods (due to [`direction` property in `QueryFunctionContext` being deprecated](https://github.com/TanStack/query/pull/7410)). - Updated dependencies [[`ff0760b5900114bcfdf420a9fba3cc278ac95afe`](https://github.com/wevm/wagmi/commit/ff0760b5900114bcfdf420a9fba3cc278ac95afe), [`95965c1f19d480b97f2b297a077a9e607dee32ad`](https://github.com/wevm/wagmi/commit/95965c1f19d480b97f2b297a077a9e607dee32ad)]: - @wagmi/connectors@5.0.21 - @wagmi/core@2.11.6 ## 2.10.8 ### Patch Changes - Updated dependencies [[`43fa971d34cac57fa5a2898ad4d839b95d7af37c`](https://github.com/wevm/wagmi/commit/43fa971d34cac57fa5a2898ad4d839b95d7af37c)]: - @wagmi/connectors@5.0.20 ## 2.10.7 ### Patch Changes - Updated dependencies [[`b7ad208030d9f2e3f89912ff76b16cdbd848feda`](https://github.com/wevm/wagmi/commit/b7ad208030d9f2e3f89912ff76b16cdbd848feda)]: - @wagmi/connectors@5.0.19 ## 2.10.6 ### Patch Changes - Updated dependencies [[`44d24620c9e3957f3245d14d6a042736371df70b`](https://github.com/wevm/wagmi/commit/44d24620c9e3957f3245d14d6a042736371df70b)]: - @wagmi/connectors@5.0.18 ## 2.10.5 ### Patch Changes - Updated dependencies [[`04f2b846b113f3d300d82c9fa75212f1805817c5`](https://github.com/wevm/wagmi/commit/04f2b846b113f3d300d82c9fa75212f1805817c5)]: - @wagmi/core@2.11.5 - @wagmi/connectors@5.0.17 ## 2.10.4 ### Patch Changes - Updated dependencies [[`9e8345cd56186b997b5e56deaa2cfc69b30d15f6`](https://github.com/wevm/wagmi/commit/9e8345cd56186b997b5e56deaa2cfc69b30d15f6), [`02c38c28d1aa0ad7a61c33775de603ed974c5c1b`](https://github.com/wevm/wagmi/commit/02c38c28d1aa0ad7a61c33775de603ed974c5c1b)]: - @wagmi/core@2.11.4 - @wagmi/connectors@5.0.16 ## 2.10.3 ### Patch Changes - Updated dependencies [[`8974e6269bb5d7bfaa90db0246bc7d13e8bff798`](https://github.com/wevm/wagmi/commit/8974e6269bb5d7bfaa90db0246bc7d13e8bff798)]: - @wagmi/core@2.11.3 - @wagmi/connectors@5.0.15 ## 2.10.2 ### Patch Changes - Updated dependencies [[`b4d9ef79deb554ee20fed6666a474be5e7cdd522`](https://github.com/wevm/wagmi/commit/b4d9ef79deb554ee20fed6666a474be5e7cdd522)]: - @wagmi/core@2.11.2 - @wagmi/connectors@5.0.14 ## 2.10.1 ### Patch Changes - Updated dependencies [[`9c862d8d63e3d692a22cef2a90782b74a9103f17`](https://github.com/wevm/wagmi/commit/9c862d8d63e3d692a22cef2a90782b74a9103f17)]: - @wagmi/connectors@5.0.13 - @wagmi/core@2.11.1 ## 2.10.0 ### Minor Changes - [#3816](https://github.com/wevm/wagmi/pull/3816) [`06bb598a7f04c7b167f5b7ff6d46bd15886a6a14`](https://github.com/wevm/wagmi/commit/06bb598a7f04c7b167f5b7ff6d46bd15886a6a14) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Added `useDeployContract` hook. ### Patch Changes - Updated dependencies [[`06bb598a7f04c7b167f5b7ff6d46bd15886a6a14`](https://github.com/wevm/wagmi/commit/06bb598a7f04c7b167f5b7ff6d46bd15886a6a14), [`24a45b269bd0214a29d6f82a84ac66ef8c3f3822`](https://github.com/wevm/wagmi/commit/24a45b269bd0214a29d6f82a84ac66ef8c3f3822)]: - @wagmi/core@2.11.0 - @wagmi/connectors@6.0.0 ## 2.9.12 ### Patch Changes - Updated dependencies [[`f2a7cefab96691ebed8b8e45ffde071c47b58dbe`](https://github.com/wevm/wagmi/commit/f2a7cefab96691ebed8b8e45ffde071c47b58dbe), [`f0ea0b2a7fe193dadfeb49a4c8031ee451c638b5`](https://github.com/wevm/wagmi/commit/f0ea0b2a7fe193dadfeb49a4c8031ee451c638b5), [`e3b124ce414b8fd1b2214e2c5a28dc72158a13d1`](https://github.com/wevm/wagmi/commit/e3b124ce414b8fd1b2214e2c5a28dc72158a13d1)]: - @wagmi/core@2.10.6 - @wagmi/connectors@5.0.11 ## 2.9.11 ### Patch Changes - Updated dependencies [[`560952acd4bfe33db6c7c07b35c613cef278677c`](https://github.com/wevm/wagmi/commit/560952acd4bfe33db6c7c07b35c613cef278677c)]: - @wagmi/connectors@5.0.10 ## 2.9.10 ### Patch Changes - Updated dependencies [[`32cdd7b7dc5aff916c040628519562c3a99d418d`](https://github.com/wevm/wagmi/commit/32cdd7b7dc5aff916c040628519562c3a99d418d)]: - @wagmi/connectors@5.0.9 ## 2.9.9 ### Patch Changes - Updated dependencies [[`c1952d1ff7f0a491dc88595a49159451b07b5621`](https://github.com/wevm/wagmi/commit/c1952d1ff7f0a491dc88595a49159451b07b5621)]: - @wagmi/connectors@5.0.8 ## 2.9.8 ### Patch Changes - Updated dependencies [[`030c7c2cb380dfd67a2182f62e2aa7a6e1601898`](https://github.com/wevm/wagmi/commit/030c7c2cb380dfd67a2182f62e2aa7a6e1601898)]: - @wagmi/core@2.10.5 - @wagmi/connectors@5.0.7 ## 2.9.7 ### Patch Changes - Updated dependencies [[`51fde8a0433b4fff357c1a8d7e08b41b4c86c968`](https://github.com/wevm/wagmi/commit/51fde8a0433b4fff357c1a8d7e08b41b4c86c968)]: - @wagmi/core@2.10.4 - @wagmi/connectors@5.0.6 ## 2.9.6 ### Patch Changes - Updated dependencies [[`70dd28669dd8d2ce08217cd02e29a8fbba7a08d4`](https://github.com/wevm/wagmi/commit/70dd28669dd8d2ce08217cd02e29a8fbba7a08d4)]: - @wagmi/connectors@5.0.5 ## 2.9.5 ### Patch Changes - Updated dependencies [[`be9e1b8a9818b92eb0654a20d9471e9e39329e7e`](https://github.com/wevm/wagmi/commit/be9e1b8a9818b92eb0654a20d9471e9e39329e7e)]: - @wagmi/connectors@5.0.4 ## 2.9.4 ### Patch Changes - Updated dependencies [[`2804a8a583b1874271154898b4bae38756ef581c`](https://github.com/wevm/wagmi/commit/2804a8a583b1874271154898b4bae38756ef581c), [`2804a8a583b1874271154898b4bae38756ef581c`](https://github.com/wevm/wagmi/commit/2804a8a583b1874271154898b4bae38756ef581c)]: - @wagmi/connectors@5.0.3 - @wagmi/core@2.10.3 ## 2.9.3 ### Patch Changes - [`ec2f63f106fd468f28b43d3b88ab3e89aaf5e81a`](https://github.com/wevm/wagmi/commit/ec2f63f106fd468f28b43d3b88ab3e89aaf5e81a) Thanks [@tmm](https://github.com/tmm)! - Fixed `useSwitchChain` `chains` typing. ## 2.9.2 ### Patch Changes - [#3940](https://github.com/wevm/wagmi/pull/3940) [`a5071f581dfdfb961718873643a2fc629101c72a`](https://github.com/wevm/wagmi/commit/a5071f581dfdfb961718873643a2fc629101c72a) Thanks [@jxom](https://github.com/jxom)! - Fixed usage of `metaMask` connector in Vite environments. - Updated dependencies [[`a5071f581dfdfb961718873643a2fc629101c72a`](https://github.com/wevm/wagmi/commit/a5071f581dfdfb961718873643a2fc629101c72a)]: - @wagmi/connectors@5.0.2 - @wagmi/core@2.10.2 ## 2.9.1 ### Patch Changes - Bumped versions. - Updated dependencies []: - @wagmi/connectors@5.0.1 - @wagmi/core@2.10.1 ## 2.9.0 ### Minor Changes - [#3928](https://github.com/wevm/wagmi/pull/3928) [`3117e71825f9c58a0d718f3d1686f1a191fa9cb1`](https://github.com/wevm/wagmi/commit/3117e71825f9c58a0d718f3d1686f1a191fa9cb1) Thanks [@tmm](https://github.com/tmm)! - Updated the default Coinbase SDK in `coinbaseWallet` Connector to v4.x. ### Patch Changes - Updated dependencies [[`3117e71825f9c58a0d718f3d1686f1a191fa9cb1`](https://github.com/wevm/wagmi/commit/3117e71825f9c58a0d718f3d1686f1a191fa9cb1), [`3117e71825f9c58a0d718f3d1686f1a191fa9cb1`](https://github.com/wevm/wagmi/commit/3117e71825f9c58a0d718f3d1686f1a191fa9cb1)]: - @wagmi/connectors@5.0.0 - @wagmi/core@2.10.0 ## 2.8.8 ### Patch Changes - [#3906](https://github.com/wevm/wagmi/pull/3906) [`32fcb4a31dde6b0206961d8ffe9c651f8a459c67`](https://github.com/wevm/wagmi/commit/32fcb4a31dde6b0206961d8ffe9c651f8a459c67) Thanks [@tmm](https://github.com/tmm)! - Added support for Vue. - Updated dependencies [[`32fcb4a31dde6b0206961d8ffe9c651f8a459c67`](https://github.com/wevm/wagmi/commit/32fcb4a31dde6b0206961d8ffe9c651f8a459c67)]: - @wagmi/connectors@4.3.10 - @wagmi/core@2.9.8 ## 2.8.7 ### Patch Changes - [#3924](https://github.com/wevm/wagmi/pull/3924) [`1f58734f88458e0f6adb05c99f0c90f36ab286b8`](https://github.com/wevm/wagmi/commit/1f58734f88458e0f6adb05c99f0c90f36ab286b8) Thanks [@jxom](https://github.com/jxom)! - Refactored `isChainsStale` logic in `walletConnect` connector. - Updated dependencies [[`1f58734f88458e0f6adb05c99f0c90f36ab286b8`](https://github.com/wevm/wagmi/commit/1f58734f88458e0f6adb05c99f0c90f36ab286b8)]: - @wagmi/connectors@4.3.9 - @wagmi/core@2.9.7 ## 2.8.6 ### Patch Changes - [#3917](https://github.com/wevm/wagmi/pull/3917) [`05948fdad5bb4a56b08916d45b3dec2cb1e5f55b`](https://github.com/wevm/wagmi/commit/05948fdad5bb4a56b08916d45b3dec2cb1e5f55b) Thanks [@jxom](https://github.com/jxom)! - Updated `@metamask/sdk`. - Updated dependencies [[`05948fdad5bb4a56b08916d45b3dec2cb1e5f55b`](https://github.com/wevm/wagmi/commit/05948fdad5bb4a56b08916d45b3dec2cb1e5f55b)]: - @wagmi/connectors@4.3.8 - @wagmi/core@2.9.6 ## 2.8.5 ### Patch Changes - [`4fecbbb66d0aacd03b8c62a6455d11a33cde8f85`](https://github.com/wevm/wagmi/commit/4fecbbb66d0aacd03b8c62a6455d11a33cde8f85) Thanks [@jxom](https://github.com/jxom)! - Fixed address comparison in `getConnectorClient`. - Updated dependencies [[`4fecbbb66d0aacd03b8c62a6455d11a33cde8f85`](https://github.com/wevm/wagmi/commit/4fecbbb66d0aacd03b8c62a6455d11a33cde8f85)]: - @wagmi/core@2.9.5 - @wagmi/connectors@4.3.7 ## 2.8.4 ### Patch Changes - Updated dependencies [[`e6139a97c4b8804d734b1547b5e3921ce01fbe24`](https://github.com/wevm/wagmi/commit/e6139a97c4b8804d734b1547b5e3921ce01fbe24)]: - @wagmi/core@2.9.4 - @wagmi/connectors@4.3.6 ## 2.8.3 ### Patch Changes - [#3904](https://github.com/wevm/wagmi/pull/3904) [`addca28ebc20f1a4367c35fe9ef786decff9c87e`](https://github.com/wevm/wagmi/commit/addca28ebc20f1a4367c35fe9ef786decff9c87e) Thanks [@jxom](https://github.com/jxom)! - Updated `@walletconnect/ethereum-provider`. - Updated dependencies [[`addca28ebc20f1a4367c35fe9ef786decff9c87e`](https://github.com/wevm/wagmi/commit/addca28ebc20f1a4367c35fe9ef786decff9c87e)]: - @wagmi/connectors@4.3.5 - @wagmi/core@2.9.3 ## 2.8.2 ### Patch Changes - [#3902](https://github.com/wevm/wagmi/pull/3902) [`204b7b624612405500ec098fb9e35facd3f74ca4`](https://github.com/wevm/wagmi/commit/204b7b624612405500ec098fb9e35facd3f74ca4) Thanks [@jxom](https://github.com/jxom)! - Made third-party SDK imports type-only. - Updated dependencies [[`204b7b624612405500ec098fb9e35facd3f74ca4`](https://github.com/wevm/wagmi/commit/204b7b624612405500ec098fb9e35facd3f74ca4)]: - @wagmi/connectors@4.3.4 - @wagmi/core@2.9.2 ## 2.8.1 ### Patch Changes - [`cda6a5d5`](https://github.com/wevm/wagmi/commit/cda6a5d56328330fbde050b4ef40b01c58d2519a) Thanks [@jxom](https://github.com/jxom)! - Updated packages. - Updated dependencies [[`cda6a5d5`](https://github.com/wevm/wagmi/commit/cda6a5d56328330fbde050b4ef40b01c58d2519a)]: - @wagmi/core@2.9.1 - @wagmi/connectors@4.3.3 ## 2.8.0 ### Minor Changes - [#3878](https://github.com/wevm/wagmi/pull/3878) [`017828fc`](https://github.com/wevm/wagmi/commit/017828fc027c7a84b54ea9d627e9389f4d60d6c2) Thanks [@jxom](https://github.com/jxom)! - Added experimental EIP-5792 Actions & Hooks. ### Patch Changes - Updated dependencies [[`017828fc`](https://github.com/wevm/wagmi/commit/017828fc027c7a84b54ea9d627e9389f4d60d6c2)]: - @wagmi/core@2.9.0 - @wagmi/connectors@4.3.2 ## 2.7.1 ### Patch Changes - [#3869](https://github.com/wevm/wagmi/pull/3869) [`d4a78eb0`](https://github.com/wevm/wagmi/commit/d4a78eb07119d2e5617e52481ac7d6c6d1583ddc) Thanks [@jxom](https://github.com/jxom)! - Fixed issue where `prepareTransactionRequest` would internally call unsupported wallet RPC methods. - Updated dependencies [[`d4a78eb0`](https://github.com/wevm/wagmi/commit/d4a78eb07119d2e5617e52481ac7d6c6d1583ddc)]: - @wagmi/core@2.8.1 - @wagmi/connectors@4.3.1 ## 2.7.0 ### Minor Changes - [#3868](https://github.com/wevm/wagmi/pull/3868) [`c2af20b8`](https://github.com/wevm/wagmi/commit/c2af20b88cf16970d087faaec10b463357a5836e) Thanks [@jxom](https://github.com/jxom)! - Added `supportsSimulation` property to connectors that indicates if the connector's wallet supports contract simulation. ### Patch Changes - [#3858](https://github.com/wevm/wagmi/pull/3858) [`0d141f17`](https://github.com/wevm/wagmi/commit/0d141f171d6ec44bcbfc9c876565b5e2fb8af6de) Thanks [@yulafezmesi](https://github.com/yulafezmesi)! - Fixed accessing reverted reason property inside `waitForTransactionReceipt`. - Updated dependencies [[`0d141f17`](https://github.com/wevm/wagmi/commit/0d141f171d6ec44bcbfc9c876565b5e2fb8af6de), [`c2af20b8`](https://github.com/wevm/wagmi/commit/c2af20b88cf16970d087faaec10b463357a5836e)]: - @wagmi/core@2.8.0 - @wagmi/connectors@5.0.0 ## 2.6.0 ### Minor Changes - [#3857](https://github.com/wevm/wagmi/pull/3857) [`d4274c03`](https://github.com/wevm/wagmi/commit/d4274c03a6af5f2d26d31432016ebc14950a330e) Thanks [@tmm](https://github.com/tmm)! - Added `addEthereumChainParameter` to `switchChain`-related methods. ### Patch Changes - Updated dependencies [[`d4274c03`](https://github.com/wevm/wagmi/commit/d4274c03a6af5f2d26d31432016ebc14950a330e), [`4781a405`](https://github.com/wevm/wagmi/commit/4781a4056d4ffc2c74f96a75429e9b2cd2417ad8), [`400c960b`](https://github.com/wevm/wagmi/commit/400c960b30d701c134850c695ae903a382c29b5b)]: - @wagmi/connectors@5.0.0 - @wagmi/core@2.7.0 ## 2.5.22 ### Patch Changes - [`e3c832a1`](https://github.com/wevm/wagmi/commit/e3c832a12c301f9b0ee129d877b3101d220ba8b2) Thanks [@jxom](https://github.com/jxom)! - Fixed undefined `navigator` issue in MetaMask connector. - Updated dependencies [[`e3c832a1`](https://github.com/wevm/wagmi/commit/e3c832a12c301f9b0ee129d877b3101d220ba8b2)]: - @wagmi/connectors@4.1.28 - @wagmi/core@2.6.19 ## 2.5.21 ### Patch Changes - [#3848](https://github.com/wevm/wagmi/pull/3848) [`dd40a41c`](https://github.com/wevm/wagmi/commit/dd40a41c526ab60a288aff2250ed8dba92a27b16) Thanks [@jxom](https://github.com/jxom)! - Updated MetaMask SDK. - Updated dependencies [[`dd40a41c`](https://github.com/wevm/wagmi/commit/dd40a41c526ab60a288aff2250ed8dba92a27b16)]: - @wagmi/connectors@4.1.27 - @wagmi/core@2.6.18 ## 2.5.20 ### Patch Changes - [#3822](https://github.com/wevm/wagmi/pull/3822) [`a97bfbae`](https://github.com/wevm/wagmi/commit/a97bfbaeb615cfef04665e5e7348d85d17f960f0) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where Wagmi would not correctly rehydrate the active chain when a persisted store was being used. - Updated dependencies [[`a97bfbae`](https://github.com/wevm/wagmi/commit/a97bfbaeb615cfef04665e5e7348d85d17f960f0)]: - @wagmi/core@2.6.17 - @wagmi/connectors@4.1.26 ## 2.5.19 ### Patch Changes - [#3793](https://github.com/wevm/wagmi/pull/3793) [`f85b83ae`](https://github.com/wevm/wagmi/commit/f85b83ae95dd0bb73ffbdb49afa174e7c68298e1) Thanks [@tmm](https://github.com/tmm)! - Wired up `config` inside hooks so you can pass it explicitly and not use the `WagmiProvider`. - Updated dependencies [[`42ad380d`](https://github.com/wevm/wagmi/commit/42ad380d9a5d8bc0f61d73612142dea9d098de5e)]: - @wagmi/connectors@4.1.25 - @wagmi/core@2.6.16 ## 2.5.18 ### Patch Changes - Updated dependencies [[`b907d5ac`](https://github.com/wevm/wagmi/commit/b907d5ac3a746bcbccc06d1fe78c5bd8f9a7d685)]: - @wagmi/core@2.6.15 - @wagmi/connectors@4.1.24 ## 2.5.17 ### Patch Changes - [#3779](https://github.com/wevm/wagmi/pull/3779) [`3da20bb8`](https://github.com/wevm/wagmi/commit/3da20bb80e7c3efeef8227ced66ad615370fc242) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where `eth_requestAccounts` would be called upon reconnect instead of `eth_accounts`. - [`a3d1858f`](https://github.com/wevm/wagmi/commit/a3d1858fce448d2b70e36ee692ef1589b74e9d3f) Thanks [@jxom](https://github.com/jxom)! - Fixed hydration conditional in `createConfig`. - Updated dependencies [[`b3b54ef1`](https://github.com/wevm/wagmi/commit/b3b54ef179c5fa0d1694d38d4b808549a0550409), [`3da20bb8`](https://github.com/wevm/wagmi/commit/3da20bb80e7c3efeef8227ced66ad615370fc242), [`a3d1858f`](https://github.com/wevm/wagmi/commit/a3d1858fce448d2b70e36ee692ef1589b74e9d3f)]: - @wagmi/core@2.6.14 - @wagmi/connectors@4.1.23 ## 2.5.16 ### Patch Changes - [`b80236dc`](https://github.com/wevm/wagmi/commit/b80236dc623095fe8f1e1d10957d7776fb6ab48b) Thanks [@jxom](https://github.com/jxom)! - Removed unneeded `uniqueBy` check on connectors state. - Updated dependencies [[`b80236dc`](https://github.com/wevm/wagmi/commit/b80236dc623095fe8f1e1d10957d7776fb6ab48b)]: - @wagmi/core@2.6.13 - @wagmi/connectors@4.1.22 ## 2.5.15 ### Patch Changes - [#3740](https://github.com/wevm/wagmi/pull/3740) [`3373c644`](https://github.com/wevm/wagmi/commit/3373c6444c38ef16532d18cfc351b3fe2bf2d351) Thanks [@BrickheadJohnny](https://github.com/BrickheadJohnny)! - Removed unnecessary re-renders from `useConnectorClient` and `useWalletClient`. - Updated dependencies [[`a59069e9`](https://github.com/wevm/wagmi/commit/a59069e9fab45dd606bb89a7f829fe94c51a5494), [`0acd3132`](https://github.com/wevm/wagmi/commit/0acd31320f534993af566be5490c2978b6184f66)]: - @wagmi/core@2.6.12 - @wagmi/connectors@4.1.21 ## 2.5.14 ### Patch Changes - [`e1ca4e63`](https://github.com/wevm/wagmi/commit/e1ca4e637ae6cec7f5902b0a2c0e0efc3b751a1d) Thanks [@tmm](https://github.com/tmm)! - Deprecated `normalizeChainId`. Use `Number` instead. - Updated dependencies [[`e1ca4e63`](https://github.com/wevm/wagmi/commit/e1ca4e637ae6cec7f5902b0a2c0e0efc3b751a1d)]: - @wagmi/connectors@4.1.20 - @wagmi/core@2.6.11 ## 2.5.13 ### Patch Changes - [`dbdca8fd`](https://github.com/wevm/wagmi/commit/dbdca8fd14b90c166222a66a373c1b33c06ce019) Thanks [@jxom](https://github.com/jxom)! - Fixed issue where duplicate connectors could be instantiated if injected after page mount. - Updated dependencies [[`dbdca8fd`](https://github.com/wevm/wagmi/commit/dbdca8fd14b90c166222a66a373c1b33c06ce019)]: - @wagmi/core@2.6.10 - @wagmi/connectors@4.1.19 ## 2.5.12 ### Patch Changes - [#3612](https://github.com/wevm/wagmi/pull/3612) [`97237bb0`](https://github.com/wevm/wagmi/commit/97237bb05c30860b9b12c094e82a38ce59d9bedf) Thanks [@m1heng](https://github.com/m1heng)! - Added missing `functionName` parameter to `useWriteContract` codegen helper. ## 2.5.11 ### Patch Changes - [#3714](https://github.com/wevm/wagmi/pull/3714) [`f1628d65`](https://github.com/wevm/wagmi/commit/f1628d65f06e9ef18e6c4e2eb4f6e3ab2e700924) Thanks [@dalechyn](https://github.com/dalechyn)! - Replaced `Omit` with `UnionOmit` for `UseMutationReturnType`. - [#3715](https://github.com/wevm/wagmi/pull/3715) [`d56edf4f`](https://github.com/wevm/wagmi/commit/d56edf4f27c52acc7a0f57114454b0d3e22cacd6) Thanks [@jxom](https://github.com/jxom)! - Fixed SSR hydration issues. - Updated dependencies [[`d56edf4f`](https://github.com/wevm/wagmi/commit/d56edf4f27c52acc7a0f57114454b0d3e22cacd6)]: - @wagmi/core@2.6.9 - @wagmi/connectors@4.1.18 ## 2.5.10 ### Patch Changes - [#3643](https://github.com/wevm/wagmi/pull/3643) [`e46bcd47`](https://github.com/wevm/wagmi/commit/e46bcd4738a18da15b53f6612b614379c1985374) Thanks [@TateB](https://github.com/TateB)! - Fixed race condition arising from `reconnect`. - Updated dependencies [[`e46bcd47`](https://github.com/wevm/wagmi/commit/e46bcd4738a18da15b53f6612b614379c1985374)]: - @wagmi/core@2.6.8 - @wagmi/connectors@4.1.17 ## 2.5.9 ### Patch Changes - [`f5648dd2`](https://github.com/wevm/wagmi/commit/f5648dd28b3576b628f57732b89287f55acbb1c1) Thanks [@jxom](https://github.com/jxom)! - Updated `prepareTransactionRequest` types for `viem@2.8.0`. - [`1c1fee6a`](https://github.com/wevm/wagmi/commit/1c1fee6ab8f01f7734ac6ce05093fa8e388beb3e) Thanks [@jxom](https://github.com/jxom)! - Updated `@walletconnect/ethereum-provider`. - Updated dependencies [[`b479b5e8`](https://github.com/wevm/wagmi/commit/b479b5e8a5866cba792862f22e6352c4fb566137), [`f5648dd2`](https://github.com/wevm/wagmi/commit/f5648dd28b3576b628f57732b89287f55acbb1c1), [`1c1fee6a`](https://github.com/wevm/wagmi/commit/1c1fee6ab8f01f7734ac6ce05093fa8e388beb3e), [`88a2d744`](https://github.com/wevm/wagmi/commit/88a2d744a1315908c9e54156026df3ad2435ad44)]: - @wagmi/core@2.6.7 - @wagmi/connectors@4.1.16 ## 2.5.8 ### Patch Changes - Updated dependencies [[`a91c0b64`](https://github.com/wevm/wagmi/commit/a91c0b64ba8b3e6537a560e69724eb601f26af27)]: - @wagmi/core@2.6.6 - @wagmi/connectors@4.1.15 ## 2.5.7 ### Patch Changes - [#3580](https://github.com/wevm/wagmi/pull/3580) [`c677dcd2`](https://github.com/wevm/wagmi/commit/c677dcd245dccdf69289a3d66dded237b09570a2) Thanks [@tmm](https://github.com/tmm)! - Made `useSwitchChain().chains` reactive. - Updated dependencies [[`ca5decdb`](https://github.com/wevm/wagmi/commit/ca5decdb712f81e3f5dab933a94b967bca5b6af4), [`c677dcd2`](https://github.com/wevm/wagmi/commit/c677dcd245dccdf69289a3d66dded237b09570a2)]: - @wagmi/connectors@4.1.14 - @wagmi/core@2.6.5 ## 2.5.6 ### Patch Changes - Updated dependencies [[`7c6618e6`](https://github.com/wevm/wagmi/commit/7c6618e6a0eb1ff39cf8f66b34d3ddc14be538fe), [`fa25b448`](https://github.com/wevm/wagmi/commit/fa25b4482504b4d9729a5687ea6d6dc959265bc0), [`895f28e8`](https://github.com/wevm/wagmi/commit/895f28e873af7c8eda5ca85734ff67c8979fd950)]: - @wagmi/core@2.6.4 - @wagmi/connectors@4.1.13 ## 2.5.5 ### Patch Changes - Updated dependencies [[`9c3b85dd`](https://github.com/wevm/wagmi/commit/9c3b85dd0a9a4a593e1d7e029345275735330e32), [`2a72214a`](https://github.com/wevm/wagmi/commit/2a72214a2901d6b6ddd39f80238aa0bd4db670a7)]: - @wagmi/core@2.6.3 - @wagmi/connectors@4.1.12 ## 2.5.4 ### Patch Changes - [`3f8203bd`](https://github.com/wevm/wagmi/commit/3f8203bd77fcf6b6756640b5971d09741ae3853d) Thanks [@tmm](https://github.com/tmm)! - Fixed `useBlock` parameters passthrough to Viem. ## 2.5.3 ### Patch Changes - [#3518](https://github.com/wevm/wagmi/pull/3518) [`338e857d`](https://github.com/wevm/wagmi/commit/338e857d8cb2fe85e13d9207bef14cada1c1962d) Thanks [@tmm](https://github.com/tmm)! - Bumped dependencies. - Updated dependencies [[`414eb048`](https://github.com/wevm/wagmi/commit/414eb048af492caac70c0e874dfc87c30702804a), [`338e857d`](https://github.com/wevm/wagmi/commit/338e857d8cb2fe85e13d9207bef14cada1c1962d), [`338e857d`](https://github.com/wevm/wagmi/commit/338e857d8cb2fe85e13d9207bef14cada1c1962d)]: - @wagmi/core@2.6.2 - @wagmi/connectors@4.1.11 ## 2.5.2 ### Patch Changes - [#3433](https://github.com/wevm/wagmi/pull/3433) [`101a7dd1`](https://github.com/wevm/wagmi/commit/101a7dd131b0cae2dc25579ecab9044290efd37b) Thanks [@tmm](https://github.com/tmm)! - Fixed `useClient` and `usePublicClient` throwing when used with unconfigured `chainId`. - [#3510](https://github.com/wevm/wagmi/pull/3510) [`660ff80d`](https://github.com/wevm/wagmi/commit/660ff80d5b046967a446eba43ee54b8359a37d0d) Thanks [@tmm](https://github.com/tmm)! - Fixed issue where connectors returning multiple addresses didn't checksum correctly. - Updated dependencies [[`660ff80d`](https://github.com/wevm/wagmi/commit/660ff80d5b046967a446eba43ee54b8359a37d0d), [`101a7dd1`](https://github.com/wevm/wagmi/commit/101a7dd131b0cae2dc25579ecab9044290efd37b)]: - @wagmi/connectors@4.1.10 - @wagmi/core@2.6.1 ## 2.5.1 ### Patch Changes - [#3496](https://github.com/wevm/wagmi/pull/3496) [`ba7f8a75`](https://github.com/wevm/wagmi/commit/ba7f8a758efb07664c6e401b5e7e325e7c62341b) Thanks [@tmm](https://github.com/tmm)! - Bumped dependencies. - Updated dependencies [[`ba7f8a75`](https://github.com/wevm/wagmi/commit/ba7f8a758efb07664c6e401b5e7e325e7c62341b), [`ba7f8a75`](https://github.com/wevm/wagmi/commit/ba7f8a758efb07664c6e401b5e7e325e7c62341b)]: - @wagmi/connectors@4.1.9 - @wagmi/core@2.6.0 ## 2.5.0 ### Minor Changes - [#3461](https://github.com/wevm/wagmi/pull/3461) [`ca98041d`](https://github.com/wevm/wagmi/commit/ca98041d1b39893d90246929485f4db0d1c6f9f7) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Added `useTransactionConfirmations` hook. ### Patch Changes - Updated dependencies [[`ca98041d`](https://github.com/wevm/wagmi/commit/ca98041d1b39893d90246929485f4db0d1c6f9f7)]: - @wagmi/core@2.5.0 - @wagmi/connectors@4.1.8 ## 2.4.0 ### Minor Changes - [#3427](https://github.com/wevm/wagmi/pull/3427) [`370f1b4a`](https://github.com/wevm/wagmi/commit/370f1b4a3f154d181acf381c31c2e7862e22c0e4) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Added `usePrepareTransactionRequest` hook. ### Patch Changes - Updated dependencies [[`370f1b4a`](https://github.com/wevm/wagmi/commit/370f1b4a3f154d181acf381c31c2e7862e22c0e4), [`370f1b4a`](https://github.com/wevm/wagmi/commit/370f1b4a3f154d181acf381c31c2e7862e22c0e4)]: - @wagmi/connectors@4.1.7 - @wagmi/core@2.4.0 ## 2.3.1 ### Patch Changes - [#3476](https://github.com/wevm/wagmi/pull/3476) [`3be5bb7b`](https://github.com/wevm/wagmi/commit/3be5bb7b0b38646e12e6da5c762ef74dff66bcc2) Thanks [@jxom](https://github.com/jxom)! - Modified persist strategy to only store "critical" properties that are needed before hydration. - Updated dependencies [[`3be5bb7b`](https://github.com/wevm/wagmi/commit/3be5bb7b0b38646e12e6da5c762ef74dff66bcc2)]: - @wagmi/core@2.3.1 - @wagmi/connectors@4.1.6 ## 2.3.0 ### Minor Changes - [#3459](https://github.com/wevm/wagmi/pull/3459) [`d950b666`](https://github.com/wevm/wagmi/commit/d950b666b56700ca039ce16cdfdf34564991e7f5) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Added `useEnsText` action. ### Patch Changes - [#3467](https://github.com/wevm/wagmi/pull/3467) [`90ef39bb`](https://github.com/wevm/wagmi/commit/90ef39bb0f4ecb3c914d317875348e35ba0f4524) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where connectors that share the same provider instance could reconnect when they have never been connected before. - [`1cfb6e5a`](https://github.com/wevm/wagmi/commit/1cfb6e5a875e707abcee00dd5739e87da05e8c90) Thanks [@jxom](https://github.com/jxom)! - Bumped listener limit on WalletConnect connector. - Updated dependencies [[`d950b666`](https://github.com/wevm/wagmi/commit/d950b666b56700ca039ce16cdfdf34564991e7f5), [`d950b666`](https://github.com/wevm/wagmi/commit/d950b666b56700ca039ce16cdfdf34564991e7f5), [`90ef39bb`](https://github.com/wevm/wagmi/commit/90ef39bb0f4ecb3c914d317875348e35ba0f4524), [`1cfb6e5a`](https://github.com/wevm/wagmi/commit/1cfb6e5a875e707abcee00dd5739e87da05e8c90)]: - @wagmi/core@2.3.0 - @wagmi/connectors@5.0.0 ## 2.2.1 ### Patch Changes - [#3443](https://github.com/wevm/wagmi/pull/3443) [`007024a6`](https://github.com/wevm/wagmi/commit/007024a684ddbecf924cdc06dd6a8854fc3d5eeb) Thanks [@jmrossy](https://github.com/jmrossy)! - Bumped dependencies. - [#3447](https://github.com/wevm/wagmi/pull/3447) [`a02a26ad`](https://github.com/wevm/wagmi/commit/a02a26ad030d3afb78f744377d61b5c60b65d97a) Thanks [@tmm](https://github.com/tmm)! - Fixed account typing. - Updated dependencies [[`007024a6`](https://github.com/wevm/wagmi/commit/007024a684ddbecf924cdc06dd6a8854fc3d5eeb), [`a02a26ad`](https://github.com/wevm/wagmi/commit/a02a26ad030d3afb78f744377d61b5c60b65d97a), [`a02a26ad`](https://github.com/wevm/wagmi/commit/a02a26ad030d3afb78f744377d61b5c60b65d97a), [`007024a6`](https://github.com/wevm/wagmi/commit/007024a684ddbecf924cdc06dd6a8854fc3d5eeb)]: - @wagmi/connectors@4.1.4 - @wagmi/core@2.2.1 ## 2.2.0 ### Minor Changes - [#3434](https://github.com/wevm/wagmi/pull/3434) [`00bf10a4`](https://github.com/wevm/wagmi/commit/00bf10a428b0d1c5dac35ebf25b19571e033ac26) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Added `useBytecode` and `useStorageAt` hooks. - [#3408](https://github.com/wevm/wagmi/pull/3408) [`fb6c4148`](https://github.com/wevm/wagmi/commit/fb6c4148d9e9e2fccfbe74c8f343b444dc68dec5) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Added `useProof` hook. - [#3416](https://github.com/wevm/wagmi/pull/3416) [`64c073f6`](https://github.com/wevm/wagmi/commit/64c073f6c2720961e2d6aff986670b73dbfab9c3) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Added `useTransactionReceipt` hook. ### Patch Changes - Updated dependencies [[`00bf10a4`](https://github.com/wevm/wagmi/commit/00bf10a428b0d1c5dac35ebf25b19571e033ac26), [`64c073f6`](https://github.com/wevm/wagmi/commit/64c073f6c2720961e2d6aff986670b73dbfab9c3), [`fb6c4148`](https://github.com/wevm/wagmi/commit/fb6c4148d9e9e2fccfbe74c8f343b444dc68dec5)]: - @wagmi/core@2.2.0 - @wagmi/connectors@5.0.0 ## 2.1.2 ### Patch Changes - [#3407](https://github.com/wevm/wagmi/pull/3407) [`e00b8205`](https://github.com/wevm/wagmi/commit/e00b82058685751637edfa9a6b2d196a12549fe7) Thanks [@jxom](https://github.com/jxom)! - Added a prelude gas estimate check to `sendTransaction`/`useSendTransaction`. - Updated dependencies [[`e00b8205`](https://github.com/wevm/wagmi/commit/e00b82058685751637edfa9a6b2d196a12549fe7)]: - @wagmi/core@2.1.2 - @wagmi/connectors@4.1.2 ## 2.1.1 ### Patch Changes - [#3402](https://github.com/wevm/wagmi/pull/3402) [`64b82282`](https://github.com/wevm/wagmi/commit/64b82282c1e57e77c25aa0814673780e4d11edd4) Thanks [@Songkeys](https://github.com/Songkeys)! - Fixed SSR cookie support for cookies that have special characters, e.g. `=`. - [`ec0d8b41`](https://github.com/wevm/wagmi/commit/ec0d8b4112181fefb11025e436a94a6114761d37) Thanks [@tmm](https://github.com/tmm)! - Added note to `metaMask` connector. - Updated dependencies [[`64b82282`](https://github.com/wevm/wagmi/commit/64b82282c1e57e77c25aa0814673780e4d11edd4), [`ec0d8b41`](https://github.com/wevm/wagmi/commit/ec0d8b4112181fefb11025e436a94a6114761d37)]: - @wagmi/core@2.1.1 - @wagmi/connectors@4.1.1 ## 2.1.0 ### Minor Changes - [#3387](https://github.com/wevm/wagmi/pull/3387) [`c9cd302e`](https://github.com/wevm/wagmi/commit/c9cd302e1c65c980deaee2e12567c2a8ec08b399) Thanks [@marthendalnunes](https://github.com/marthendalnunes)! - Added `useCall` hook. ### Patch Changes - Updated dependencies [[`c9cd302e`](https://github.com/wevm/wagmi/commit/c9cd302e1c65c980deaee2e12567c2a8ec08b399)]: - @wagmi/core@2.1.0 - @wagmi/connectors@5.0.0 ## 2.0.3 ### Patch Changes - [#3384](https://github.com/wevm/wagmi/pull/3384) [`ee868c33`](https://github.com/wevm/wagmi/commit/ee868c3385dae511230b6ddcb5627c1293cc1844) Thanks [@tmm](https://github.com/tmm)! - Fixed connectors not bubbling error when connecting with `chainId` and subsequent user rejection. - Updated dependencies [[`ee868c33`](https://github.com/wevm/wagmi/commit/ee868c3385dae511230b6ddcb5627c1293cc1844)]: - @wagmi/connectors@4.0.2 - @wagmi/core@2.0.2 ## 2.0.2 ### Patch Changes - [#3379](https://github.com/wevm/wagmi/pull/3379) [`30a186e5`](https://github.com/wevm/wagmi/commit/30a186e53d1135657d04f72f40d1c27186025370) Thanks [@tmm](https://github.com/tmm)! - Fixed `useConnect` error getting unset. ## 2.0.1 ### Major Changes - [#3333](https://github.com/wevm/wagmi/pull/3333) [`b3a0baaa`](https://github.com/wevm/wagmi/commit/b3a0baaaee7decf750d376aab2502cd33ca4825a) Thanks [@tmm](https://github.com/tmm)! - Wagmi 2.0 featuring: - Full TanStack Query support + queryKeys - Connect multiple connectors - Switch chains while disconnected - EIP-6963 enabled - Strongly typed chainId and chain properties - Smaller bundle size - Miscellaneous improvements and bug fixes [Breaking Changes & Migration Guide](https://wagmi.sh/react/guides/migrate-from-v1-to-v2) ### Patch Changes - Updated dependencies [[`b3a0baaa`](https://github.com/wevm/wagmi/commit/b3a0baaaee7decf750d376aab2502cd33ca4825a), [`b3a0baaa`](https://github.com/wevm/wagmi/commit/b3a0baaaee7decf750d376aab2502cd33ca4825a)]: - @wagmi/connectors@4.0.0 - @wagmi/core@2.0.0 ## 1.4.13 ### Patch Changes - Updated dependencies []: - @wagmi/core@1.4.13 ## 1.4.12 ### Patch Changes - [`53ca1f7e`](https://github.com/wevm/wagmi/commit/53ca1f7eb411d912e11fcce7e03bd61ed067959c) Thanks [@tmm](https://github.com/tmm)! - Removed LedgerConnector due to security vulnerability - Updated dependencies [[`53ca1f7e`](https://github.com/wevm/wagmi/commit/53ca1f7eb411d912e11fcce7e03bd61ed067959c)]: - @wagmi/core@1.4.12 ## 1.4.11 ### Patch Changes - [#3299](https://github.com/wevm/wagmi/pull/3299) [`b02020b3`](https://github.com/wevm/wagmi/commit/b02020b3724e0228198f35817611bb063295906e) Thanks [@dasanra](https://github.com/dasanra)! - Fixed issue with [Safe SDK](https://github.com/wevm/viem/issues/579) by bumping `@safe-global/safe-apps-provider@0.18.1` - Updated dependencies [[`b02020b3`](https://github.com/wevm/wagmi/commit/b02020b3724e0228198f35817611bb063295906e)]: - @wagmi/core@1.4.11 ## 1.4.10 ### Patch Changes - Updated dependencies []: - @wagmi/core@1.4.10 ## 1.4.9 ### Patch Changes - [#3276](https://github.com/wevm/wagmi/pull/3276) [`83223a06`](https://github.com/wevm/wagmi/commit/83223a0659e2f675d897a1d3374c7af752c16abf) Thanks [@glitch-txs](https://github.com/glitch-txs)! - Removed required namespaces from WalletConnect connector - Updated dependencies [[`83223a06`](https://github.com/wevm/wagmi/commit/83223a0659e2f675d897a1d3374c7af752c16abf)]: - @wagmi/core@1.4.9 ## 1.4.8 ### Patch Changes - Updated dependencies []: - @wagmi/core@1.4.8 ## 1.4.7 ### Patch Changes - Updated dependencies []: - @wagmi/core@1.4.7 ## 1.4.6 ### Patch Changes - Updated dependencies []: - @wagmi/core@1.4.6 ## 1.4.5 ### Patch Changes - Updated dependencies []: - @wagmi/core@1.4.5 ## 1.4.4 ### Patch Changes - [#3125](https://github.com/wagmi-dev/wagmi/pull/3125) [`725e73fe`](https://github.com/wagmi-dev/wagmi/commit/725e73feb9143dbaa6d540bb76d2009cef29da0b) Thanks [@lukasrosario](https://github.com/lukasrosario)! - Fixed an issue where `dataSuffix` was not being passed down into viem's `simulateContract`, causing the data to be omitted from requests. - Updated dependencies [[`725e73fe`](https://github.com/wagmi-dev/wagmi/commit/725e73feb9143dbaa6d540bb76d2009cef29da0b)]: - @wagmi/core@1.4.4 ## 1.4.3 ### Patch Changes - [#3076](https://github.com/wagmi-dev/wagmi/pull/3076) [`4c36831b`](https://github.com/wagmi-dev/wagmi/commit/4c36831b7aa44d03b5c0decf64dcd20faae28a67) Thanks [@jxom](https://github.com/jxom)! - Pass `chain` to viem `sendTransaction`/`writeContract`. - [#3006](https://github.com/wagmi-dev/wagmi/pull/3006) [`f2ddce23`](https://github.com/wagmi-dev/wagmi/commit/f2ddce23324aff0a91e066100918dac552dc3b4a) Thanks [@jxom](https://github.com/jxom)! - Changed `normalize` to a dynamic import. - Updated dependencies [[`4c36831b`](https://github.com/wagmi-dev/wagmi/commit/4c36831b7aa44d03b5c0decf64dcd20faae28a67), [`f2ddce23`](https://github.com/wagmi-dev/wagmi/commit/f2ddce23324aff0a91e066100918dac552dc3b4a)]: - @wagmi/core@1.4.3 ## 1.4.2 ### Patch Changes - Updated dependencies []: - @wagmi/core@1.4.2 ## 1.4.1 ### Patch Changes - Updated dependencies []: - @wagmi/core@1.4.1 ## 1.4.0 ### Minor Changes - [#2956](https://github.com/wagmi-dev/wagmi/pull/2956) [`2abeb285`](https://github.com/wagmi-dev/wagmi/commit/2abeb285674af3e539cc2550b1f5027b1eb0c895) Thanks [@tmm](https://github.com/tmm)! - Replaced `@wagmi/chains` with `viem/chains`. ### Patch Changes - Updated dependencies [[`2abeb285`](https://github.com/wagmi-dev/wagmi/commit/2abeb285674af3e539cc2550b1f5027b1eb0c895)]: - @wagmi/core@1.4.0 ## 1.3.11 ### Patch Changes - [`557e6400`](https://github.com/wagmi-dev/wagmi/commit/557e6400b9cef3b2c5131739143956c37d7c934a) Thanks [@jxom](https://github.com/jxom)! - Updated references. - Updated dependencies [[`557e6400`](https://github.com/wagmi-dev/wagmi/commit/557e6400b9cef3b2c5131739143956c37d7c934a)]: - @wagmi/core@1.3.10 ## 1.3.10 ### Patch Changes - [`247c5d11`](https://github.com/wagmi-dev/wagmi/commit/247c5d113e83acf3a6894264c00d4b125d455107) Thanks [@jxom](https://github.com/jxom)! - Updated references. - Updated dependencies [[`247c5d11`](https://github.com/wagmi-dev/wagmi/commit/247c5d113e83acf3a6894264c00d4b125d455107)]: - @wagmi/core@1.3.9 ## 1.3.9 ### Patch Changes - [#2741](https://github.com/wagmi-dev/wagmi/pull/2741) [`5b1453d9`](https://github.com/wagmi-dev/wagmi/commit/5b1453d95973ed51f1c235a919fffb707eab9b70) Thanks [@jxom](https://github.com/jxom)! - Updated references - Updated dependencies [[`5b1453d9`](https://github.com/wagmi-dev/wagmi/commit/5b1453d95973ed51f1c235a919fffb707eab9b70)]: - @wagmi/core@1.3.8 ## 1.3.8 ### Patch Changes - [#2700](https://github.com/wagmi-dev/wagmi/pull/2700) [`30118e97`](https://github.com/wagmi-dev/wagmi/commit/30118e979b1b00302e035f31f58c15d1aed911d5) Thanks [@jxom](https://github.com/jxom)! - Updated references. - Updated dependencies [[`30118e97`](https://github.com/wagmi-dev/wagmi/commit/30118e979b1b00302e035f31f58c15d1aed911d5)]: - @wagmi/core@1.3.7 ## 1.3.7 ### Patch Changes - [`7ad2fdb8`](https://github.com/wagmi-dev/wagmi/commit/7ad2fdb81c7734d0c8107670800c68390e3bad99) Thanks [@jxom](https://github.com/jxom)! - Updated references. - Updated dependencies [[`7ad2fdb8`](https://github.com/wagmi-dev/wagmi/commit/7ad2fdb81c7734d0c8107670800c68390e3bad99)]: - @wagmi/core@1.3.6 ## 1.3.6 ### Patch Changes - [`aab63fc1`](https://github.com/wagmi-dev/wagmi/commit/aab63fc1f8949004573978ecd8574fada3360758) Thanks [@jxom](https://github.com/jxom)! - Updated references. - Updated dependencies [[`aab63fc1`](https://github.com/wagmi-dev/wagmi/commit/aab63fc1f8949004573978ecd8574fada3360758)]: - @wagmi/core@1.3.5 ## 1.3.5 ### Patch Changes - [#2669](https://github.com/wagmi-dev/wagmi/pull/2669) [`db75c459`](https://github.com/wagmi-dev/wagmi/commit/db75c4593b9c46970dc9d3c96d7adafc76878fc3) Thanks [@llllvvuu](https://github.com/llllvvuu)! - Modified `useAccount` and `useNetwork` to be reactive of wagmi Config (`config`). ## 1.3.4 ### Patch Changes - [`b056f809`](https://github.com/wagmi-dev/wagmi/commit/b056f8095674d4addc6ecd09adf6001fe52e2b15) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where `onConnect` was not being called when multiple instances of `useAccount` existed. - [`22246d98`](https://github.com/wagmi-dev/wagmi/commit/22246d9884277d28ccad6ca2d9529b96b67d47fc) Thanks [@jxom](https://github.com/jxom)! - Updated references. - Updated dependencies [[`22246d98`](https://github.com/wagmi-dev/wagmi/commit/22246d9884277d28ccad6ca2d9529b96b67d47fc)]: - @wagmi/core@1.3.4 ## 1.3.3 ### Patch Changes - [`1946aa43`](https://github.com/wagmi-dev/wagmi/commit/1946aa43a65b684ef41b7b4c43c67bf29c13e854) Thanks [@jxom](https://github.com/jxom)! - Updated references - Updated dependencies [[`1946aa43`](https://github.com/wagmi-dev/wagmi/commit/1946aa43a65b684ef41b7b4c43c67bf29c13e854)]: - @wagmi/core@1.3.3 ## 1.3.2 ### Patch Changes - [`e86d0940`](https://github.com/wagmi-dev/wagmi/commit/e86d09409bb20b64d24e1263abcf0291314f03c7) Thanks [@jxom](https://github.com/jxom)! - Updated references - Updated dependencies [[`e86d0940`](https://github.com/wagmi-dev/wagmi/commit/e86d09409bb20b64d24e1263abcf0291314f03c7)]: - @wagmi/core@1.3.2 ## 1.3.1 ### Patch Changes - [`964042fa`](https://github.com/wagmi-dev/wagmi/commit/964042fa94d682977923c595820c58283fb9244a) Thanks [@jxom](https://github.com/jxom)! - Updated references. - Updated dependencies [[`964042fa`](https://github.com/wagmi-dev/wagmi/commit/964042fa94d682977923c595820c58283fb9244a)]: - @wagmi/core@1.3.1 ## 1.3.0 ### Minor Changes - [#2619](https://github.com/wagmi-dev/wagmi/pull/2619) [`0d79748c`](https://github.com/wagmi-dev/wagmi/commit/0d79748cec2b6ac2410ad2c9816cc662f2b70962) Thanks [@jxom](https://github.com/jxom)! - Updated references: - Updated `@safe-global/safe-apps-sdk` to `^8.0.0` (the one with `viem` support) ### Patch Changes - Updated dependencies [[`0d79748c`](https://github.com/wagmi-dev/wagmi/commit/0d79748cec2b6ac2410ad2c9816cc662f2b70962)]: - @wagmi/core@1.3.0 ## 1.2.2 ### Patch Changes - [#2611](https://github.com/wagmi-dev/wagmi/pull/2611) [`6d1ed7a1`](https://github.com/wagmi-dev/wagmi/commit/6d1ed7a156729b4df5d66fef3ae9a8b5762a2d34) Thanks [@jxom](https://github.com/jxom)! - Updated references. - Updated dependencies [[`6d1ed7a1`](https://github.com/wagmi-dev/wagmi/commit/6d1ed7a156729b4df5d66fef3ae9a8b5762a2d34)]: - @wagmi/core@1.2.2 ## 1.2.1 ### Patch Changes - [#2589](https://github.com/wagmi-dev/wagmi/pull/2589) [`9680c347`](https://github.com/wagmi-dev/wagmi/commit/9680c347476500d28ceca20d23eeaed7931cb6e0) Thanks [@jxom](https://github.com/jxom)! - Fixed `writeContract` parameters to be compatible with `prepareWriteContract`. - [#2587](https://github.com/wagmi-dev/wagmi/pull/2587) [`cfff9994`](https://github.com/wagmi-dev/wagmi/commit/cfff999459384ac644ff7e62f53a7b787cf37507) Thanks [@jxom](https://github.com/jxom)! - Updated references - Updated dependencies [[`9680c347`](https://github.com/wagmi-dev/wagmi/commit/9680c347476500d28ceca20d23eeaed7931cb6e0), [`cfff9994`](https://github.com/wagmi-dev/wagmi/commit/cfff999459384ac644ff7e62f53a7b787cf37507)]: - @wagmi/core@1.2.1 ## 1.2.0 ### Minor Changes - [#2536](https://github.com/wagmi-dev/wagmi/pull/2536) [`85e9760a`](https://github.com/wagmi-dev/wagmi/commit/85e9760a140cb169ac6236d9466b96e2105dd193) Thanks [@tmm](https://github.com/tmm)! - Changed `Address` type import from ABIType to viem. ### Patch Changes - [#2539](https://github.com/wagmi-dev/wagmi/pull/2539) [`96319c64`](https://github.com/wagmi-dev/wagmi/commit/96319c640b9d07b375821c08a5c213355d8c290b) Thanks [@jxom](https://github.com/jxom)! - Updated references - Updated dependencies [[`85e9760a`](https://github.com/wagmi-dev/wagmi/commit/85e9760a140cb169ac6236d9466b96e2105dd193), [`96319c64`](https://github.com/wagmi-dev/wagmi/commit/96319c640b9d07b375821c08a5c213355d8c290b)]: - @wagmi/core@1.2.0 ## 1.1.1 ### Patch Changes - [`02b98a9f`](https://github.com/wagmi-dev/wagmi/commit/02b98a9f9b2c503a47af4a8967e0202b5db21787) Thanks [@jxom](https://github.com/jxom)! - Updated `viem` peer dependency. - [`02b98a9f`](https://github.com/wagmi-dev/wagmi/commit/02b98a9f9b2c503a47af4a8967e0202b5db21787) Thanks [@jxom](https://github.com/jxom)! - Updated references. - Updated dependencies [[`02b98a9f`](https://github.com/wagmi-dev/wagmi/commit/02b98a9f9b2c503a47af4a8967e0202b5db21787), [`02b98a9f`](https://github.com/wagmi-dev/wagmi/commit/02b98a9f9b2c503a47af4a8967e0202b5db21787)]: - @wagmi/core@1.1.1 ## 1.1.0 ### Minor Changes - [#2482](https://github.com/wagmi-dev/wagmi/pull/2482) [`8764b54a`](https://github.com/wagmi-dev/wagmi/commit/8764b54aab68020063946112e8fe52aff650c99c) Thanks [@tmm](https://github.com/tmm)! - Bumped minimum TypeScript version to v5.0.4. ### Patch Changes - [#2471](https://github.com/wagmi-dev/wagmi/pull/2471) [`74099cef`](https://github.com/wagmi-dev/wagmi/commit/74099cefd922317641529f7881a4c8a740d62cbe) Thanks [@iuriiiurevich](https://github.com/iuriiiurevich)! - Added `keepPreviousData` prop to `useContractRead`. - [#2484](https://github.com/wagmi-dev/wagmi/pull/2484) [`3adf1f4f`](https://github.com/wagmi-dev/wagmi/commit/3adf1f4feab863cb7b5d52c81ad46f7e4eb56f09) Thanks [@jxom](https://github.com/jxom)! - Updated `abitype` to 0.8.7 - [#2484](https://github.com/wagmi-dev/wagmi/pull/2484) [`3adf1f4f`](https://github.com/wagmi-dev/wagmi/commit/3adf1f4feab863cb7b5d52c81ad46f7e4eb56f09) Thanks [@jxom](https://github.com/jxom)! - Updated references. - [`01d4a6ed`](https://github.com/wagmi-dev/wagmi/commit/01d4a6ed53110712692599095d94f04dfb5b6e38) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where `useInvalidateOnBlock`'s `onBlock` was being called on every render. - Updated dependencies [[`8764b54a`](https://github.com/wagmi-dev/wagmi/commit/8764b54aab68020063946112e8fe52aff650c99c), [`3adf1f4f`](https://github.com/wagmi-dev/wagmi/commit/3adf1f4feab863cb7b5d52c81ad46f7e4eb56f09), [`3adf1f4f`](https://github.com/wagmi-dev/wagmi/commit/3adf1f4feab863cb7b5d52c81ad46f7e4eb56f09)]: - @wagmi/core@1.1.0 ## 1.0.9 ### Patch Changes - [#2446](https://github.com/wagmi-dev/wagmi/pull/2446) [`899d8c06`](https://github.com/wagmi-dev/wagmi/commit/899d8c0698e6cc958ca8ad9ec586883edf20516e) Thanks [@iuriiiurevich](https://github.com/iuriiiurevich)! - Added `cancelRefetch: false` to `useInvalidateOnBlock`. ## 1.0.8 ### Patch Changes - [#2441](https://github.com/wagmi-dev/wagmi/pull/2441) [`326edee4`](https://github.com/wagmi-dev/wagmi/commit/326edee4bc85db84a7a4e3768e33785849ab8d8e) Thanks [@tmm](https://github.com/tmm)! - Fixed internal type issue - Updated dependencies [[`326edee4`](https://github.com/wagmi-dev/wagmi/commit/326edee4bc85db84a7a4e3768e33785849ab8d8e)]: - @wagmi/core@1.0.8 ## 1.0.7 ### Patch Changes - [#2433](https://github.com/wagmi-dev/wagmi/pull/2433) [`54fcff5f`](https://github.com/wagmi-dev/wagmi/commit/54fcff5f02f6933bbbe045ee0c83c5a78b6bba49) Thanks [@jxom](https://github.com/jxom)! - Added ability to pass an `account` to `useContractWrite`/`usePrepareContractWrite`. - Updated dependencies [[`54fcff5f`](https://github.com/wagmi-dev/wagmi/commit/54fcff5f02f6933bbbe045ee0c83c5a78b6bba49)]: - @wagmi/core@1.0.7 ## 1.0.6 ### Patch Changes - [`ca2e1e96`](https://github.com/wagmi-dev/wagmi/commit/ca2e1e96149b87a7dc42c9db07e1f1ad2bb02c4a) Thanks [@jxom](https://github.com/jxom)! - Updated references. - [#2401](https://github.com/wagmi-dev/wagmi/pull/2401) [`0f9dc875`](https://github.com/wagmi-dev/wagmi/commit/0f9dc875e90cfdd7a2028e04b7204caf9ea313b2) Thanks [@jxom](https://github.com/jxom)! - Exposed `account` on `readContract`/`useContractRead`. - Updated dependencies [[`ca2e1e96`](https://github.com/wagmi-dev/wagmi/commit/ca2e1e96149b87a7dc42c9db07e1f1ad2bb02c4a), [`0f9dc875`](https://github.com/wagmi-dev/wagmi/commit/0f9dc875e90cfdd7a2028e04b7204caf9ea313b2)]: - @wagmi/core@1.0.6 ## 1.0.5 ### Patch Changes - [`90e2b3b3`](https://github.com/wagmi-dev/wagmi/commit/90e2b3b39efe0585fe28645ac2264109be17362a) Thanks [@jxom](https://github.com/jxom)! - Updated references. - Updated dependencies [[`90e2b3b3`](https://github.com/wagmi-dev/wagmi/commit/90e2b3b39efe0585fe28645ac2264109be17362a)]: - @wagmi/core@1.0.5 ## 1.0.4 ### Patch Changes - [#2344](https://github.com/wagmi-dev/wagmi/pull/2344) [`8a725458`](https://github.com/wagmi-dev/wagmi/commit/8a72545853ae1024acd9efd18c06142e8c6c5750) Thanks [@jxom](https://github.com/jxom)! - Added gas estimation back into `prepareSendTransaction`. - Updated dependencies [[`8a725458`](https://github.com/wagmi-dev/wagmi/commit/8a72545853ae1024acd9efd18c06142e8c6c5750)]: - @wagmi/core@1.0.4 ## 1.0.3 ### Patch Changes - [#2338](https://github.com/wagmi-dev/wagmi/pull/2338) [`92bfdc2c`](https://github.com/wagmi-dev/wagmi/commit/92bfdc2c744539558ba93c95f140b46ad331cee4) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where synchronous switch chain behavior (WalletConnect v2) would encounter chain id race conditions in `watchWalletClient`. - Updated dependencies [[`92bfdc2c`](https://github.com/wagmi-dev/wagmi/commit/92bfdc2c744539558ba93c95f140b46ad331cee4)]: - @wagmi/core@1.0.3 ## 1.0.2 ### Patch Changes - Updated dependencies [[`09a4fd38`](https://github.com/wevm/wagmi/commit/09a4fd38f44eb176797925fd85314be17b610cd4)]: - @wagmi/core@1.0.2 ## 1.0.1 ### Patch Changes - [`ea651cd7`](https://github.com/wevm/wagmi/commit/ea651cd7fc75b7866272605467db11fd6e1d81af) Thanks [@jxom](https://github.com/jxom)! - Downgraded abitype. - Updated dependencies [[`ea651cd7`](https://github.com/wevm/wagmi/commit/ea651cd7fc75b7866272605467db11fd6e1d81af)]: - @wagmi/core@1.0.1 ## 1.0.0 ### Major Changes - [#2235](https://github.com/wevm/wagmi/pull/2235) [`5be0655c`](https://github.com/wevm/wagmi/commit/5be0655c8e48b25d38009022461fbf611af54349) Thanks [@jxom](https://github.com/jxom)! - Released v1. Read [Migration Guide](https://next.wagmi.sh/react/migration-guide#1xx-breaking-changes). ### Patch Changes - Updated dependencies [[`5be0655c`](https://github.com/wevm/wagmi/commit/5be0655c8e48b25d38009022461fbf611af54349)]: - @wagmi/core@1.0.0 ## 1.0.0-next.9 ### Patch Changes - Fixed `useContractEvent` effect dependencies. ## 1.0.0-next.8 ### Patch Changes - Added "use client" banner ## 1.0.0-next.7 ### Major Changes - [#2235](https://github.com/wevm/wagmi/pull/2235) [`708b2ce2`](https://github.com/wevm/wagmi/commit/708b2ce26efa8d3d910806a97cea5171dabc65de) Thanks [@jxom](https://github.com/jxom)! - Added `config.setPublicClient` & `config.setWebSocketPublicClient` - Updated references. ### Patch Changes - Updated dependencies [[`708b2ce2`](https://github.com/wevm/wagmi/commit/708b2ce26efa8d3d910806a97cea5171dabc65de)]: - @wagmi/core@1.0.0-next.7 ## 1.0.0-next.6 ### Major Changes - Added `config.setConnectors` ### Patch Changes - Updated dependencies [[`708b2ce2`](https://github.com/wevm/wagmi/commit/708b2ce26efa8d3d910806a97cea5171dabc65de)]: - @wagmi/core@1.0.0-next.6 ## 1.0.0-next.5 ### Major Changes - [#2235](https://github.com/wevm/wagmi/pull/2235) [`708b2ce2`](https://github.com/wevm/wagmi/commit/708b2ce26efa8d3d910806a97cea5171dabc65de) Thanks [@jxom](https://github.com/jxom)! - Added `config.setPublicClient` & `config.setWebSocketPublicClient` ### Patch Changes - Updated dependencies [[`708b2ce2`](https://github.com/wevm/wagmi/commit/708b2ce26efa8d3d910806a97cea5171dabc65de)]: - @wagmi/core@1.0.0-next.5 ## 1.0.0-next.4 ### Major Changes - Updated viem. Removed `goerli` export from main entrypoint. ### Patch Changes - Updated dependencies []: - @wagmi/core@1.0.0-next.4 ## 1.0.0-next.3 ### Major Changes - Updated references. ### Patch Changes - Updated dependencies []: - @wagmi/core@1.0.0-next.3 ## 1.0.0-next.2 ### Major Changes - **Breaking:** Renamed `createClient` to `createConfig` - **Breaking:** Renamed `useClient` to `useConfig` - **Breaking:** Removed `request` as an argument to `usePrepareSendTransaction` & `useSendTransaction`. Arguments now belong on the root level of the Hook. ### Patch Changes - Updated dependencies []: - @wagmi/core@1.0.0-next.2 ## 1.0.0-next.1 ### Major Changes - updated viem ### Patch Changes - Updated dependencies []: - @wagmi/core@1.0.0-next.1 ## 1.0.0-next.0 ### Major Changes - [`a7dda00c`](https://github.com/wevm/wagmi/commit/a7dda00c5b546f8b2c42b527e4d9ac1b9e9ab1fb) Thanks [@jxom](https://github.com/jxom)! - Released v1. ### Patch Changes - Updated dependencies [[`a7dda00c`](https://github.com/wevm/wagmi/commit/a7dda00c5b546f8b2c42b527e4d9ac1b9e9ab1fb)]: - @wagmi/core@1.0.0-next.0 ## 0.12.13 ### Patch Changes - [#2270](https://github.com/wevm/wagmi/pull/2270) [`6d1fa9df`](https://github.com/wevm/wagmi/commit/6d1fa9df790287729c3b33d4f01fd23c2f8153f1) Thanks [@jxom](https://github.com/jxom)! - Updated references. - Updated dependencies [[`6d1fa9df`](https://github.com/wevm/wagmi/commit/6d1fa9df790287729c3b33d4f01fd23c2f8153f1)]: - @wagmi/core@0.10.11 ## 0.12.12 ### Patch Changes - [#2208](https://github.com/wevm/wagmi/pull/2208) [`cfc696d8`](https://github.com/wevm/wagmi/commit/cfc696d83c6f768a2e1a29c5197efeed7f1d40a1) Thanks [@bangtoven](https://github.com/bangtoven)! - Bumped references to apply coinbase wallet sdk updates - Updated dependencies [[`cfc696d8`](https://github.com/wevm/wagmi/commit/cfc696d83c6f768a2e1a29c5197efeed7f1d40a1)]: - @wagmi/core@0.10.10 ## 0.12.11 ### Patch Changes - [#2203](https://github.com/wevm/wagmi/pull/2203) [`a4ca4b05`](https://github.com/wevm/wagmi/commit/a4ca4b05c5bd20c20c5d0741bfb18f2c798b9529) Thanks [@tmm](https://github.com/tmm)! - Downgraded abitype. ## 0.12.10 ### Patch Changes - [#2143](https://github.com/wevm/wagmi/pull/2143) [`26dc5326`](https://github.com/wevm/wagmi/commit/26dc53260fde1d3278018c0b20a6d48a093d9427) Thanks [@tmm](https://github.com/tmm)! - Exported Sepolia Chain. - [#2146](https://github.com/wevm/wagmi/pull/2146) [`21b6842e`](https://github.com/wevm/wagmi/commit/21b6842e8c296a0bbe71ebe0780d898abc4cf4a8) Thanks [@tmm](https://github.com/tmm)! - Bumped references - Updated dependencies [[`26dc5326`](https://github.com/wevm/wagmi/commit/26dc53260fde1d3278018c0b20a6d48a093d9427), [`21b6842e`](https://github.com/wevm/wagmi/commit/21b6842e8c296a0bbe71ebe0780d898abc4cf4a8)]: - @wagmi/core@0.10.9 ## 0.12.9 ### Patch Changes - [#2120](https://github.com/wevm/wagmi/pull/2120) [`664c2b16`](https://github.com/wevm/wagmi/commit/664c2b1690bdce1ad7a619ac8f673c168dec6529) Thanks [@jxom](https://github.com/jxom)! - Bumped React Query & ABIType dependencies ## 0.12.8 ### Patch Changes - [#2099](https://github.com/wevm/wagmi/pull/2099) [`f1fee5b3`](https://github.com/wevm/wagmi/commit/f1fee5b30a1bd13b5e66118bf9cdc44b0dc003a1) Thanks [@jxom](https://github.com/jxom)! - Added chains: - `nexi` - `polygonZkEvm` - `xdc` - `xdcTestnet` - [#2085](https://github.com/wevm/wagmi/pull/2085) [`7d64e3f5`](https://github.com/wevm/wagmi/commit/7d64e3f538a6149777bfa84ea9435769b2a7db58) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where multicall would not throw if the target chain was not configured on the wagmi client. - Updated dependencies [[`f1fee5b3`](https://github.com/wevm/wagmi/commit/f1fee5b30a1bd13b5e66118bf9cdc44b0dc003a1), [`7d64e3f5`](https://github.com/wevm/wagmi/commit/7d64e3f538a6149777bfa84ea9435769b2a7db58)]: - @wagmi/core@0.10.8 ## 0.12.7 ### Patch Changes - [#2082](https://github.com/wevm/wagmi/pull/2082) [`2ccc8a25`](https://github.com/wevm/wagmi/commit/2ccc8a255e93f0a2bb7b22101656b3905ec59abd) Thanks [@jxom](https://github.com/jxom)! - Updated references. - Updated dependencies [[`2ccc8a25`](https://github.com/wevm/wagmi/commit/2ccc8a255e93f0a2bb7b22101656b3905ec59abd)]: - @wagmi/core@0.10.7 ## 0.12.6 ### Patch Changes - [#2056](https://github.com/wevm/wagmi/pull/2056) [`944f6513`](https://github.com/wevm/wagmi/commit/944f6513adf09a6f0b3bd34f591d3bbd1f1ffd2e) Thanks [@tmm](https://github.com/tmm)! - Bumped references. - Updated dependencies [[`944f6513`](https://github.com/wevm/wagmi/commit/944f6513adf09a6f0b3bd34f591d3bbd1f1ffd2e)]: - @wagmi/core@0.10.6 ## 0.12.5 ### Patch Changes - [#2053](https://github.com/wevm/wagmi/pull/2053) [`665df1bf`](https://github.com/wevm/wagmi/commit/665df1bf2afccb533102069def395e19fb7194dd) Thanks [@tmm](https://github.com/tmm)! - Fixed issue where you add a new chain to MetaMask, but the switch after is rejected. - Updated dependencies [[`665df1bf`](https://github.com/wevm/wagmi/commit/665df1bf2afccb533102069def395e19fb7194dd)]: - @wagmi/core@0.10.5 ## 0.12.4 ### Patch Changes - [#2046](https://github.com/wevm/wagmi/pull/2046) [`90d8e9b8`](https://github.com/wevm/wagmi/commit/90d8e9b87962b72c54311649537e91a953660f9b) Thanks [@tmm](https://github.com/tmm)! - Exported internal type. - Updated dependencies [[`90d8e9b8`](https://github.com/wevm/wagmi/commit/90d8e9b87962b72c54311649537e91a953660f9b)]: - @wagmi/core@0.10.4 ## 0.12.3 ### Patch Changes - [#2039](https://github.com/wevm/wagmi/pull/2039) [`bac893ab`](https://github.com/wevm/wagmi/commit/bac893ab26012d4d8741c4f80e8b8813aee26f0c) Thanks [@tmm](https://github.com/tmm)! - Updated references. - [#2043](https://github.com/wevm/wagmi/pull/2043) [`49a58320`](https://github.com/wevm/wagmi/commit/49a58320ab5f1f13bc4de25abcc028c8335e98f0) Thanks [@tmm](https://github.com/tmm)! - Removed `InjectedConnector` `shimChainChangedDisconnect` shim (no longer necessary). - [#2042](https://github.com/wevm/wagmi/pull/2042) [`e7ac7afc`](https://github.com/wevm/wagmi/commit/e7ac7afccb005e8d208c78d55b1fec979b8522a6) Thanks [@tmm](https://github.com/tmm)! - Fixed exposed types that weren't passed down. - Updated dependencies [[`bac893ab`](https://github.com/wevm/wagmi/commit/bac893ab26012d4d8741c4f80e8b8813aee26f0c), [`49a58320`](https://github.com/wevm/wagmi/commit/49a58320ab5f1f13bc4de25abcc028c8335e98f0)]: - @wagmi/core@0.10.3 ## 0.12.2 ### Patch Changes - [#2016](https://github.com/wevm/wagmi/pull/2016) [`06bf61de`](https://github.com/wevm/wagmi/commit/06bf61dee6d2920777bd9392491e6b7aedebe7ab) Thanks [@jxom](https://github.com/jxom)! - Added chains: - `boba` - `chronos` - `crossbell` - `dfk` - `dogechain` - `flare` - `flareTestnet` - `klaytn` - `scrollTestnet` - `shardeumSphinx` - `skaleCalypso` - `skaleCalypsoTestnet` - `skaleChaosTestnet` - `skaleCryptoBlades` - `skaleCryptoColosseum` - `skaleEuropa` - `skaleEuropaTestnet` - `skaleExorde` - `skaleHumanProtocol` - `skaleNebula` - `skaleNebulaTestnet` - `skaleRazor` - `skaleTitan` - `skaleTitanTestnet` - `songbird` - `songbirdTestnet` - `titan` - `titanTestnet` - `wanchain` - `wanchainTestnet` - [#2016](https://github.com/wevm/wagmi/pull/2016) [`06bf61de`](https://github.com/wevm/wagmi/commit/06bf61dee6d2920777bd9392491e6b7aedebe7ab) Thanks [@jxom](https://github.com/jxom)! - Updated references/ submodule. - Updated dependencies [[`06bf61de`](https://github.com/wevm/wagmi/commit/06bf61dee6d2920777bd9392491e6b7aedebe7ab), [`06bf61de`](https://github.com/wevm/wagmi/commit/06bf61dee6d2920777bd9392491e6b7aedebe7ab)]: - @wagmi/core@0.10.2 ## 0.12.0 ### Minor Changes - [#1902](https://github.com/wevm/wagmi/pull/1902) [`0994e896`](https://github.com/wevm/wagmi/commit/0994e8966349b8811db0a5886db3831dafc99245) Thanks [@jxom](https://github.com/jxom)! - **Breaking:** Removed the `version` config option for `WalletConnectConnector`. `WalletConnectConnector` now uses WalletConnect v2 by default. WalletConnect v1 is now `WalletConnectLegacyConnector`. ### WalletConnect v2 ```diff import { WalletConnectConnector } from 'wagmi/connectors/walletConnect' const connector = new WalletConnectConnector({ options: { - version: '2', projectId: 'abc', }, }) ``` ### WalletConnect v1 ```diff -import { WalletConnectConnector } from 'wagmi/connectors/walletConnect' +import { WalletConnectConnector } from 'wagmi/connectors/walletConnectLegacy' -const connector = new WalletConnectConnector({ +const connector = new WalletConnectLegacyConnector({ options: { qrcode: true, }, }) ``` ### Patch Changes - Updated dependencies [[`0994e896`](https://github.com/wevm/wagmi/commit/0994e8966349b8811db0a5886db3831dafc99245)]: - @wagmi/core@0.10.0 ## 0.11.7 ### Patch Changes - [#1907](https://github.com/wevm/wagmi/pull/1907) [`cc4e74ee`](https://github.com/wevm/wagmi/commit/cc4e74ee19665eccb3767052dab6ab956ff4e676) Thanks [@jxom](https://github.com/jxom)! - Added the following chains to the `wagmi/chains` entrypoint: - `baseGoerli` - `harmonyOne` - `polygonZkEvmTestnet` - Updated dependencies [[`cc4e74ee`](https://github.com/wevm/wagmi/commit/cc4e74ee19665eccb3767052dab6ab956ff4e676)]: - @wagmi/core@0.9.7 ## 0.11.6 ### Patch Changes - [#1882](https://github.com/wevm/wagmi/pull/1882) [`282cc1b0`](https://github.com/wevm/wagmi/commit/282cc1b02003684d582cea411b11792a59c26fd0) Thanks [@tmm](https://github.com/tmm)! - Updated references. - Updated dependencies [[`282cc1b0`](https://github.com/wevm/wagmi/commit/282cc1b02003684d582cea411b11792a59c26fd0)]: - @wagmi/core@0.9.6 ## 0.11.5 ### Patch Changes - [#1812](https://github.com/wevm/wagmi/pull/1812) [`c7fd7fbd`](https://github.com/wevm/wagmi/commit/c7fd7fbde6f6c69a3a9a4f89d948c4dfb1d22679) Thanks [@jxom](https://github.com/jxom)! - Added the following chains to the `wagmi/chains` entrypoint: - `filecoinCalibration` - `moonbaseAlpha` - `moonbeam` - `moonriver` - Updated dependencies [[`c7fd7fbd`](https://github.com/wevm/wagmi/commit/c7fd7fbde6f6c69a3a9a4f89d948c4dfb1d22679)]: - @wagmi/core@0.9.5 ## 0.11.4 ### Patch Changes - [#1679](https://github.com/wevm/wagmi/pull/1679) [`3cef111b`](https://github.com/wevm/wagmi/commit/3cef111b1e30120233d8754b33587cdf94aedd8f) Thanks [@aj-may](https://github.com/aj-may)! - Fixed `useAccount` `onConnect` and `onDisconnect` callbacks for React Strict Mode. - [#1786](https://github.com/wevm/wagmi/pull/1786) [`b173a431`](https://github.com/wevm/wagmi/commit/b173a43165c7925a4e56ce1e0327a31917e7edc5) Thanks [@tmm](https://github.com/tmm)! - Locked ethers peer dependency version to >=5.5.1 <6 - [#1787](https://github.com/wevm/wagmi/pull/1787) [`f023fd8f`](https://github.com/wevm/wagmi/commit/f023fd8f66befb78b9a4df5ca971ceaa64e37ab4) Thanks [@tmm](https://github.com/tmm)! - Added `SafeConnector` - Updated dependencies [[`b173a431`](https://github.com/wevm/wagmi/commit/b173a43165c7925a4e56ce1e0327a31917e7edc5), [`f023fd8f`](https://github.com/wevm/wagmi/commit/f023fd8f66befb78b9a4df5ca971ceaa64e37ab4)]: - @wagmi/core@0.9.4 ## 0.11.3 ### Patch Changes - [#1773](https://github.com/wevm/wagmi/pull/1773) [`9aaf1955`](https://github.com/wevm/wagmi/commit/9aaf195514d3b5f4d085c797fc5021d42a9efb6c) Thanks [@jxom](https://github.com/jxom)! - Updated `@walletconnect/universal-provider` on `WalletConnectConnector` v2. Added more signable methods to `WalletConnectConnector` v2. - [#1773](https://github.com/wevm/wagmi/pull/1773) [`9aaf1955`](https://github.com/wevm/wagmi/commit/9aaf195514d3b5f4d085c797fc5021d42a9efb6c) Thanks [@jxom](https://github.com/jxom)! - Added Telos to the `wagmi/chains` entrypoint. Thanks @donnyquixotic! - Updated dependencies [[`9aaf1955`](https://github.com/wevm/wagmi/commit/9aaf195514d3b5f4d085c797fc5021d42a9efb6c), [`9aaf1955`](https://github.com/wevm/wagmi/commit/9aaf195514d3b5f4d085c797fc5021d42a9efb6c)]: - @wagmi/core@0.9.3 ## 0.11.2 ### Patch Changes - [#1756](https://github.com/wevm/wagmi/pull/1756) [`31d06b8c`](https://github.com/wevm/wagmi/commit/31d06b8ce1e7af5e9d1a7ba57f1743b2dff7a53d) Thanks [@jxom](https://github.com/jxom)! - Added OKC Chain. Thanks @clark-cui! - [#1756](https://github.com/wevm/wagmi/pull/1756) [`31d06b8c`](https://github.com/wevm/wagmi/commit/31d06b8ce1e7af5e9d1a7ba57f1743b2dff7a53d) Thanks [@jxom](https://github.com/jxom)! - Fixed race condition between `switchNetwork` and mutation Actions that use `chainId` (e.g. `sendTransaction`). Thanks @DanInTheD4rk! - Updated dependencies [[`31d06b8c`](https://github.com/wevm/wagmi/commit/31d06b8ce1e7af5e9d1a7ba57f1743b2dff7a53d), [`31d06b8c`](https://github.com/wevm/wagmi/commit/31d06b8ce1e7af5e9d1a7ba57f1743b2dff7a53d)]: - @wagmi/core@0.9.2 ## 0.11.1 ### Patch Changes - [#1752](https://github.com/wevm/wagmi/pull/1752) [`144a0e76`](https://github.com/wevm/wagmi/commit/144a0e76ef4bb9ba0650b5ffb9c63f95329819a4) Thanks [@jxom](https://github.com/jxom)! - Improved `WalletConnectConnector` (v2) initialization & updated dependencies. - [#1752](https://github.com/wevm/wagmi/pull/1752) [`144a0e76`](https://github.com/wevm/wagmi/commit/144a0e76ef4bb9ba0650b5ffb9c63f95329819a4) Thanks [@jxom](https://github.com/jxom)! - Added the following chains to the `wagmi/chains` entrypoint: - Aurora – thanks @salil-naik - Bronos – thanks @chedetinaveen - Canto – thanks @tster - Celo – thanks @aaronmgdr - Updated dependencies [[`144a0e76`](https://github.com/wevm/wagmi/commit/144a0e76ef4bb9ba0650b5ffb9c63f95329819a4), [`144a0e76`](https://github.com/wevm/wagmi/commit/144a0e76ef4bb9ba0650b5ffb9c63f95329819a4)]: - @wagmi/core@0.9.1 ## 0.11.0 ### Minor Changes - [#1732](https://github.com/wevm/wagmi/pull/1732) [`01e21897`](https://github.com/wevm/wagmi/commit/01e2189747a5c22dc758c6d719b4145adc2a643c) Thanks [@tmm](https://github.com/tmm)! - Bumped minimum TypeScript version to typescript@>=4.9.4. TypeScript 5.0 is coming soon and has some great features we are excited to bring into wagmi. To prepare for this, update your TypeScript version to 4.9.4 or higher. There are likely no [breaking changes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#correctness-fixes-and-breaking-changes) if you are coming from typescript@4.7.x || typescript@4.8.x. ### Patch Changes - Updated dependencies [[`01e21897`](https://github.com/wevm/wagmi/commit/01e2189747a5c22dc758c6d719b4145adc2a643c)]: - @wagmi/core@0.9.0 ## 0.10.15 ### Patch Changes - [#1718](https://github.com/wevm/wagmi/pull/1718) [`e62b5ef8`](https://github.com/wevm/wagmi/commit/e62b5ef8aaa8063abb5264790768899ea35bbd31) Thanks [@tmm](https://github.com/tmm)! - Updated references - Updated dependencies [[`e62b5ef8`](https://github.com/wevm/wagmi/commit/e62b5ef8aaa8063abb5264790768899ea35bbd31)]: - @wagmi/core@0.8.19 ## 0.10.14 ### Patch Changes - [#1708](https://github.com/wevm/wagmi/pull/1708) [`07fc3801`](https://github.com/wevm/wagmi/commit/07fc3801fa13c2cb5f7cf9b86ba8320b05a6a135) Thanks [@jxom](https://github.com/jxom)! - Updated `references/` submodule. - Updated dependencies [[`07fc3801`](https://github.com/wevm/wagmi/commit/07fc3801fa13c2cb5f7cf9b86ba8320b05a6a135)]: - @wagmi/core@0.8.18 ## 0.10.13 ### Patch Changes - [#1705](https://github.com/wevm/wagmi/pull/1705) [`9ff797dc`](https://github.com/wevm/wagmi/commit/9ff797dcb979dc86b798a432b74c98598165430d) Thanks [@jxom](https://github.com/jxom)! - Added the following chains to the `wagmi/chains` entrypoint: - `crossbell` (thanks @Songkeys) - `filecoin` & `filecoinHyperspace` (thanks @neil0x46dc) - `gnosisChiado` (thanks @theNvN) - `metis` & `metisGoerli` (thanks @CookedCookee) - Updated dependencies [[`9ff797dc`](https://github.com/wevm/wagmi/commit/9ff797dcb979dc86b798a432b74c98598165430d)]: - @wagmi/core@0.8.17 ## 0.10.12 ### Patch Changes - [#1699](https://github.com/wevm/wagmi/pull/1699) [`2f1e7950`](https://github.com/wevm/wagmi/commit/2f1e7950e55550d9b50ef5ccb97cb609f4af39b1) Thanks [@tmm](https://github.com/tmm)! - Added public RPC URL property to Chain - Updated dependencies [[`2f1e7950`](https://github.com/wevm/wagmi/commit/2f1e7950e55550d9b50ef5ccb97cb609f4af39b1)]: - @wagmi/core@0.8.16 ## 0.10.11 ### Patch Changes - [#1685](https://github.com/wevm/wagmi/pull/1685) [`917f5bc1`](https://github.com/wevm/wagmi/commit/917f5bc1fad578e35a8c6ee787e339bfdc156bab) Thanks [@jxom](https://github.com/jxom)! - Replaced qrcodemodal with web3modal for the WalletConnect v2 Connector. - Updated dependencies [[`917f5bc1`](https://github.com/wevm/wagmi/commit/917f5bc1fad578e35a8c6ee787e339bfdc156bab)]: - @wagmi/core@0.8.15 ## 0.10.10 ### Patch Changes - [#1648](https://github.com/wevm/wagmi/pull/1648) [`a2db9170`](https://github.com/wevm/wagmi/commit/a2db91709720161cd70eeb5e84dd78433264f0a3) Thanks [@tmm](https://github.com/tmm)! - Exported internal type. ## 0.10.9 ### Patch Changes - [#1646](https://github.com/wevm/wagmi/pull/1646) [`fcdbe353`](https://github.com/wevm/wagmi/commit/fcdbe3531e6d05cda4a4a511bae1ad4c9e426d88) Thanks [@jxom](https://github.com/jxom)! - Upgraded `zustand` to v4.3.1. - Updated dependencies [[`fcdbe353`](https://github.com/wevm/wagmi/commit/fcdbe3531e6d05cda4a4a511bae1ad4c9e426d88)]: - @wagmi/core@0.8.14 ## 0.10.8 ### Patch Changes - [#1639](https://github.com/wevm/wagmi/pull/1639) [`c6869f06`](https://github.com/wevm/wagmi/commit/c6869f0604fffb197752a08256f31db77f52e746) Thanks [@jxom](https://github.com/jxom)! - Added `isRainbow` flag to `InjectedConnector`. - Updated dependencies [[`c6869f06`](https://github.com/wevm/wagmi/commit/c6869f0604fffb197752a08256f31db77f52e746)]: - @wagmi/core@0.8.13 ## 0.10.7 ### Patch Changes - [#1636](https://github.com/wevm/wagmi/pull/1636) [`025f6771`](https://github.com/wevm/wagmi/commit/025f6771b32ff7eed22f527be81c5141ddaf9c3d) Thanks [@DanielSinclair](https://github.com/DanielSinclair)! - Added `isRainbow` flag to injected `window.ethereum` types. - Updated dependencies [[`025f6771`](https://github.com/wevm/wagmi/commit/025f6771b32ff7eed22f527be81c5141ddaf9c3d)]: - @wagmi/core@0.8.12 ## 0.10.6 ### Patch Changes - [#1623](https://github.com/wevm/wagmi/pull/1623) [`c97a4bc5`](https://github.com/wevm/wagmi/commit/c97a4bc5df422dc9a9d3d8bac0261ec6933ce15b) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where `useSigner` would not update on account change. ## 0.10.5 ### Patch Changes - [#1621](https://github.com/wevm/wagmi/pull/1621) [`5812b590`](https://github.com/wevm/wagmi/commit/5812b5909277bf2862cb57a31d52465b47291410) Thanks [@tmm](https://github.com/tmm)! - Bumped @wagmi/connectors - Updated dependencies [[`5812b590`](https://github.com/wevm/wagmi/commit/5812b5909277bf2862cb57a31d52465b47291410)]: - @wagmi/core@0.8.11 ## 0.10.4 ### Patch Changes - [#1607](https://github.com/wevm/wagmi/pull/1607) [`49a41357`](https://github.com/wevm/wagmi/commit/49a41357f9ca39479bdf759f5998bc169a91ac87) Thanks [@tmm](https://github.com/tmm)! - Exported hook types. ## 0.10.3 ### Patch Changes - [#1598](https://github.com/wevm/wagmi/pull/1598) [`fc10ebe6`](https://github.com/wevm/wagmi/commit/fc10ebe659dd5f3b7a8e00581f094652280a779b) Thanks [@jxom](https://github.com/jxom)! - Fixed CJS dependency version range - Updated dependencies [[`fc10ebe6`](https://github.com/wevm/wagmi/commit/fc10ebe659dd5f3b7a8e00581f094652280a779b)]: - @wagmi/core@0.8.10 ## 0.10.2 ### Patch Changes - [#1593](https://github.com/wevm/wagmi/pull/1593) [`216d555c`](https://github.com/wevm/wagmi/commit/216d555c62bd95c3c7c8f8e20f7269f6c8504610) Thanks [@jxom](https://github.com/jxom)! - Added CJS escape hatch bundle under the "cjs" tag. - Updated dependencies [[`216d555c`](https://github.com/wevm/wagmi/commit/216d555c62bd95c3c7c8f8e20f7269f6c8504610)]: - @wagmi/core@0.8.9 ## 0.10.1 ### Patch Changes - [#1573](https://github.com/wevm/wagmi/pull/1573) [`ef380d9c`](https://github.com/wevm/wagmi/commit/ef380d9c6d51ae0495b9c35925d2843c75d97fd4) Thanks [@tmm](https://github.com/tmm)! - Updated internal types. - Updated dependencies [[`ef380d9c`](https://github.com/wevm/wagmi/commit/ef380d9c6d51ae0495b9c35925d2843c75d97fd4)]: - @wagmi/core@0.8.8 ## 0.10.0 ### Minor Changes - [#1470](https://github.com/wevm/wagmi/pull/1470) [`3a1a6c9f`](https://github.com/wevm/wagmi/commit/3a1a6c9fe5db5c360adfd116f9a03a1238b5720c) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The `useSigner` hook now always returns `undefined` when no signer is present. Previously, it returned `null`. When no signer is present, the hook will be in an `"idle"` status. ### Patch Changes - [#1470](https://github.com/wevm/wagmi/pull/1470) [`3a1a6c9f`](https://github.com/wevm/wagmi/commit/3a1a6c9fe5db5c360adfd116f9a03a1238b5720c) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where `useSigner` would broadcast to other `useSigner`s unnecessarily. - [#1470](https://github.com/wevm/wagmi/pull/1470) [`3a1a6c9f`](https://github.com/wevm/wagmi/commit/3a1a6c9fe5db5c360adfd116f9a03a1238b5720c) Thanks [@jxom](https://github.com/jxom)! - The `WalletConnectConnector` now supports WalletConnect v2. It can be enabled by setting `version` to `'2'` and supplying a [WalletConnect Cloud `projectId`](https://cloud.walletconnect.com/sign-in). - [#1570](https://github.com/wevm/wagmi/pull/1570) [`216f585b`](https://github.com/wevm/wagmi/commit/216f585be8a9e3a56e3243f49ccd54d655b5a6dd) Thanks [@jxom](https://github.com/jxom)! - Added `useWatchPendingTransactions` - Updated dependencies [[`216f585b`](https://github.com/wevm/wagmi/commit/216f585be8a9e3a56e3243f49ccd54d655b5a6dd), [`3a1a6c9f`](https://github.com/wevm/wagmi/commit/3a1a6c9fe5db5c360adfd116f9a03a1238b5720c)]: - @wagmi/core@0.8.7 ## 0.9.6 ### Patch Changes - [#1539](https://github.com/wevm/wagmi/pull/1539) [`732da004`](https://github.com/wevm/wagmi/commit/732da0042c7e28091b2e36a484ea8239971306f5) Thanks [@0xFlicker](https://github.com/0xFlicker)! - All Providers (ie. Alchemy, Infura, Public) now use the ENS Registry address on the wagmi `Chain` object (`chain.contracts.ensRegistry`). - [#1574](https://github.com/wevm/wagmi/pull/1574) [`ecde3d10`](https://github.com/wevm/wagmi/commit/ecde3d1029ccdf90e2853ba0e9ae4f5f4ebb9c4c) Thanks [@jxom](https://github.com/jxom)! - Added the following chains: - `iotex` - `iotexTestnet` - `zkSync` - `zkSyncTestnet` - Updated dependencies [[`732da004`](https://github.com/wevm/wagmi/commit/732da0042c7e28091b2e36a484ea8239971306f5), [`ecde3d10`](https://github.com/wevm/wagmi/commit/ecde3d1029ccdf90e2853ba0e9ae4f5f4ebb9c4c)]: - @wagmi/core@0.8.6 ## 0.9.5 ### Patch Changes - [#1542](https://github.com/wevm/wagmi/pull/1542) [`731b3b73`](https://github.com/wevm/wagmi/commit/731b3b733c6a093d1693d49de601705b7c730549) Thanks [@jxom](https://github.com/jxom)! - Added the following chains: - `evmos` - `evmosTestnet` - `gnosis` - [#1542](https://github.com/wevm/wagmi/pull/1542) [`731b3b73`](https://github.com/wevm/wagmi/commit/731b3b733c6a093d1693d49de601705b7c730549) Thanks [@jxom](https://github.com/jxom)! - Updated Goerli symbol to `"ETH"`. - [#1542](https://github.com/wevm/wagmi/pull/1542) [`731b3b73`](https://github.com/wevm/wagmi/commit/731b3b733c6a093d1693d49de601705b7c730549) Thanks [@jxom](https://github.com/jxom)! - Updated Arbitrum Goerli RPC and Block Explorer. - [#1542](https://github.com/wevm/wagmi/pull/1542) [`731b3b73`](https://github.com/wevm/wagmi/commit/731b3b733c6a093d1693d49de601705b7c730549) Thanks [@jxom](https://github.com/jxom)! - Fixed issue where connecting to MetaMask may return with a stale address. - [#1542](https://github.com/wevm/wagmi/pull/1542) [`731b3b73`](https://github.com/wevm/wagmi/commit/731b3b733c6a093d1693d49de601705b7c730549) Thanks [@jxom](https://github.com/jxom)! - Removed ENS registry for Sepolia. - Updated dependencies [[`731b3b73`](https://github.com/wevm/wagmi/commit/731b3b733c6a093d1693d49de601705b7c730549), [`731b3b73`](https://github.com/wevm/wagmi/commit/731b3b733c6a093d1693d49de601705b7c730549), [`731b3b73`](https://github.com/wevm/wagmi/commit/731b3b733c6a093d1693d49de601705b7c730549), [`731b3b73`](https://github.com/wevm/wagmi/commit/731b3b733c6a093d1693d49de601705b7c730549), [`731b3b73`](https://github.com/wevm/wagmi/commit/731b3b733c6a093d1693d49de601705b7c730549)]: - @wagmi/core@0.8.5 ## 0.9.4 ### Patch Changes - [#1508](https://github.com/wevm/wagmi/pull/1508) [`0b50b62f`](https://github.com/wevm/wagmi/commit/0b50b62f7389619e429509a3e337e451e823b059) Thanks [@jxom](https://github.com/jxom)! - Updated `@wagmi/chains` to `0.1.3`. - [#1507](https://github.com/wevm/wagmi/pull/1507) [`7a083bcf`](https://github.com/wevm/wagmi/commit/7a083bcf31d671817a4da2f40fb2160a1ba9d7b7) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where `useBlockNumber` would return data when `watch` is enabled and `enabled` is falsy. - [#1504](https://github.com/wevm/wagmi/pull/1504) [`11b8b794`](https://github.com/wevm/wagmi/commit/11b8b794fbfd4a2b40f39962e2758e9fbf48cb54) Thanks [@tmm](https://github.com/tmm)! - Converted ethers custom "ACTION_REJECTED" error to standard RPC Error. - Updated dependencies [[`0b50b62f`](https://github.com/wevm/wagmi/commit/0b50b62f7389619e429509a3e337e451e823b059), [`11b8b794`](https://github.com/wevm/wagmi/commit/11b8b794fbfd4a2b40f39962e2758e9fbf48cb54)]: - @wagmi/core@0.8.4 ## 0.9.3 ### Patch Changes - [#1431](https://github.com/wevm/wagmi/pull/1431) [`af28f8f9`](https://github.com/wevm/wagmi/commit/af28f8f9cfc227e7c391927fdb934183edb5c2dc) Thanks [@jxom](https://github.com/jxom)! - Re-export connectors from `@wagmi/connectors` - [#1431](https://github.com/wevm/wagmi/pull/1431) [`af28f8f9`](https://github.com/wevm/wagmi/commit/af28f8f9cfc227e7c391927fdb934183edb5c2dc) Thanks [@jxom](https://github.com/jxom)! - Added `LedgerConnector` connector - Updated dependencies [[`af28f8f9`](https://github.com/wevm/wagmi/commit/af28f8f9cfc227e7c391927fdb934183edb5c2dc), [`af28f8f9`](https://github.com/wevm/wagmi/commit/af28f8f9cfc227e7c391927fdb934183edb5c2dc)]: - @wagmi/core@0.8.3 ## 0.9.2 ### Patch Changes - [#1442](https://github.com/wevm/wagmi/pull/1442) [`cde15289`](https://github.com/wevm/wagmi/commit/cde152899c758dea10787412b0aef669ed7202b2) Thanks [@0xproflupin](https://github.com/0xproflupin)! - Added Phantom wallet support to `InjectedConnector` - [#1448](https://github.com/wevm/wagmi/pull/1448) [`c6075f3a`](https://github.com/wevm/wagmi/commit/c6075f3a16885d850ad2656272351f9517c9f67b) Thanks [@tmm](https://github.com/tmm)! - Updated [ABIType](https://github.com/wevm/abitype) version. - [#1444](https://github.com/wevm/wagmi/pull/1444) [`310a8bc4`](https://github.com/wevm/wagmi/commit/310a8bc428ce4e7f68377f581b45dcdd64381cce) Thanks [@jxom](https://github.com/jxom)! - Assert that a `connector` exists before invoking the callback in `watchSigner`. - [#1434](https://github.com/wevm/wagmi/pull/1434) [`100e2a3b`](https://github.com/wevm/wagmi/commit/100e2a3b22f4602716554487b1d98738e053be76) Thanks [@tmm](https://github.com/tmm)! - Updated `MockConnector` `chainId` behavior to default to first chain from `chains` if not provided in `options`. - Updated dependencies [[`cde15289`](https://github.com/wevm/wagmi/commit/cde152899c758dea10787412b0aef669ed7202b2), [`c6075f3a`](https://github.com/wevm/wagmi/commit/c6075f3a16885d850ad2656272351f9517c9f67b), [`310a8bc4`](https://github.com/wevm/wagmi/commit/310a8bc428ce4e7f68377f581b45dcdd64381cce), [`100e2a3b`](https://github.com/wevm/wagmi/commit/100e2a3b22f4602716554487b1d98738e053be76)]: - @wagmi/core@0.8.2 ## 0.9.1 ### Patch Changes - [#1437](https://github.com/wevm/wagmi/pull/1437) [`c34a3dc6`](https://github.com/wevm/wagmi/commit/c34a3dc6396e6473d9f0505fad88ec910f8f5275) Thanks [@jxom](https://github.com/jxom)! - Omitted `"EIP712Domain"` type from `signTypedData` `types` arg since ethers throws an [internal error](https://github.com/ethers-io/ethers.js/blob/c80fcddf50a9023486e9f9acb1848aba4c19f7b6/packages/hash/src.ts/typed-data.ts#L466) if you include it. - [#1445](https://github.com/wevm/wagmi/pull/1445) [`51dd53cb`](https://github.com/wevm/wagmi/commit/51dd53cba3fe0f79fa1393270b738194577ddf54) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where the wagmi client wouldn't rehydrate the store in local storage when `autoConnect` is truthy. - Updated dependencies [[`c34a3dc6`](https://github.com/wevm/wagmi/commit/c34a3dc6396e6473d9f0505fad88ec910f8f5275), [`51dd53cb`](https://github.com/wevm/wagmi/commit/51dd53cba3fe0f79fa1393270b738194577ddf54)]: - @wagmi/core@0.8.1 ## 0.9.0 ### Minor Changes - [#1344](https://github.com/wevm/wagmi/pull/1344) [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: With the introduction of the [`wagmi/chains` entrypoint](/react/chains#wagmichains), `wagmi` no longer exports the following: - `chain` - `allChains` - `defaultChains` - `defaultL2Chains` - `chainId` - `etherscanBlockExplorers` - `alchemyRpcUrls`, `infuraRpcUrls`, `publicRpcUrls` Read below for migration steps. #### Removed `chain` The `chain` export has been removed. `wagmi` now only exports the `mainnet` & `goerli` chains. If you need to use an alternative chain (`polygon`, `optimism`, etc), you will need to import it from the [`wagmi/chains` entrypoint](/react/chains#wagmichains). ```diff import { - chain configureChains } from 'wagmi' + import { mainnet, polygon, optimism } from 'wagmi/chains' const { ... } = configureChains( - [chain.mainnet, chain.polygon, chain.optimism], + [mainnet, polygon, optimism], { ... } ) ``` #### Removed `allChains` The `allChains` export has been removed. If you need a list of all chains, you can utilize [`wagmi/chains` entrypoint](/react/chains#wagmichains). ```diff - import { allChains } from 'wagmi' + import * as allChains from 'wagmi/chains' const { ... } = configureChains(allChains, ...) ``` #### Removed `defaultChains` & `defaultL2Chains` The `defaultChains` & `defaultL2Chains` exports have been removed. If you still need the `defaultChains` or `defaultL2Chains` exports, you can build them yourself: ```diff - import { defaultChains } from 'wagmi' + import { mainnet, goerli } from 'wagmi/chains' + const defaultChains = [mainnet, goerli] ``` > The `defaultChains` export was previously populated with `mainnet` & `goerli`. ```diff - import { defaultL2Chains } from 'wagmi' + import { + arbitrum, + arbitrumGoerli, + polygon, + polygonMumbai, + optimism, + optimismGoerli + } from 'wagmi/chains' + const defaultL2Chains = [ + arbitrum, + arbitrumGoerli, + polygon, + polygonMumbai, + optimism + optimismGoerli + ] ``` > The `defaultL2Chains` export was previously populated with `arbitrum` & `optimism`. #### Removed `chainId` The `chainId` export has been removed. You can extract a chain ID from the chain itself. ```diff - import { chainId } from 'wagmi' + import { mainnet, polygon, optimism } from 'wagmi/chains' -const mainnetChainId = chainId.mainnet -const polygonChainId = chainId.polygon -const optimismChainId = chainId.optimism +const mainnetChainId = mainnet.chainId +const polygonChainId = polygon.chainId +const optimismChainId = optimism.chainId ``` #### Removed `etherscanBlockExplorers` The `etherscanBlockExplorers` export has been removed. You can extract a block explorer from the chain itself. ```diff - import { etherscanBlockExplorers } from 'wagmi' + import { mainnet, polygon, optimism } from 'wagmi/chains' -const mainnetEtherscanBlockExplorer = etherscanBlockExplorers.mainnet -const polygonEtherscanBlockExplorer = etherscanBlockExplorers.polygon -const optimismEtherscanBlockExplorer = etherscanBlockExplorers.optimism +const mainnetEtherscanBlockExplorer = mainnet.blockExplorer +const polygonEtherscanBlockExplorer = polygon.blockExplorer +const optimismEtherscanBlockExplorer = optimism.blockExplorer ``` #### Removed `alchemyRpcUrls`, `infuraRpcUrls` & `publicRpcUrls` The `alchemyRpcUrls`, `infuraRpcUrls` & `publicRpcUrls` exports have been removed. You can extract a RPC URL from the chain itself. ```diff - import { alchemyRpcUrls, infuraRpcUrls, publicRpcUrls } from 'wagmi' + import { mainnet } from 'wagmi/chains' -const mainnetAlchemyRpcUrl = alchemyRpcUrls.mainnet -const mainnetInfuraRpcUrl = infuraRpcUrls.mainnet -const mainnetOptimismRpcUrl = publicRpcUrls.mainnet +const mainnetAlchemyRpcUrl = mainnet.rpcUrls.alchemy +const mainnetInfuraRpcUrl = mainnet.rpcUrls.infura +const mainnetOptimismRpcUrl = mainnet.rpcUrls.optimism ``` - [#1344](https://github.com/wevm/wagmi/pull/1344) [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: the shape of the `Chain` type has been modified. #### RPC URLs The `rpcUrls` shape has changed to include an array of URLs, and also the transport method (`http` or `webSocket`): ```diff type Chain = { ... rpcUrls: { - [key: string]: string + [key: string]: { + http: string[] + webSocket: string[] + } } ... } ``` Note that you will also need to ensure that usage is migrated: ```diff - const rpcUrl = mainnet.rpcUrls.alchemy + const rpcUrl = mainnet.rpcUrls.alchemy.http[0] ``` #### Contracts The `multicall` and `ens` attributes have been moved into the `contracts` object: ```diff type Contract = { address: Address blockCreated?: number } type Chain = { ... - multicall: Contract - ens: Contract + contracts: { + multicall3: Contract + ensRegistry: Contract + } ... } ``` Note that you will also need to ensure that usage is migrated: ```diff - const multicallContract = mainnet.multicall + const multicallContract = mainnet.contracts.multicall3 ``` - [#1344](https://github.com/wevm/wagmi/pull/1344) [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: Removed the `wait` config option on `useWaitForTransaction`. Use the transaction `hash` instead. ```diff const { data } = useWaitForTransaction({ - wait: transaction.wait + hash: transaction.hash }) ``` - [#1344](https://github.com/wevm/wagmi/pull/1344) [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652) Thanks [@jxom](https://github.com/jxom)! - Updated errors to use `cause` instead of `internal` - [#1344](https://github.com/wevm/wagmi/pull/1344) [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652) Thanks [@jxom](https://github.com/jxom)! - `useEnsResolver`'s result is no longer persisted by the query client since it cannot serialize its prototype methods. - [#1344](https://github.com/wevm/wagmi/pull/1344) [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: Changed `useWaitForTransaction` behavior to return an error if the transaction reverted. ### Patch Changes - [#1344](https://github.com/wevm/wagmi/pull/1344) [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652) Thanks [@jxom](https://github.com/jxom)! - `useWaitForTransaction` now throws an error for cancelled or replaced transactions. - [#1344](https://github.com/wevm/wagmi/pull/1344) [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652) Thanks [@jxom](https://github.com/jxom)! - `useWaitForTransaction` now respects repriced (sped up) transactions. - [#1344](https://github.com/wevm/wagmi/pull/1344) [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652) Thanks [@jxom](https://github.com/jxom)! - Updated `@coinbase/wallet-sdk` to `^3.6.0`. - Updated dependencies [[`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652), [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652), [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652), [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652), [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652), [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652), [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652), [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652), [`57a19374`](https://github.com/wevm/wagmi/commit/57a1937464a4ccf72719fc86c38d1734f6306652)]: - @wagmi/core@0.8.0 ## 0.8.10 ### Patch Changes - [#1411](https://github.com/wevm/wagmi/pull/1411) [`659be184`](https://github.com/wevm/wagmi/commit/659be1840c613ce9f7aca9ac96694c4f60da4a66) Thanks [@tmm](https://github.com/tmm)! - Fixed issue where block invalidation was not properly disabled when setting `enabled: false`. - [#1409](https://github.com/wevm/wagmi/pull/1409) [`b557b3ee`](https://github.com/wevm/wagmi/commit/b557b3ee4fc58217e61d860fc3d1109d2abc813e) Thanks [@jxom](https://github.com/jxom)! - Ensure that `useSyncExternalStoreWithTracked` rerenders when no values are being tracked. - Updated dependencies [[`659be184`](https://github.com/wevm/wagmi/commit/659be1840c613ce9f7aca9ac96694c4f60da4a66)]: - @wagmi/core@0.7.9 ## 0.8.9 ### Patch Changes - [#1406](https://github.com/wevm/wagmi/pull/1406) [`4f18c450`](https://github.com/wevm/wagmi/commit/4f18c450a4d7952bfcfa6c533348ffbe55893d3c) Thanks [@tmm](https://github.com/tmm)! - Function for selecting the [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) Ethereum Provider to target. Defaults to `() => typeof window !== 'undefined' ? window.ethereum : undefined`. ```ts import { InjectedConnector } from "wagmi/connectors/injected"; const connector = new InjectedConnector({ options: { name: "My Injected Wallet", getProvider: () => typeof window !== "undefined" ? window.myInjectedWallet : undefined, }, }); ``` - Updated dependencies [[`4f18c450`](https://github.com/wevm/wagmi/commit/4f18c450a4d7952bfcfa6c533348ffbe55893d3c)]: - @wagmi/core@0.7.8 ## 0.8.8 ### Patch Changes - [#1386](https://github.com/wevm/wagmi/pull/1386) [`206a2adb`](https://github.com/wevm/wagmi/commit/206a2adbb4ee5149a364543b34612050ccf78c21) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where `persister` would still use `window.localStorage` instead of the wagmi `storage`. - [#1376](https://github.com/wevm/wagmi/pull/1376) [`a70a9528`](https://github.com/wevm/wagmi/commit/a70a9528f93f4d7fea28b7652751dfef2dcacf9b) Thanks [@jxom](https://github.com/jxom)! - Fixed issue where `switchChain` on `WalletConnectConnector` would not resolve. - [#1392](https://github.com/wevm/wagmi/pull/1392) [`88afc849`](https://github.com/wevm/wagmi/commit/88afc84978afe9689ab7364633e4422ecd7699ea) Thanks [@tmm](https://github.com/tmm)! - Added check for active connector when connecting - Updated dependencies [[`206a2adb`](https://github.com/wevm/wagmi/commit/206a2adbb4ee5149a364543b34612050ccf78c21), [`a70a9528`](https://github.com/wevm/wagmi/commit/a70a9528f93f4d7fea28b7652751dfef2dcacf9b), [`206a2adb`](https://github.com/wevm/wagmi/commit/206a2adbb4ee5149a364543b34612050ccf78c21), [`88afc849`](https://github.com/wevm/wagmi/commit/88afc84978afe9689ab7364633e4422ecd7699ea)]: - @wagmi/core@0.7.7 ## 0.8.7 ### Patch Changes - [#1384](https://github.com/wevm/wagmi/pull/1384) [`027e88d6`](https://github.com/wevm/wagmi/commit/027e88d6e5f8d028d46ee78aec8500701e0173d9) Thanks [@tmm](https://github.com/tmm)! - Fixed issue reconnecting after disconnect with `MetaMaskConnector` in MetaMask mobile browser. - [#1377](https://github.com/wevm/wagmi/pull/1377) [`089c4f3b`](https://github.com/wevm/wagmi/commit/089c4f3b3b8ce5cf7807f144410e2f64b72e0580) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where transforming `useContractRead`, `useContractReads` or `useContractInfiniteReads`'s return data via `select` wasn't inferring the type. - Updated dependencies [[`027e88d6`](https://github.com/wevm/wagmi/commit/027e88d6e5f8d028d46ee78aec8500701e0173d9)]: - @wagmi/core@0.7.6 ## 0.8.6 ### Patch Changes - [`1169914a`](https://github.com/wevm/wagmi/commit/1169914a0f0ad2810ca1c536b1f1bc6c20f2c1be) Thanks [@jxom](https://github.com/jxom)! - Use `get_accounts` for `getSigner` in InjectedConnector - Updated dependencies [[`1169914a`](https://github.com/wevm/wagmi/commit/1169914a0f0ad2810ca1c536b1f1bc6c20f2c1be)]: - @wagmi/core@0.7.5 ## 0.8.5 ### Patch Changes - [#1282](https://github.com/wevm/wagmi/pull/1282) [`6d286c9e`](https://github.com/wevm/wagmi/commit/6d286c9ed6f64a9872352904d4d171a6bc1c7a96) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where `useContractRead` would perform an unnecessary rerender if another hook had `watch` enabled. ## 0.8.4 ### Patch Changes - [#1309](https://github.com/wevm/wagmi/pull/1309) [`1f4a4261`](https://github.com/wevm/wagmi/commit/1f4a4261247b1d3a90e3123157bc851a35d49b9c) Thanks [@tmm](https://github.com/tmm)! - Fixed internal type - Updated dependencies [[`1f4a4261`](https://github.com/wevm/wagmi/commit/1f4a4261247b1d3a90e3123157bc851a35d49b9c)]: - @wagmi/core@0.7.4 ## 0.8.3 ### Patch Changes - [#1294](https://github.com/wevm/wagmi/pull/1294) [`b2f88949`](https://github.com/wevm/wagmi/commit/b2f88949f32aabaf13f318472648cd51a8b7f2e7) Thanks [@tmm](https://github.com/tmm)! - Set `abi` return type value for `usePrepareContractWrite` as more permissive when not inferrable as `Abi`. - Updated dependencies [[`b2f88949`](https://github.com/wevm/wagmi/commit/b2f88949f32aabaf13f318472648cd51a8b7f2e7)]: - @wagmi/core@0.7.3 ## 0.8.2 ### Patch Changes - [`e9f806b6`](https://github.com/wevm/wagmi/commit/e9f806b652ba62effb3ddac464815e447fc287f6) Thanks [@tmm](https://github.com/tmm)! - Bumped abitype and zustand versions. - [#1290](https://github.com/wevm/wagmi/pull/1290) [`88450052`](https://github.com/wevm/wagmi/commit/88450052b9f070fe53e18d84f72918c410b961f0) Thanks [@tmm](https://github.com/tmm)! - Fixed `useAccount`'s' `onConnect` callback `isReconnected` flag. - Updated dependencies [[`e9f806b6`](https://github.com/wevm/wagmi/commit/e9f806b652ba62effb3ddac464815e447fc287f6)]: - @wagmi/core@0.7.2 ## 0.8.1 ### Patch Changes - [#1272](https://github.com/wevm/wagmi/pull/1272) [`1f7fc41`](https://github.com/wevm/wagmi/commit/1f7fc419f7960bbdc51dfa85c2f33b89f1ecc1bf) Thanks [@tmm](https://github.com/tmm)! - Fixed ethers import path - Updated dependencies [[`1f7fc41`](https://github.com/wevm/wagmi/commit/1f7fc419f7960bbdc51dfa85c2f33b89f1ecc1bf)]: - @wagmi/core@0.7.1 ## 0.8.0 ### Minor Changes - [#1202](https://github.com/wevm/wagmi/pull/1202) [`9bf56af`](https://github.com/wevm/wagmi/commit/9bf56af3c30bdb80abb1e785c002e00986fadfb2) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: Removed the following deprecated chains: - `ropsten` - `rinkeby` - `kovan` - `optimismKovan` - `arbitrumRinkeby` If you feel you still need to include one of these testnets in your application, you will have to define it manually: ```diff -import { rinkeby } from 'wagmi' +import { Chain } from 'wagmi' +export const rinkeby: Chain = { + id: 4, + name: 'Rinkeby', + network: 'rinkeby', + nativeCurrency: { name: 'Rinkeby Ether', symbol: 'ETH', decimals: 18 }, + rpcUrls: { + alchemy: 'https://eth-rinkeby.alchemyapi.io/v2', + default: 'https://rpc.ankr.com/eth_rinkeby', + infura: 'https://rinkeby.infura.io/v3', + public: 'https://rpc.ankr.com/eth_rinkeby', + }, + blockExplorers: { + etherscan: 'https://rinkeby.etherscan.io', + default: 'https://rinkeby.etherscan.io', + }, + ens: { + address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', + }, + multicall: { + address: '0xca11bde05977b3631167028862be2a173976ca11', + blockCreated: 10299530, + }, + testnet: true, } ``` You can reference these removed chains [here](https://github.com/wevm/wagmi/blob/389765f7d9af063ab0df07389a2bbfbc10a41060/packages/core/src/constants/chains.ts). - [#1202](https://github.com/wevm/wagmi/pull/1202) [`9bf56af`](https://github.com/wevm/wagmi/commit/9bf56af3c30bdb80abb1e785c002e00986fadfb2) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: Made `apiKey` required on `infuraProvider` and `alchemyProvider`. ```diff import { configureChains } from 'wagmi' const config = configureChains(defaultChains, [ - alchemyProvider(), + alchemyProvider({ apiKey: process.env.ALCHEMY_API_KEY }) ]) ``` You can find your Alchemy API key from the [Alchemy Dashboard](https://dashboard.alchemyapi.io/), or your Infura API key from the [Infura Dashboard](https://infura.io/login). - [#1202](https://github.com/wevm/wagmi/pull/1202) [`9bf56af`](https://github.com/wevm/wagmi/commit/9bf56af3c30bdb80abb1e785c002e00986fadfb2) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: `addressOrName` renamed to `address` for `useBalance` and `useEnsAvatar`. ```diff const result = useBalance({ - addressOrName: '0x…', + address: '0x…', }) ``` If you were using an ENS name instead of an address, you can resolve the name to an address before passing it to the action. ```diff + const { data: address } = useEnsAddress({ name: 'example.eth' }) const result = useBalance({ - addressOrName: 'example.eth', + address, }) ``` - [#1202](https://github.com/wevm/wagmi/pull/1202) [`9bf56af`](https://github.com/wevm/wagmi/commit/9bf56af3c30bdb80abb1e785c002e00986fadfb2) Thanks [@tmm](https://github.com/tmm)! - Removed CommonJS support ### Patch Changes - Updated dependencies [[`9bf56af`](https://github.com/wevm/wagmi/commit/9bf56af3c30bdb80abb1e785c002e00986fadfb2), [`9bf56af`](https://github.com/wevm/wagmi/commit/9bf56af3c30bdb80abb1e785c002e00986fadfb2), [`9bf56af`](https://github.com/wevm/wagmi/commit/9bf56af3c30bdb80abb1e785c002e00986fadfb2), [`9bf56af`](https://github.com/wevm/wagmi/commit/9bf56af3c30bdb80abb1e785c002e00986fadfb2)]: - @wagmi/core@0.7.0 ## 0.7.15 ### Patch Changes - [#1262](https://github.com/wevm/wagmi/pull/1262) [`45e2ca4`](https://github.com/wevm/wagmi/commit/45e2ca4d1f33a7b1165c387d420b8d47f4f66935) Thanks [@tmm](https://github.com/tmm)! - Added default for `structuralSharing` for `useContractRead`, `useContractReads`, and `useContractInfiniteReads`. ## 0.7.14 ### Patch Changes - [#1260](https://github.com/wevm/wagmi/pull/1260) [`0e12f03`](https://github.com/wevm/wagmi/commit/0e12f0380442bccca9ed18991e783819778032fe) Thanks [@ilmpc](https://github.com/ilmpc)! - Deprecated `isDataEqual` option from and added `structuralSharing` option to `useContractRead`, `useContractReads`, and `useContractInfiniteReads`. ## 0.7.13 ### Patch Changes - [#1250](https://github.com/wevm/wagmi/pull/1250) [`ce2e0f4`](https://github.com/wevm/wagmi/commit/ce2e0f4a46b8fd1c509ead552012ef4c072a525b) Thanks [@tmm](https://github.com/tmm)! - Added support for Trust Wallet browser extension. - Updated dependencies [[`ce2e0f4`](https://github.com/wevm/wagmi/commit/ce2e0f4a46b8fd1c509ead552012ef4c072a525b)]: - @wagmi/core@0.6.12 ## 0.7.12 ### Patch Changes - [#1234](https://github.com/wevm/wagmi/pull/1234) [`3ff9303`](https://github.com/wevm/wagmi/commit/3ff930349250f62137cca4ca3b382522882abf8a) Thanks [@tmm](https://github.com/tmm)! - Fixed issue with adding chain to wallet without block explorer URL. - Updated dependencies [[`3ff9303`](https://github.com/wevm/wagmi/commit/3ff930349250f62137cca4ca3b382522882abf8a)]: - @wagmi/core@0.6.11 ## 0.7.11 ### Patch Changes - [#1232](https://github.com/wevm/wagmi/pull/1232) [`c0ca509`](https://github.com/wevm/wagmi/commit/c0ca509506dcf6d98b058df549dc761c9a5f3d1c) Thanks [@tmm](https://github.com/tmm)! - Added validation to check that chain is configured for connector when accessing `Signer`. - Updated dependencies [[`c0ca509`](https://github.com/wevm/wagmi/commit/c0ca509506dcf6d98b058df549dc761c9a5f3d1c)]: - @wagmi/core@0.6.10 ## 0.7.10 ### Patch Changes - [#1206](https://github.com/wevm/wagmi/pull/1206) [`15ff089`](https://github.com/wevm/wagmi/commit/15ff0896216abecf5967294ae5aeb26ea7fb480b) Thanks [@jxom](https://github.com/jxom)! - Added `scopeKey` as a configuration option to the Hooks which scope its cache to a given context. Hooks that have identical scope will share the same cache. - [#1207](https://github.com/wevm/wagmi/pull/1207) [`c73d463`](https://github.com/wevm/wagmi/commit/c73d463d65c9dbfcfe709187e47323a769589741) Thanks [@lvshaoping007](https://github.com/lvshaoping007)! - Added Kucoin wallet support to `InjectedConnector` - Updated dependencies [[`c73d463`](https://github.com/wevm/wagmi/commit/c73d463d65c9dbfcfe709187e47323a769589741)]: - @wagmi/core@0.6.9 ## 0.7.9 ### Patch Changes - [#1201](https://github.com/wevm/wagmi/pull/1201) [`9a07efa`](https://github.com/wevm/wagmi/commit/9a07efaa397d3ba03f2edbe527c359f21e22139a) Thanks [@jxom](https://github.com/jxom)! - Fixed issue where non-checksum addresses did not resolve with an ENS name - [#1132](https://github.com/wevm/wagmi/pull/1132) [`d41c0d6`](https://github.com/wevm/wagmi/commit/d41c0d650f8c0e54145758685b7604b8909d7ae0) Thanks [@toniocodo](https://github.com/toniocodo)! - Added ERC-4626 ABI - Updated dependencies [[`d41c0d6`](https://github.com/wevm/wagmi/commit/d41c0d650f8c0e54145758685b7604b8909d7ae0), [`9a07efa`](https://github.com/wevm/wagmi/commit/9a07efaa397d3ba03f2edbe527c359f21e22139a)]: - @wagmi/core@0.6.8 ## 0.7.8 ### Patch Changes - [#1174](https://github.com/wevm/wagmi/pull/1174) [`196a458`](https://github.com/wevm/wagmi/commit/196a458f64141e8a9f39c1b1e1af5937f692cb39) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where `client.chains` (active connector chains) would be populated when there is no active connector (disconnected user). - [#1176](https://github.com/wevm/wagmi/pull/1176) [`389765f`](https://github.com/wevm/wagmi/commit/389765f7d9af063ab0df07389a2bbfbc10a41060) Thanks [@jxom](https://github.com/jxom)! - Migrate away from Alchemy RPC URLs in the public RPC URL list - Updated dependencies [[`196a458`](https://github.com/wevm/wagmi/commit/196a458f64141e8a9f39c1b1e1af5937f692cb39), [`389765f`](https://github.com/wevm/wagmi/commit/389765f7d9af063ab0df07389a2bbfbc10a41060)]: - @wagmi/core@0.6.7 ## 0.7.7 ### Patch Changes - [#1166](https://github.com/wevm/wagmi/pull/1166) [`6fbe910`](https://github.com/wevm/wagmi/commit/6fbe91080b54e33e8543e9638ff5089e749ada3f) Thanks [@jxom](https://github.com/jxom)! - Export the React entrypoint `Client` type instead of `@wagmi/core`'s `Client`. - [`81ce9e6`](https://github.com/wevm/wagmi/commit/81ce9e64d85f7d01370324c1a529988a0919894f) Thanks [@jxom](https://github.com/jxom)! - Add `isPortal` to injected MetaMask flags. - [`c2c0109`](https://github.com/wevm/wagmi/commit/c2c01096ef4cd0ffadbb49062969c208604c6194) Thanks [@jxom](https://github.com/jxom)! - Add etherscan block explorer to Optimism Goerli - Updated dependencies [[`81ce9e6`](https://github.com/wevm/wagmi/commit/81ce9e64d85f7d01370324c1a529988a0919894f), [`c2c0109`](https://github.com/wevm/wagmi/commit/c2c01096ef4cd0ffadbb49062969c208604c6194)]: - @wagmi/core@0.6.6 ## 0.7.6 ### Patch Changes - [#1162](https://github.com/wevm/wagmi/pull/1162) [`30335b3`](https://github.com/wevm/wagmi/commit/30335b3199fb425e398e9c492b50c68d5e2ade7e) Thanks [@tmm](https://github.com/tmm)! - Fixed issue where non-indexed event parameter types were set to `null`. - [#1162](https://github.com/wevm/wagmi/pull/1162) [`30335b3`](https://github.com/wevm/wagmi/commit/30335b3199fb425e398e9c492b50c68d5e2ade7e) Thanks [@tmm](https://github.com/tmm)! - Fixed issue where `useContractReads` and `useContractInfiniteReads` types were slowing down TypeScript compiler. - Updated dependencies [[`30335b3`](https://github.com/wevm/wagmi/commit/30335b3199fb425e398e9c492b50c68d5e2ade7e), [`30335b3`](https://github.com/wevm/wagmi/commit/30335b3199fb425e398e9c492b50c68d5e2ade7e)]: - @wagmi/core@0.6.5 ## 0.7.5 ### Patch Changes - [#1103](https://github.com/wevm/wagmi/pull/1103) [`651eda0`](https://github.com/wevm/wagmi/commit/651eda06384bd0955268427f898e9337b2dc5a31) Thanks [@tmm](https://github.com/tmm)! - Bumped `abitype` dependency. - Updated dependencies [[`651eda0`](https://github.com/wevm/wagmi/commit/651eda06384bd0955268427f898e9337b2dc5a31)]: - @wagmi/core@0.6.4 ## 0.7.4 ### Patch Changes - [#1099](https://github.com/wevm/wagmi/pull/1099) [`748e617`](https://github.com/wevm/wagmi/commit/748e61719ad706acae057be903321ebe0c2e817e) Thanks [@jxom](https://github.com/jxom)! - Added `isFetchedAfterMount` to the return value of hooks. The `isFetchedAfterMount` will be truthy if the hook has fetched after the component has been mounted. This value can be utilized to not show the result if it has previously been cached. - [#1091](https://github.com/wevm/wagmi/pull/1091) [`a3aaf59`](https://github.com/wevm/wagmi/commit/a3aaf590e8e993017baa9a1ac50ecd63dd287caf) Thanks [@tmm](https://github.com/tmm)! - Fixed `useAccount` `onConnect`/`onDisconnect` from not firing when the account was already connected/disconnected. ## 0.7.3 ### Patch Changes - [#1086](https://github.com/wevm/wagmi/pull/1086) [`4e28d2a`](https://github.com/wevm/wagmi/commit/4e28d2ad4c2e6b3479b728563040b9529463cbcf) Thanks [@tmm](https://github.com/tmm)! - Exposed module types. - Updated dependencies [[`4e28d2a`](https://github.com/wevm/wagmi/commit/4e28d2ad4c2e6b3479b728563040b9529463cbcf)]: - @wagmi/core@0.6.3 ## 0.7.2 ### Patch Changes - [#1080](https://github.com/wevm/wagmi/pull/1080) [`3be5e8b`](https://github.com/wevm/wagmi/commit/3be5e8b01e58ed40cc9dab7ef9533c0197cb74d0) Thanks [@tmm](https://github.com/tmm)! - Added `abitype` to `dependencies` so types ship correctly. - Updated dependencies [[`3be5e8b`](https://github.com/wevm/wagmi/commit/3be5e8b01e58ed40cc9dab7ef9533c0197cb74d0)]: - @wagmi/core@0.6.2 ## 0.7.1 ### Patch Changes - [#1074](https://github.com/wevm/wagmi/pull/1074) [`8db807f`](https://github.com/wevm/wagmi/commit/8db807f16149aa278c2a7db9ee5245431db12173) Thanks [@IljaDaderko](https://github.com/IljaDaderko)! - Exported `EventListener` type - Updated dependencies [[`8db807f`](https://github.com/wevm/wagmi/commit/8db807f16149aa278c2a7db9ee5245431db12173)]: - @wagmi/core@0.6.1 ## 0.7.0 ### Minor Changes - [#940](https://github.com/wevm/wagmi/pull/940) [`b6cb8f4`](https://github.com/wevm/wagmi/commit/b6cb8f4cd15eb13073bc7e9ecb4bfa2c261c0663) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: `usePrepareContractWrite` now throws when a `chainId` is specified and the end-user is on a different chain id (the wrong network). If you wish to defer this check until the click handler is pressed, you can place `chainId` in `useContractWrite` instead: ```diff import { usePrepareContractWrite, useContractWrite } from 'wagmi' import { optimism } from 'wagmi/chains' // ... const { config } = usePrepareContractWrite({ addressOrName: '0xaf0326d92b97df1221759476b072abfd8084f9be', contractInterface: ['function mint()'], functionName: 'mint', }) const { write } = useContractWrite({ ...config, + chainId: optimism.id }) ``` - [#940](https://github.com/wevm/wagmi/pull/940) [`b6cb8f4`](https://github.com/wevm/wagmi/commit/b6cb8f4cd15eb13073bc7e9ecb4bfa2c261c0663) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The `usePrepareSendTransaction` hook will now only run when the end-user is connected to their wallet. This is to reach parity with `usePrepareContractWrite`. If the end-user is not connected, then the `usePrepareSendTransaction` hook will remain idle. - [#940](https://github.com/wevm/wagmi/pull/940) [`b6cb8f4`](https://github.com/wevm/wagmi/commit/b6cb8f4cd15eb13073bc7e9ecb4bfa2c261c0663) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: `usePrepareSendTransaction` now throws when a `chainId` is specified and the end-user is on a different chain id (the wrong network). If you wish to defer this check until the click handler is pressed, you can place `chainId` in `useContractWrite` instead: ```diff import { usePrepareSendTransaction, useContractWrite } from 'wagmi' import { optimism } from 'wagmi/chains' // ... const { config } = usePrepareSendTransaction({ request: { to: 'moxey.eth', value: parseEther('1'), }, }) const { sendTransaction } = useSendTransaction({ ...config, + chainId: optimism.id }) ``` - [#941](https://github.com/wevm/wagmi/pull/941) [`0c96009`](https://github.com/wevm/wagmi/commit/0c96009398647a515a57f72ef25c32724f7c978c) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: `useContractEvent` no longer accepts a `signerOrProvider` configuration option. - [#941](https://github.com/wevm/wagmi/pull/941) [`0c96009`](https://github.com/wevm/wagmi/commit/0c96009398647a515a57f72ef25c32724f7c978c) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: `addressOrName` and `contractInterface` renamed to `address` and `abi` respectively for contract hooks: `useContract`, `useContractEvent`, `useContractRead`, `useContractReads`, `useContractInfiniteReads`, `useContractWrite`, `usePrepareContractWrite`. ```diff import { useContractRead } from 'wagmi' const result = useContractRead({ - addressOrName: '0x…', + address: '0x…', - contractInterface: […] as const, + abi: […] as const, functionName: 'balanceOf', args: ['0x…'], }) ``` If you were using an ENS name instead of an address, you can resolve the name to an address before passing it to the action. ```diff - import { useContractRead } from 'wagmi' + import { useContractRead, useEnsAddress } from 'wagmi' + const { data: address} = useEnsAddress({ name: 'example.eth'}) const result = useContractRead({ - addressOrName: 'example.eth', + address, abi: […], functionName: 'balanceOf', args: ['0x…'], }) ``` - [#941](https://github.com/wevm/wagmi/pull/941) [`0c96009`](https://github.com/wevm/wagmi/commit/0c96009398647a515a57f72ef25c32724f7c978c) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: Updated TypeScript generics for contract and typed data hooks. Adding a [const assertion](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions) to `abi` allows TypeScript to infer `functionName`, `args`, `overrides`, and return types for functions, and `eventName` and `listener` types for events. ```diff import { useContractRead } from 'wagmi' const result = useContractRead({ address: '0x…', - abi: […], + abi: […] as const, functionName: 'balanceOf', // will autocomplete and catch typos args: ['0x…'], // inferred based on `abi`, `functionName`, `args` }) result.data // inferred based on `functionName` ``` This works for the following actions: `useContractRead`, `useContractWrite`, `usePrepareContractWrite`, `useContractReads`, `useContractInfiniteReads`, and `useContractEvent`. Adding a [const assertion](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions) to `useSignTypedData`'s config option, `types`, allows TypeScript to infer `value`. ```diff import { useSignTypedData } from 'wagmi' const result = useSignTypedData({ domain: { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', }, types: { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], - }, + } as const, value: { // `value` is inferred based on `types` from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) ``` - [#941](https://github.com/wevm/wagmi/pull/941) [`0c96009`](https://github.com/wevm/wagmi/commit/0c96009398647a515a57f72ef25c32724f7c978c) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: Updated TypeScript version to `typescript@>=4.7.4`. `@wagmi/core` can now infer types based on [ABI](https://docs.soliditylang.org/en/v0.8.15/abi-spec.html#json) and [EIP-712](https://eips.ethereum.org/EIPS/eip-712) Typed Data definitions, giving you full end-to-end type-safety from your contracts to your frontend and incredible developer experience (e.g. autocomplete contract function names and catch misspellings, type contract function arguments, etc.). For this to work, you must upgrade to `typescript@>=4.7.4`. Why is TypeScript v4.7.4 or greater necessary? TypeScript 4.7.4 introduced the ability to [extend constraints on inferred type variables](https://devblogs.microsoft.com/typescript/announcing-typescript-4-7/#extends-constraints-on-infer-type-variables), which is used extensively to help narrow types for ABIs. Good news! When upgrading TypeScript from 4.6 to 4.7 there are likely no [breaking changes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-7.html#breaking-changes) for your set up. - [#941](https://github.com/wevm/wagmi/pull/941) [`0c96009`](https://github.com/wevm/wagmi/commit/0c96009398647a515a57f72ef25c32724f7c978c) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: Updated `paginatedIndexesConfig` `fn` parameter return type. `fn` now returns an array instead of a single object. ```diff import { BigNumber } from 'ethers' import { paginatedIndexesConfig, useContractInfiniteReads } from 'wagmi' useContractInfiniteReads({ cacheKey: 'contracts', ...paginatedIndexesConfig( - (index) => ({ + (index) => [{ ...mlootContractConfig, functionName: 'tokenURI', args: [BigNumber.from(index)] as const, - }), + }], { start: 0, perPage: 10, direction: 'increment' }, ), }) ``` - [#941](https://github.com/wevm/wagmi/pull/941) [`0c96009`](https://github.com/wevm/wagmi/commit/0c96009398647a515a57f72ef25c32724f7c978c) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: `args` config option must now be an array for the following hooks: `useContractRead`, `useContractWrite`, `usePrepareContractWrite`, `useContractReads`, and `useContractInfiniteReads`. ```diff import { useContractRead } from 'wagmi' const { data } = useContractRead({ address: '0x…', abi: […], functionName: 'balanceOf', - args: '0x…', + args: ['0x…'], }) ``` ### Patch Changes - [#940](https://github.com/wevm/wagmi/pull/940) [`b6cb8f4`](https://github.com/wevm/wagmi/commit/b6cb8f4cd15eb13073bc7e9ecb4bfa2c261c0663) Thanks [@jxom](https://github.com/jxom)! - The `useSigner` hook now accepts an optional `chainId` to use for signer initialization as an argument. ```tsx import { useSigner } from "wagmi"; import { optimism } from "wagmi/core"; // ... useSigner({ chainId: optimism.id }); ``` - [#1061](https://github.com/wevm/wagmi/pull/1061) [`a4ffe8b`](https://github.com/wevm/wagmi/commit/a4ffe8b25516d5504685ae94579da4cd8c409329) Thanks [@alecananian](https://github.com/alecananian)! - Added Arbitrum Goerli Arbiscan block explorer - [#1050](https://github.com/wevm/wagmi/pull/1050) [`73d4d47`](https://github.com/wevm/wagmi/commit/73d4d47bc679f4f9a1cf46010fe2bf858c9d0b5c) Thanks [@jxom](https://github.com/jxom)! - update dependencies - `@coinbase/wallet-sdk@3.5.3` - `@tanstack/query-sync-storage-persister@4.10.1` - `@tanstack/react-query@4.10.1` - `@tanstack/react-query-persist-client@4.10.1` - `@walletconnect/ethereum-provider@1.8.0` - [#1048](https://github.com/wevm/wagmi/pull/1048) [`ed13074`](https://github.com/wevm/wagmi/commit/ed130747c0f28c1d9980a1328883e4000a60455e) Thanks [@Max-3-7](https://github.com/Max-3-7)! - Added support for Avalanche core wallet - [#1046](https://github.com/wevm/wagmi/pull/1046) [`ab9ecaa`](https://github.com/wevm/wagmi/commit/ab9ecaa74dfa4324279e167dd7e348319ef7d35d) Thanks [@jxom](https://github.com/jxom)! - make ethers block format validator compatible with Celo - Updated dependencies [[`b6cb8f4`](https://github.com/wevm/wagmi/commit/b6cb8f4cd15eb13073bc7e9ecb4bfa2c261c0663), [`b6cb8f4`](https://github.com/wevm/wagmi/commit/b6cb8f4cd15eb13073bc7e9ecb4bfa2c261c0663), [`a4ffe8b`](https://github.com/wevm/wagmi/commit/a4ffe8b25516d5504685ae94579da4cd8c409329), [`b6cb8f4`](https://github.com/wevm/wagmi/commit/b6cb8f4cd15eb13073bc7e9ecb4bfa2c261c0663), [`0c96009`](https://github.com/wevm/wagmi/commit/0c96009398647a515a57f72ef25c32724f7c978c), [`b6cb8f4`](https://github.com/wevm/wagmi/commit/b6cb8f4cd15eb13073bc7e9ecb4bfa2c261c0663), [`ed13074`](https://github.com/wevm/wagmi/commit/ed130747c0f28c1d9980a1328883e4000a60455e), [`b6cb8f4`](https://github.com/wevm/wagmi/commit/b6cb8f4cd15eb13073bc7e9ecb4bfa2c261c0663), [`ab9ecaa`](https://github.com/wevm/wagmi/commit/ab9ecaa74dfa4324279e167dd7e348319ef7d35d), [`0c96009`](https://github.com/wevm/wagmi/commit/0c96009398647a515a57f72ef25c32724f7c978c), [`0c96009`](https://github.com/wevm/wagmi/commit/0c96009398647a515a57f72ef25c32724f7c978c), [`73d4d47`](https://github.com/wevm/wagmi/commit/73d4d47bc679f4f9a1cf46010fe2bf858c9d0b5c), [`0c96009`](https://github.com/wevm/wagmi/commit/0c96009398647a515a57f72ef25c32724f7c978c), [`0c96009`](https://github.com/wevm/wagmi/commit/0c96009398647a515a57f72ef25c32724f7c978c)]: - @wagmi/core@0.6.0 ## 0.6.8 ### Patch Changes - [`0b77286b`](https://github.com/wevm/wagmi/commit/0b77286b89cb8603426cf5081872416c291a6531) Thanks [@jxom](https://github.com/jxom)! - Isolate wagmi's React Query `queryClient` instance. * [`8cb07462`](https://github.com/wevm/wagmi/commit/8cb07462acc3c5637398d11d2451f8b8e330d553) Thanks [@jxom](https://github.com/jxom)! - Added `chainId` as an argument to `watchBlockNumber`. - [`53c1a474`](https://github.com/wevm/wagmi/commit/53c1a4747d03b685e8cfbf55361fc2a56777fb06) Thanks [@tmm](https://github.com/tmm)! - Added missing `decimals` option to `Connector` `watchAsset` * [`4d74dd4f`](https://github.com/wevm/wagmi/commit/4d74dd4ff827ba5c43c3546a218f38cee45ea76a) Thanks [@jxom](https://github.com/jxom)! - Support ERC20 contracts that represent strings as bytes32 * Updated dependencies [[`8cb07462`](https://github.com/wevm/wagmi/commit/8cb07462acc3c5637398d11d2451f8b8e330d553), [`53c1a474`](https://github.com/wevm/wagmi/commit/53c1a4747d03b685e8cfbf55361fc2a56777fb06), [`4d74dd4f`](https://github.com/wevm/wagmi/commit/4d74dd4ff827ba5c43c3546a218f38cee45ea76a)]: - @wagmi/core@0.5.8 ## 0.6.7 ### Patch Changes - [`aa51bc4d`](https://github.com/wevm/wagmi/commit/aa51bc4dc5683bf0178597d2fdb8f2e9d82e7970) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue in `CoinbaseWalletConnector` where the browser extension would unintendedly reset the network when the browser is refreshed. * [#955](https://github.com/wevm/wagmi/pull/955) [`e326cd80`](https://github.com/wevm/wagmi/commit/e326cd80fe65267db623eb6c80ccdd75572914cf) Thanks [@0xFlicker](https://github.com/0xFlicker)! - Added Infura RPC URL for Sepolia - [`cec14089`](https://github.com/wevm/wagmi/commit/cec14089500c86687226ab272b4c3fcb85ae3d69) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where `useProvider` & `getProvider` were not returning referentially equal providers. * [`cec14089`](https://github.com/wevm/wagmi/commit/cec14089500c86687226ab272b4c3fcb85ae3d69) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where the `watch` option was not respecting the neighboring `chainId` option in `useBlockNumber`. - [`cec14089`](https://github.com/wevm/wagmi/commit/cec14089500c86687226ab272b4c3fcb85ae3d69) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where block listeners (via `watch`) were firing excessively on L2 chains. - Updated dependencies [[`aa51bc4d`](https://github.com/wevm/wagmi/commit/aa51bc4dc5683bf0178597d2fdb8f2e9d82e7970), [`e326cd80`](https://github.com/wevm/wagmi/commit/e326cd80fe65267db623eb6c80ccdd75572914cf), [`cec14089`](https://github.com/wevm/wagmi/commit/cec14089500c86687226ab272b4c3fcb85ae3d69), [`cec14089`](https://github.com/wevm/wagmi/commit/cec14089500c86687226ab272b4c3fcb85ae3d69), [`cec14089`](https://github.com/wevm/wagmi/commit/cec14089500c86687226ab272b4c3fcb85ae3d69)]: - @wagmi/core@0.5.7 ## 0.6.6 ### Patch Changes - [#936](https://github.com/wevm/wagmi/pull/936) [`3329d1f`](https://github.com/wevm/wagmi/commit/3329d1f5880431566e14ac1640f48d0975aec4c2) Thanks [@jxom](https://github.com/jxom)! - Added the ability to provide a custom logger to override how logs are broadcasted to the consumer in wagmi. A custom logger can be provided to the wagmi client via `logger`. ### API ```tsx logger?: { warn: typeof console.warn | null } ``` ### Examples **Passing in a custom logger** You can pass in a function to define your own custom logger. ```diff + import { logWarn } from './logger'; const client = createClient({ ... + logger: { + warn: message => logWarn(message) + } ... }) ``` **Disabling a logger** You can disable a logger by passing `null` as the value. ```diff const client = createClient({ ... + logger: { + warn: null + } ... }) ``` * [#889](https://github.com/wevm/wagmi/pull/889) [`27788ed`](https://github.com/wevm/wagmi/commit/27788ed989b5dc26849c7945fb91a92e56766018) Thanks [@jxom](https://github.com/jxom)! - Make multicall & readContracts more error robust * Updated dependencies [[`3329d1f`](https://github.com/wevm/wagmi/commit/3329d1f5880431566e14ac1640f48d0975aec4c2), [`27788ed`](https://github.com/wevm/wagmi/commit/27788ed989b5dc26849c7945fb91a92e56766018)]: - @wagmi/core@0.5.6 ## 0.6.5 ### Patch Changes - [#912](https://github.com/wevm/wagmi/pull/912) [`e529e12`](https://github.com/wevm/wagmi/commit/e529e125c713ed3ef24a59c6bf226fe4deee7ac9) Thanks [@zouhangwithsweet](https://github.com/zouhangwithsweet)! - Added BitKeep to injected flags - [#912](https://github.com/wevm/wagmi/pull/910) Thanks [@mytangying](https://github.com/zouhangwithsweet)! - Added MathWallet to injected flags - [#904](https://github.com/wevm/wagmi/pull/904) [`c231058`](https://github.com/wevm/wagmi/commit/c23105850f335f8798031e14c7098b7dee8c2975) Thanks [@jxom](https://github.com/jxom)! - Removed `contractInterface` & `signer` from persisted query keys. - Updated dependencies [[`e529e12`](https://github.com/wevm/wagmi/commit/e529e125c713ed3ef24a59c6bf226fe4deee7ac9), [`c231058`](https://github.com/wevm/wagmi/commit/c23105850f335f8798031e14c7098b7dee8c2975)]: - @wagmi/core@0.5.5 ## 0.6.4 ### Patch Changes - [#852](https://github.com/wevm/wagmi/pull/852) [`c3192d0`](https://github.com/wevm/wagmi/commit/c3192d0663aa332ae9edfd9dd49b333454013ab7) Thanks [@skeithc](https://github.com/skeithc)! - Added support for the Sepolia testnet - Updated dependencies [[`c3192d0`](https://github.com/wevm/wagmi/commit/c3192d0663aa332ae9edfd9dd49b333454013ab7)]: - @wagmi/core@0.5.4 ## 0.6.3 ### Patch Changes - [#835](https://github.com/wevm/wagmi/pull/835) [`1b85e54`](https://github.com/wevm/wagmi/commit/1b85e54ae654e2564cf5bc2dae6411fe0a25875c) Thanks [@jxom](https://github.com/jxom)! - Update `@coinbase/wallet-sdk` to `3.4.1` * [#843](https://github.com/wevm/wagmi/pull/843) [`e77dee6`](https://github.com/wevm/wagmi/commit/e77dee6a606b8aac4279569c54cec8902476fee9) Thanks [@tmm](https://github.com/tmm)! - Fix `MockConnector` entrypoint path - [#834](https://github.com/wevm/wagmi/pull/834) [`9655879`](https://github.com/wevm/wagmi/commit/96558793b0319df47aefafa6b7b9c959068d491b) Thanks [@jxom](https://github.com/jxom)! - Update zustand to `4.0.0` * [#833](https://github.com/wevm/wagmi/pull/833) [`3ae6d0f`](https://github.com/wevm/wagmi/commit/3ae6d0f5e2d65432024272b43afe68a8f63bb7ea) Thanks [@jxom](https://github.com/jxom)! - Updated `react-query@4.0.0-beta.23` to `@tanstack/react-query@^4.0.10` * Updated dependencies [[`1b85e54`](https://github.com/wevm/wagmi/commit/1b85e54ae654e2564cf5bc2dae6411fe0a25875c), [`9655879`](https://github.com/wevm/wagmi/commit/96558793b0319df47aefafa6b7b9c959068d491b)]: - @wagmi/core@0.5.3 ## 0.6.2 ### Patch Changes - [#823](https://github.com/wevm/wagmi/pull/823) [`10b8b78`](https://github.com/wevm/wagmi/commit/10b8b78605b7246b2c55b8d69f96663906e5cd20) Thanks [@tmm](https://github.com/tmm)! - Add Optimism Goerli to `chain` lookup. - Updated dependencies [[`10b8b78`](https://github.com/wevm/wagmi/commit/10b8b78605b7246b2c55b8d69f96663906e5cd20)]: - @wagmi/core@0.5.2 ## 0.6.1 ### Patch Changes - [#767](https://github.com/wevm/wagmi/pull/767) [`e9392f3`](https://github.com/wevm/wagmi/commit/e9392f396e48e928bd9d2522e3ad671c589f08cb) Thanks [@klyap](https://github.com/klyap)! - Add Optimism Goerli chain ahead of [Kovan deprecation](https://dev.optimism.io/kovan-to-goerli). * [#817](https://github.com/wevm/wagmi/pull/817) [`7e5cac7`](https://github.com/wevm/wagmi/commit/7e5cac75815dcd8aa563462342a4853fc5207735) Thanks [@alecananian](https://github.com/alecananian)! - Added custom name mapping for 1inch Wallet injected provider - [#806](https://github.com/wevm/wagmi/pull/806) [`0b34e56`](https://github.com/wevm/wagmi/commit/0b34e56db97e6dcdb71088e0149b2d55ebc604a5) Thanks [@vmichalik](https://github.com/vmichalik)! - Fix canonical testnet native asset symbols by changing them to ETH * [#778](https://github.com/wevm/wagmi/pull/778) [`0892908`](https://github.com/wevm/wagmi/commit/08929084eeeba1a3a55aa098fa9d92a243685ad5) Thanks [@0xcadams](https://github.com/0xcadams)! - Add Arbitrum Goerli chain. * Updated dependencies [[`e9392f3`](https://github.com/wevm/wagmi/commit/e9392f396e48e928bd9d2522e3ad671c589f08cb), [`7e5cac7`](https://github.com/wevm/wagmi/commit/7e5cac75815dcd8aa563462342a4853fc5207735), [`0b34e56`](https://github.com/wevm/wagmi/commit/0b34e56db97e6dcdb71088e0149b2d55ebc604a5), [`0892908`](https://github.com/wevm/wagmi/commit/08929084eeeba1a3a55aa098fa9d92a243685ad5)]: - @wagmi/core@0.5.1 ## 0.6.0 ### Minor Changes - [#658](https://github.com/wevm/wagmi/pull/658) [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432) Thanks [@jxom](https://github.com/jxom)! - **Breaking:** The `useSendTransaction` hook's `data` now returns an object only consisting of `hash` & `wait`, and not the full [`TransactionResponse`](https://docs.ethers.io/v5/api/providers/types/#providers-TransactionResponse). If you require the full `TransactionResponse`, you can use `useTransaction`: ```diff import { useSendTransaction, useTransaction } from 'wagmi' const { data: { hash, wait, - ...transaction } } = useSendTransaction(...) +const { data: transaction } = useTransaction({ hash }) ``` > Why? The old implementation of `useSendTransaction` created a long-running async task, causing [UX pitfalls](https://wagmi.sh/docs/prepare-hooks#ux-pitfalls-without-prepare-hooks) when invoked in a click handler. * [#658](https://github.com/wevm/wagmi/pull/658) [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The configuration passed to the `useSendTransaction` hook now needs to be either: - prepared with the `usePrepareSendTransaction` hook **(new)**, or - recklessly unprepared **(previous functionality)** > Why? [Read here](https://wagmi.sh/docs/prepare-hooks) ### Prepared usage ```diff import { usePrepareSendTransaction, useSendTransaction } from 'wagmi' +const { config } = usePrepareSendTransaction({ + request: { + to: 'moxey.eth', + value: parseEther('1'), + } +}) const { data } = useSendTransaction({ - request: { - to: 'moxey.eth', - value: parseEther('1') - } + ...config }) ``` ### Recklessly unprepared usage If you are not ready to upgrade to `usePrepareSendTransaction`, it is possible to use `useSendTransaction` without preparing the configuration first by passing `mode: 'recklesslyUnprepared'`. ```diff import { useSendTransaction } from 'wagmi' const { data } = useSendTransaction({ + mode: 'recklesslyUnprepared', request: { to: 'moxey.eth', value: parseEther('1'), } }) ``` - [#658](https://github.com/wevm/wagmi/pull/658) [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: If a `chainId` is passed to `useContractWrite` or `useSendTransaction`, it will no longer attempt to switch chain before sending the transaction. Instead, it will throw an error if the user is on the wrong chain. > Why? Eagerly prompting to switch chain in these actions created a long-running async task that that makes [iOS App Links](https://wagmi.sh/docs/prepare-hooks#ios-app-link-constraints) vulnerable. * [#760](https://github.com/wevm/wagmi/pull/760) [`d8af6bf`](https://github.com/wevm/wagmi/commit/d8af6bf50885aec110ae4d64716642453aa27896) Thanks [@tmm](https://github.com/tmm)! - **Breaking:** `alchemyProvider` and `infuraProvider` now use a generic `apiKey` configuration option instead of `alchemyId` and `infuraId`. ```diff import { alchemyProvider } from '@wagmi/core/providers/alchemy' import { infuraProvider } from '@wagmi/core/providers/infura' alchemyProvider({ - alchemyId: 'yourAlchemyApiKey', + apiKey: 'yourAlchemyApiKey', }) infuraProvider({ - infuraId: 'yourInfuraApiKey', + apiKey: 'yourInfuraApiKey', }) ``` - [#658](https://github.com/wevm/wagmi/pull/658) [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432) Thanks [@jxom](https://github.com/jxom)! - Added the `usePrepareContractWrite` hook that eagerly fetches the parameters required for sending a contract write transaction such as the gas estimate. It returns config to be passed through to `useContractWrite`. ```ts const { config } = usePrepareContractWrite({ addressOrName: "0xecb504d39723b0be0e3a9aa33d646642d1051ee1", contractInterface: wagmigotchiABI, functionName: "feed", }); const { write } = useContractWrite(config); ``` * [#658](https://github.com/wevm/wagmi/pull/658) [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432) Thanks [@jxom](https://github.com/jxom)! - **Breaking:** When `useSendTransaction` is in "prepare mode" (used with `usePrepareSendTransaction`), `sendTransaction`/`sendTransactionAsync` will be `undefined` until the configuration has been prepared. Ensure that your usage reflects this. ```tsx const { config } = usePrepareSendTransaction({ ... }) const { sendTransaction } = useSendTransaction(config) ``` - [#658](https://github.com/wevm/wagmi/pull/658) [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432) Thanks [@jxom](https://github.com/jxom)! - Added the `usePrepareSendTransaction` hook that eagerly fetches the parameters required for sending a transaction such as the gas estimate and resolving an ENS address (if required). It returns config to be passed through to `useSendTransaction`. ```ts import { usePrepareSendTransaction, useSendTransaction } from "@wagmi/core"; const { config } = usePrepareSendTransaction({ request: { to: "moxey.eth", value: parseEther("1"), }, }); const { sendTransaction } = useSendTransaction(config); ``` * [#658](https://github.com/wevm/wagmi/pull/658) [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432) Thanks [@jxom](https://github.com/jxom)! - **Breaking:** The `sendTransaction`/`sendTransactionAsync` configuration object has now been altered to only accept "reckless" configuration. If one or more of these values are set, it can lead to [UX pitfalls](https://wagmi.sh/docs/prepare-hooks#ux-pitfalls-without-prepare-hooks). ```diff ``` - [#727](https://github.com/wevm/wagmi/pull/727) [`ac3b9b8`](https://github.com/wevm/wagmi/commit/ac3b9b87f80cb45b65d003f09d916d7d1427a62e) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: Moved the `pollingInterval` config option from the chain provider config to `configureChains` config. ```diff const { chains, provider } = configureChains( [chain.mainnet, chain.polygon], [ - alchemyProvider({ apiKey, pollingInterval: 5000 }), - publicProvider({ pollingInterval: 5000 }) + alchemyProvider({ apiKey }), + publicProvider() ], + { pollingInterval: 5000 } ) ``` * [#658](https://github.com/wevm/wagmi/pull/658) [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432) Thanks [@jxom](https://github.com/jxom)! - **Breaking:** When `useContractWrite` is in "prepare mode" (used with `usePrepareContractWrite`), `write`/`writeAsync` will be `undefined` until the configuration has been prepared. Ensure that your usage reflects this. ```tsx const { config } = usePrepareContractWrite({ ... }) const { write } = useContractWrite(config) ``` - [#658](https://github.com/wevm/wagmi/pull/658) [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The configuration passed to the `useContractWrite` hook now needs to be either: - prepared with the `usePrepareContractWrite` hook **(new)**, or - recklessly unprepared **(previous functionality)** > Why? [Read here](https://wagmi.sh/docs/prepare-hooks) ### Prepared usage ```diff import { usePrepareContractWrite, useContractWrite } from 'wagmi' +const { config } = usePrepareContractWrite({ + addressOrName: '0x...', + contractInterface: wagmiAbi, + functionName: 'mint', + args: [tokenId] +}) const { data } = useContractWrite({ - addressOrName: '0x...', - contractInterface: wagmiAbi, - functionName: 'mint', - args: [tokenId], + ...config }) ``` ### Recklessly unprepared usage If you are not ready to upgrade to `usePrepareContractWrite`, it is possible to use `useContractWrite` without preparing the configuration first by passing `mode: 'recklesslyUnprepared'`. ```diff import { useContractWrite } from 'wagmi' const { data } = useContractWrite({ + mode: 'recklesslyUnprepared', addressOrName: '0x...', contractInterface: wagmiAbi, functionName: 'mint', args: [tokenId], }) ``` ### Patch Changes - [#733](https://github.com/wevm/wagmi/pull/733) [`6232487`](https://github.com/wevm/wagmi/commit/623248703bc728d539e28bf8a89b8ab22f0a5703) Thanks [@tmm](https://github.com/tmm)! - Add mock connector entrypoint * [#762](https://github.com/wevm/wagmi/pull/762) [`ccaeed5`](https://github.com/wevm/wagmi/commit/ccaeed53d731f51879e0cdd5648797a32f7d7a31) Thanks [@jxom](https://github.com/jxom)! - Fix `useContractRead` return value unexpectedly returning null for falsy values - [#734](https://github.com/wevm/wagmi/pull/734) [`7c2fa04`](https://github.com/wevm/wagmi/commit/7c2fa04e9b695840d6fa088e1f8d069f3c916551) Thanks [@jxom](https://github.com/jxom)! - Fix issue where `useProvider` & `useWebSocketProvider` would not update when `chainId` config changes * [#739](https://github.com/wevm/wagmi/pull/739) [`c2295a5`](https://github.com/wevm/wagmi/commit/c2295a56cc86d02cc6602e2b4557b8ab9a091a3f) Thanks [@tmm](https://github.com/tmm)! - Fix balance formatting for tokens that do not have 18 decimals. - [#759](https://github.com/wevm/wagmi/pull/759) [`959953d`](https://github.com/wevm/wagmi/commit/959953d1f5b3e8189bac56de245c62333470d18e) Thanks [@tmm](https://github.com/tmm)! - Added `useTransaction` hook: ```ts import { useTransaction } from "wagmi"; const result = useTransaction({ hash: "0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060", }); ``` - Updated dependencies [[`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432), [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432), [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432), [`d8af6bf`](https://github.com/wevm/wagmi/commit/d8af6bf50885aec110ae4d64716642453aa27896), [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432), [`c2295a5`](https://github.com/wevm/wagmi/commit/c2295a56cc86d02cc6602e2b4557b8ab9a091a3f), [`ac3b9b8`](https://github.com/wevm/wagmi/commit/ac3b9b87f80cb45b65d003f09d916d7d1427a62e), [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432), [`d70c115`](https://github.com/wevm/wagmi/commit/d70c115131f299fb61f87867b6ac4218e0bcf432), [`959953d`](https://github.com/wevm/wagmi/commit/959953d1f5b3e8189bac56de245c62333470d18e)]: - @wagmi/core@0.5.0 ## 0.5.11 ### Patch Changes - [`4c7d123`](https://github.com/wevm/wagmi/commit/4c7d123c8e74f93e770096857eb8c40ce0a47681) Thanks [@jxom](https://github.com/jxom)! - Fix issue where `useProvider` & `useWebSocketProvider` would not update when `chainId` config changes ## 0.5.10 ### Patch Changes - [#713](https://github.com/tmm/wagmi/pull/713) [`08b0113`](https://github.com/tmm/wagmi/commit/08b0113bef9f32dceab2ecd823b1ee00f9bdc45d) Thanks [@jxom](https://github.com/jxom)! - Fix an issue where the `useContractRead` query function could return `undefined` instead of a serializable `null`. * [#725](https://github.com/tmm/wagmi/pull/725) [`b976920`](https://github.com/tmm/wagmi/commit/b97692051d778d7e112872663832c97963a8029a) Thanks [@tmm](https://github.com/tmm)! - Lock `react-query` version - [#721](https://github.com/tmm/wagmi/pull/721) [`abea25f`](https://github.com/tmm/wagmi/commit/abea25fd15d81d1ecaec9d3fbd687042ab29b1e6) Thanks [@tmm](https://github.com/tmm)! - Add `name` to `useToken` `data` value. - Updated dependencies [[`abea25f`](https://github.com/tmm/wagmi/commit/abea25fd15d81d1ecaec9d3fbd687042ab29b1e6), [`abea25f`](https://github.com/tmm/wagmi/commit/abea25fd15d81d1ecaec9d3fbd687042ab29b1e6)]: - @wagmi/core@0.4.9 ## 0.5.9 ### Patch Changes - [#677](https://github.com/tmm/wagmi/pull/677) [`35e4219`](https://github.com/tmm/wagmi/commit/35e42199af9dd346549c1718e144728f55b8d7dd) Thanks [@jxom](https://github.com/jxom)! - Move `parseContractResult` to `@wagmi/core` * [#677](https://github.com/tmm/wagmi/pull/677) [`35e4219`](https://github.com/tmm/wagmi/commit/35e42199af9dd346549c1718e144728f55b8d7dd) Thanks [@jxom](https://github.com/jxom)! - Parse tuples correctly in `parseContractResult` * Updated dependencies [[`35e4219`](https://github.com/tmm/wagmi/commit/35e42199af9dd346549c1718e144728f55b8d7dd)]: - @wagmi/core@0.4.7 ## 0.5.8 ### Patch Changes - [#670](https://github.com/tmm/wagmi/pull/670) [`29a0d21`](https://github.com/tmm/wagmi/commit/29a0d21ee83995559f63542778dfa805f15e7441) Thanks [@tmm](https://github.com/tmm)! - Fix broken release not containing `deepEqual` from `@wagmi/core`. - Updated dependencies [[`29a0d21`](https://github.com/tmm/wagmi/commit/29a0d21ee83995559f63542778dfa805f15e7441)]: - @wagmi/core@0.4.6 ## 0.5.7 ### Patch Changes - [#659](https://github.com/tmm/wagmi/pull/659) [`be76586`](https://github.com/tmm/wagmi/commit/be76586431238dc5a0970a6f10a3dff9faa8ca2d) Thanks [@jxom](https://github.com/jxom)! - Added an `isDataEqual` config option to `useContractRead`, `useContractReads` & `useContractInfiniteReads` to define whether or not that data has changed. Defaults to `deepEqual`. * [#659](https://github.com/tmm/wagmi/pull/659) [`be76586`](https://github.com/tmm/wagmi/commit/be76586431238dc5a0970a6f10a3dff9faa8ca2d) Thanks [@jxom](https://github.com/jxom)! - Added `onBlock` config to `useBlockNumber` - [#659](https://github.com/tmm/wagmi/pull/659) [`be76586`](https://github.com/tmm/wagmi/commit/be76586431238dc5a0970a6f10a3dff9faa8ca2d) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue where `useContractRead` & `useContractReads` would return unstable data. ## 0.5.6 ### Patch Changes - [#654](https://github.com/tmm/wagmi/pull/654) [`e66530b`](https://github.com/tmm/wagmi/commit/e66530bf4881b3533c528f8c5a5f41be0eab0a64) Thanks [@jxom](https://github.com/jxom)! - omit `contractInterface` from `useContractRead` & `useContractReads` query key hash * [#654](https://github.com/tmm/wagmi/pull/654) [`e66530b`](https://github.com/tmm/wagmi/commit/e66530bf4881b3533c528f8c5a5f41be0eab0a64) Thanks [@jxom](https://github.com/jxom)! - fix `multicall` returning nullish data for all calls unexpectedly * Updated dependencies [[`e66530b`](https://github.com/tmm/wagmi/commit/e66530bf4881b3533c528f8c5a5f41be0eab0a64)]: - @wagmi/core@0.4.5 ## 0.5.5 ### Patch Changes - [#629](https://github.com/tmm/wagmi/pull/629) [`199db71`](https://github.com/tmm/wagmi/commit/199db7165eed43d36cb882d373f95e7c49212f23) Thanks [@jxom](https://github.com/jxom)! - Add `wagmi/actions` entrypoint that exports imperative `@wagmi/core` actions * [#616](https://github.com/tmm/wagmi/pull/616) [`7a7a17a`](https://github.com/tmm/wagmi/commit/7a7a17a46d4c9e6465cc46a111b5fe8a56109f1b) Thanks [@tmm](https://github.com/tmm)! - Adds `UNSTABLE_shimOnConnectSelectAccount` flag. With this flag and "disconnected" with `shimDisconnect` enabled, the user is prompted to select a different MetaMask account (than the currently connected account) when trying to connect (e.g. `useConnect`/`connect` action). * Updated dependencies [[`7a7a17a`](https://github.com/tmm/wagmi/commit/7a7a17a46d4c9e6465cc46a111b5fe8a56109f1b)]: - @wagmi/core@0.4.4 ## 0.5.4 ### Patch Changes - [#631](https://github.com/tmm/wagmi/pull/631) [`a780e32`](https://github.com/tmm/wagmi/commit/a780e32e91a0072c795fa0b5a6111302768e2a01) Thanks [@tmm](https://github.com/tmm)! - Fix WalletConnect stale session - Updated dependencies [[`a780e32`](https://github.com/tmm/wagmi/commit/a780e32e91a0072c795fa0b5a6111302768e2a01)]: - @wagmi/core@0.4.3 ## 0.5.3 ### Patch Changes - [#627](https://github.com/tmm/wagmi/pull/627) [`5985530`](https://github.com/tmm/wagmi/commit/59855301d138313e83a607b3f05053e9f46a78a8) Thanks [@jxom](https://github.com/jxom)! - equalityFn in `useSyncExternalStoreWithTracked` should return truthy when there are no tracked keys. ## 0.5.2 ### Patch Changes - [#624](https://github.com/tmm/wagmi/pull/624) [`416fa7e`](https://github.com/tmm/wagmi/commit/416fa7ee1f8019ab86e33fb93783ffddecc02c49) Thanks [@jxom](https://github.com/jxom)! - Fix broken `WebSocketProvider` type defs - Updated dependencies [[`416fa7e`](https://github.com/tmm/wagmi/commit/416fa7ee1f8019ab86e33fb93783ffddecc02c49)]: - @wagmi/core@0.4.2 ## 0.5.1 ### Patch Changes - [#622](https://github.com/tmm/wagmi/pull/622) [`d171581`](https://github.com/tmm/wagmi/commit/d171581464891dd870d97b6232205da0cb152d9b) Thanks [@tmm](https://github.com/tmm)! - Use `domain.chainId` to validate and switch chain before signing in `useSignTypedData`. * [#618](https://github.com/tmm/wagmi/pull/618) [`a5138e8`](https://github.com/tmm/wagmi/commit/a5138e82a00e4d9469ad78c97b2d34200d7f1fbe) Thanks [@tmm](https://github.com/tmm)! - Fix adding chains when using MetaMask mobile app, add `publicRpcUrls` constant, and default to public endpoint when adding chain. * Updated dependencies [[`d171581`](https://github.com/tmm/wagmi/commit/d171581464891dd870d97b6232205da0cb152d9b), [`a5138e8`](https://github.com/tmm/wagmi/commit/a5138e82a00e4d9469ad78c97b2d34200d7f1fbe)]: - @wagmi/core@0.4.1 ## 0.5.0 ### Minor Changes - [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The `useContractWrite` hook parameters have been consolidated into a singular config parameter. Before: ```tsx useContractWrite( { addressOrName: mlootContractAddress, contractInterface: mlootABI, }, "claim", ); ``` After: ```tsx useContractWrite({ addressOrName: mlootContractAddress, contractInterface: mlootABI, functionName: "claim", }); ``` * [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The `useContractEvent` hook parameters have been consolidated into a singular config parameter. Before: ```tsx useContractEvent( { addressOrName: uniContractAddress, contractInterface: erc20ABI, }, 'Transfer', listener, ), ``` After: ```tsx useContractEvent({ addressOrName: uniContractAddress, contractInterface: erc20ABI, eventName: "Transfer", listener, }); ``` - [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The `client` prop is now required on `WagmiConfig`. ````diff ```tsx import { createClient, + configureChains, + defaultChains } from 'wagmi' +import { publicProvider } from 'wagmi/providers/public' +const { provider, webSocketProvider } = configureChains(defaultChains, [ + publicProvider(), +]) +const client = createClient({ + provider, + webSocketProvider, +}) function App() { return ( ) } ```` * [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The `provider` config option is now required on `createClient`. It is recommended to pass the [`provider` given from `configureChains`](https://wagmi.sh/docs/providers/configuring-chains). ```diff import { createClient, + defaultChains, + configureChains } from 'wagmi' +import { publicProvider } from 'wagmi/providers/publicProvider' +const { provider } = configureChains(defaultChains, [ + publicProvider +]) const client = createClient({ + provider }) ``` If you previously used an ethers.js Provider, you now need to provide your `chains` on the Provider instance: ```diff import { createClient, + defaultChains } from 'wagmi' import ethers from 'ethers' const client = createClient({ - provider: getDefaultProvider() + provider: Object.assign(getDefaultProvider(), { chains: defaultChains }) }) ``` - [`4f8f3c0`](https://github.com/tmm/wagmi/commit/4f8f3c0d65383bd8bbdfc3f1033adfdb11d80ebb) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Use ethereum-lists chains symbols * [#582](https://github.com/tmm/wagmi/pull/582) [`b03830a`](https://github.com/tmm/wagmi/commit/b03830a54465215c2526f9509543fe2c978bfe70) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The following changes were made to the `useAccount` return value: ### The `data` value is now `address` & `connector` ```diff { - data?: { - address: string - connector: Connector - } + address?: string + connector?: Connector } ``` ### Global connection status values have been added The following global connection status values have been added: ```diff { + isConnecting: boolean + isReconnecting: boolean + isConnected: boolean + isDisconnected: boolean + status: 'connecting' | 'reconnecting' | 'connected' | 'disconnected' } ``` The `useAccount` hook is now aware of any connection event in your application, so now you can use these connection status values to determine if your user is connected, disconnected or connecting to a wallet on a global scope. ### `error`, states & `refetch` values have been removed Since the `useAccount` hook never dealt with asynchronous data, all of these values were redundant & unused. ```diff { - error?: Error - isIdle: boolean - isLoading: boolean - isFetching: boolean - isSuccess: boolean - isError: boolean - isFetched: boolean - isRefetching: boolean - refetch: (options: { - throwOnError: boolean - cancelRefetch: boolean - }) => Promise<{ - address: string - connector: Connector - }> - status: 'idle' | 'error' | 'loading' | 'success' } ``` ### Summary of changes Below is the whole diff of changes to the `useAccount` return value. ```diff { - data?: { - address: string - connector: Connector - } + address?: string + connector?: Connector - error?: Error - isIdle: boolean - isLoading: boolean - isFetching: boolean - isSuccess: boolean - isError: boolean - isFetched: boolean - isRefetching: boolean + isConnecting: boolean + isReconnecting: boolean + isConnected: boolean + isDisconnected: boolean - refetch: (options: { - throwOnError: boolean - cancelRefetch: boolean - }) => Promise<{ - address: string - connector: Connector - }> - status: 'idle' | 'error' | 'loading' | 'success' + status: 'connecting' | 'reconnecting' | 'connected' | 'disconnected' } ``` - [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4) Thanks [@jxom](https://github.com/jxom)! - **Breaking:** Removed the `chainId` parameter from `connectors` function on `createClient`. ```diff const client = createClient({ - connectors({ chainId }) { + connectors() { ... } }) ``` If you previously derived RPC URLs from the `chainId` on `connectors`, you can now remove that logic as `wagmi` now handles RPC URLs internally when used with `configureChains`. ```diff import { chain, + configureChains, createClient } from 'wagmi'; +import { publicProvider } from 'wagmi/providers/public' import { CoinbaseWalletConnector } from 'wagmi/connectors/coinbaseWallet' import { InjectedConnector } from 'wagmi/connectors/injected' import { MetaMaskConnector } from 'wagmi/connectors/metaMask' import { WalletConnectConnector } from 'wagmi/connectors/walletConnect' +const { chains } = configureChains( + [chain.mainnet], + [publicProvider()] +); const client = createClient({ - connectors({ chainId }) { - const chain = chains.find((x) => x.id === chainId) ?? defaultChain - const rpcUrl = chain.rpcUrls.alchemy - ? `${chain.rpcUrls.alchemy}/${alchemyId}` - : chain.rpcUrls.default - return [ + connectors: [ new MetaMaskConnector({ chains }), new CoinbaseWalletConnector({ chains, options: { appName: 'wagmi', - chainId: chain.id, - jsonRpcUrl: rpcUrl, }, }), new WalletConnectConnector({ chains, options: { qrcode: true, - rpc: { [chain.id]: rpcUrl }, }, }), new InjectedConnector({ chains, options: { name: 'Injected' }, }), ] - }, }) ``` * [#596](https://github.com/tmm/wagmi/pull/596) [`a770af7`](https://github.com/tmm/wagmi/commit/a770af7d2cb214b6620d5341115f1e938e1e77ff) Thanks [@tmm](https://github.com/tmm)! - **Breaking**: `TypedDataDomain` and `TypedDataField` types were removed and incorporated into `SignTypedDataArgs`. - [#582](https://github.com/tmm/wagmi/pull/582) [`b03830a`](https://github.com/tmm/wagmi/commit/b03830a54465215c2526f9509543fe2c978bfe70) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The following changes were made to the `useAccount` configuration: ## `onConnect` has been added The `onConnect` callback is invoked when the account connects. It provides the connected address & connector, as well as a `isReconnected` flag for if the user reconnected via `autoConnect`. ```tsx const account = useAccount({ onConnect({ address, connector, isReconnected }) { console.log("Connected"); }, }); ``` ## `onDisconnect` has been added The `onDisconnect` callback is invoked when the account disconnected. ```tsx const account = useAccount({ onDisconnect() { console.log("Disconnected"); }, }); ``` ## `suspense` has been removed The `useAccount` hook is a synchronous hook – so `suspense` never worked. ```diff const account = useAccount({ - suspense: true, }) ``` ## `onError` has been removed The `useAccount` hook never had any error definitions – so `onError` was never invoked. ```diff const account = useAccount({ - onError(error) { - console.log('Error', error) - }, }) ``` ## `onSettled` has been removed The `useAccount` hook is a synchronous hook. `onSettled` was always invoked immediately. ```diff const account = useAccount({ - onSettled(data) { - console.log('Settled', data) - }, }) ``` If you used `onSettled`, you can move the code beneath the `useAccount` hook: ```diff const account = useAccount({ - onSettled(data) { - console.log('Address:', data.address) - }, }) + console.log('Address:', account.address) ``` ## `onSuccess` has been removed The `useAccount` hook is a synchronous hook. `onSuccess` was always invoked immediately. ```diff const account = useAccount({ - onSuccess(data) { - console.log('Success', data) - }, }) ``` If you used `onSuccess`, you can move the code beneath the `useAccount` hook: ```diff const account = useAccount({ - onSuccess(data) { - console.log('Address:', data.address) - }, }) + console.log('Address:', account.address) ``` * [#582](https://github.com/tmm/wagmi/pull/582) [`b03830a`](https://github.com/tmm/wagmi/commit/b03830a54465215c2526f9509543fe2c978bfe70) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The following changes were made to the `useConnect` return value: ### Connection status flags have been moved The `isConnected`, `isConnecting`, `isReconnecting` & `isDisconnected` flags have been moved to the `useAccount` hook. ```diff -import { useConnect } from 'wagmi' +import { useAccount } from 'wagmi' function App() { const { isConnected, isConnecting, isConnecting, isDisconnected - } = useConnect() + } = useAccount() } ``` ### New `connect` mutation status flags have been added The `isLoading`, `isSuccess` and `isError` flags have been added to `useConnect`. These flags represent the **local** async state of `useConnect`. ### `activeConnector` has been removed The `activeConnector` value has been removed. You can find the active connector on `useAccount`. ```diff -import { useConnect } from 'wagmi' +import { useAccount } from 'wagmi' function App() { - const { activeConnector } = useConnect() + const { connector } = useAccount() } ``` - [#582](https://github.com/tmm/wagmi/pull/582) [`b03830a`](https://github.com/tmm/wagmi/commit/b03830a54465215c2526f9509543fe2c978bfe70) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The following changes were made to the `useConnect` configuration: ### `onBeforeConnect` has been renamed The `onBeforeConnect` callback has been renamed to `onMutate` ### `onConnect` has been renamed The `onConnect` callback has been renamed to `onSuccess` * [#582](https://github.com/tmm/wagmi/pull/582) [`b03830a`](https://github.com/tmm/wagmi/commit/b03830a54465215c2526f9509543fe2c978bfe70) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The `connector` parameter to `connect` & `connectAsync` now has to be in the config object parameter shape. ```diff import { useConnect } from 'wagmi' function App() { const { connect, connectors } = useConnect() return ( ) } ``` - [#582](https://github.com/tmm/wagmi/pull/582) [`b03830a`](https://github.com/tmm/wagmi/commit/b03830a54465215c2526f9509543fe2c978bfe70) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The "switch network" functionality has been moved out of `useNetwork` into a new `useSwitchNetwork` hook. The `useNetwork` hook now accepts no configuration and only returns `chain` (renamed from `activeChain`) and `chains`. ```diff import { useNetwork + useSwitchNetwork } from 'wagmi' const { - activeChain + chain, chains, - data, - error, - isError, - isIdle, - isLoading, - isSuccess, - pendingChainId, - switchNetwork, - switchNetworkAsync, - status, - reset, -} = useNetwork({ - chainId: 69, - onError(error) {}, - onMutate(args) {}, - onSettled(data, error) {}, - onSuccess(data) {} -}) +} = useNetwork() +const { + data, + error, + isError, + isIdle, + isLoading, + isSuccess, + pendingChainId, + switchNetwork, + switchNetworkAsync, + status, + reset, +} = useSwitchNetwork({ + chainId: 69, + onError(error) {}, + onMutate(args) {}, + onSettled(data, error) {}, + onSuccess(data) {} +}) ``` * [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4) Thanks [@jxom](https://github.com/jxom)! - **Breaking**: The `useContractRead` hook parameters have been consolidated into a singular config parameter. Before: ```tsx useContractRead( { addressOrName: wagmigotchiContractAddress, contractInterface: wagmigotchiABI, }, "love", { args: "0x27a69ffba1e939ddcfecc8c7e0f967b872bac65c" }, ); ``` After: ```tsx useContractRead({ addressOrName: wagmigotchiContractAddress, contractInterface: wagmigotchiABI, functionName: "love", args: "0x27a69ffba1e939ddcfecc8c7e0f967b872bac65c", }); ``` ### Patch Changes - [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4) Thanks [@jxom](https://github.com/jxom)! - Added a `useContractInfiniteReads` hook that provides the ability to call multiple ethers Contract read-only methods with "infinite scrolling" ("fetch more") support. Useful for rendering a dynamic list of contract data. [Learn more](https://wagmi.sh/docs/hooks/useContractInfiniteReads) * [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4) Thanks [@jxom](https://github.com/jxom)! - Added a `useContractReads` hook that provides the ability to batch up multiple ethers Contract read-only methods. [Learn more](https://wagmi.sh/docs/hooks/useContractReads) - [#598](https://github.com/tmm/wagmi/pull/598) [`fef26bf`](https://github.com/tmm/wagmi/commit/fef26bf8aef76fc9621e3cd54d4e0ca8f69abb38) Thanks [@markdalgleish](https://github.com/markdalgleish)! - Update `@coinbase/wallet-sdk` to fix errors when connecting with older versions of the Coinbase Wallet extension and mobile app. * [#611](https://github.com/tmm/wagmi/pull/611) [`3089c34`](https://github.com/tmm/wagmi/commit/3089c34196d4034acabac031e0a2f7ee63ae30cc) Thanks [@tmm](https://github.com/tmm)! - Added `chainId` config parameter for `useContractWrite` and `useSendTransaction`. If `chainId` is provided, the connector will validate that `chainId` is the active chain before sending a transaction (and switch to `chainId` if necessary). * Updated dependencies [[`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4), [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4), [`4f8f3c0`](https://github.com/tmm/wagmi/commit/4f8f3c0d65383bd8bbdfc3f1033adfdb11d80ebb), [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4), [`3089c34`](https://github.com/tmm/wagmi/commit/3089c34196d4034acabac031e0a2f7ee63ae30cc), [`a770af7`](https://github.com/tmm/wagmi/commit/a770af7d2cb214b6620d5341115f1e938e1e77ff), [`4f8f3c0`](https://github.com/tmm/wagmi/commit/4f8f3c0d65383bd8bbdfc3f1033adfdb11d80ebb), [`fef26bf`](https://github.com/tmm/wagmi/commit/fef26bf8aef76fc9621e3cd54d4e0ca8f69abb38), [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4), [`3089c34`](https://github.com/tmm/wagmi/commit/3089c34196d4034acabac031e0a2f7ee63ae30cc), [`b03830a`](https://github.com/tmm/wagmi/commit/b03830a54465215c2526f9509543fe2c978bfe70), [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4), [`fc94210`](https://github.com/tmm/wagmi/commit/fc94210b67daa91aa164625dfe189d5b6c2f92d4)]: - @wagmi/core@0.4.0 ## 0.4.12 ### Patch Changes - [#570](https://github.com/tmm/wagmi/pull/570) [`0e3fe15`](https://github.com/tmm/wagmi/commit/0e3fe15445377f35d6f4142b49bf1c96bfeb62cd) Thanks [@tmm](https://github.com/tmm)! - adds chain for [Foundry](https://github.com/foundry-rs) - Updated dependencies [[`0e3fe15`](https://github.com/tmm/wagmi/commit/0e3fe15445377f35d6f4142b49bf1c96bfeb62cd)]: - @wagmi/core@0.3.8 ## 0.4.11 ### Patch Changes - [#566](https://github.com/tmm/wagmi/pull/566) [`8713c00`](https://github.com/tmm/wagmi/commit/8713c00f70fcac3afef4ba183e3c87c6d3cbbf65) Thanks [@jxom](https://github.com/jxom)! - Fixed `parseContractResult` breaking `useContractRead` for more complex contract types ## 0.4.10 ### Patch Changes - [`20a1ab7`](https://github.com/tmm/wagmi/commit/20a1ab7bd02a24c4f1ea02be1bc3ecfbe4abc584) Thanks [@jxom](https://github.com/jxom)! - Updated to `react-query@4.0.0-beta.23` * [`20a1ab7`](https://github.com/tmm/wagmi/commit/20a1ab7bd02a24c4f1ea02be1bc3ecfbe4abc584) Thanks [@jxom](https://github.com/jxom)! - Fixed an issue in `useContractRead` where contract structs wouldn't be parsed back to an ethers `Result` correctly. ## 0.4.9 ### Patch Changes - [#555](https://github.com/tmm/wagmi/pull/555) [`8bf014d`](https://github.com/tmm/wagmi/commit/8bf014d8167e9f9feb1fd91488aab42dd51c92af) Thanks [@tmm](https://github.com/tmm)! - wire up `useEnsName` `chainId` ## 0.4.8 ### Patch Changes - [#550](https://github.com/tmm/wagmi/pull/550) [`2a5313e`](https://github.com/tmm/wagmi/commit/2a5313e8cbc9ba6335e8e4b85e43862c9b711bd3) Thanks [@tmm](https://github.com/tmm)! - fix `CoinbaseWalletConnector` possible type error * [#548](https://github.com/tmm/wagmi/pull/548) [`0c48719`](https://github.com/tmm/wagmi/commit/0c487199f2421f042abc1f1d139468ccbbc5646a) Thanks [@dohaki](https://github.com/dohaki)! - add ensAddress to Chain type - [#549](https://github.com/tmm/wagmi/pull/549) [`89b3a74`](https://github.com/tmm/wagmi/commit/89b3a74ead4234daacd0dcf8506659887ebf0553) Thanks [@tmm](https://github.com/tmm)! - Turns on [`noUncheckedIndexedAccess`](https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess=) and [`strictNullChecks`](https://www.typescriptlang.org/tsconfig#strictNullChecks=) for better runtime safety. - Updated dependencies [[`2a5313e`](https://github.com/tmm/wagmi/commit/2a5313e8cbc9ba6335e8e4b85e43862c9b711bd3), [`0c48719`](https://github.com/tmm/wagmi/commit/0c487199f2421f042abc1f1d139468ccbbc5646a), [`89b3a74`](https://github.com/tmm/wagmi/commit/89b3a74ead4234daacd0dcf8506659887ebf0553)]: - @wagmi/core@0.3.7 ## 0.4.7 ### Patch Changes - [#526](https://github.com/tmm/wagmi/pull/526) [`e95c5f9`](https://github.com/tmm/wagmi/commit/e95c5f91859e57d079b962a72d06b93dce004d2f) Thanks [@jxom](https://github.com/jxom)! - Added `shimChainChangedDisconnect` option to `InjectedConnector`. Defaults to `true` for `MetaMaskConnector`. * [#526](https://github.com/tmm/wagmi/pull/526) [`e95c5f9`](https://github.com/tmm/wagmi/commit/e95c5f91859e57d079b962a72d06b93dce004d2f) Thanks [@jxom](https://github.com/jxom)! - Added `chainId` config option to `useConnect()` & `connect()`. Consumers can now pick what chain they want their user to be connected to. Examples: ```tsx import { useConnect, chain } from "wagmi"; import { InjectedConnector } from "wagmi/connectors/injected"; function App() { const connect = useConnect({ chainId: chain.polygon.id, }); } ``` ```tsx import { useConnect, chain } from "wagmi"; import { InjectedConnector } from "wagmi/connectors/injected"; function App() { const connect = useConnect(); return ( ); } ``` * Updated dependencies [[`e95c5f9`](https://github.com/tmm/wagmi/commit/e95c5f91859e57d079b962a72d06b93dce004d2f), [`e95c5f9`](https://github.com/tmm/wagmi/commit/e95c5f91859e57d079b962a72d06b93dce004d2f), [`e95c5f9`](https://github.com/tmm/wagmi/commit/e95c5f91859e57d079b962a72d06b93dce004d2f)]: - @wagmi/core@0.3.6 ## 0.4.6 ### Patch Changes - [#543](https://github.com/tmm/wagmi/pull/543) [`4d489fd`](https://github.com/tmm/wagmi/commit/4d489fd630dd8c00440bdaf4d646de662c41ff52) Thanks [@tmm](https://github.com/tmm)! - fix fee data formatting for null values - Updated dependencies [[`4d489fd`](https://github.com/tmm/wagmi/commit/4d489fd630dd8c00440bdaf4d646de662c41ff52)]: - @wagmi/core@0.3.5 ## 0.4.5 ### Patch Changes - [`01cc47b`](https://github.com/tmm/wagmi/commit/01cc47b2385c78d82bc799c2dedacb2a42457e2f) Thanks [@jxom](https://github.com/jxom)! - Update `react-query` to `4.0.0-beta.19` ## 0.4.4 ### Patch Changes - [`c4deb66`](https://github.com/tmm/wagmi/commit/c4deb6655a52e4cc4e5b3fd82202db11d6106848) Thanks [@jxom](https://github.com/jxom)! - infer `options.chainId` config from `chains` on WalletConnectConnector - Updated dependencies [[`c4deb66`](https://github.com/tmm/wagmi/commit/c4deb6655a52e4cc4e5b3fd82202db11d6106848)]: - @wagmi/core@0.3.4 ## 0.4.3 ### Patch Changes - [#486](https://github.com/tmm/wagmi/pull/486) [`dbfe3dd`](https://github.com/tmm/wagmi/commit/dbfe3dd320d178d6854a8096101200c1508786bb) Thanks [@tmm](https://github.com/tmm)! - add chains entrypoint - Updated dependencies [[`dbfe3dd`](https://github.com/tmm/wagmi/commit/dbfe3dd320d178d6854a8096101200c1508786bb)]: - @wagmi/core@0.3.3 ## 0.4.2 ### Patch Changes - [`b1a2e58`](https://github.com/tmm/wagmi/commit/b1a2e5830e325be448bf865aeccda60217fc8d75) Thanks [@jxom](https://github.com/jxom)! - Made the `defaultChains` type generic in `configureChains`. ## 0.4.1 ### Patch Changes - [#484](https://github.com/tmm/wagmi/pull/484) [`1b9a503`](https://github.com/tmm/wagmi/commit/1b9a5033d51c6655b4f6570c490da6e0e9a29da9) Thanks [@tmm](https://github.com/tmm)! - export React Context - Updated dependencies [[`1b9a503`](https://github.com/tmm/wagmi/commit/1b9a5033d51c6655b4f6570c490da6e0e9a29da9)]: - @wagmi/core@0.3.1 ## 0.4.0 ### Minor Changes - [#468](https://github.com/tmm/wagmi/pull/468) [`44a884b`](https://github.com/tmm/wagmi/commit/44a884b84171c418f57701e80ef8de972948ef0b) Thanks [@tmm](https://github.com/tmm)! - **Breaking:** Duplicate exports with different names and the same functionality were removed to simplify the public API. In addition, confusing exports were renamed to be more descriptive. - `createWagmiClient` alias was removed. Use `createClient` instead. - `useWagmiClient` alias was removed. Use `useClient` instead. - `WagmiClient` alias was removed. Use `Client` instead. - `createWagmiStorage` alias was removed. Use `createStorage` instead. - `Provider` was renamed and `WagmiProvider` alias was removed. Use `WagmiConfig` instead. * [#408](https://github.com/tmm/wagmi/pull/408) [`bfcc3a5`](https://github.com/tmm/wagmi/commit/bfcc3a51bbb1551753e3ccde6af134e9fd4fec9a) Thanks [@jxom](https://github.com/jxom)! - Add `configureChains` API. The `configureChains` function allows you to configure your chains with a selected provider (Alchemy, Infura, JSON RPC, Public RPC URLs). This means you don't have to worry about deriving your own RPC URLs for each chain, or instantiating a Ethereum Provider. `configureChains` accepts 3 parameters: an array of chains, and an array of providers, and a config object. [Learn more about configuring chains & providers.](https://wagmi.sh/docs/providers/configuring-chains) ### Before ```tsx import { providers } from "ethers"; import { chain, createClient, defaultChains } from "wagmi"; import { CoinbaseWalletConnector } from "wagmi/connectors/coinbaseWallet"; import { InjectedConnector } from "wagmi/connectors/injected"; import { MetaMaskConnector } from "wagmi/connectors/metaMask"; import { WalletConnectConnector } from "wagmi/connectors/walletConnect"; const alchemyId = process.env.ALCHEMY_ID; const chains = defaultChains; const defaultChain = chain.mainnet; const client = createClient({ autoConnect: true, connectors({ chainId }) { const chain = chains.find((x) => x.id === chainId) ?? defaultChain; const rpcUrl = chain.rpcUrls.alchemy ? `${chain.rpcUrls.alchemy}/${alchemyId}` : chain.rpcUrls.default; return [ new MetaMaskConnector({ chains }), new CoinbaseWalletConnector({ chains, options: { appName: "wagmi", chainId: chain.id, jsonRpcUrl: rpcUrl, }, }), new WalletConnectConnector({ chains, options: { qrcode: true, rpc: { [chain.id]: rpcUrl }, }, }), new InjectedConnector({ chains, options: { name: "Injected", shimDisconnect: true, }, }), ]; }, provider: ({ chainId }) => new providers.AlchemyProvider(chainId, alchemyId), }); ``` ### After ```tsx import { chain, createClient, defaultChains } from "wagmi"; import { alchemyProvider } from "wagmi/providers/alchemy"; import { publicProvider } from "wagmi/providers/public"; import { CoinbaseWalletConnector } from "wagmi/connectors/coinbaseWallet"; import { InjectedConnector } from "wagmi/connectors/injected"; import { MetaMaskConnector } from "wagmi/connectors/metaMask"; import { WalletConnectConnector } from "wagmi/connectors/walletConnect"; const alchemyId = process.env.ALCHEMY_ID; const { chains, provider, webSocketProvider } = configureChains( defaultChains, [alchemyProvider({ alchemyId }), publicProvider()], ); const client = createClient({ autoConnect: true, connectors: [ new MetaMaskConnector({ chains }), new CoinbaseWalletConnector({ chains, options: { appName: "wagmi", }, }), new WalletConnectConnector({ chains, options: { qrcode: true, }, }), new InjectedConnector({ chains, options: { name: "Injected", shimDisconnect: true, }, }), ], provider, webSocketProvider, }); ``` ### Patch Changes - [#404](https://github.com/tmm/wagmi/pull/404) [`f81c156`](https://github.com/tmm/wagmi/commit/f81c15665e2e71534f84ada3fa705f2d78627472) Thanks [@holic](https://github.com/holic)! - Add `ProviderRpcError` and `RpcError` error classes. Certain wagmi-standardized errors may wrap `ProviderRpcError` or `RpcError`. For these cases, you can access the original provider rpc or rpc error value using the `internal` property. * [#459](https://github.com/tmm/wagmi/pull/459) [`72dcf7c`](https://github.com/tmm/wagmi/commit/72dcf7c09e814261b2e43a8fa364c57675c472de) Thanks [@tmm](https://github.com/tmm)! - update dependencies - [#447](https://github.com/tmm/wagmi/pull/447) [`b9ebf78`](https://github.com/tmm/wagmi/commit/b9ebf782e0900725bcb76483686b30f09d357ebd) Thanks [@tmm](https://github.com/tmm)! - Fix case where connector disconnected while app was closed and stale data was returned when autoconnecting. For example, [MetaMask was locked](https://github.com/tmm/wagmi/issues/444) when page was closed. - Updated dependencies [[`f81c156`](https://github.com/tmm/wagmi/commit/f81c15665e2e71534f84ada3fa705f2d78627472), [`bfcc3a5`](https://github.com/tmm/wagmi/commit/bfcc3a51bbb1551753e3ccde6af134e9fd4fec9a), [`44a884b`](https://github.com/tmm/wagmi/commit/44a884b84171c418f57701e80ef8de972948ef0b), [`72dcf7c`](https://github.com/tmm/wagmi/commit/72dcf7c09e814261b2e43a8fa364c57675c472de), [`a54f3e2`](https://github.com/tmm/wagmi/commit/a54f3e23ea385ed8aa4ad188128d7089ba20f83e), [`b9ebf78`](https://github.com/tmm/wagmi/commit/b9ebf782e0900725bcb76483686b30f09d357ebd), [`bfcc3a5`](https://github.com/tmm/wagmi/commit/bfcc3a51bbb1551753e3ccde6af134e9fd4fec9a)]: - @wagmi/core@0.3.0 ## 0.3.5 ### Patch Changes - [`4e03666`](https://github.com/tmm/wagmi/commit/4e03666428d42fc9186c617001b5eb356229677e) Thanks [@tmm](https://github.com/tmm)! - bump dependencies #429 add imToken support for WC switch chains #432 fix MetaMask and Brave Wallet collision #436 - Updated dependencies [[`4e03666`](https://github.com/tmm/wagmi/commit/4e03666428d42fc9186c617001b5eb356229677e)]: - @wagmi/core@0.2.5 ## 0.3.4 ### Patch Changes - [#421](https://github.com/tmm/wagmi/pull/421) [`a232b3f`](https://github.com/tmm/wagmi/commit/a232b3ff5cc41e882c4d2a34c599a8cb670edd2b) Thanks [@tmm](https://github.com/tmm)! - fix erc721 abi - Updated dependencies [[`a232b3f`](https://github.com/tmm/wagmi/commit/a232b3ff5cc41e882c4d2a34c599a8cb670edd2b)]: - @wagmi/core@0.2.4 ## 0.3.3 ### Patch Changes - [#412](https://github.com/tmm/wagmi/pull/412) [`80bef4f`](https://github.com/tmm/wagmi/commit/80bef4ff3f714b0b8f896f1b4b658acc7266299b) Thanks [@markdalgleish](https://github.com/markdalgleish)! - Import providers from `ethers` peer dependency rather than `@ethersproject/providers` to avoid multiple conflicting versions being installed - Updated dependencies [[`80bef4f`](https://github.com/tmm/wagmi/commit/80bef4ff3f714b0b8f896f1b4b658acc7266299b)]: - @wagmi/core@0.2.3 ## 0.3.2 ### Patch Changes - [`018c2a1`](https://github.com/tmm/wagmi/commit/018c2a11b22ee513571cc7f83fd63f7eb169ee70) Thanks [@tmm](https://github.com/tmm)! - - warn and fallback to default client #380 - remove signerOrProvider option from read contract #390 - MetaMaskConnector #391 - Updated dependencies [[`018c2a1`](https://github.com/tmm/wagmi/commit/018c2a11b22ee513571cc7f83fd63f7eb169ee70)]: - @wagmi/core@0.2.2 ## 0.3.1 ### Patch Changes - [`afc4607`](https://github.com/tmm/wagmi/commit/afc46071e91601ab8a2b465524da796cd60b6ad4) Thanks [@tmm](https://github.com/tmm)! - - Fix time scaling e9593df - Use fully-specified path for use-sync-external-store import 7b235c1 - Update serialize 236fc17 - Updated dependencies [[`afc4607`](https://github.com/tmm/wagmi/commit/afc46071e91601ab8a2b465524da796cd60b6ad4)]: - @wagmi/core@0.2.1 ## 0.3.0 ### Minor Changes - [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - don't persist account data when `autoConnect` is falsy * [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - - fix(@wagmi/core): persist connector chains to local storage - [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - - Favour `message` event over `connecting` event to conform to EIP-1193 - Export `useWaitForTransaction` * [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - force address to be required in `useAccount` - [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - Initial 0.3.0 release * [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - Add `cacheOnBlock` config for `useContractRead` Update `react-query` to v4 Fix `watchBlockNumber` listener leak - [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - - fix `useContractWrite` mutation fn arguments * [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - Update react-query to 4.0.0-beta.5 ### Patch Changes - [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - add chainId to actions and hooks * [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - showtime - [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - improve type support for ethers providers * [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - update zustand - [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - update babel target * [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - update block explorers and rpc urls structure - [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - keep previous data when watching * [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - republish - [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - fix stale connectors when switching chains * [#311](https://github.com/tmm/wagmi/pull/311) [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d) Thanks [@tmm](https://github.com/tmm)! - last beta * Updated dependencies [[`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d), [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d), [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d), [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d), [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d), [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d), [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d), [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d), [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d), [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d), [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d), [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d), [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d), [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d), [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d), [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d), [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d), [`24ce011`](https://github.com/tmm/wagmi/commit/24ce0113022b890e9582c6cc24035926e0d2b32d)]: - @wagmi/core@0.2.0 ## 0.3.0-next.21 ### Patch Changes - showtime - Updated dependencies []: - @wagmi/core@0.2.0-next.18 ## 0.3.0-next.20 ### Patch Changes - update block explorers and rpc urls structure - Updated dependencies []: - @wagmi/core@0.2.0-next.17 ## 0.3.0-next.19 ### Minor Changes - Update react-query to 4.0.0-beta.5 ## 0.3.0-next.18 ### Patch Changes - last beta - Updated dependencies []: - @wagmi/core@0.2.0-next.16 ## 0.3.0-next.17 ### Patch Changes - update zustand - Updated dependencies []: - @wagmi/core@0.2.0-next.15 ## 0.3.0-next.16 ### Minor Changes - Add `cacheOnBlock` config for `useContractRead` - Update `react-query` to v4 - Fix `watchBlockNumber` listener leak ### Patch Changes - Updated dependencies []: - @wagmi/core@0.2.0-next.14 ## 0.3.0-next.15 ### Patch Changes - keep previous data when watching - Updated dependencies []: - @wagmi/core@0.2.0-next.13 ## 0.3.0-next.14 ### Patch Changes - add chainId to actions and hooks - Updated dependencies []: - @wagmi/core@0.2.0-next.12 ## 0.3.0-next.13 ### Patch Changes - fix stale connectors when switching chains - Updated dependencies []: - @wagmi/core@0.2.0-next.11 ## 0.3.0-next.12 ### Patch Changes - republish - Updated dependencies []: - @wagmi/core@0.2.0-next.10 ## 0.3.0-next.11 ### Patch Changes - improve type support for ethers providers - Updated dependencies []: - @wagmi/core@0.2.0-next.9 ## 0.3.0-next.10 ### Patch Changes - update babel target - Updated dependencies []: - @wagmi/core@0.2.0-next.8 ## 0.3.0-next.9 ### Minor Changes - - Favour `message` event over `connecting` event to conform to EIP-1193 - Export `useWaitForTransaction` ### Patch Changes - Updated dependencies []: - @wagmi/core@0.2.0-next.7 ## 0.3.0-next.8 ### Patch Changes - Updated dependencies []: - @wagmi/core@0.2.0-next.6 ## 0.3.0-next.7 ### Minor Changes - don't persist account data when `autoConnect` is falsy ### Patch Changes - Updated dependencies []: - @wagmi/core@0.2.0-next.5 ## 0.3.0-next.6 ### Minor Changes - fix `useContractWrite` mutation fn arguments ### Patch Changes - Updated dependencies []: - @wagmi/core@0.2.0-next.4 ## 0.3.0-next.5 ### Patch Changes - Updated dependencies []: - @wagmi/core@0.2.0-next.3 ## 0.3.0-next.4 ### Minor Changes - force address to be required in `useAccount` ## 0.3.0-next.3 ### Patch Changes - Updated dependencies []: - @wagmi/core@0.2.0-next.2 ## 0.3.0-next.2 ### Minor Changes - Initial 0.3.0 release ### Patch Changes - Updated dependencies []: - @wagmi/core@0.2.0-next.1 ## 0.2.28 ### Patch Changes - [`747d895`](https://github.com/tmm/wagmi/commit/747d895a54b562958afde34b1d34e81ab5039e2c) Thanks [@tmm](https://github.com/tmm)! - add warning to WalletLinkConnector - Updated dependencies [[`747d895`](https://github.com/tmm/wagmi/commit/747d895a54b562958afde34b1d34e81ab5039e2c)]: - wagmi-core@0.1.22 ## 0.2.27 ### Patch Changes - [`c858c51`](https://github.com/tmm/wagmi/commit/c858c51b44d9039f1d0db5bcf016639f47d1931f) Thanks [@tmm](https://github.com/tmm)! - update coinbase connector - Updated dependencies [[`c858c51`](https://github.com/tmm/wagmi/commit/c858c51b44d9039f1d0db5bcf016639f47d1931f)]: - wagmi-core@0.1.21 ## 0.2.26 ### Patch Changes - Updated dependencies [[`36e6989`](https://github.com/tmm/wagmi/commit/36e69894f4c27aaad7fb6d678476c8bb870244bb)]: - wagmi-core@0.1.20 ## 0.2.25 ### Patch Changes - [`d467df6`](https://github.com/tmm/wagmi/commit/d467df6374210dbc4b016788b4beb4fded54cb4d) Thanks [@tmm](https://github.com/tmm)! - fix global type leaking - Updated dependencies [[`d467df6`](https://github.com/tmm/wagmi/commit/d467df6374210dbc4b016788b4beb4fded54cb4d)]: - wagmi-core@0.1.19 ## 0.2.24 ### Patch Changes - [#294](https://github.com/tmm/wagmi/pull/294) [`1d253f3`](https://github.com/tmm/wagmi/commit/1d253f3a59b61d24c88d25c99decd84a6c734e5d) Thanks [@tmm](https://github.com/tmm)! - change babel target - Updated dependencies [[`1d253f3`](https://github.com/tmm/wagmi/commit/1d253f3a59b61d24c88d25c99decd84a6c734e5d)]: - wagmi-core@0.1.18 ## 0.2.23 ### Patch Changes - [#292](https://github.com/tmm/wagmi/pull/292) [`53c9be1`](https://github.com/tmm/wagmi/commit/53c9be17ee0c2ae6b8f34f2351b8858257b3f5f2) Thanks [@tmm](https://github.com/tmm)! - fix private fields - Updated dependencies [[`53c9be1`](https://github.com/tmm/wagmi/commit/53c9be17ee0c2ae6b8f34f2351b8858257b3f5f2)]: - wagmi-core@0.1.17 ## 0.2.22 ### Patch Changes - [`79a2499`](https://github.com/tmm/wagmi/commit/79a249989029f818c32c0e84c0dd2c75e8aa990a) Thanks [@tmm](https://github.com/tmm)! - update build target to es2021 - Updated dependencies [[`79a2499`](https://github.com/tmm/wagmi/commit/79a249989029f818c32c0e84c0dd2c75e8aa990a)]: - wagmi-core@0.1.16 ## 0.2.21 ### Patch Changes - [`f9790b5`](https://github.com/tmm/wagmi/commit/f9790b55600df09c77bb8ca349c5a3457df1b07c) Thanks [@tmm](https://github.com/tmm)! - fix WalletConnect issue - Updated dependencies [[`f9790b5`](https://github.com/tmm/wagmi/commit/f9790b55600df09c77bb8ca349c5a3457df1b07c)]: - wagmi-core@0.1.15 ## 0.2.20 ### Patch Changes - [`fed29fb`](https://github.com/tmm/wagmi/commit/fed29fb4714abe234e2dabb63782cfc4439a10cf) Thanks [@tmm](https://github.com/tmm)! - export useSignTypedData ## 0.2.19 ### Patch Changes - [`6987278`](https://github.com/tmm/wagmi/commit/69872786e0b54b89a20945cc5471c1f4675b0a68) Thanks [@tmm](https://github.com/tmm)! - add useSignedTypeData ## 0.2.18 ### Patch Changes - [#236](https://github.com/tmm/wagmi/pull/236) [`53bad61`](https://github.com/tmm/wagmi/commit/53bad615788764e31121678083c382c1bd042fe8) Thanks [@markdalgleish](https://github.com/markdalgleish)! - Updated `@walletconnect/ethereum-provider` to [v1.7.4](https://github.com/WalletConnect/walletconnect-monorepo/releases/tag/1.7.4) - Updated dependencies [[`53bad61`](https://github.com/tmm/wagmi/commit/53bad615788764e31121678083c382c1bd042fe8)]: - wagmi-core@0.1.14 ## 0.2.17 ### Patch Changes - [`8e9412a`](https://github.com/tmm/wagmi/commit/8e9412af71958301ae2f9748febb936e79900aa0) Thanks [@tmm](https://github.com/tmm)! - bump walletlink - Updated dependencies [[`8e9412a`](https://github.com/tmm/wagmi/commit/8e9412af71958301ae2f9748febb936e79900aa0)]: - wagmi-core@0.1.13 ## 0.2.16 ### Patch Changes - [#210](https://github.com/tmm/wagmi/pull/210) [`684468a`](https://github.com/tmm/wagmi/commit/684468aee3e42a1ce2b4b599f3f17d1819213de8) Thanks [@tmm](https://github.com/tmm)! - update chains to match chainslist.org - Updated dependencies [[`684468a`](https://github.com/tmm/wagmi/commit/684468aee3e42a1ce2b4b599f3f17d1819213de8)]: - wagmi-core@0.1.12 ## 0.2.15 ### Patch Changes - [#195](https://github.com/tmm/wagmi/pull/195) [`25b6083`](https://github.com/tmm/wagmi/commit/25b6083a662a0236794d1765343467691421c14b) Thanks [@tmm](https://github.com/tmm)! - rename wagmi-private to wagmi-core - Updated dependencies [[`25b6083`](https://github.com/tmm/wagmi/commit/25b6083a662a0236794d1765343467691421c14b)]: - wagmi-core@0.1.11 ## 0.2.14 ### Patch Changes - [#192](https://github.com/tmm/wagmi/pull/192) [`428cedb`](https://github.com/tmm/wagmi/commit/428cedb3dec4e3e4b9f4559c8e65932e05f94e05) Thanks [@tmm](https://github.com/tmm)! - rename core and testing packages - Updated dependencies [[`428cedb`](https://github.com/tmm/wagmi/commit/428cedb3dec4e3e4b9f4559c8e65932e05f94e05)]: - wagmi-core@0.1.10 ## 0.2.13 ### Patch Changes - [#190](https://github.com/tmm/wagmi/pull/190) [`7034bb8`](https://github.com/tmm/wagmi/commit/7034bb868412b9f481b206371280e84c2d52706d) Thanks [@tmm](https://github.com/tmm)! - add shim for metamask chain changed to prevent disconnect - Updated dependencies [[`7034bb8`](https://github.com/tmm/wagmi/commit/7034bb868412b9f481b206371280e84c2d52706d)]: - wagmi-private@0.1.9 ## 0.2.12 ### Patch Changes - [`566b47f`](https://github.com/tmm/wagmi/commit/566b47f53c80e1cdcc368d43c53b1772eeb5be20) Thanks [@tmm](https://github.com/tmm)! - fix contract read skip option ## 0.2.11 ### Patch Changes - [`09f0719`](https://github.com/tmm/wagmi/commit/09f071947012e3133362a7eb80c0f39356899190) Thanks [@tmm](https://github.com/tmm)! - - safe state updates h/t @bpierre - add useEnsResolveName hook h/t @shunkakinoki ## 0.2.10 ### Patch Changes - [#159](https://github.com/tmm/wagmi/pull/159) [`981438d`](https://github.com/tmm/wagmi/commit/981438d527fb6b5f025dd9bb405fa9e7a2751597) Thanks [@markdalgleish](https://github.com/markdalgleish)! - add `WagmiProvider` alias for `Provider` ## 0.2.9 ### Patch Changes - [#137](https://github.com/tmm/wagmi/pull/137) [`dceeb43`](https://github.com/tmm/wagmi/commit/dceeb430d9021fbf98366859cb1cd0149e80c55c) Thanks [@tmm](https://github.com/tmm)! - add siwe guide - Updated dependencies [[`dceeb43`](https://github.com/tmm/wagmi/commit/dceeb430d9021fbf98366859cb1cd0149e80c55c)]: - wagmi-private@0.1.8 ## 0.2.8 ### Patch Changes - [`b49cb89`](https://github.com/tmm/wagmi/commit/b49cb89ef59289ee1185eafab427d3ab55c17c25) Thanks [@tmm](https://github.com/tmm)! - refactor contract read/write hook state ## 0.2.7 ### Patch Changes - [`7132631`](https://github.com/tmm/wagmi/commit/713263159899feb257c11614716f0af4f6b06a14) Thanks [@tmm](https://github.com/tmm)! - update contract read and write state ## 0.2.6 ### Patch Changes - [#127](https://github.com/tmm/wagmi/pull/127) [`f05b031`](https://github.com/tmm/wagmi/commit/f05b0310f7f7e6447e9b6c81cedbb27dcf2f3649) Thanks [@tmm](https://github.com/tmm)! - update switch chain return type - Updated dependencies [[`f05b031`](https://github.com/tmm/wagmi/commit/f05b0310f7f7e6447e9b6c81cedbb27dcf2f3649)]: - wagmi-private@0.1.7 ## 0.2.5 ### Patch Changes - [`1412eed`](https://github.com/tmm/wagmi/commit/1412eed0d1494bb4f8c6845a0e890f79e4e68e03) Thanks [@tmm](https://github.com/tmm)! - add frame to injected - Updated dependencies [[`1412eed`](https://github.com/tmm/wagmi/commit/1412eed0d1494bb4f8c6845a0e890f79e4e68e03)]: - wagmi-private@0.1.6 ## 0.2.4 ### Patch Changes - [#122](https://github.com/tmm/wagmi/pull/122) [`94f599c`](https://github.com/tmm/wagmi/commit/94f599cc1de74a977956d4118d85ab0d36915471) Thanks [@tmm](https://github.com/tmm)! - add decimals to useBalance ## 0.2.3 ### Patch Changes - [`e338c3b`](https://github.com/tmm/wagmi/commit/e338c3b6cc255742be6a67593aa5da6c17e90fbd) Thanks [@tmm](https://github.com/tmm)! - checksum connector address on change events add shim to injected connector for simulating disconnect - Updated dependencies [[`e338c3b`](https://github.com/tmm/wagmi/commit/e338c3b6cc255742be6a67593aa5da6c17e90fbd)]: - wagmi-private@0.1.5 ## 0.2.2 ### Patch Changes - [`0176c4e`](https://github.com/tmm/wagmi/commit/0176c4e83fb0c5f159c3c802a1da3d6deb2184ae) Thanks [@tmm](https://github.com/tmm)! - added switchChain to WalletConnect and WalletLink connectors - Updated dependencies [[`0176c4e`](https://github.com/tmm/wagmi/commit/0176c4e83fb0c5f159c3c802a1da3d6deb2184ae)]: - wagmi-private@0.1.4 ## 0.2.1 ### Patch Changes - [`f12d9cc`](https://github.com/tmm/wagmi/commit/f12d9ccfdf87a2f75299b53a7dd6b1ad046a49d8) Thanks [@tmm](https://github.com/tmm)! - fixes overrides type ## 0.2.0 ### Minor Changes - [#98](https://github.com/tmm/wagmi/pull/98) [`b2ec758`](https://github.com/tmm/wagmi/commit/b2ec7580436f52fd35005c6dd3f4472650a14d02) Thanks [@oveddan](https://github.com/oveddan)! - Exported Context ## 0.1.7 ### Patch Changes - [`d965757`](https://github.com/tmm/wagmi/commit/d9657578bc17648716c4671b8cc35ad295bc71d2) Thanks [@tmm](https://github.com/tmm)! - use balance eth symbol ## 0.1.6 ### Patch Changes - [`071d7fb`](https://github.com/tmm/wagmi/commit/071d7fbca35ec4832700b5343661ceb2dae20598) Thanks [@tmm](https://github.com/tmm)! - add hardhat chain - Updated dependencies [[`071d7fb`](https://github.com/tmm/wagmi/commit/071d7fbca35ec4832700b5343661ceb2dae20598)]: - wagmi-private@0.1.3 ## 0.1.5 ### Patch Changes - [`db4d869`](https://github.com/tmm/wagmi/commit/db4d869fd9380b26a1f3f96ab34abd14ca73d068) Thanks [@tmm](https://github.com/tmm)! - - add global connecting property for `Provider` `autoConnect` (h/t @sammdec) - fix `useContractEvent` error (h/t @math-marcellino) ## 0.1.4 ### Patch Changes - [#73](https://github.com/tmm/wagmi/pull/73) [`0c78ccc`](https://github.com/tmm/wagmi/commit/0c78ccc4e7f311525d4ea712b79cf532899e2006) Thanks [@tmm](https://github.com/tmm)! - fix module exports ## 0.1.3 ### Patch Changes - [`78bade9`](https://github.com/tmm/wagmi/commit/78bade9d0da97ab38a7e6594c34e3841ec1c8fe6) Thanks [@tmm](https://github.com/tmm)! - add type definitions - Updated dependencies [[`78bade9`](https://github.com/tmm/wagmi/commit/78bade9d0da97ab38a7e6594c34e3841ec1c8fe6)]: - wagmi-private@0.1.2 ## 0.1.2 ### Patch Changes - [#56](https://github.com/tmm/wagmi/pull/56) [`2ebfd8e`](https://github.com/tmm/wagmi/commit/2ebfd8e85b560f25cd46cff04619c84643cab297) Thanks [@tmm](https://github.com/tmm)! - add chain support status - Updated dependencies [[`2ebfd8e`](https://github.com/tmm/wagmi/commit/2ebfd8e85b560f25cd46cff04619c84643cab297)]: - wagmi-private@0.1.1 ## 0.1.1 ### Patch Changes - [#54](https://github.com/tmm/wagmi/pull/54) [`25acd3d`](https://github.com/tmm/wagmi/commit/25acd3dfbb4498af5e1139ae9c892f5013404cbc) Thanks [@tmm](https://github.com/tmm)! - Stale contract object when useContract hook arguments change @zakangelle ## 0.1.0 ### Minor Changes - [#52](https://github.com/tmm/wagmi/pull/52) [`da7a3a6`](https://github.com/tmm/wagmi/commit/da7a3a615def2443f65c041999100ce35e9774cc) Thanks [@tmm](https://github.com/tmm)! - Moves connectors to their own entrypoints to reduce bundle size. ```ts // old - WalletLinkConnector unused, but still in final bundle import { InjectedConnector, WalletConnectConnector } from "wagmi"; // new - WalletLinkConnector not in final bundle import { InjectedConnector } from "wagmi/connectors/injected"; import { WalletConnectConnector } from "wagmi/connectors/walletConnect"; ``` ### Patch Changes - Updated dependencies [[`da7a3a6`](https://github.com/tmm/wagmi/commit/da7a3a615def2443f65c041999100ce35e9774cc)]: - wagmi-private@0.1.0 ## 0.0.17 ### Patch Changes - [#25](https://github.com/tmm/wagmi/pull/25) [`9a7dab7`](https://github.com/tmm/wagmi/commit/9a7dab78b3518658bc7d85dc397990f0d28da175) Thanks [@tmm](https://github.com/tmm)! - update response types - Updated dependencies [[`9a7dab7`](https://github.com/tmm/wagmi/commit/9a7dab78b3518658bc7d85dc397990f0d28da175)]: - wagmi-private@0.0.17 ## 0.0.16 ### Patch Changes - [`d1574cf`](https://github.com/tmm/wagmi/commit/d1574cf5f7a578ccd480889c2e375134145a4aba) Thanks [@tmm](https://github.com/tmm)! - add better type information for contract results - Updated dependencies [[`d1574cf`](https://github.com/tmm/wagmi/commit/d1574cf5f7a578ccd480889c2e375134145a4aba)]: - wagmi-private@0.0.16 ## 0.0.15 ### Patch Changes - [`3909624`](https://github.com/tmm/wagmi/commit/39096249c1fa9516beabb11735beb67c94032879) Thanks [@tmm](https://github.com/tmm)! - make contract read and write execute overrides param optional - Updated dependencies [[`3909624`](https://github.com/tmm/wagmi/commit/39096249c1fa9516beabb11735beb67c94032879)]: - wagmi-private@0.0.15 ## 0.0.14 ### Patch Changes - [`63312e2`](https://github.com/tmm/wagmi/commit/63312e2b06b8d835abc2908cba399d941ca79408) Thanks [@tmm](https://github.com/tmm)! - add once to contract event - Updated dependencies [[`63312e2`](https://github.com/tmm/wagmi/commit/63312e2b06b8d835abc2908cba399d941ca79408)]: - wagmi-private@0.0.14 ## 0.0.13 ### Patch Changes - [`6f890b0`](https://github.com/tmm/wagmi/commit/6f890b0dabbdbea913ec91cb8bfc970c05ed0a93) Thanks [@tmm](https://github.com/tmm)! - update readme - Updated dependencies [[`6f890b0`](https://github.com/tmm/wagmi/commit/6f890b0dabbdbea913ec91cb8bfc970c05ed0a93)]: - wagmi-private@0.0.13 ## 0.0.12 ### Patch Changes - [#19](https://github.com/tmm/wagmi/pull/19) [`7bc1c47`](https://github.com/tmm/wagmi/commit/7bc1c47875e9ef24e9c79cfafc6b23e7a838b5bc) Thanks [@tmm](https://github.com/tmm)! - remove console log from walletlink connector - Updated dependencies [[`7bc1c47`](https://github.com/tmm/wagmi/commit/7bc1c47875e9ef24e9c79cfafc6b23e7a838b5bc)]: - wagmi-private@0.0.12 ## 0.0.11 ### Patch Changes - [#17](https://github.com/tmm/wagmi/pull/17) [`571648b`](https://github.com/tmm/wagmi/commit/571648b754f7f538536bafc9387bd3104657ea49) Thanks [@tmm](https://github.com/tmm)! - standardize connector provider - Updated dependencies [[`571648b`](https://github.com/tmm/wagmi/commit/571648b754f7f538536bafc9387bd3104657ea49)]: - wagmi-private@0.0.11 ## 0.0.10 ### Patch Changes - [#15](https://github.com/tmm/wagmi/pull/15) [`5f7675c`](https://github.com/tmm/wagmi/commit/5f7675c3ffd848522d4117c07c1f62b17dfc6616) Thanks [@tmm](https://github.com/tmm)! - read and write contract functions - Updated dependencies [[`5f7675c`](https://github.com/tmm/wagmi/commit/5f7675c3ffd848522d4117c07c1f62b17dfc6616)]: - wagmi-private@0.0.10 ## 0.0.9 ### Patch Changes - [#13](https://github.com/tmm/wagmi/pull/13) [`e5545f5`](https://github.com/tmm/wagmi/commit/e5545f5565cf0bbf5e62ec7ccab3051705b1d313) Thanks [@tmm](https://github.com/tmm)! - add testing package - Updated dependencies [[`e5545f5`](https://github.com/tmm/wagmi/commit/e5545f5565cf0bbf5e62ec7ccab3051705b1d313)]: - wagmi-private@0.0.9 ## 0.0.8 ### Patch Changes - [`5332500`](https://github.com/tmm/wagmi/commit/5332500918ac240d29ffe4d2aed8566a8ac001e4) Thanks [@tmm](https://github.com/tmm)! - update signing - Updated dependencies [[`5332500`](https://github.com/tmm/wagmi/commit/5332500918ac240d29ffe4d2aed8566a8ac001e4)]: - wagmi-private@0.0.8 ## 0.0.7 ### Patch Changes - [`0bff89a`](https://github.com/tmm/wagmi/commit/0bff89ab2ad28b2cb9b346d1ac870e859d9278bc) Thanks [@tmm](https://github.com/tmm)! - update injected connector - Updated dependencies [[`0bff89a`](https://github.com/tmm/wagmi/commit/0bff89ab2ad28b2cb9b346d1ac870e859d9278bc)]: - wagmi-private@0.0.7 ## 0.0.6 ### Patch Changes - [`37d39d1`](https://github.com/tmm/wagmi/commit/37d39d174ddfa122462bbe2d02141cd61eb9db4a) Thanks [@tmm](https://github.com/tmm)! - add message signing - Updated dependencies [[`37d39d1`](https://github.com/tmm/wagmi/commit/37d39d174ddfa122462bbe2d02141cd61eb9db4a)]: - wagmi-private@0.0.6 ## 0.0.5 ### Patch Changes - [`d7d94f0`](https://github.com/tmm/wagmi/commit/d7d94f06f7d30468e5e39d64db63124c6315cf82) Thanks [@tmm](https://github.com/tmm)! - fix injected connector name - Updated dependencies [[`d7d94f0`](https://github.com/tmm/wagmi/commit/d7d94f06f7d30468e5e39d64db63124c6315cf82)]: - wagmi-private@0.0.5 ## 0.0.4 ### Patch Changes - [`29fbe29`](https://github.com/tmm/wagmi/commit/29fbe2920046b9e87a34faa04500ccf3c4f83748) Thanks [@tmm](https://github.com/tmm)! - fix external deps - Updated dependencies [[`29fbe29`](https://github.com/tmm/wagmi/commit/29fbe2920046b9e87a34faa04500ccf3c4f83748)]: - wagmi-private@0.0.4 ## 0.0.3 ### Patch Changes - [#6](https://github.com/tmm/wagmi/pull/6) [`8dc3a5d`](https://github.com/tmm/wagmi/commit/8dc3a5d5f418813b09663534fe585d9bcf94dbeb) Thanks [@tmm](https://github.com/tmm)! - clean up deps - Updated dependencies [[`8dc3a5d`](https://github.com/tmm/wagmi/commit/8dc3a5d5f418813b09663534fe585d9bcf94dbeb)]: - wagmi-private@0.0.3 ## 0.0.2 ### Patch Changes - [#4](https://github.com/tmm/wagmi/pull/4) [`2fbd821`](https://github.com/tmm/wagmi/commit/2fbd8216379bd03c9cc5c06b10b75637e75cb7d8) Thanks [@tmm](https://github.com/tmm)! - init changesets - Updated dependencies [[`2fbd821`](https://github.com/tmm/wagmi/commit/2fbd8216379bd03c9cc5c06b10b75637e75cb7d8)]: - wagmi-private@0.0.2 ================================================ FILE: packages/react/README.md ================================================ # wagmi React Hooks for Ethereum ## Installation ```bash pnpm add wagmi viem @tanstack/react-query ``` ## Documentation For documentation and guides, visit [wagmi.sh](https://wagmi.sh). ================================================ FILE: packages/react/package.json ================================================ { "name": "wagmi", "description": "React Hooks for Ethereum", "version": "3.5.0", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/wevm/wagmi.git", "directory": "packages/react" }, "scripts": { "build": "pnpm run build:esm+types", "build:esm+types": "tsc --project tsconfig.build.json --outDir ./dist/esm --declaration --declarationMap --declarationDir ./dist/types", "check:types": "tsc --noEmit", "clean": "rm -rf dist tsconfig.tsbuildinfo actions chains codegen connectors query tempo", "test:build": "publint --strict && attw --pack --ignore-rules cjs-resolves-to-esm" }, "files": [ "dist/**", "!dist/**/*.tsbuildinfo", "src/**/*.ts", "!src/**/*.test.ts", "!src/**/*.test-d.ts", "/actions", "/chains", "/codegen", "/connectors", "/query", "/tempo" ], "sideEffects": false, "type": "module", "main": "./dist/esm/exports/index.js", "types": "./dist/types/exports/index.d.ts", "typings": "./dist/types/exports/index.d.ts", "exports": { ".": { "types": "./dist/types/exports/index.d.ts", "default": "./dist/esm/exports/index.js" }, "./actions": { "types": "./dist/types/exports/actions.d.ts", "default": "./dist/esm/exports/actions.js" }, "./chains": { "types": "./dist/types/exports/chains.d.ts", "default": "./dist/esm/exports/chains.js" }, "./codegen": { "types": "./dist/types/exports/codegen.d.ts", "default": "./dist/esm/exports/codegen.js" }, "./connectors": { "types": "./dist/types/exports/connectors.d.ts", "default": "./dist/esm/exports/connectors.js" }, "./query": { "types": "./dist/types/exports/query.d.ts", "default": "./dist/esm/exports/query.js" }, "./tempo": { "types": "./dist/types/exports/tempo.d.ts", "default": "./dist/esm/exports/tempo.js" }, "./package.json": "./package.json" }, "typesVersions": { "*": { "actions": [ "./dist/types/exports/actions.d.ts" ], "chains": [ "./dist/types/exports/chains.d.ts" ], "codegen": [ "./dist/types/exports/codegen.d.ts" ], "connectors": [ "./dist/types/exports/connectors.d.ts" ], "query": [ "./dist/types/exports/query.d.ts" ], "tempo": [ "./dist/types/exports/tempo.d.ts" ] } }, "peerDependencies": { "@tanstack/react-query": ">=5.0.0", "react": ">=18", "typescript": ">=5.7.3", "viem": "2.x" }, "peerDependenciesMeta": { "typescript": { "optional": true } }, "dependencies": { "@wagmi/connectors": "workspace:*", "@wagmi/core": "workspace:*", "use-sync-external-store": "1.4.0" }, "devDependencies": { "@tanstack/react-query": "catalog:", "@types/react": "catalog:", "@types/react-dom": "catalog:", "@types/use-sync-external-store": "^0.0.6", "react": "catalog:", "react-dom": "catalog:" }, "contributors": [ "awkweb.eth ", "jxom.eth " ], "funding": "https://github.com/sponsors/wevm", "keywords": [ "wagmi", "react", "hooks", "eth", "ethereum", "dapps", "wallet", "web3" ] } ================================================ FILE: packages/react/src/context.test.tsx ================================================ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { connect, createConfig, http, mock } from '@wagmi/core' import { accounts, addressRegex, config, mainnet } from '@wagmi/test' import { render } from '@wagmi/test/react' import * as React from 'react' import { expect, test } from 'vitest' import { WagmiProvider } from './context.js' import { useConnection } from './hooks/useConnection.js' import { useConnectorClient } from './hooks/useConnectorClient.js' React test('default', async () => { function Component() { const { address } = useConnection() const { data } = useConnectorClient() return (

wevm

useConnection: {address}
useConnectorClient: {data?.account?.address}
) } const queryClient = new QueryClient() const screen = await render( , ) await expect.element(screen.getByRole('heading')).toHaveTextContent('wevm') screen.unmount() }) test('fake ssr config', async () => { const config = createConfig({ chains: [mainnet], pollingInterval: 100, ssr: true, transports: { [mainnet.id]: http(), }, }) const queryClient = new QueryClient() const screen = await render(

wevm

, ) await expect.element(screen.getByRole('heading')).toHaveTextContent('wevm') screen.unmount() }) test('mock reconnect', async () => { function Component() { const { address } = useConnection() return (

{address}

) } const connector = mock({ accounts, features: { reconnect: true }, }) const config = createConfig({ chains: [mainnet], connectors: [connector], storage: null, transports: { [mainnet.id]: http(), }, }) await connect(config, { connector }) const queryClient = new QueryClient() const screen = await render( , ) await expect .element(screen.getByRole('heading')) .toHaveTextContent(addressRegex) screen.unmount() }) ================================================ FILE: packages/react/src/context.ts ================================================ 'use client' import type { ResolvedRegister, State } from '@wagmi/core' import { createContext, createElement } from 'react' import { Hydrate } from './hydrate.js' export const WagmiContext = createContext< ResolvedRegister['config'] | undefined >(undefined) export type WagmiProviderProps = { config: ResolvedRegister['config'] initialState?: State | undefined reconnectOnMount?: boolean | undefined } export function WagmiProvider( parameters: React.PropsWithChildren, ) { const { children, config } = parameters const props = { value: config } return createElement( Hydrate, parameters, createElement(WagmiContext.Provider, props, children), ) } ================================================ FILE: packages/react/src/errors/base.test.ts ================================================ import { expect, test } from 'vitest' import { BaseError } from './base.js' test('BaseError', () => { expect(new BaseError('An error occurred.')).toMatchInlineSnapshot(` [WagmiError: An error occurred. Version: wagmi@x.y.z] `) expect( new BaseError('An error occurred.', { details: 'details' }), ).toMatchInlineSnapshot(` [WagmiError: An error occurred. Details: details Version: wagmi@x.y.z] `) expect(new BaseError('', { details: 'details' })).toMatchInlineSnapshot(` [WagmiError: An error occurred. Details: details Version: wagmi@x.y.z] `) }) test('BaseError (w/ docsPath)', () => { expect( new BaseError('An error occurred.', { details: 'details', docsPath: '/lol', }), ).toMatchInlineSnapshot(` [WagmiError: An error occurred. Docs: https://wagmi.sh/react/lol.html Details: details Version: wagmi@x.y.z] `) expect( new BaseError('An error occurred.', { cause: new BaseError('error', { docsPath: '/docs' }), }), ).toMatchInlineSnapshot(` [WagmiError: An error occurred. Docs: https://wagmi.sh/react/docs.html Version: wagmi@x.y.z] `) expect( new BaseError('An error occurred.', { cause: new BaseError('error'), docsPath: '/lol', }), ).toMatchInlineSnapshot(` [WagmiError: An error occurred. Docs: https://wagmi.sh/react/lol.html Version: wagmi@x.y.z] `) expect( new BaseError('An error occurred.', { details: 'details', docsPath: '/lol', docsSlug: 'test', }), ).toMatchInlineSnapshot(` [WagmiError: An error occurred. Docs: https://wagmi.sh/react/lol.html#test Details: details Version: wagmi@x.y.z] `) }) test('BaseError (w/ metaMessages)', () => { expect( new BaseError('An error occurred.', { details: 'details', metaMessages: ['Reason: idk', 'Cause: lol'], }), ).toMatchInlineSnapshot(` [WagmiError: An error occurred. Reason: idk Cause: lol Details: details Version: wagmi@x.y.z] `) }) test('inherited BaseError', () => { const err = new BaseError('An error occurred.', { details: 'details', docsPath: '/lol', }) expect( new BaseError('An internal error occurred.', { cause: err, }), ).toMatchInlineSnapshot(` [WagmiError: An internal error occurred. Docs: https://wagmi.sh/react/lol.html Details: details Version: wagmi@x.y.z] `) }) test('inherited Error', () => { const err = new Error('details') expect( new BaseError('An internal error occurred.', { cause: err, docsPath: '/lol', }), ).toMatchInlineSnapshot(` [WagmiError: An internal error occurred. Docs: https://wagmi.sh/react/lol.html Details: details Version: wagmi@x.y.z] `) }) test('walk: no predicate fn (walks to leaf)', () => { class FooError extends BaseError {} class BarError extends BaseError {} const err = new BaseError('test1', { cause: new FooError('test2', { cause: new BarError('test3') }), }) expect(err.walk()).toMatchInlineSnapshot(` [WagmiError: test3 Version: wagmi@x.y.z] `) }) test('walk: predicate fn', () => { class FooError extends BaseError {} class BarError extends BaseError {} const err = new BaseError('test1', { cause: new FooError('test2', { cause: new BarError('test3') }), }) expect(err.walk((err) => err instanceof FooError)).toMatchInlineSnapshot(` [WagmiError: test2 Version: wagmi@x.y.z] `) }) ================================================ FILE: packages/react/src/errors/base.ts ================================================ import { BaseError as CoreError } from '@wagmi/core' import { getVersion } from '../utils/getVersion.js' export type BaseErrorType = BaseError & { name: 'WagmiError' } export class BaseError extends CoreError { override name = 'WagmiError' override get docsBaseUrl() { return 'https://wagmi.sh/react' } override get version() { return getVersion() } } ================================================ FILE: packages/react/src/errors/context.test.ts ================================================ import { expect, test } from 'vitest' import { WagmiProviderNotFoundError } from './context.js' test('WagmiProviderNotFoundError', () => { expect(new WagmiProviderNotFoundError()).toMatchInlineSnapshot(` [WagmiProviderNotFoundError: \`useConfig\` must be used within \`WagmiProvider\`. Docs: https://wagmi.sh/react/api/WagmiProvider.html Version: wagmi@x.y.z] `) }) ================================================ FILE: packages/react/src/errors/context.ts ================================================ import { BaseError } from './base.js' export type WagmiProviderNotFoundErrorType = WagmiProviderNotFoundError & { name: 'WagmiProviderNotFoundError' } export class WagmiProviderNotFoundError extends BaseError { override name = 'WagmiProviderNotFoundError' constructor() { super('`useConfig` must be used within `WagmiProvider`.', { docsPath: '/api/WagmiProvider', }) } } ================================================ FILE: packages/react/src/exports/actions.test.ts ================================================ import { expect, test } from 'vitest' import * as actions from './actions.js' test('exports', () => { expect(Object.keys(actions)).toMatchInlineSnapshot(` [ "call", "connect", "deployContract", "disconnect", "estimateFeesPerGas", "estimateGas", "estimateMaxPriorityFeePerGas", "getAccount", "getBalance", "getBlobBaseFee", "getBlock", "getBlockNumber", "getBlockTransactionCount", "getBytecode", "getCallsStatus", "getCapabilities", "getChainId", "getChains", "getClient", "getConnection", "getConnections", "getConnectorClient", "getConnectors", "getContractEvents", "getEnsAddress", "getEnsAvatar", "getEnsName", "getEnsResolver", "getEnsText", "getFeeHistory", "getGasPrice", "getProof", "getPublicClient", "getStorageAt", "getTransaction", "getTransactionConfirmations", "getTransactionCount", "getTransactionReceipt", "getWalletClient", "multicall", "prepareTransactionRequest", "readContract", "readContracts", "reconnect", "sendCalls", "sendTransaction", "showCallsStatus", "signMessage", "signTransaction", "signTypedData", "simulateContract", "switchAccount", "switchChain", "switchConnection", "verifyMessage", "verifyTypedData", "waitForCallsStatus", "waitForTransactionReceipt", "watchAccount", "watchAsset", "watchBlockNumber", "watchBlocks", "watchChainId", "watchClient", "watchConnection", "watchConnections", "watchConnectors", "watchContractEvent", "watchPendingTransactions", "watchPublicClient", "writeContract", ] `) }) ================================================ FILE: packages/react/src/exports/actions.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // @wagmi/core/actions //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module // biome-ignore lint/performance/noReExportAll: entrypoint module export * from '@wagmi/core/actions' ================================================ FILE: packages/react/src/exports/chains.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // viem/chains //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module // biome-ignore lint/performance/noReExportAll: entrypoint module export * from 'viem/chains' ================================================ FILE: packages/react/src/exports/codegen.test.ts ================================================ import { expect, test } from 'vitest' import * as codegen from './codegen.js' test('exports', () => { expect(Object.keys(codegen)).toMatchInlineSnapshot(` [ "createReadContract", "createSimulateContract", "createUseReadContract", "createUseSimulateContract", "createUseWatchContractEvent", "createUseWriteContract", "createWatchContractEvent", "createWriteContract", ] `) }) ================================================ FILE: packages/react/src/exports/codegen.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // @wagmi/core/codegen //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module // biome-ignore lint/performance/noReExportAll: entrypoint module export * from '@wagmi/core/codegen' //////////////////////////////////////////////////////////////////////////////// // Hooks //////////////////////////////////////////////////////////////////////////////// export { type CreateUseReadContractParameters, type CreateUseReadContractReturnType, createUseReadContract, } from '../hooks/codegen/createUseReadContract.js' export { type CreateUseSimulateContractParameters, type CreateUseSimulateContractReturnType, createUseSimulateContract, } from '../hooks/codegen/createUseSimulateContract.js' export { type CreateUseWatchContractEventParameters, type CreateUseWatchContractEventReturnType, createUseWatchContractEvent, } from '../hooks/codegen/createUseWatchContractEvent.js' export { type CreateUseWriteContractParameters, type CreateUseWriteContractReturnType, createUseWriteContract, } from '../hooks/codegen/createUseWriteContract.js' ================================================ FILE: packages/react/src/exports/connectors.test.ts ================================================ import { expect, test } from 'vitest' import * as connectors from './connectors.js' test('exports', () => { expect(Object.keys(connectors)).toMatchInlineSnapshot(` [ "baseAccount", "coinbaseWallet", "injected", "metaMask", "mock", "porto", "safe", "version", "walletConnect", ] `) }) ================================================ FILE: packages/react/src/exports/connectors.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // @wagmi/connectors //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module // biome-ignore lint/performance/noReExportAll: entrypoint module export * from '@wagmi/connectors' ================================================ FILE: packages/react/src/exports/index.test.ts ================================================ import { expect, test } from 'vitest' import * as react from './index.js' test('exports', () => { expect(Object.keys(react)).toMatchInlineSnapshot(` [ "BaseError", "ChainNotConfiguredError", "ConnectorAccountNotFoundError", "ConnectorAlreadyConnectedError", "ConnectorChainMismatchError", "ConnectorNotFoundError", "ConnectorUnavailableReconnectingError", "Hydrate", "ProviderNotFoundError", "SwitchChainNotSupportedError", "WagmiContext", "WagmiProvider", "WagmiProviderNotFoundError", "cookieStorage", "cookieToInitialState", "createConfig", "createConnector", "createStorage", "custom", "deepEqual", "deserialize", "fallback", "http", "injected", "mock", "noopStorage", "parseCookie", "serialize", "unstable_connector", "useAccount", "useAccountEffect", "useBalance", "useBlobBaseFee", "useBlock", "useBlockNumber", "useBlockTransactionCount", "useBytecode", "useCall", "useCallsStatus", "useCapabilities", "useChainId", "useChains", "useClient", "useConfig", "useConnect", "useConnection", "useConnectionEffect", "useConnections", "useConnectorClient", "useConnectors", "useContractEvents", "useDeployContract", "useDisconnect", "useEnsAddress", "useEnsAvatar", "useEnsName", "useEnsResolver", "useEnsText", "useEstimateFeesPerGas", "useEstimateGas", "useEstimateMaxPriorityFeePerGas", "useFeeHistory", "useGasPrice", "useInfiniteReadContracts", "usePrepareTransactionRequest", "useProof", "usePublicClient", "useReadContract", "useReadContracts", "useReconnect", "useSendCalls", "useSendCallsSync", "useSendTransaction", "useSendTransactionSync", "useShowCallsStatus", "useSignMessage", "useSignTransaction", "useSignTypedData", "useSimulateContract", "useStorageAt", "useSwitchAccount", "useSwitchChain", "useSwitchConnection", "useTransaction", "useTransactionConfirmations", "useTransactionCount", "useTransactionReceipt", "useVerifyMessage", "useVerifyTypedData", "useWaitForCallsStatus", "useWaitForTransactionReceipt", "useWalletClient", "useWatchAsset", "useWatchBlockNumber", "useWatchBlocks", "useWatchContractEvent", "useWatchPendingTransactions", "useWriteContract", "useWriteContractSync", "version", "webSocket", ] `) }) ================================================ FILE: packages/react/src/exports/index.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // Context //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module export { WagmiContext, WagmiProvider, type WagmiProviderProps, } from '../context.js' //////////////////////////////////////////////////////////////////////////////// // Errors //////////////////////////////////////////////////////////////////////////////// export { BaseError, type BaseErrorType } from '../errors/base.js' export { WagmiProviderNotFoundError, type WagmiProviderNotFoundErrorType, } from '../errors/context.js' //////////////////////////////////////////////////////////////////////////////// // Hooks //////////////////////////////////////////////////////////////////////////////// export { type UseBalanceParameters, type UseBalanceReturnType, useBalance, } from '../hooks/useBalance.js' export { type UseBlobBaseFeeParameters, type UseBlobBaseFeeReturnType, useBlobBaseFee, } from '../hooks/useBlobBaseFee.js' export { type UseBlockParameters, type UseBlockReturnType, useBlock, } from '../hooks/useBlock.js' export { type UseBlockNumberParameters, type UseBlockNumberReturnType, useBlockNumber, } from '../hooks/useBlockNumber.js' export { type UseBlockTransactionCountParameters, type UseBlockTransactionCountReturnType, useBlockTransactionCount, } from '../hooks/useBlockTransactionCount.js' export { type UseBytecodeParameters, type UseBytecodeReturnType, useBytecode, } from '../hooks/useBytecode.js' export { type UseCallParameters, type UseCallReturnType, useCall, } from '../hooks/useCall.js' export { type UseCallsStatusParameters, type UseCallsStatusReturnType, useCallsStatus, } from '../hooks/useCallsStatus.js' export { type UseCapabilitiesParameters, type UseCapabilitiesReturnType, useCapabilities, } from '../hooks/useCapabilities.js' export { type UseChainIdParameters, type UseChainIdReturnType, useChainId, } from '../hooks/useChainId.js' export { type UseChainsParameters, type UseChainsReturnType, useChains, } from '../hooks/useChains.js' export { type UseClientParameters, type UseClientReturnType, useClient, } from '../hooks/useClient.js' export { type UseConfigParameters, type UseConfigReturnType, useConfig, } from '../hooks/useConfig.js' export { type UseConnectParameters, type UseConnectReturnType, useConnect, } from '../hooks/useConnect.js' export { /** @deprecated use `UseConnectionParameters` instead */ type UseConnectionParameters as UseAccountParameters, type UseConnectionParameters, /** @deprecated use `UseConnectionsReturnType` instead */ type UseConnectionReturnType as UseAccountReturnType, type UseConnectionReturnType, /** @deprecated use `useConnection` instead */ useConnection as useAccount, useConnection, } from '../hooks/useConnection.js' export { /** @deprecated use `UseConnectionEffectParameters` instead */ type UseConnectionEffectParameters as UseAccountEffectParameters, type UseConnectionEffectParameters, /** @deprecated use `useConnectionEffect` instead */ useConnectionEffect as useAccountEffect, useConnectionEffect, } from '../hooks/useConnectionEffect.js' export { type UseConnectionsParameters, type UseConnectionsReturnType, useConnections, } from '../hooks/useConnections.js' export { type UseConnectorClientParameters, type UseConnectorClientReturnType, useConnectorClient, } from '../hooks/useConnectorClient.js' export { type UseConnectorsParameters, type UseConnectorsReturnType, useConnectors, } from '../hooks/useConnectors.js' export { type UseContractEventsParameters, type UseContractEventsReturnType, useContractEvents, } from '../hooks/useContractEvents.js' export { type UseDeployContractParameters, type UseDeployContractReturnType, useDeployContract, } from '../hooks/useDeployContract.js' export { type UseDisconnectParameters, type UseDisconnectReturnType, useDisconnect, } from '../hooks/useDisconnect.js' export { type UseEnsAddressParameters, type UseEnsAddressReturnType, useEnsAddress, } from '../hooks/useEnsAddress.js' export { type UseEnsAvatarParameters, type UseEnsAvatarReturnType, useEnsAvatar, } from '../hooks/useEnsAvatar.js' export { type UseEnsNameParameters, type UseEnsNameReturnType, useEnsName, } from '../hooks/useEnsName.js' export { type UseEnsResolverParameters, type UseEnsResolverReturnType, useEnsResolver, } from '../hooks/useEnsResolver.js' export { type UseEnsTextParameters, type UseEnsTextReturnType, useEnsText, } from '../hooks/useEnsText.js' export { type UseEstimateFeesPerGasParameters, type UseEstimateFeesPerGasReturnType, useEstimateFeesPerGas, } from '../hooks/useEstimateFeesPerGas.js' export { type UseEstimateGasParameters, type UseEstimateGasReturnType, useEstimateGas, } from '../hooks/useEstimateGas.js' export { type UseEstimateMaxPriorityFeePerGasParameters, type UseEstimateMaxPriorityFeePerGasReturnType, useEstimateMaxPriorityFeePerGas, } from '../hooks/useEstimateMaxPriorityFeePerGas.js' export { type UseFeeHistoryParameters, type UseFeeHistoryReturnType, useFeeHistory, } from '../hooks/useFeeHistory.js' export { type UseGasPriceParameters, type UseGasPriceReturnType, useGasPrice, } from '../hooks/useGasPrice.js' export { type UseInfiniteContractReadsParameters, type UseInfiniteContractReadsReturnType, useInfiniteReadContracts, } from '../hooks/useInfiniteReadContracts.js' export { type UsePrepareTransactionRequestParameters, type UsePrepareTransactionRequestReturnType, usePrepareTransactionRequest, } from '../hooks/usePrepareTransactionRequest.js' export { type UseProofParameters, type UseProofReturnType, useProof, } from '../hooks/useProof.js' export { type UsePublicClientParameters, type UsePublicClientReturnType, usePublicClient, } from '../hooks/usePublicClient.js' export { type UseReadContractParameters, type UseReadContractReturnType, useReadContract, } from '../hooks/useReadContract.js' export { type UseReadContractsParameters, type UseReadContractsReturnType, useReadContracts, } from '../hooks/useReadContracts.js' export { type UseReconnectParameters, type UseReconnectReturnType, useReconnect, } from '../hooks/useReconnect.js' export { type UseSendCallsParameters, type UseSendCallsReturnType, useSendCalls, } from '../hooks/useSendCalls.js' export { type UseSendCallsSyncParameters, type UseSendCallsSyncReturnType, useSendCallsSync, } from '../hooks/useSendCallsSync.js' export { type UseSendTransactionParameters, type UseSendTransactionReturnType, useSendTransaction, } from '../hooks/useSendTransaction.js' export { type UseSendTransactionSyncParameters, type UseSendTransactionSyncReturnType, useSendTransactionSync, } from '../hooks/useSendTransactionSync.js' export { type UseShowCallsStatusParameters, type UseShowCallsStatusReturnType, useShowCallsStatus, } from '../hooks/useShowCallsStatus.js' export { type UseSignMessageParameters, type UseSignMessageReturnType, useSignMessage, } from '../hooks/useSignMessage.js' export { type UseSignTransactionParameters, type UseSignTransactionReturnType, useSignTransaction, } from '../hooks/useSignTransaction.js' export { type UseSignTypedDataParameters, type UseSignTypedDataReturnType, useSignTypedData, } from '../hooks/useSignTypedData.js' export { type UseSimulateContractParameters, type UseSimulateContractReturnType, useSimulateContract, } from '../hooks/useSimulateContract.js' export { type UseStorageAtParameters, type UseStorageAtReturnType, useStorageAt, } from '../hooks/useStorageAt.js' export { type UseSwitchChainParameters, type UseSwitchChainReturnType, useSwitchChain, } from '../hooks/useSwitchChain.js' export { /** @deprecated use `UseSwitchConnectionParameters` instead */ type UseSwitchConnectionParameters as UseSwitchAccountParameters, type UseSwitchConnectionParameters, /** @deprecated use `UseSwitchConnectionReturnType` instead */ type UseSwitchConnectionReturnType as UseSwitchAccountReturnType, type UseSwitchConnectionReturnType, /** @deprecated use `useSwitchConnection` instead */ useSwitchConnection as useSwitchAccount, useSwitchConnection, } from '../hooks/useSwitchConnection.js' export { type UseTransactionParameters, type UseTransactionReturnType, useTransaction, } from '../hooks/useTransaction.js' export { type UseTransactionConfirmationsParameters, type UseTransactionConfirmationsReturnType, useTransactionConfirmations, } from '../hooks/useTransactionConfirmations.js' export { type UseTransactionCountParameters, type UseTransactionCountReturnType, useTransactionCount, } from '../hooks/useTransactionCount.js' export { type UseTransactionReceiptParameters, type UseTransactionReceiptReturnType, useTransactionReceipt, } from '../hooks/useTransactionReceipt.js' export { type UseVerifyMessageParameters, type UseVerifyMessageReturnType, useVerifyMessage, } from '../hooks/useVerifyMessage.js' export { type UseVerifyTypedDataParameters, type UseVerifyTypedDataReturnType, useVerifyTypedData, } from '../hooks/useVerifyTypedData.js' export { type UseWaitForCallsStatusParameters, type UseWaitForCallsStatusReturnType, useWaitForCallsStatus, } from '../hooks/useWaitForCallsStatus.js' export { type UseWaitForTransactionReceiptParameters, type UseWaitForTransactionReceiptReturnType, useWaitForTransactionReceipt, } from '../hooks/useWaitForTransactionReceipt.js' export { type UseWalletClientParameters, type UseWalletClientReturnType, useWalletClient, } from '../hooks/useWalletClient.js' export { type UseWatchAssetParameters, type UseWatchAssetReturnType, useWatchAsset, } from '../hooks/useWatchAsset.js' export { type UseWatchBlockNumberParameters, type UseWatchBlockNumberReturnType, useWatchBlockNumber, } from '../hooks/useWatchBlockNumber.js' export { type UseWatchBlocksParameters, type UseWatchBlocksReturnType, useWatchBlocks, } from '../hooks/useWatchBlocks.js' export { type UseWatchContractEventParameters, type UseWatchContractEventReturnType, useWatchContractEvent, } from '../hooks/useWatchContractEvent.js' export { type UseWatchPendingTransactionsParameters, type UseWatchPendingTransactionsReturnType, useWatchPendingTransactions, } from '../hooks/useWatchPendingTransactions.js' export { type UseWriteContractParameters, type UseWriteContractReturnType, useWriteContract, } from '../hooks/useWriteContract.js' export { type UseWriteContractSyncParameters, type UseWriteContractSyncReturnType, useWriteContractSync, } from '../hooks/useWriteContractSync.js' //////////////////////////////////////////////////////////////////////////////// // Hydrate //////////////////////////////////////////////////////////////////////////////// export { Hydrate, type HydrateProps, } from '../hydrate.js' //////////////////////////////////////////////////////////////////////////////// // @wagmi/core //////////////////////////////////////////////////////////////////////////////// export { ChainNotConfiguredError, // Errors type ChainNotConfiguredErrorType, type Config, // Config type Connection, type Connector, ConnectorAccountNotFoundError, type ConnectorAccountNotFoundErrorType, ConnectorAlreadyConnectedError, type ConnectorAlreadyConnectedErrorType, ConnectorChainMismatchError, type ConnectorChainMismatchErrorType, // Connector type ConnectorEventMap, ConnectorNotFoundError, type ConnectorNotFoundErrorType, ConnectorUnavailableReconnectingError, type ConnectorUnavailableReconnectingErrorType, type CreateConfigParameters, type CreateConnectorFn, // Storage type CreateStorageParameters, // Utilities cookieStorage, cookieToInitialState, createConfig, createConnector, createStorage, // Transports custom, deepEqual, deserialize, fallback, http, injected, mock, noopStorage, type PartializedState, ProviderNotFoundError, type ProviderNotFoundErrorType, parseCookie, // Types type Register, type ResolvedRegister, type State, type Storage, SwitchChainNotSupportedError, type SwitchChainNotSupportedErrorType, serialize, type Transport, unstable_connector, webSocket, } from '@wagmi/core' //////////////////////////////////////////////////////////////////////////////// // Version //////////////////////////////////////////////////////////////////////////////// export { version } from '../version.js' ================================================ FILE: packages/react/src/exports/query.test.ts ================================================ import { expect, test } from 'vitest' import * as query from './query.js' test('exports', () => { expect(Object.keys(query)).toMatchInlineSnapshot(` [ "callQueryKey", "callQueryOptions", "connectMutationOptions", "deployContractMutationOptions", "disconnectMutationOptions", "estimateFeesPerGasQueryKey", "estimateFeesPerGasQueryOptions", "estimateGasQueryKey", "estimateGasQueryOptions", "estimateMaxPriorityFeePerGasQueryKey", "estimateMaxPriorityFeePerGasQueryOptions", "getBalanceQueryKey", "getBalanceQueryOptions", "getBlobBaseFeeQueryKey", "getBlobBaseFeeQueryOptions", "getBlockNumberQueryKey", "getBlockNumberQueryOptions", "getBlockQueryKey", "getBlockQueryOptions", "getBlockTransactionCountQueryKey", "getBlockTransactionCountQueryOptions", "getBytecodeQueryKey", "getBytecodeQueryOptions", "getCallsStatusQueryKey", "getCallsStatusQueryOptions", "getCapabilitiesQueryKey", "getCapabilitiesQueryOptions", "getConnectorClientQueryKey", "getConnectorClientQueryOptions", "getContractEventsQueryKey", "getContractEventsQueryOptions", "getEnsAddressQueryKey", "getEnsAddressQueryOptions", "getEnsAvatarQueryKey", "getEnsAvatarQueryOptions", "getEnsNameQueryKey", "getEnsNameQueryOptions", "getEnsResolverQueryKey", "getEnsResolverQueryOptions", "getEnsTextQueryKey", "getEnsTextQueryOptions", "getFeeHistoryQueryKey", "getFeeHistoryQueryOptions", "getGasPriceQueryKey", "getGasPriceQueryOptions", "getProofQueryKey", "getProofQueryOptions", "getStorageAtQueryKey", "getStorageAtQueryOptions", "getTransactionConfirmationsQueryKey", "getTransactionConfirmationsQueryOptions", "getTransactionCountQueryKey", "getTransactionCountQueryOptions", "getTransactionQueryKey", "getTransactionQueryOptions", "getTransactionReceiptQueryKey", "getTransactionReceiptQueryOptions", "getWalletClientQueryKey", "getWalletClientQueryOptions", "hashFn", "infiniteReadContractsQueryKey", "infiniteReadContractsQueryOptions", "prepareTransactionRequestQueryKey", "prepareTransactionRequestQueryOptions", "readContractQueryKey", "readContractQueryOptions", "readContractsQueryKey", "readContractsQueryOptions", "reconnectMutationOptions", "sendCallsMutationOptions", "sendCallsSyncMutationOptions", "sendTransactionMutationOptions", "sendTransactionSyncMutationOptions", "showCallsStatusMutationOptions", "signMessageMutationOptions", "signTransactionMutationOptions", "signTypedDataMutationOptions", "simulateContractQueryKey", "simulateContractQueryOptions", "structuralSharing", "switchAccountMutationOptions", "switchChainMutationOptions", "switchConnectionMutationOptions", "useInfiniteQuery", "useMutation", "useQuery", "verifyMessageQueryKey", "verifyMessageQueryOptions", "verifyTypedDataQueryKey", "verifyTypedDataQueryOptions", "waitForCallsStatusQueryKey", "waitForCallsStatusQueryOptions", "waitForTransactionReceiptQueryKey", "waitForTransactionReceiptQueryOptions", "watchAssetMutationOptions", "writeContractMutationOptions", "writeContractSyncMutationOptions", ] `) }) ================================================ FILE: packages/react/src/exports/query.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // @wagmi/core/query //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module // biome-ignore lint/performance/noReExportAll: entrypoint module export * from '@wagmi/core/query' export { type UseInfiniteQueryParameters, type UseInfiniteQueryReturnType, type UseMutationParameters, type UseMutationReturnType, type UseQueryParameters, type UseQueryReturnType, useInfiniteQuery, useMutation, useQuery, } from '../utils/query.js' ================================================ FILE: packages/react/src/exports/tempo.test.ts ================================================ import { expect, test } from 'vitest' import * as tempo from './tempo.js' test('exports', () => { expect(Object.keys(tempo)).toMatchInlineSnapshot(` [ "Actions", "Hooks", "KeyManager", "dangerous_secp256k1", "webAuthn", ] `) }) ================================================ FILE: packages/react/src/exports/tempo.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // Tempo //////////////////////////////////////////////////////////////////////////////// /** biome-ignore-all lint/performance/noReExportAll: entrypoint */ // biome-ignore lint/performance/noBarrelFile: entrypoint module export { Actions, type Dangerous_Secp256k1Parameters, dangerous_secp256k1, KeyManager, type WebAuthnParameters, webAuthn, } from '@wagmi/core/tempo' // Export Hooks export * as Hooks from '../tempo/hooks/index.js' ================================================ FILE: packages/react/src/hooks/AGENTS.md ================================================ # Agent Guidelines Agent guidance for React hooks > **Communication Style**: Be brief, concise. Maximize information density, minimize tokens. Incomplete sentences acceptable when clear. Remove filler words. Prioritize clarity over grammar. ## Query Hook Format ```ts 'use client' import type { Config, MyActionErrorType, ResolvedRegister } from '@wagmi/core' import type { Compute } from '@wagmi/core/internal' import { type MyActionData, type MyActionOptions, myActionQueryOptions, } from '@wagmi/core/query' import type { ConfigParameter } from '../types/properties.js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseMyActionParameters< config extends Config = Config, selectData = MyActionData, > = Compute & ConfigParameter> export type UseMyActionReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useMyAction */ export function useMyAction< config extends Config = ResolvedRegister['config'], selectData = MyActionData, >( parameters: UseMyActionParameters = {}, ): UseMyActionReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = myActionQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ``` ## Key Patterns ### `'use client'` Directive All hooks must start with `'use client'` directive. ### `useConfig` and `useChainId` Query hooks always call these to get config from React context and current chain: ```ts const config = useConfig(parameters) const chainId = useChainId({ config }) ``` ### `ResolvedRegister['config']` Use `ResolvedRegister['config']` as default for `config` in the **function signature only** (not in type definitions). This allows type inference when config is injected via React context: ```ts // Type definition uses Config export type UseMyActionParameters< config extends Config = Config, selectData = MyActionData, > = ... // Function uses ResolvedRegister['config'] export function useMyAction< config extends Config = ResolvedRegister['config'], selectData = MyActionData, >(...) { ... } ``` ### `enabled` and `structuralSharing` Do NOT set `enabled` or `structuralSharing` in hooks. These are handled by `queryOptions` from `@wagmi/core/query`. ### Doc Comment Use a simple link to the docs: ```ts /** https://wagmi.sh/react/api/hooks/useMyAction */ ``` ## Type Parameter Nuances ### `Compute` vs `UnionCompute` - **`Compute`**: Use for simple hooks with straightforward parameter types - **`UnionCompute`**: Use for complex type inference (e.g., contract-related hooks) - **Neither**: Some hooks with very complex inference may not support either ### `const` Modifier Use `const` for type parameters that need literal type inference (e.g., abi, args): ```ts export function useReadContract< const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, const args extends ContractFunctionArgs, config extends Config = ResolvedRegister['config'], selectData = ReadContractData, > ``` ### Default Parameter Value - **Simple cases**: `parameters: UseMyActionParameters = {}` - **Complex generics**: `parameters: UseMyActionParameters<...> = {} as any` ================================================ FILE: packages/react/src/hooks/codegen/createUseReadContract.test-d.ts ================================================ import { abi, mainnet, optimism } from '@wagmi/test' import { assertType, expectTypeOf, test } from 'vitest' import { createUseReadContract } from './createUseReadContract.js' test('default', () => { const useReadErc20 = createUseReadContract({ abi: abi.erc20, }) const result = useReadErc20({ functionName: 'balanceOf', args: ['0x'], chainId: 123, }) expectTypeOf(result.data).toEqualTypeOf() }) test('select data', () => { const useReadErc20 = createUseReadContract({ abi: abi.erc20, }) const result = useReadErc20({ address: '0x', functionName: 'balanceOf', args: ['0x'], query: { select(data) { expectTypeOf(data).toEqualTypeOf() return data?.toString() }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) test('multichain address', () => { const useReadErc20 = createUseReadContract({ abi: abi.erc20, address: { [mainnet.id]: '0x', [optimism.id]: '0x', }, }) const result = useReadErc20({ functionName: 'balanceOf', args: ['0x'], chainId: mainnet.id, // ^? }) assertType(result.data) useReadErc20({ functionName: 'balanceOf', args: ['0x'], // @ts-expect-error chain id must match address keys chainId: 420, }) useReadErc20({ functionName: 'balanceOf', args: ['0x'], // @ts-expect-error address not allowed address: '0x', }) }) test('overloads', () => { const useReadViewOverloads = createUseReadContract({ abi: abi.viewOverloads, }) const result1 = useReadViewOverloads({ functionName: 'foo', }) assertType(result1.data) const result2 = useReadViewOverloads({ functionName: 'foo', args: [], }) assertType(result2.data) const result3 = useReadViewOverloads({ functionName: 'foo', args: ['0x'], }) assertType(result3.data) const result4 = useReadViewOverloads({ functionName: 'foo', args: ['0x', '0x'], }) assertType< | { foo: `0x${string}` bar: `0x${string}` } | undefined >(result4.data) }) test('functionName', () => { const useReadErc20BalanceOf = createUseReadContract({ abi: abi.erc20, address: '0x', functionName: 'balanceOf', }) const result = useReadErc20BalanceOf({ args: ['0x'], chainId: 1, }) expectTypeOf(result.data).toEqualTypeOf() }) test('functionName with overloads', () => { const useReadViewOverloads = createUseReadContract({ abi: abi.viewOverloads, functionName: 'foo', }) const result1 = useReadViewOverloads() assertType(result1.data) const result2 = useReadViewOverloads({ args: [], }) assertType(result2.data) const result3 = useReadViewOverloads({ args: ['0x'], }) assertType(result3.data) const result4 = useReadViewOverloads({ args: ['0x', '0x'], }) assertType< | { foo: `0x${string}` bar: `0x${string}` } | undefined >(result4.data) }) ================================================ FILE: packages/react/src/hooks/codegen/createUseReadContract.test.ts ================================================ import { connect, createConfig, disconnect, http, mock, switchChain, } from '@wagmi/core' import { abi, accounts, address, chain, config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { createUseReadContract } from './createUseReadContract.js' test('default', async () => { const useReadWagmiMintExample = createUseReadContract({ address: address.wagmiMintExample, abi: abi.wagmiMintExample, }) const { result } = await renderHook(() => useReadWagmiMintExample({ functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": 10n, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "readContract", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": [ "0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC", ], "chainId": 1, "functionName": "balanceOf", }, ], "refetch": [Function], "status": "success", } `) }) test('multichain', async () => { const useReadWagmiMintExample = createUseReadContract({ address: { [chain.mainnet.id]: address.wagmiMintExample, [chain.mainnet2.id]: address.wagmiMintExample, }, abi: abi.wagmiMintExample, }) const { result } = await renderHook(() => useReadWagmiMintExample({ functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], chainId: chain.mainnet2.id, }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": 10n, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "readContract", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": [ "0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC", ], "chainId": 456, "functionName": "balanceOf", }, ], "refetch": [Function], "status": "success", } `) }) test('functionName', async () => { const useReadWagmiMintExampleBalanceOf = createUseReadContract({ address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'balanceOf', }) const { result } = await renderHook(() => useReadWagmiMintExampleBalanceOf({ args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": 10n, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "readContract", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": [ "0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC", ], "chainId": 1, "functionName": "balanceOf", }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: syncConnectedChain on', async () => { await disconnect(config) await connect(config, { connector: config.connectors[0]!, chainId: chain.mainnet.id, }) const useReadWagmiMintExample = createUseReadContract({ address: { [chain.mainnet.id]: address.wagmiMintExample, [chain.mainnet2.id]: address.wagmiMintExample, }, abi: abi.wagmiMintExample, }) const { rerender, result } = await renderHook(() => useReadWagmiMintExample({ functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000, }) expect(result.current.queryKey).toMatchInlineSnapshot(` [ "readContract", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": [ "0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC", ], "chainId": 1, "functionName": "balanceOf", }, ] `) await switchChain(config, { chainId: chain.mainnet2.id }) rerender() await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000, }) expect(result.current.queryKey).toMatchInlineSnapshot(` [ "readContract", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": [ "0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC", ], "chainId": 456, "functionName": "balanceOf", }, ] `) await disconnect(config) }) test('behavior: syncConnectedChain off', async () => { const config = createConfig({ chains: [chain.mainnet, chain.mainnet2, chain.optimism], connectors: [mock({ accounts })], pollingInterval: 100, storage: null, syncConnectedChain: false, transports: { [chain.mainnet.id]: http(), [chain.mainnet2.id]: http(), [chain.optimism.id]: http(), }, }) await disconnect(config) await connect(config, { connector: config.connectors[0]!, chainId: chain.mainnet.id, }) const useReadWagmiMintExample = createUseReadContract({ address: { [chain.mainnet.id]: address.wagmiMintExample, [chain.mainnet2.id]: address.wagmiMintExample, }, abi: abi.wagmiMintExample, }) const { rerender, result } = await renderHook(() => useReadWagmiMintExample({ functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000, }) expect(result.current.queryKey).toMatchInlineSnapshot(` [ "readContract", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": [ "0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC", ], "chainId": 456, "functionName": "balanceOf", }, ] `) await switchChain(config, { chainId: chain.optimism.id }) rerender() await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000, }) expect(result.current.queryKey).toMatchInlineSnapshot(` [ "readContract", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": [ "0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC", ], "chainId": 456, "functionName": "balanceOf", }, ] `) await disconnect(config) }) ================================================ FILE: packages/react/src/hooks/codegen/createUseReadContract.ts ================================================ import type { Config, ReadContractErrorType, ReadContractParameters, ResolvedRegister, } from '@wagmi/core' import type { ConfigParameter, QueryParameter, ScopeKeyParameter, UnionCompute, UnionExactPartial, } from '@wagmi/core/internal' import type { ReadContractData, ReadContractQueryFnData, ReadContractQueryKey, } from '@wagmi/core/query' import type { Abi, Address, ContractFunctionArgs, ContractFunctionName, ExactPartial, } from 'viem' import { useChainId } from '../useChainId.js' import { useConfig } from '../useConfig.js' import { type UseReadContractReturnType, useReadContract, } from '../useReadContract.js' type stateMutability = 'pure' | 'view' export type CreateUseReadContractParameters< abi extends Abi | readonly unknown[], address extends Address | Record | undefined = undefined, functionName extends | ContractFunctionName | undefined = undefined, > = { abi: abi | Abi | readonly unknown[] address?: address | Address | Record | undefined functionName?: | functionName | ContractFunctionName | undefined } export type CreateUseReadContractReturnType< abi extends Abi | readonly unknown[], address extends Address | Record | undefined, functionName extends ContractFunctionName | undefined, /// omittedProperties extends 'abi' | 'address' | 'functionName' = | 'abi' | (address extends undefined ? never : 'address') | (functionName extends undefined ? never : 'functionName'), > = < name extends functionName extends ContractFunctionName ? functionName : ContractFunctionName, const args extends ContractFunctionArgs, config extends Config = ResolvedRegister['config'], selectData = ReadContractData, >( parameters?: UnionCompute< UnionExactPartial< // TODO: Ideally use UnionStrictOmit with omittedProperties (abi, address, functionName) ReadContractParameters > & ScopeKeyParameter & ConfigParameter & QueryParameter< ReadContractQueryFnData, ReadContractErrorType, selectData, ReadContractQueryKey > > & (address extends Record ? { chainId?: keyof address | undefined } : unknown) & ExactPartial>, ) => UseReadContractReturnType export function createUseReadContract< const abi extends Abi | readonly unknown[], const address extends | Address | Record | undefined = undefined, functionName extends | ContractFunctionName | undefined = undefined, >( props: CreateUseReadContractParameters, ): CreateUseReadContractReturnType { if (props.address !== undefined && typeof props.address === 'object') return (parameters) => { const config = useConfig(parameters) const configChainId = useChainId({ config }) const chainId = (parameters as { chainId?: number })?.chainId ?? configChainId return useReadContract({ ...(parameters as any), ...(props.functionName ? { functionName: props.functionName } : {}), address: props.address?.[chainId], abi: props.abi, }) } return (parameters) => { return useReadContract({ ...(parameters as any), ...(props.address ? { address: props.address } : {}), ...(props.functionName ? { functionName: props.functionName } : {}), abi: props.abi, }) } } ================================================ FILE: packages/react/src/hooks/codegen/createUseSimulateContract.test-d.ts ================================================ import { abi, mainnet, optimism } from '@wagmi/test' import type { Address } from 'viem' import { assertType, expectTypeOf, test } from 'vitest' import { createUseSimulateContract } from './createUseSimulateContract.js' test('default', () => { const useSimulateErc20 = createUseSimulateContract({ abi: abi.erc20, }) const result = useSimulateErc20({ functionName: 'transferFrom', args: ['0x', '0x', 123n], chainId: 123, }) result.data?.request.chainId expectTypeOf(result.data).toMatchTypeOf< | { result: boolean request: { chainId: 123 abi: readonly [ { readonly name: 'transferFrom' readonly type: 'function' readonly stateMutability: 'nonpayable' readonly inputs: readonly [ { readonly type: 'address'; readonly name: 'sender' }, { readonly type: 'address'; readonly name: 'recipient' }, { readonly type: 'uint256'; readonly name: 'amount' }, ] readonly outputs: readonly [{ type: 'bool' }] }, ] functionName: 'transferFrom' args: readonly [Address, Address, bigint] } } | undefined >() }) test('select data', () => { const useSimulateErc20 = createUseSimulateContract({ abi: abi.erc20, }) const result = useSimulateErc20({ address: '0x', functionName: 'transferFrom', args: ['0x', '0x', 123n], query: { select(data) { expectTypeOf(data.result).toEqualTypeOf() return data?.toString() }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) test('multichain address', () => { const useSimulateErc20 = createUseSimulateContract({ abi: abi.erc20, address: { [mainnet.id]: '0x', [optimism.id]: '0x', }, }) const result = useSimulateErc20({ functionName: 'transferFrom', args: ['0x', '0x', 123n], chainId: optimism.id, }) expectTypeOf(result.data?.result).toEqualTypeOf() useSimulateErc20({ functionName: 'transferFrom', args: ['0x', '0x', 123n], // @ts-expect-error chain id must match address keys chainId: 420, }) useSimulateErc20({ functionName: 'transferFrom', args: ['0x', '0x', 123n], // @ts-expect-error address not allowed address: '0x', }) }) test('overloads', () => { const useSimulateWriteOverloads = createUseSimulateContract({ abi: abi.writeOverloads, }) const result1 = useSimulateWriteOverloads({ functionName: 'foo', }) assertType(result1.data?.result) const result2 = useSimulateWriteOverloads({ functionName: 'foo', args: [], }) assertType(result2.data?.result) const result3 = useSimulateWriteOverloads({ functionName: 'foo', args: ['0x'], }) assertType(result3.data?.result) const result4 = useSimulateWriteOverloads({ functionName: 'foo', args: ['0x', '0x'], }) assertType< | { foo: `0x${string}` bar: `0x${string}` } | undefined >(result4.data?.result) }) test('functionName', () => { const useSimulateErc20 = createUseSimulateContract({ abi: abi.erc20, functionName: 'transferFrom', }) const result = useSimulateErc20({ args: ['0x', '0x', 123n], chainId: 123, }) result.data?.request.chainId expectTypeOf(result.data).toMatchTypeOf< | { result: boolean request: { chainId: 123 abi: readonly [ { readonly name: 'transferFrom' readonly type: 'function' readonly stateMutability: 'nonpayable' readonly inputs: readonly [ { readonly type: 'address'; readonly name: 'sender' }, { readonly type: 'address'; readonly name: 'recipient' }, { readonly type: 'uint256'; readonly name: 'amount' }, ] readonly outputs: readonly [{ type: 'bool' }] }, ] functionName: 'transferFrom' args: readonly [Address, Address, bigint] } } | undefined >() }) test('functionName with overloads', () => { const useSimulateWriteOverloads = createUseSimulateContract({ abi: abi.writeOverloads, functionName: 'foo', }) const result1 = useSimulateWriteOverloads({}) assertType(result1.data?.result) const result2 = useSimulateWriteOverloads({ args: [], }) assertType(result2.data?.result) const result3 = useSimulateWriteOverloads({ args: ['0x'], }) assertType(result3.data?.result) const result4 = useSimulateWriteOverloads({ args: ['0x', '0x'], }) assertType< | { foo: `0x${string}` bar: `0x${string}` } | undefined >(result4.data?.result) }) ================================================ FILE: packages/react/src/hooks/codegen/createUseSimulateContract.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { abi, address, chain, config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { beforeEach, expect, test, vi } from 'vitest' import { createUseSimulateContract } from './createUseSimulateContract.js' const connector = config.connectors[0]! beforeEach(async () => { await disconnect(config).catch(() => {}) }) test('default', async () => { await connect(config, { connector }) const useSimulateWagmiMintExample = createUseSimulateContract({ address: address.wagmiMintExample, abi: abi.wagmiMintExample, }) const { result } = await renderHook(() => useSimulateWagmiMintExample({ functionName: 'mint', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": { "chainId": 1, "request": { "abi": [ { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "account": { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "type": "json-rpc", }, "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": undefined, "chainId": 1, "dataSuffix": undefined, "functionName": "mint", }, "result": undefined, }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "simulateContract", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "chainId": 1, "functionName": "mint", }, ], "refetch": [Function], "status": "success", } `) await disconnect(config, { connector }) }) test('multichain', async () => { await connect(config, { connector }) const useReadWagmiMintExample = createUseSimulateContract({ address: { [chain.mainnet.id]: address.wagmiMintExample, [chain.mainnet2.id]: address.wagmiMintExample, }, abi: abi.wagmiMintExample, }) const { result } = await renderHook(() => useReadWagmiMintExample({ functionName: 'mint', chainId: chain.mainnet2.id, }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": { "chainId": 456, "request": { "abi": [ { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "account": { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "type": "json-rpc", }, "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": undefined, "chainId": 456, "dataSuffix": undefined, "functionName": "mint", }, "result": undefined, }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "simulateContract", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "chainId": 456, "functionName": "mint", }, ], "refetch": [Function], "status": "success", } `) await disconnect(config, { connector }) }) test('functionName', async () => { await connect(config, { connector }) const useSimulateWagmiMintExample = createUseSimulateContract({ address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'mint', }) const { result } = await renderHook(() => useSimulateWagmiMintExample({})) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": { "chainId": 1, "request": { "abi": [ { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "account": { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "type": "json-rpc", }, "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": undefined, "chainId": 1, "dataSuffix": undefined, "functionName": "mint", }, "result": undefined, }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "simulateContract", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "chainId": 1, "functionName": "mint", }, ], "refetch": [Function], "status": "success", } `) await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/codegen/createUseSimulateContract.ts ================================================ import type { Config, ResolvedRegister, SimulateContractErrorType, SimulateContractParameters, } from '@wagmi/core' import type { ConfigParameter, QueryParameter, ScopeKeyParameter, UnionExactPartial, } from '@wagmi/core/internal' import type { SimulateContractData, SimulateContractQueryFnData, } from '@wagmi/core/query' import type { Abi, Address, ContractFunctionArgs, ContractFunctionName, } from 'viem' import { useChainId } from '../useChainId.js' import { useConfig } from '../useConfig.js' import { type UseSimulateContractReturnType, useSimulateContract, } from '../useSimulateContract.js' type stateMutability = 'nonpayable' | 'payable' export type CreateUseSimulateContractParameters< abi extends Abi | readonly unknown[], address extends Address | Record | undefined = undefined, functionName extends | ContractFunctionName | undefined = undefined, > = { abi: abi | Abi | readonly unknown[] address?: address | Address | Record | undefined functionName?: | functionName | ContractFunctionName | undefined } export type CreateUseSimulateContractReturnType< abi extends Abi | readonly unknown[], address extends Address | Record | undefined, functionName extends ContractFunctionName | undefined, > = < name extends functionName extends ContractFunctionName ? functionName : ContractFunctionName, const args extends ContractFunctionArgs, config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = SimulateContractData, >( parameters?: { abi?: undefined address?: address extends undefined ? Address : undefined functionName?: functionName extends undefined ? name : undefined chainId?: address extends Record ? | keyof address | (chainId extends keyof address ? chainId : never) | undefined : chainId | number | undefined } & UnionExactPartial< // TODO: Take `abi` and `address` from above and omit from below (currently breaks inference) SimulateContractParameters > & ScopeKeyParameter & ConfigParameter & QueryParameter< SimulateContractQueryFnData, SimulateContractErrorType, selectData // TODO: Add `SimulateContractQueryKey` as 4th type param (currently causes TS2589) >, ) => UseSimulateContractReturnType export function createUseSimulateContract< const abi extends Abi | readonly unknown[], const address extends | Address | Record | undefined = undefined, functionName extends | ContractFunctionName | undefined = undefined, >( props: CreateUseSimulateContractParameters, ): CreateUseSimulateContractReturnType { if (props.address !== undefined && typeof props.address === 'object') return (parameters) => { const config = useConfig(parameters) const configChainId = useChainId({ config }) const chainId = (parameters as { chainId?: number })?.chainId ?? configChainId return useSimulateContract({ ...(parameters as any), ...(props.functionName ? { functionName: props.functionName } : {}), address: props.address?.[chainId], abi: props.abi, }) } return (parameters) => { return useSimulateContract({ ...(parameters as any), ...(props.address ? { address: props.address } : {}), ...(props.functionName ? { functionName: props.functionName } : {}), abi: props.abi, }) } } ================================================ FILE: packages/react/src/hooks/codegen/createUseWatchContractEvent.test-d.ts ================================================ import { createConfig, http, webSocket } from '@wagmi/core' import { abi, mainnet, optimism } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { createUseWatchContractEvent } from './createUseWatchContractEvent.js' test('default', () => { const useWatchErc20Event = createUseWatchContractEvent({ abi: abi.erc20, }) useWatchErc20Event({ eventName: 'Transfer', chainId: 123, onLogs(logs) { expectTypeOf(logs[0]!.eventName).toEqualTypeOf<'Transfer'>() expectTypeOf(logs[0]!.args).toEqualTypeOf<{ from?: `0x${string}` | undefined to?: `0x${string}` | undefined value?: bigint | undefined }>() }, }) }) test('multichain address', () => { const useWatchErc20Event = createUseWatchContractEvent({ abi: abi.erc20, address: { [mainnet.id]: '0x', [optimism.id]: '0x', }, }) useWatchErc20Event({ eventName: 'Transfer', chainId: mainnet.id, // ^? }) useWatchErc20Event({ eventName: 'Transfer', // @ts-expect-error chain id must match address keys chainId: 420, }) useWatchErc20Event({ eventName: 'Transfer', // @ts-expect-error chain id must match address keys address: '0x', }) }) test('differing transports', () => { const useWatchErc20Event = createUseWatchContractEvent({ abi: abi.erc20, }) const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: webSocket(), }, }) useWatchErc20Event({ config, poll: false, address: '0x', onLogs() {}, }) useWatchErc20Event({ config, chainId: mainnet.id, poll: true, address: '0x', onLogs() {}, }) useWatchErc20Event({ config, chainId: mainnet.id, // @ts-expect-error poll required since http transport poll: false, address: '0x', onLogs() {}, }) useWatchErc20Event({ config, chainId: optimism.id, poll: true, address: '0x', onLogs() {}, }) useWatchErc20Event({ config, chainId: optimism.id, poll: false, address: '0x', onLogs() {}, }) }) test('eventName', () => { const useWatchErc20Event = createUseWatchContractEvent({ abi: abi.erc20, eventName: 'Transfer', }) useWatchErc20Event({ chainId: 123, onLogs(logs) { expectTypeOf(logs[0]!.eventName).toEqualTypeOf<'Transfer'>() expectTypeOf(logs[0]!.args).toEqualTypeOf<{ from?: `0x${string}` | undefined to?: `0x${string}` | undefined value?: bigint | undefined }>() }, }) }) ================================================ FILE: packages/react/src/hooks/codegen/createUseWatchContractEvent.test.ts ================================================ import { abi, address, chain, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import type { WatchEventOnLogsParameter } from 'viem' import { test } from 'vitest' import { createUseWatchContractEvent } from './createUseWatchContractEvent.js' test('default', async () => { const useWatchErc20Event = createUseWatchContractEvent({ address: address.usdc, abi: abi.wagmiMintExample, }) let logs: WatchEventOnLogsParameter = [] renderHook(() => useWatchErc20Event({ eventName: 'Transfer', onLogs(next) { logs = logs.concat(next) }, }), ) await wait(500) }) test('multichain', async () => { const useWatchErc20Event = createUseWatchContractEvent({ address: { [chain.mainnet.id]: address.usdc, [chain.mainnet2.id]: address.usdc, }, abi: abi.wagmiMintExample, }) let logs: WatchEventOnLogsParameter = [] renderHook(() => useWatchErc20Event({ eventName: 'Transfer', chainId: chain.mainnet2.id, onLogs(next) { logs = logs.concat(next) }, }), ) await wait(500) }) ================================================ FILE: packages/react/src/hooks/codegen/createUseWatchContractEvent.ts ================================================ import type { Config, ResolvedRegister, WatchContractEventParameters, } from '@wagmi/core' import type { ConfigParameter, EnabledParameter, UnionCompute, UnionExactPartial, UnionStrictOmit, } from '@wagmi/core/internal' import type { Abi, Address, ContractEventName } from 'viem' import { useChainId } from '../useChainId.js' import { useConfig } from '../useConfig.js' import { useWatchContractEvent } from '../useWatchContractEvent.js' export type CreateUseWatchContractEventParameters< abi extends Abi | readonly unknown[], address extends Address | Record | undefined = undefined, eventName extends ContractEventName | undefined = undefined, > = { abi: abi | Abi | readonly unknown[] address?: address | Address | Record | undefined eventName?: eventName | ContractEventName | undefined } export type CreateUseWatchContractEventReturnType< abi extends Abi | readonly unknown[], address extends Address | Record | undefined, eventName extends ContractEventName | undefined, /// omittedProperties extends 'abi' | 'address' | 'chainId' | 'eventName' = | 'abi' | (address extends undefined ? never : 'address') | (address extends Record ? 'chainId' : never) | (eventName extends undefined ? never : 'eventName'), > = < name extends eventName extends ContractEventName ? eventName : ContractEventName, strict extends boolean | undefined = undefined, config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], >( parameters?: UnionCompute< UnionExactPartial< UnionStrictOmit< WatchContractEventParameters, omittedProperties > > & ConfigParameter & EnabledParameter > & (address extends Record ? { chainId?: keyof address | undefined } : unknown), ) => void export function createUseWatchContractEvent< const abi extends Abi | readonly unknown[], const address extends | Address | Record | undefined = undefined, eventName extends ContractEventName | undefined = undefined, >( props: CreateUseWatchContractEventParameters, ): CreateUseWatchContractEventReturnType { if (props.address !== undefined && typeof props.address === 'object') return (parameters) => { const config = useConfig(parameters) const configChainId = useChainId({ config }) const chainId = (parameters as { chainId?: number })?.chainId ?? configChainId return useWatchContractEvent({ ...(parameters as any), ...(props.eventName ? { eventName: props.eventName } : {}), address: props.address?.[chainId], abi: props.abi, }) } return (parameters) => { return useWatchContractEvent({ ...(parameters as any), ...(props.address ? { address: props.address } : {}), ...(props.eventName ? { eventName: props.eventName } : {}), abi: props.abi, }) } } ================================================ FILE: packages/react/src/hooks/codegen/createUseWriteContract.test-d.ts ================================================ import { abi } from '@wagmi/test' import type { Address, Hash } from 'viem' import { mainnet, optimism } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { useSimulateContract } from '../useSimulateContract.js' import { createUseWriteContract } from './createUseWriteContract.js' const contextValue = { foo: 'bar' } as const test('default', () => { const useWriteErc20 = createUseWriteContract({ abi: abi.erc20, }) const { writeContract } = useWriteErc20() writeContract({ address: '0x', functionName: 'transfer', args: ['0x', 123n], }) }) test('context', () => { const useWriteErc20 = createUseWriteContract({ abi: abi.erc20, }) const { writeContract } = useWriteErc20({ mutation: { onMutate() { return contextValue }, onSuccess(data, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(variables.functionName).toEqualTypeOf() expectTypeOf(variables.args).toEqualTypeOf< readonly unknown[] | undefined >() expectTypeOf(context).toEqualTypeOf() }, }, }) writeContract( { address: '0x', functionName: 'transfer', args: ['0x', 123n], }, { onSuccess(data, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(variables.functionName).toEqualTypeOf<'transfer'>() expectTypeOf(variables.args).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, }, ) }) test('multichain address', () => { const useWriteErc20 = createUseWriteContract({ abi: abi.erc20, address: { [mainnet.id]: '0x', [optimism.id]: '0x', }, }) const { writeContract } = useWriteErc20() writeContract({ functionName: 'transfer', args: ['0x', 123n], chainId: mainnet.id, // ^? }) writeContract({ functionName: 'transfer', args: ['0x', 123n], // @ts-expect-error chain id must match address keys chainId: 420, }) writeContract({ // @ts-expect-error address not allowed address: '0x', functionName: 'transfer', args: ['0x', 123n], }) }) test('overloads', () => { const useWriteOverloads = createUseWriteContract({ abi: abi.writeOverloads, address: { [mainnet.id]: '0x', [optimism.id]: '0x', }, }) const { writeContract } = useWriteOverloads() writeContract({ functionName: 'foo', args: [], }) writeContract({ functionName: 'foo', args: ['0x'], }) writeContract({ functionName: 'foo', args: ['0x', '0x'], }) }) test('useSimulateContract', () => { const useWriteErc20 = createUseWriteContract({ abi: abi.erc20, address: { [mainnet.id]: '0x', [optimism.id]: '0x', }, }) const { data } = useSimulateContract({ address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], chainId: 1, }) const { writeContract } = useWriteErc20() const request = data?.request if (request) writeContract(request) }) test('functionName', () => { const useWriteErc20 = createUseWriteContract({ abi: abi.erc20, functionName: 'transfer', }) const { writeContract } = useWriteErc20() writeContract({ address: '0x', args: ['0x', 123n], }) }) ================================================ FILE: packages/react/src/hooks/codegen/createUseWriteContract.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { abi, address, chain, config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { createUseWriteContract } from './createUseWriteContract.js' test('default', () => { const useWriteErc20 = createUseWriteContract({ abi: abi.erc20, }) renderHook(() => useWriteErc20()) }) const connector = config.connectors[0]! test('multichain', async () => { const useWriteWagmiMintExample = createUseWriteContract({ address: { [chain.mainnet.id]: address.wagmiMintExample, [chain.mainnet2.id]: address.wagmiMintExample, }, abi: abi.wagmiMintExample, }) await connect(config, { connector }) const { result } = await renderHook(() => useWriteWagmiMintExample()) result.current.writeContract({ functionName: 'mint' }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) console.log(result.current.data) expect(result.current.data).toBeDefined() await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/codegen/createUseWriteContract.ts ================================================ import type { MutateOptions } from '@tanstack/react-query' import type { Config, ResolvedRegister, WriteContractErrorType, } from '@wagmi/core' import type { ChainIdParameter, Compute, ConnectorParameter, SelectChains, UnionCompute, UnionStrictOmit, } from '@wagmi/core/internal' import type { WriteContractData, WriteContractVariables, } from '@wagmi/core/query' import { useCallback } from 'react' import type { Abi, Account, Address, Chain, ContractFunctionArgs, ContractFunctionName, } from 'viem' import type { WriteContractParameters as viem_WriteContractParameters } from 'viem/actions' import { useChainId } from '../useChainId.js' import { useConfig } from '../useConfig.js' import { type UseWriteContractParameters, useWriteContract, type UseWriteContractReturnType as wagmi_UseWriteContractReturnType, } from '../useWriteContract.js' type stateMutability = 'nonpayable' | 'payable' export type CreateUseWriteContractParameters< abi extends Abi | readonly unknown[], address extends Address | Record | undefined = undefined, functionName extends | ContractFunctionName | undefined = undefined, > = { abi: abi | Abi | readonly unknown[] address?: address | Address | Record | undefined functionName?: | functionName | ContractFunctionName | undefined } export type CreateUseWriteContractReturnType< abi extends Abi | readonly unknown[], address extends Address | Record | undefined, functionName extends ContractFunctionName | undefined, > = ( parameters?: UseWriteContractParameters, ) => Compute< Omit< wagmi_UseWriteContractReturnType, 'writeContract' | 'writeContractAsync' > & { mutate: < const abi2 extends abi, name extends functionName extends ContractFunctionName< abi, stateMutability > ? functionName : ContractFunctionName, args extends ContractFunctionArgs, chainId extends config['chains'][number]['id'], >( variables: Variables< abi2, functionName, name, args, config, chainId, address >, options?: | MutateOptions< WriteContractData, WriteContractErrorType, WriteContractVariables< abi2, name, args, config, chainId, // use `functionName` to make sure it's not union of all possible function names name >, context > | undefined, ) => void mutateAsync: < const abi2 extends abi, name extends functionName extends ContractFunctionName< abi, stateMutability > ? functionName : ContractFunctionName, args extends ContractFunctionArgs, chainId extends config['chains'][number]['id'], >( variables: Variables< abi2, functionName, name, args, config, chainId, address >, options?: | MutateOptions< WriteContractData, WriteContractErrorType, WriteContractVariables< abi2, name, args, config, chainId, // use `functionName` to make sure it's not union of all possible function names name >, context > | undefined, ) => Promise /** @deprecated use `mutate` instead */ writeContract: < const abi2 extends abi, name extends functionName extends ContractFunctionName< abi, stateMutability > ? functionName : ContractFunctionName, args extends ContractFunctionArgs, chainId extends config['chains'][number]['id'], >( variables: Variables< abi2, functionName, name, args, config, chainId, address >, options?: | MutateOptions< WriteContractData, WriteContractErrorType, WriteContractVariables< abi2, name, args, config, chainId, // use `functionName` to make sure it's not union of all possible function names name >, context > | undefined, ) => void /** @deprecated use `mutateAsync` instead */ writeContractAsync: < const abi2 extends abi, name extends functionName extends ContractFunctionName< abi, stateMutability > ? functionName : ContractFunctionName, args extends ContractFunctionArgs, chainId extends config['chains'][number]['id'], >( variables: Variables< abi2, functionName, name, args, config, chainId, address >, options?: | MutateOptions< WriteContractData, WriteContractErrorType, WriteContractVariables< abi2, name, args, config, chainId, // use `functionName` to make sure it's not union of all possible function names name >, context > | undefined, ) => Promise } > export function createUseWriteContract< const abi extends Abi | readonly unknown[], const address extends | Address | Record | undefined = undefined, functionName extends | ContractFunctionName | undefined = undefined, >( props: CreateUseWriteContractParameters, ): CreateUseWriteContractReturnType { if (props.address !== undefined && typeof props.address === 'object') return (parameters) => { const config = useConfig(parameters) const result = useWriteContract(parameters) const configChainId = useChainId({ config }) type Args = Parameters const mutate = useCallback( (...args: Args) => { const chainId = (() => { if (args[0].chainId) return args[0].chainId return configChainId })() const variables = { ...(args[0] as any), address: chainId ? props.address?.[chainId] : undefined, ...(props.functionName ? { functionName: props.functionName } : {}), abi: props.abi, } result.writeContract(variables, args[1] as any) }, [props, configChainId, result.writeContract], ) const mutateAsync = useCallback( (...args: Args) => { const chainId = (() => { if (args[0].chainId) return args[0].chainId return configChainId })() const variables = { ...(args[0] as any), address: chainId ? props.address?.[chainId] : undefined, ...(props.functionName ? { functionName: props.functionName } : {}), abi: props.abi, } return result.writeContractAsync(variables, args[1] as any) }, [props, configChainId, result.writeContractAsync], ) return { ...(result as any), mutate, mutateAsync, writeContract: mutate, writeContractAsync: mutateAsync, } } return (parameters) => { const result = useWriteContract(parameters) type Args = Parameters const mutate = useCallback( (...args: Args) => { const variables = { ...(args[0] as any), ...(props.address ? { address: props.address } : {}), ...(props.functionName ? { functionName: props.functionName } : {}), abi: props.abi, } result.mutate(variables, args[1] as any) }, [props, result.mutate], ) const mutateAsync = useCallback( (...args: Args) => { const variables = { ...(args[0] as any), ...(props.address ? { address: props.address } : {}), ...(props.functionName ? { functionName: props.functionName } : {}), abi: props.abi, } return result.mutateAsync(variables, args[1] as any) }, [props, result.mutateAsync], ) return { ...(result as any), mutate, mutateAsync, writeContract: mutate, writeContractAsync: mutateAsync, } } } type Variables< abi extends Abi | readonly unknown[], functionName extends ContractFunctionName | undefined, name extends ContractFunctionName, args extends ContractFunctionArgs, config extends Config, chainId extends config['chains'][number]['id'], address extends Address | Record | undefined, /// allFunctionNames = ContractFunctionName, chains extends readonly Chain[] = SelectChains, omittedProperties extends 'abi' | 'address' | 'functionName' = | 'abi' | (address extends undefined ? never : 'address') | (functionName extends undefined ? never : 'functionName'), > = UnionCompute< { [key in keyof chains]: UnionStrictOmit< viem_WriteContractParameters< abi, name, args, chains[key], Account, chains[key], allFunctionNames >, omittedProperties | 'chain' > }[number] & (address extends Record ? { chainId?: | keyof address | (chainId extends keyof address ? chainId : never) | undefined } : Compute>) & ConnectorParameter > ================================================ FILE: packages/react/src/hooks/useBalance.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useBalance } from './useBalance.js' test('select data', () => { const result = useBalance({ query: { select(data) { return data?.value }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useBalance.test.ts ================================================ import { accounts, chain, testClient, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { type Address, parseEther } from 'viem' import { beforeEach, expect, test, vi } from 'vitest' import { useBalance } from './useBalance.js' const address = accounts[0] beforeEach(async () => { await testClient.mainnet.setBalance({ address, value: parseEther('10000') }) await testClient.mainnet.mine({ blocks: 1 }) await testClient.mainnet2.setBalance({ address, value: parseEther('69') }) await testClient.mainnet2.mine({ blocks: 1 }) }) test('default', async () => { const { result } = await renderHook(() => useBalance({ address })) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toMatchObject( expect.objectContaining({ decimals: expect.any(Number), symbol: expect.any(String), value: expect.any(BigInt), }), ) expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "balance", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: chainId', async () => { const { result } = await renderHook(() => useBalance({ address, chainId: chain.mainnet2.id }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": { "decimals": 18, "symbol": "WAG", "value": 69000000000000000000n, }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "balance", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 456, }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: address: undefined -> defined', async () => { let address: Address | undefined const { result, rerender } = await renderHook(() => useBalance({ address })) expect(result.current).toMatchInlineSnapshot(` { "data": undefined, "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "balance", { "address": undefined, "chainId": 1, }, ], "refetch": [Function], "status": "pending", } `) address = accounts[0] rerender() await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": { "decimals": 18, "symbol": "ETH", "value": 10000000000000000000000n, }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "balance", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: disabled when properties missing', async () => { const { result } = await renderHook(() => useBalance()) await wait(100) await vi.waitFor(() => expect(result.current.isPending).toBeTruthy()) }) ================================================ FILE: packages/react/src/hooks/useBalance.ts ================================================ 'use client' import type { Config, GetBalanceErrorType, ResolvedRegister } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetBalanceData, type GetBalanceOptions, getBalanceQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseBalanceParameters< config extends Config = Config, selectData = GetBalanceData, > = Compute & ConfigParameter> export type UseBalanceReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useBalance */ export function useBalance< config extends Config = ResolvedRegister['config'], selectData = GetBalanceData, >( parameters: UseBalanceParameters = {}, ): UseBalanceReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getBalanceQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useBlobBaseFee.test.ts ================================================ import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useBlobBaseFee } from './useBlobBaseFee.js' test('default', async () => { const { result } = await renderHook(() => useBlobBaseFee()) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current.data).toBeTypeOf('bigint') expect(result.current.queryKey[0]).toBe('blobBaseFee') }) ================================================ FILE: packages/react/src/hooks/useBlobBaseFee.ts ================================================ 'use client' import type { Config, GetBlobBaseFeeErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetBlobBaseFeeData, type GetBlobBaseFeeOptions, getBlobBaseFeeQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseBlobBaseFeeParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetBlobBaseFeeData, > = Compute< GetBlobBaseFeeOptions & ConfigParameter > export type UseBlobBaseFeeReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useBlobBaseFee */ export function useBlobBaseFee< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetBlobBaseFeeData, >( parameters: UseBlobBaseFeeParameters = {}, ): UseBlobBaseFeeReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getBlobBaseFeeQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useBlock.test-d.ts ================================================ import { createConfig, http, webSocket } from '@wagmi/core' import { mainnet, optimism } from '@wagmi/core/chains' import { expectTypeOf, test } from 'vitest' import { useBlock } from './useBlock.js' test('select data', () => { const result = useBlock({ query: { select(data) { return data?.number }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) test('differing transports', () => { const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: webSocket(), }, }) useBlock({ config, watch: { poll: false, }, }) useBlock({ config, chainId: mainnet.id, watch: { poll: true, }, }) useBlock({ config, chainId: mainnet.id, watch: { // @ts-expect-error poll: false, }, }) useBlock({ config, chainId: optimism.id, watch: { poll: true, }, }) useBlock({ config, chainId: optimism.id, watch: { poll: false, }, }) }) ================================================ FILE: packages/react/src/hooks/useBlock.test.ts ================================================ import { testClient } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useBlock } from './useBlock.js' test('mounts', async () => { const { result } = await renderHook(() => useBlock()) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toBeDefined() expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "block", { "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: watch', async () => { await testClient.mainnet.restart() const { result } = await renderHook(() => useBlock({ watch: true })) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const block = result.current.data! expect(block).toBeDefined() await testClient.mainnet.mine({ blocks: 1 }) await vi.waitFor(() => { expect(result.current.data?.number).toEqual(block.number + 1n) }) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitFor(() => { expect(result.current.data?.number).toEqual(block.number + 2n) }) }) ================================================ FILE: packages/react/src/hooks/useBlock.ts ================================================ 'use client' import { useQueryClient } from '@tanstack/react-query' import type { Config, GetBlockErrorType, ResolvedRegister } from '@wagmi/core' import type { Compute, ConfigParameter, UnionCompute, UnionStrictOmit, } from '@wagmi/core/internal' import { type GetBlockData, type GetBlockOptions, getBlockQueryOptions, } from '@wagmi/core/query' import type { BlockTag } from 'viem' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' import { type UseWatchBlocksParameters, useWatchBlocks, } from './useWatchBlocks.js' export type UseBlockParameters< includeTransactions extends boolean = false, blockTag extends BlockTag = 'latest', config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetBlockData, > = Compute< GetBlockOptions & ConfigParameter & { watch?: | boolean | UnionCompute< UnionStrictOmit< UseWatchBlocksParameters< includeTransactions, blockTag, config, chainId >, 'chainId' | 'config' | 'onBlock' | 'onError' > > | undefined } > export type UseBlockReturnType< includeTransactions extends boolean = false, blockTag extends BlockTag = 'latest', config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetBlockData, > = UseQueryReturnType /** https://wagmi.sh/react/hooks/useBlock */ export function useBlock< includeTransactions extends boolean = false, blockTag extends BlockTag = 'latest', config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetBlockData, >( parameters: UseBlockParameters< includeTransactions, blockTag, config, chainId, selectData > = {}, ): UseBlockReturnType< includeTransactions, blockTag, config, chainId, selectData > { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getBlockQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) const queryClient = useQueryClient() useWatchBlocks({ ...({ config: parameters.config, chainId: parameters.chainId!, ...(typeof parameters.watch === 'object' ? parameters.watch : {}), } as UseWatchBlocksParameters), enabled: Boolean( (options.enabled ?? true) && (typeof parameters.watch === 'object' ? parameters.watch.enabled : parameters.watch), ), onBlock(block) { queryClient.setQueryData(options.queryKey, block) }, }) return useQuery(options) as any } ================================================ FILE: packages/react/src/hooks/useBlockNumber.test-d.ts ================================================ import { createConfig, http, webSocket } from '@wagmi/core' import { mainnet, optimism } from '@wagmi/core/chains' import { expectTypeOf, test } from 'vitest' import { useBlockNumber } from './useBlockNumber.js' test('select data', () => { const result = useBlockNumber({ query: { select(data) { expectTypeOf(data).toEqualTypeOf() return data?.toString() }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) test('differing transports', () => { const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: webSocket(), }, }) useBlockNumber({ config, watch: { poll: false, }, }) useBlockNumber({ config, chainId: mainnet.id, watch: { poll: true, }, }) useBlockNumber({ config, chainId: mainnet.id, watch: { // @ts-expect-error poll: false, }, }) useBlockNumber({ config, chainId: optimism.id, watch: { poll: true, }, }) useBlockNumber({ config, chainId: optimism.id, watch: { poll: false, }, }) }) ================================================ FILE: packages/react/src/hooks/useBlockNumber.test.ts ================================================ import { testClient } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useBlockNumber } from './useBlockNumber.js' test('mounts', async () => { await testClient.mainnet.resetFork() const { result } = await renderHook(() => useBlockNumber()) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": 23535880n, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "blockNumber", { "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: watch', async () => { await testClient.mainnet.restart() const { result } = await renderHook(() => useBlockNumber({ watch: true })) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const blockNumber = result.current.data! expect(result.current.data).toBeTypeOf('bigint') await testClient.mainnet.mine({ blocks: 1 }) await vi.waitFor(() => { expect(result.current.data).toEqual(blockNumber + 1n) }) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitFor(() => { expect(result.current.data).toEqual(blockNumber + 2n) }) }) ================================================ FILE: packages/react/src/hooks/useBlockNumber.ts ================================================ 'use client' import { useQueryClient } from '@tanstack/react-query' import type { Config, GetBlockNumberErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter, UnionCompute, UnionStrictOmit, } from '@wagmi/core/internal' import { type GetBlockNumberData, type GetBlockNumberOptions, getBlockNumberQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' import { type UseWatchBlockNumberParameters, useWatchBlockNumber, } from './useWatchBlockNumber.js' export type UseBlockNumberParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetBlockNumberData, > = Compute< GetBlockNumberOptions & ConfigParameter & { watch?: | boolean | UnionCompute< UnionStrictOmit< UseWatchBlockNumberParameters, 'chainId' | 'config' | 'onBlockNumber' | 'onError' > > | undefined } > export type UseBlockNumberReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useBlockNumber */ export function useBlockNumber< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetBlockNumberData, >( parameters: UseBlockNumberParameters = {}, ): UseBlockNumberReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getBlockNumberQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) const queryClient = useQueryClient() useWatchBlockNumber({ ...({ config: parameters.config, chainId: parameters.chainId, ...(typeof parameters.watch === 'object' ? parameters.watch : {}), } as UseWatchBlockNumberParameters), enabled: Boolean( (options.enabled ?? true) && (typeof parameters.watch === 'object' ? parameters.watch.enabled : parameters.watch), ), onBlockNumber(blockNumber) { queryClient.setQueryData(options.queryKey, blockNumber) }, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useBlockTransactionCount.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useBlockTransactionCount } from './useBlockTransactionCount.js' test('select data', () => { const result = useBlockTransactionCount({ query: { select(data) { return data }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useBlockTransactionCount.test.ts ================================================ import { chain } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useBlockTransactionCount } from './useBlockTransactionCount.js' test('default', async () => { const { result } = await renderHook(() => useBlockTransactionCount({})) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toBeTypeOf('number') expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "blockTransactionCount", { "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: chainId', async () => { const { result } = await renderHook(() => useBlockTransactionCount({ chainId: chain.mainnet2.id }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toBeTypeOf('number') expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "blockTransactionCount", { "chainId": 456, }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: blockNumber', async () => { const { result } = await renderHook(() => useBlockTransactionCount({ blockNumber: 13677382n }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toBeTypeOf('number') expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "blockTransactionCount", { "blockNumber": 13677382n, "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: blockHash', async () => { const { result } = await renderHook(() => useBlockTransactionCount({ blockHash: '0x6201f37a245850d1f11e4be3ac45bc51bd9d43ee4a127192cad550f351cfa575', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toBeTypeOf('number') expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "blockTransactionCount", { "blockHash": "0x6201f37a245850d1f11e4be3ac45bc51bd9d43ee4a127192cad550f351cfa575", "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: blockTag', async () => { const { result } = await renderHook(() => useBlockTransactionCount({ blockTag: 'safe', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toBeTypeOf('number') expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "blockTransactionCount", { "blockTag": "safe", "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) ================================================ FILE: packages/react/src/hooks/useBlockTransactionCount.ts ================================================ 'use client' import type { Config, GetBlockTransactionCountErrorType, ResolvedRegister, } from '@wagmi/core' import type { ConfigParameter, UnionCompute } from '@wagmi/core/internal' import { type GetBlockTransactionCountData, type GetBlockTransactionCountOptions, getBlockTransactionCountQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseBlockTransactionCountParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetBlockTransactionCountData, > = UnionCompute< GetBlockTransactionCountOptions & ConfigParameter > export type UseBlockTransactionCountReturnType< selectData = GetBlockTransactionCountData, > = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useBlockTransactionCount */ export function useBlockTransactionCount< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetBlockTransactionCountData, >( parameters: UseBlockTransactionCountParameters< config, chainId, selectData > = {}, ): UseBlockTransactionCountReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getBlockTransactionCountQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useBytecode.test-d.ts ================================================ import type { Hex } from 'viem' import { expectTypeOf, test } from 'vitest' import { useBytecode } from './useBytecode.js' test('select data', () => { const result = useBytecode({ query: { select(data) { return data }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useBytecode.test.ts ================================================ import { address, chain, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import type { Address } from 'viem' import { expect, test, vi } from 'vitest' import { useBytecode } from './useBytecode.js' test('default', async () => { const { result } = await renderHook(() => useBytecode({ address: address.wagmiMintExample, }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getBytecode", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) expect(data).toMatch(/^0x.*/) }) test('parameters: blockNumber', async () => { const { result } = await renderHook(() => useBytecode({ address: address.wagmiMintExample, blockNumber: 15564163n, }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": null, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getBytecode", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "blockNumber": 15564163n, "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: blockTag', async () => { const { result } = await renderHook(() => useBytecode({ address: address.wagmiMintExample, blockTag: 'earliest', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": null, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getBytecode", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "blockTag": "earliest", "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: chainId', async () => { const { result } = await renderHook(() => useBytecode({ address: address.wagmiMintExample, chainId: chain.optimism.id, }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": null, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getBytecode", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "chainId": 10, }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: address: undefined -> defined', async () => { const { result, rerender } = await renderHook( (props) => useBytecode({ address: props?.address, }), { initialProps: { address: undefined as Address | undefined } }, ) expect(result.current).toMatchInlineSnapshot(` { "data": undefined, "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "getBytecode", { "address": undefined, "chainId": 1, }, ], "refetch": [Function], "status": "pending", } `) rerender({ address: address.wagmiMintExample }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getBytecode", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) expect(data).toMatch(/^0x.*/) }) test('behavior: disabled when properties missing', async () => { const { result } = await renderHook(() => useBytecode()) await wait(100) await vi.waitFor(() => expect(result.current.isPending).toBeTruthy()) }) ================================================ FILE: packages/react/src/hooks/useBytecode.ts ================================================ 'use client' import type { Config, GetBytecodeErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetBytecodeData, type GetBytecodeOptions, getBytecodeQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseBytecodeParameters< config extends Config = Config, selectData = GetBytecodeData, > = Compute & ConfigParameter> export type UseBytecodeReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useBytecode */ export function useBytecode< config extends Config = ResolvedRegister['config'], selectData = GetBytecodeData, >( parameters: UseBytecodeParameters = {}, ): UseBytecodeReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getBytecodeQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useCall.test-d.ts ================================================ import type { CallReturnType } from 'viem' import { expectTypeOf, test } from 'vitest' import { useCall } from './useCall.js' test('select data', () => { const result = useCall({ query: { select(data) { return data }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useCall.test.ts ================================================ import { accounts, address, chain } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useCall } from './useCall.js' const name4bytes = '0x06fdde03' const account = accounts[0] test('default', async () => { const { result } = await renderHook(() => useCall({ account, data: name4bytes, to: address.wagmiMintExample, }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": { "data": "0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000", }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "call", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 1, "data": "0x06fdde03", "to": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: blockTag', async () => { const { result } = await renderHook(() => useCall({ account, data: name4bytes, to: address.wagmiMintExample, blockTag: 'safe', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": { "data": "0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000", }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "call", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "blockTag": "safe", "chainId": 1, "data": "0x06fdde03", "to": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: blockNumber', async () => { const { result } = await renderHook(() => useCall({ account, data: name4bytes, to: address.wagmiMintExample, blockNumber: 16280770n, }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": { "data": "0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000", }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "call", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "blockNumber": 16280770n, "chainId": 1, "data": "0x06fdde03", "to": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: chainId', async () => { const { result } = await renderHook(() => useCall({ account, data: name4bytes, to: address.wagmiMintExample, chainId: chain.mainnet2.id, }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": { "data": "0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000", }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "call", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 456, "data": "0x06fdde03", "to": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", }, ], "refetch": [Function], "status": "success", } `) }) ================================================ FILE: packages/react/src/hooks/useCall.ts ================================================ 'use client' import type { CallErrorType, Config, ResolvedRegister } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type CallData, type CallOptions, callQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseCallParameters< config extends Config = Config, selectData = CallData, > = Compute & ConfigParameter> export type UseCallReturnType = UseQueryReturnType< selectData, CallErrorType > /** https://wagmi.sh/react/api/hooks/useCall */ export function useCall< config extends Config = ResolvedRegister['config'], selectData = CallData, >( parameters: UseCallParameters = {}, ): UseCallReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = callQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useCallsStatus.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { accounts, config, testClient } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { parseEther } from 'viem' import { expect, test, vi } from 'vitest' import { useCallsStatus } from './useCallsStatus.js' import { useSendCalls } from './useSendCalls.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const { result } = await renderHook(() => useSendCalls()) result.current.mutate({ calls: [ { data: '0xdeadbeef', to: accounts[1], value: parseEther('1'), }, { to: accounts[2], value: parseEther('2'), }, { to: accounts[3], value: parseEther('3'), }, ], }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { result: result_2 } = await renderHook(() => useCallsStatus({ id: result.current.data?.id! }), ) await vi.waitFor(() => expect(result_2.current.isSuccess).toBeTruthy(), { timeout: 10_000, }) expect(result_2.current.data).toMatchInlineSnapshot( ` { "atomic": false, "chainId": 1, "id": "0xb24b52a86aa2b0bae6f1e44868c3a13d2572e766a1f6364afd93d1757839b8a1", "receipts": [], "status": "pending", "statusCode": 100, "version": "2.0.0", } `, ) await testClient.mainnet.mine({ blocks: 1 }) const { result: result_3 } = await renderHook(() => useCallsStatus({ id: result.current.data?.id! }), ) await vi.waitFor(() => expect(result_3.current.isSuccess).toBeTruthy(), { timeout: 10_000, }) expect(result_3.current.data?.status).toBe('success') expect(result_3.current.data?.statusCode).toBe(200) expect( result_3.current.data?.receipts?.map((x) => ({ ...x, blockHash: undefined, transactionHash: undefined, })), ).toMatchInlineSnapshot( ` [ { "blockHash": undefined, "blockNumber": 23535881n, "gasUsed": 21160n, "logs": [], "status": "success", "transactionHash": undefined, }, { "blockHash": undefined, "blockNumber": 23535881n, "gasUsed": 21000n, "logs": [], "status": "success", "transactionHash": undefined, }, { "blockHash": undefined, "blockNumber": 23535881n, "gasUsed": 21000n, "logs": [], "status": "success", "transactionHash": undefined, }, ] `, ) await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/useCallsStatus.ts ================================================ 'use client' import type { Config, GetCallsStatusErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetCallsStatusData, type GetCallsStatusOptions, getCallsStatusQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useConfig } from './useConfig.js' import { useConnection } from './useConnection.js' export type UseCallsStatusParameters< config extends Config = Config, selectData = GetCallsStatusData, > = Compute & ConfigParameter> export type UseCallsStatusReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useCallsStatus */ export function useCallsStatus< config extends Config = ResolvedRegister['config'], selectData = GetCallsStatusData, >( parameters: UseCallsStatusParameters, ): UseCallsStatusReturnType { const config = useConfig(parameters) const { connector } = useConnection({ config }) const options = getCallsStatusQueryOptions(config, { ...parameters, connector: parameters.connector ?? connector, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useCapabilities.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { accounts, config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useCapabilities } from './useCapabilities.js' const connector = config.connectors[0]! test('mounts', async () => { await connect(config, { connector }) const { result } = await renderHook(() => useCapabilities()) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { queryKey: _, ...rest } = result.current expect(rest).toMatchInlineSnapshot(` { "data": { "8453": { "paymasterService": { "supported": true, }, "sessionKeys": { "supported": true, }, }, "84532": { "paymasterService": { "supported": true, }, }, }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "refetch": [Function], "status": "success", } `) await disconnect(config, { connector }) }) test('args: account', async () => { await connect(config, { connector }) const { result } = await renderHook(() => useCapabilities({ account: accounts[1] }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { queryKey: _, ...rest } = result.current expect(rest).toMatchInlineSnapshot(` { "data": { "8453": { "paymasterService": { "supported": false, }, "sessionKeys": { "supported": true, }, }, "84532": { "paymasterService": { "supported": false, }, }, }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "refetch": [Function], "status": "success", } `) await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/useCapabilities.ts ================================================ 'use client' import type { Config, GetCapabilitiesErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetCapabilitiesData, type GetCapabilitiesOptions, getCapabilitiesQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useConfig } from './useConfig.js' import { useConnection } from './useConnection.js' export type UseCapabilitiesParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = GetCapabilitiesData, > = Compute< GetCapabilitiesOptions & ConfigParameter > export type UseCapabilitiesReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = GetCapabilitiesData, > = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useCapabilities */ export function useCapabilities< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = GetCapabilitiesData, >( parameters: UseCapabilitiesParameters = {}, ): UseCapabilitiesReturnType { const config = useConfig(parameters) const { address, connector } = useConnection({ config }) const options = getCapabilitiesQueryOptions(config, { ...parameters, account: parameters.account ?? address, connector: parameters.connector ?? connector, }) return useQuery(options as never) as any } ================================================ FILE: packages/react/src/hooks/useChainId.test-d.ts ================================================ import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useChainId } from './useChainId.js' test('default', () => { const chainId = useChainId() expectTypeOf(chainId).toEqualTypeOf() }) test('parameters: config', () => { const chainId = useChainId({ config }) expectTypeOf(chainId).toEqualTypeOf<1 | 456 | 10>() }) ================================================ FILE: packages/react/src/hooks/useChainId.test.ts ================================================ import { config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { createElement, Fragment } from 'react' import { expect, test } from 'vitest' import { useChainId } from './useChainId.js' test('default', async () => { const { result, rerender } = await renderHook(() => useChainId()) expect(result.current).toMatchInlineSnapshot('1') config.setState((x) => ({ ...x, chainId: 456 })) rerender() expect(result.current).toMatchInlineSnapshot('456') }) test('parameters: config', async () => { const { result } = await renderHook(() => useChainId({ config }), { wrapper: ({ children }) => createElement(Fragment, { children }), }) expect(result.current).toBeDefined() }) ================================================ FILE: packages/react/src/hooks/useChainId.ts ================================================ 'use client' import { type Config, type GetChainIdReturnType, getChainId, type ResolvedRegister, watchChainId, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { useSyncExternalStore } from 'react' import { useConfig } from './useConfig.js' export type UseChainIdParameters = ConfigParameter export type UseChainIdReturnType = GetChainIdReturnType /** https://wagmi.sh/react/api/hooks/useChainId */ export function useChainId( parameters: UseChainIdParameters = {}, ): UseChainIdReturnType { const config = useConfig(parameters) return useSyncExternalStore( (onChange) => watchChainId(config, { onChange }), () => getChainId(config), () => getChainId(config), ) } ================================================ FILE: packages/react/src/hooks/useChains.test.ts ================================================ import { chain, config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { createElement, Fragment } from 'react' import { expect, test } from 'vitest' import { useChains } from './useChains.js' test('default', async () => { const { result } = await renderHook(() => useChains()) expect(result.current.map((x) => x.id)).toMatchInlineSnapshot(` [ 1, 456, 10, ] `) }) test('parameters: config', async () => { const { result } = await renderHook(() => useChains({ config }), { wrapper: ({ children }) => createElement(Fragment, { children }), }) expect(result.current.map((x) => x.id)).toMatchInlineSnapshot(` [ 1, 456, 10, ] `) }) test('behavior: chains updates', async () => { const { act, result } = await renderHook(() => useChains()) const chains = result.current expect( result.current.map(({ id, name }) => ({ id, name, })), ).toMatchInlineSnapshot(` [ { "id": 1, "name": "Ethereum", }, { "id": 456, "name": "Ethereum", }, { "id": 10, "name": "OP Mainnet", }, ] `) await act(() => config._internal.chains.setState([chain.mainnet, chain.mainnet2]), ) expect( result.current.map(({ id, name }) => ({ id, name, })), ).toMatchInlineSnapshot(` [ { "id": 1, "name": "Ethereum", }, { "id": 456, "name": "Ethereum", }, ] `) await act(() => config._internal.chains.setState(chains)) expect( result.current.map(({ id, name }) => ({ id, name, })), ).toMatchInlineSnapshot(` [ { "id": 1, "name": "Ethereum", }, { "id": 456, "name": "Ethereum", }, { "id": 10, "name": "OP Mainnet", }, ] `) }) ================================================ FILE: packages/react/src/hooks/useChains.ts ================================================ 'use client' import { type Config, type GetChainsReturnType, getChains, type ResolvedRegister, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { watchChains } from '@wagmi/core/internal' import { useSyncExternalStore } from 'react' import { useConfig } from './useConfig.js' export type UseChainsParameters = ConfigParameter export type UseChainsReturnType = GetChainsReturnType /** https://wagmi.sh/react/api/hooks/useChains */ export function useChains( parameters: UseChainsParameters = {}, ): UseChainsReturnType { const config = useConfig(parameters) return useSyncExternalStore( (onChange) => watchChains(config, { onChange }), () => getChains(config), () => getChains(config), ) } ================================================ FILE: packages/react/src/hooks/useClient.test-d.ts ================================================ import { chain, config } from '@wagmi/test' import type { Chain } from 'viem' import { expectTypeOf, test } from 'vitest' import { useClient } from './useClient.js' test('default', () => { const client = useClient({ config }) expectTypeOf(client.chain).toEqualTypeOf<(typeof config)['chains'][number]>() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) test('parameters: chainId', () => { const client = useClient({ config, chainId: chain.mainnet.id, }) expectTypeOf(client.chain).toEqualTypeOf() expectTypeOf(client.chain).not.toEqualTypeOf() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) test('behavior: unconfigured chain', () => { { const client = useClient({ chainId: 123456 }) if (client) { expectTypeOf(client.chain).toEqualTypeOf() expectTypeOf(client.transport.type).toEqualTypeOf() } else { expectTypeOf(client).toEqualTypeOf() } } const client = useClient({ config, // @ts-expect-error chainId: 123456, }) expectTypeOf(client).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useClient.test.ts ================================================ import { switchChain } from '@wagmi/core' import { config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { createElement, Fragment } from 'react' import { expect, test } from 'vitest' import { useClient } from './useClient.js' test('default', async () => { const { result, rerender } = await renderHook(() => useClient()) expect(result.current?.chain.id).toEqual(1) await switchChain(config, { chainId: 456 }) rerender() expect(result.current?.chain.id).toEqual(456) }) test('parameters: config', async () => { const { result } = await renderHook(() => useClient({ config }), { wrapper: ({ children }) => createElement(Fragment, { children }), }) expect(result.current).toBeDefined() }) test('behavior: unconfigured chain', async () => { const { result } = await renderHook(() => useClient({ chainId: 123456 })) expect(result.current).toBeUndefined() }) ================================================ FILE: packages/react/src/hooks/useClient.ts ================================================ 'use client' import { type Config, type GetClientParameters, type GetClientReturnType, getClient, type ResolvedRegister, watchClient, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector.js' import { useConfig } from './useConfig.js' export type UseClientParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] | number | undefined = | config['chains'][number]['id'] | undefined, > = Compute & ConfigParameter> export type UseClientReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] | number | undefined = | config['chains'][number]['id'] | undefined, > = GetClientReturnType /** https://wagmi.sh/react/api/hooks/useClient */ export function useClient< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] | number | undefined = | config['chains'][number]['id'] | undefined, >( parameters: UseClientParameters = {}, ): UseClientReturnType { const config = useConfig(parameters) return useSyncExternalStoreWithSelector( (onChange) => watchClient(config, { onChange }), () => getClient(config, parameters), () => getClient(config, parameters), (x) => x, (a, b) => a?.uid === b?.uid, ) as any } ================================================ FILE: packages/react/src/hooks/useConfig.test-d.ts ================================================ import type { Config } from '@wagmi/core' import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useConfig } from './useConfig.js' test('default', async () => { const result = useConfig() expectTypeOf(result).toEqualTypeOf() }) test('parameters: config', async () => { const result = useConfig({ config }) expectTypeOf(result).not.toEqualTypeOf() expectTypeOf(result).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useConfig.test.ts ================================================ import { createWrapper, renderHook } from '@wagmi/test/react' import * as React from 'react' import { expect, test, vi } from 'vitest' import { useConfig } from './useConfig.js' test('mounts', async () => { const { result } = await renderHook(() => useConfig()) expect(result.current).toBeDefined() }) test('behavior: throws when not inside Provider', async () => { vi.spyOn(console, 'error').mockImplementation(() => {}) await expect( renderHook(() => useConfig(), { wrapper: createWrapper( (props) => React.createElement('div', undefined, props.children), undefined, ), }), ).rejects.toThrowErrorMatchingInlineSnapshot(` [WagmiProviderNotFoundError: \`useConfig\` must be used within \`WagmiProvider\`. Docs: https://wagmi.sh/react/api/WagmiProvider.html Version: wagmi@x.y.z] `) }) ================================================ FILE: packages/react/src/hooks/useConfig.ts ================================================ 'use client' import type { Config, ResolvedRegister } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { useContext } from 'react' import { WagmiContext } from '../context.js' import { WagmiProviderNotFoundError } from '../errors/context.js' export type UseConfigParameters = ConfigParameter export type UseConfigReturnType = config /** https://wagmi.sh/react/api/hooks/useConfig */ export function useConfig( parameters: UseConfigParameters = {}, ): UseConfigReturnType { // biome-ignore lint/correctness/useHookAtTopLevel: false alarm const config = parameters.config ?? useContext(WagmiContext) if (!config) throw new WagmiProviderNotFoundError() return config as UseConfigReturnType } ================================================ FILE: packages/react/src/hooks/useConnect.test-d.ts ================================================ import type { ConnectErrorType, Connector, CreateConnectorFn, } from '@wagmi/core' import { config } from '@wagmi/test' import type { Address, Hex } from 'viem' import { assertType, expectTypeOf, test } from 'vitest' import { useConnect } from './useConnect.js' const connector = config.connectors[0]! const contextValue = { foo: 'bar' } as const test('context', () => { const connect = useConnect({ mutation: { onMutate(variables) { assertType<{ chainId?: number | undefined connector: Connector | CreateConnectorFn withCapabilities?: boolean | undefined }>(variables) return contextValue }, onError(error, variables, context) { assertType<{ chainId?: number | undefined connector: Connector | CreateConnectorFn withCapabilities?: boolean | undefined }>(variables) expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf<{ chainId?: number | undefined connector: Connector | CreateConnectorFn withCapabilities?: boolean | undefined }>(variables) expectTypeOf(data).toEqualTypeOf<{ accounts: | readonly [Address, ...Address[]] | readonly [ { address: Address; capabilities: Record }, ...{ address: Address capabilities: Record }[], ] chainId: number }>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf< | { accounts: | readonly [Address, ...Address[]] | readonly [ { address: Address capabilities: Record }, ...{ address: Address capabilities: Record }[], ] chainId: number } | undefined >() assertType<{ chainId?: number | undefined connector: Connector | CreateConnectorFn withCapabilities?: boolean | undefined }>(variables) expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(connect.data).toEqualTypeOf< | { accounts: | readonly [Address, ...Address[]] | readonly [ { address: Address; capabilities: Record }, ...{ address: Address; capabilities: Record }[], ] chainId: number } | undefined >() expectTypeOf(connect.error).toEqualTypeOf() expectTypeOf(connect.variables).toMatchTypeOf< | { chainId?: number | undefined connector: CreateConnectorFn | Connector } | undefined >() expectTypeOf(connect.context).toEqualTypeOf() connect.mutate( { connector, foo: 'bar', }, { onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ chainId?: number | undefined connector: typeof connector | CreateConnectorFn foo?: string | undefined withCapabilities?: boolean | undefined }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ chainId?: number | undefined connector: typeof connector | CreateConnectorFn foo?: string | undefined withCapabilities?: boolean | undefined }>() expectTypeOf(data).toEqualTypeOf<{ accounts: readonly [Address, ...Address[]] chainId: number }>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf<{ chainId?: number | undefined connector: typeof connector | CreateConnectorFn foo?: string | undefined withCapabilities?: boolean | undefined }>() expectTypeOf(context).toEqualTypeOf() }, }, ) connect.mutate( { connector, foo: 'bar', withCapabilities: true, }, { onSuccess(data, _variables, _context) { expectTypeOf(data).toEqualTypeOf<{ accounts: readonly [ { address: Address capabilities: { foo: { bar: Hex } } }, ...{ address: Address capabilities: { foo: { bar: Hex } } }[], ] chainId: number }>() }, onSettled(data, _error, _variables, _context) { expectTypeOf(data).toEqualTypeOf< | { accounts: readonly [ { address: Address capabilities: { foo: { bar: Hex } } }, ...{ address: Address capabilities: { foo: { bar: Hex } } }[], ] chainId: number } | undefined >() }, }, ) ;(async () => { const res = await connect.mutateAsync({ connector, foo: 'bar', withCapabilities: true, }) expectTypeOf(res).toEqualTypeOf<{ accounts: readonly [ { address: Address capabilities: { foo: { bar: Hex } } }, ...{ address: Address capabilities: { foo: { bar: Hex } } }[], ] chainId: number }>() })() }) ================================================ FILE: packages/react/src/hooks/useConnect.test.ts ================================================ import { disconnect } from '@wagmi/core' import { config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { afterEach, expect, test, vi } from 'vitest' import { useConnect } from './useConnect.js' import { useConnection } from './useConnection.js' import { useConnectors } from './useConnectors.js' const connector = config.connectors[0]! afterEach(async () => { if (config.state.current === connector.uid) await disconnect(config, { connector }) }) test('default', async () => { const { result } = await renderHook(() => ({ useConnection: useConnection(), useConnect: useConnect(), useConnectors: useConnectors(), })) expect(result.current.useConnection.address).not.toBeDefined() expect(result.current.useConnection.status).toEqual('disconnected') result.current.useConnect.mutate({ connector: result.current.useConnectors[0]!, }) await vi.waitFor(() => expect(result.current.useConnection.isConnected).toBeTruthy(), ) expect(result.current.useConnection.address).toBeDefined() expect(result.current.useConnection.status).toEqual('connected') }) ================================================ FILE: packages/react/src/hooks/useConnect.ts ================================================ 'use client' import { useMutation } from '@tanstack/react-query' import type { Config, ConnectErrorType, ResolvedRegister } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type ConnectData, type ConnectMutate, type ConnectMutateAsync, type ConnectOptions, type ConnectVariables, connectMutationOptions, } from '@wagmi/core/query' import { useEffect } from 'react' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' import { type UseConnectorsReturnType, useConnectors } from './useConnectors.js' export type UseConnectParameters< config extends Config = Config, context = unknown, > = Compute & ConnectOptions> export type UseConnectReturnType< config extends Config = Config, context = unknown, > = Compute< UseMutationReturnType< ConnectData, ConnectErrorType, ConnectVariables, context, ConnectMutate, ConnectMutateAsync > & { /** @deprecated use `mutate` instead */ connect: ConnectMutate /** @deprecated use `mutateAsync` instead */ connectAsync: ConnectMutateAsync /** @deprecated use `useConnectors` instead */ connectors: Compute | config['connectors'] } > /** https://wagmi.sh/react/api/hooks/useConnect */ export function useConnect< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: UseConnectParameters = {}, ): UseConnectReturnType { const config = useConfig(parameters) const options = connectMutationOptions(config, parameters) const mutation = useMutation(options) // Reset mutation back to an idle state when the connector disconnects. useEffect(() => { return config.subscribe( ({ status }) => status, (status, previousStatus) => { if (previousStatus === 'connected' && status === 'disconnected') mutation.reset() }, ) }, [config, mutation.reset]) type Return = UseConnectReturnType return { ...(mutation as Return), connect: mutation.mutate as Return['mutate'], connectAsync: mutation.mutateAsync as Return['mutateAsync'], connectors: useConnectors({ config }), } } ================================================ FILE: packages/react/src/hooks/useConnection.test-d.ts ================================================ import type { Connector } from '@wagmi/core' import type { Address, Chain } from 'viem' import { expectTypeOf, test } from 'vitest' import { useConnection } from './useConnection.js' test('states', () => { const result = useConnection() switch (result.status) { case 'reconnecting': { expectTypeOf(result).toMatchTypeOf<{ address: Address | undefined chain: Chain | undefined chainId: number | undefined connector: Connector | undefined isConnected: boolean isConnecting: false isDisconnected: false isReconnecting: true status: 'reconnecting' }>() break } case 'connecting': { expectTypeOf(result).toMatchTypeOf<{ address: Address | undefined chain: Chain | undefined chainId: number | undefined connector: Connector | undefined isConnected: false isReconnecting: false isConnecting: true isDisconnected: false status: 'connecting' }>() break } case 'connected': { expectTypeOf(result).toMatchTypeOf<{ address: Address chain: Chain | undefined chainId: number connector: Connector isConnected: true isConnecting: false isDisconnected: false isReconnecting: false status: 'connected' }>() break } case 'disconnected': { expectTypeOf(result).toMatchTypeOf<{ address: undefined chain: undefined chainId: undefined connector: undefined isConnected: false isReconnecting: false isConnecting: false isDisconnected: true status: 'disconnected' }>() break } } }) ================================================ FILE: packages/react/src/hooks/useConnection.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import * as React from 'react' import { expect, test } from 'vitest' import { useConnection } from './useConnection.js' test('default', async () => { const { result, rerender } = await renderHook(() => useConnection()) expect(result.current.address).not.toBeDefined() expect(result.current.status).toEqual('disconnected') await connect(config, { connector: config.connectors[0]! }) rerender() expect(result.current.address).toBeDefined() expect(result.current.status).toEqual('connected') await disconnect(config) }) test('parameters: config', async () => { const { result } = await renderHook(() => useConnection({ config }), { wrapper: ({ children }) => React.createElement(React.Fragment, { children }), }) expect(result.current).toBeDefined() }) ================================================ FILE: packages/react/src/hooks/useConnection.ts ================================================ 'use client' import { type Config, type GetConnectionReturnType, getConnection, type ResolvedRegister, watchConnection, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { useConfig } from './useConfig.js' import { useSyncExternalStoreWithTracked } from './useSyncExternalStoreWithTracked.js' export type UseConnectionParameters = ConfigParameter export type UseConnectionReturnType = GetConnectionReturnType /** https://wagmi.sh/react/api/hooks/useConnection */ export function useConnection< config extends Config = ResolvedRegister['config'], >( parameters: UseConnectionParameters = {}, ): UseConnectionReturnType { const config = useConfig(parameters) return useSyncExternalStoreWithTracked( (onChange) => watchConnection(config, { onChange }), () => getConnection(config), ) } ================================================ FILE: packages/react/src/hooks/useConnectionEffect.test.ts ================================================ import { mock } from '@wagmi/connectors' import { connect, createConfig, disconnect, http } from '@wagmi/core' import { accounts, chain, config } from '@wagmi/test' import { createWrapper, renderHook } from '@wagmi/test/react' import { createElement, Fragment } from 'react' import { expect, test, vi } from 'vitest' import { WagmiProvider } from '../context.js' import { useConnect } from './useConnect.js' import { useConnectionEffect } from './useConnectionEffect.js' import { useConnectors } from './useConnectors.js' import { useDisconnect } from './useDisconnect.js' test('parameters: config', async () => { const { result } = await renderHook(() => useConnectionEffect({ config }), { wrapper: ({ children }) => createElement(Fragment, { children }), }) expect(result.current).toBeUndefined() }) test('behavior: connect and disconnect called once', async () => { const onConnect = vi.fn() const onDisconnect = vi.fn() const { result } = await renderHook(() => ({ useConnectionEffect: useConnectionEffect({ onConnect, onDisconnect }), useConnect: useConnect(), useConnectors: useConnectors(), useDisconnect: useDisconnect(), })) result.current.useConnect.mutate({ connector: result.current.useConnectors[0]!, }) await vi.waitFor(() => expect(result.current.useConnect.isSuccess).toBeTruthy(), ) result.current.useConnect.mutate({ connector: result.current.useConnectors[0]!, }) await vi.waitFor(() => expect(result.current.useConnect.isSuccess).toBeTruthy(), ) result.current.useDisconnect.mutate() await vi.waitFor(() => expect(result.current.useDisconnect.isSuccess).toBeTruthy(), ) result.current.useDisconnect.mutate() await vi.waitFor(() => expect(result.current.useDisconnect.isSuccess).toBeTruthy(), ) expect(onConnect).toBeCalledTimes(1) expect(onDisconnect).toBeCalledTimes(1) }) test('behavior: connect called on reconnect', async () => { const config = createConfig({ chains: [chain.mainnet], connectors: [ mock({ accounts, features: { reconnect: true }, }), ], transports: { [chain.mainnet.id]: http() }, }) await connect(config, { connector: config.connectors[0]! }) const onConnect = vi.fn((data) => { expect(data.isReconnected).toBeTruthy() }) renderHook(() => useConnectionEffect({ onConnect }), { wrapper: createWrapper(WagmiProvider, { config, reconnectOnMount: true }), }) await vi.waitFor(() => expect(onConnect).toBeCalledTimes(1), { timeout: 10_000, }) await disconnect(config) }) ================================================ FILE: packages/react/src/hooks/useConnectionEffect.ts ================================================ 'use client' import { type GetConnectionReturnType, watchConnection } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { useEffect } from 'react' import { useConfig } from './useConfig.js' export type UseConnectionEffectParameters = Compute< { onConnect?( data: Compute< Pick< Extract, 'address' | 'addresses' | 'chain' | 'chainId' | 'connector' > & { isReconnected: boolean } >, ): void onDisconnect?(): void } & ConfigParameter > /** https://wagmi.sh/react/api/hooks/useConnectionEffect */ export function useConnectionEffect( parameters: UseConnectionEffectParameters = {}, ) { const { onConnect, onDisconnect } = parameters const config = useConfig(parameters) useEffect(() => { return watchConnection(config, { onChange(data, prevData) { if ( (prevData.status === 'reconnecting' || (prevData.status === 'connecting' && prevData.address === undefined)) && data.status === 'connected' ) { const { address, addresses, chain, chainId, connector } = data const isReconnected = prevData.status === 'reconnecting' || // if `previousAccount.status` is `undefined`, the connector connected immediately. prevData.status === undefined onConnect?.({ address, addresses, chain, chainId, connector, isReconnected, }) } else if ( prevData.status === 'connected' && data.status === 'disconnected' ) onDisconnect?.() }, }) }, [config, onConnect, onDisconnect]) } ================================================ FILE: packages/react/src/hooks/useConnections.test.ts ================================================ import { connect } from '@wagmi/core' import { config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { createElement, Fragment } from 'react' import { expect, test } from 'vitest' import { useConnections } from './useConnections.js' test('default', async () => { const { result, rerender } = await renderHook(() => useConnections()) expect(result.current).toEqual([]) await connect(config, { connector: config.connectors[0]! }) rerender() expect(result.current.length).toBe(1) }) test('parameters: config', async () => { const { result } = await renderHook(() => useConnections({ config }), { wrapper: ({ children }) => createElement(Fragment, { children }), }) expect(result.current).toBeDefined() }) ================================================ FILE: packages/react/src/hooks/useConnections.ts ================================================ 'use client' import { type GetConnectionsReturnType, getConnections, watchConnections, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { useSyncExternalStore } from 'react' import { useConfig } from './useConfig.js' export type UseConnectionsParameters = ConfigParameter export type UseConnectionsReturnType = GetConnectionsReturnType /** https://wagmi.sh/react/api/hooks/useConnections */ export function useConnections( parameters: UseConnectionsParameters = {}, ): UseConnectionsReturnType { const config = useConfig(parameters) return useSyncExternalStore( (onChange) => watchConnections(config, { onChange }), () => getConnections(config), () => getConnections(config), ) } ================================================ FILE: packages/react/src/hooks/useConnectorClient.test-d.ts ================================================ import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useConnectorClient } from './useConnectorClient.js' test('parameters: config', async () => { const client = useConnectorClient({ config }) expectTypeOf(client.data?.chain?.id!).toEqualTypeOf<1 | 456 | 10>() const client2 = useConnectorClient({ config, chainId: 1 }) expectTypeOf(client2.data?.chain?.id!).toEqualTypeOf<1>() }) ================================================ FILE: packages/react/src/hooks/useConnectorClient.test.tsx ================================================ import { connect, disconnect } from '@wagmi/core' import { config, wait } from '@wagmi/test' import { render, renderHook } from '@wagmi/test/react' import * as React from 'react' import { expect, test, vi } from 'vitest' import { useConnect } from './useConnect.js' import { useConnection } from './useConnection.js' import { useConnectorClient } from './useConnectorClient.js' import { useConnectors } from './useConnectors.js' import { useDisconnect } from './useDisconnect.js' import { useSwitchChain } from './useSwitchChain.js' const connector = config.connectors[0]! test('default', async () => { const { result } = await renderHook(() => useConnectorClient()) await vi.waitFor(() => expect(result.current.isPending).toBeTruthy()) expect(result.current).toMatchInlineSnapshot(` { "data": undefined, "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "connectorClient", { "chainId": 1, }, ], "refetch": [Function], "status": "pending", } `) }) test('behavior: connected on mount', async () => { await connect(config, { connector }) const { result } = await renderHook(() => useConnectorClient()) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, queryKey: _, ...rest } = result.current expect(data).toMatchObject( expect.objectContaining({ account: expect.any(Object), chain: expect.any(Object), }), ) expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": true, "refetch": [Function], "status": "success", } `) await disconnect(config, { connector }) }) test('behavior: connect and disconnect', async () => { const { result } = await renderHook(() => ({ useConnect: useConnect(), useConnectors: useConnectors(), useConnectorClient: useConnectorClient(), useDisconnect: useDisconnect(), })) expect(result.current.useConnectorClient.data).not.toBeDefined() result.current.useConnect.connect({ connector: result.current.useConnectors[0]!, }) await vi.waitFor(() => expect(result.current.useConnectorClient.data).toBeDefined(), ) result.current.useDisconnect.disconnect() await vi.waitFor(() => expect(result.current.useConnectorClient.data).not.toBeDefined(), ) }) test('behavior: switch chains', async () => { await connect(config, { connector }) const { act, result } = await renderHook(() => ({ useConnectorClient: useConnectorClient(), useSwitchChain: useSwitchChain(), })) expect(result.current.useConnectorClient.data).not.toBeDefined() await vi.waitFor(() => expect(result.current.useConnectorClient.data).toBeDefined(), ) await act(() => result.current.useSwitchChain.switchChain({ chainId: 456 })) await vi.waitUntil(() => result.current.useSwitchChain.isSuccess, { timeout: 10_000, }) await act(() => result.current.useSwitchChain.reset()) await vi.waitUntil(() => result.current.useConnectorClient.isSuccess, { timeout: 10_000, }) expect(result.current.useConnectorClient.data?.chain.id).toEqual(456) await act(() => result.current.useSwitchChain.switchChain({ chainId: 1 })) await vi.waitUntil(() => result.current.useSwitchChain.isSuccess, { timeout: 10_000, }) await vi.waitUntil(() => result.current.useConnectorClient.isSuccess, { timeout: 10_000, }) expect(result.current.useConnectorClient.data?.chain.id).toEqual(1) await disconnect(config, { connector }) }) test('behavior: disabled when properties missing', async () => { await disconnect(config, { connector }) const { result } = await renderHook(() => useConnectorClient()) await wait(0) await vi.waitFor(() => expect(result.current.isPending).toBeTruthy()) }) test('behavior: disabled when connecting', async () => { const { result } = await renderHook(() => useConnectorClient()) config.setState((x) => ({ ...x, status: 'connecting' })) await wait(0) expect(result.current.isLoading).not.toBeTruthy() }) test('behavior: re-render does not invalidate query', async () => { await disconnect(config, { connector }) const screen = await render() await screen.getByTestId('connect').click() await vi.waitFor(async () => { await expect .element(screen.getByTestId('address')) .toHaveTextContent('0x95132632579b073D12a6673e18Ab05777a6B86f8') await expect.element(screen.getByTestId('client')).toBeVisible() await expect.element(screen.getByTestId('child-client')).toBeVisible() await expect .element(screen.getByTestId('render-count')) .toHaveTextContent('1') }) const initialClient = screen.getByTestId('child-client') await screen.getByTestId('rerender').click() await vi.waitFor(() => expect.element(screen.getByTestId('render-count')).toHaveTextContent('2'), ) await expect .element(screen.getByTestId('child-client').element()) .toEqual(initialClient.element()) }) test('behavior: connector is on a different chain', async () => { await disconnect(config, { connector }) await connect(config, { connector }) config.setState((state) => { const uid = state.current! const connection = state.connections.get(uid)! return { ...state, connections: new Map(state.connections).set(uid, { ...connection, chainId: 456, }), } }) const { result } = await renderHook(() => useConnectorClient()) await vi.waitUntil(() => result.current.isError, 10_000) const { error } = result.current expect(error?.message).toMatchInlineSnapshot(` "The current chain of the connector (id: 1) does not match the connection's chain (id: 456). Current Chain ID: 1 Expected Chain ID: 456 Version: @wagmi/core@x.y.z" `) await disconnect(config, { connector }) }) function Parent() { const [renderCount, setRenderCount] = React.useState(1) const { connect } = useConnect() const connectors = useConnectors() const { address } = useConnection() const { data } = useConnectorClient() return ( <>
{address}
{data?.uid}
) } function Child(props: { renderCount: number }) { const { renderCount } = props const { data } = useConnectorClient() return (
{data?.uid} {renderCount}
) } ================================================ FILE: packages/react/src/hooks/useConnectorClient.ts ================================================ 'use client' import { useQueryClient } from '@tanstack/react-query' import type { Config, GetConnectorClientErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetConnectorClientData, type GetConnectorClientOptions, getConnectorClientQueryOptions, } from '@wagmi/core/query' import { useEffect, useRef } from 'react' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' import { useConnection } from './useConnection.js' export type UseConnectorClientParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetConnectorClientData, > = Compute< GetConnectorClientOptions & ConfigParameter > export type UseConnectorClientReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetConnectorClientData, > = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useConnectorClient */ export function useConnectorClient< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetConnectorClientData, >( parameters: UseConnectorClientParameters = {}, ): UseConnectorClientReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const { address, connector } = useConnection({ config }) const options = getConnectorClientQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, connector: parameters.connector ?? connector, query: parameters.query as any, }) const addressRef = useRef(address) const queryClient = useQueryClient() // biome-ignore lint/correctness/useExhaustiveDependencies: `queryKey` not required useEffect(() => { const previousAddress = addressRef.current if (!address && previousAddress) { // remove when account is disconnected queryClient.removeQueries({ queryKey: options.queryKey }) addressRef.current = undefined } else if (address !== previousAddress) { // invalidate when address changes queryClient.invalidateQueries({ queryKey: options.queryKey }) addressRef.current = address } }, [address, queryClient]) return useQuery(options) as any } ================================================ FILE: packages/react/src/hooks/useConnectors.test.ts ================================================ import { mock } from '@wagmi/connectors' import { accounts, config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { createElement, Fragment } from 'react' import { expect, test } from 'vitest' import { useConnectors } from './useConnectors.js' test('default', async () => { const { result, rerender } = await renderHook(() => useConnectors()) const count = config.connectors.length expect(result.current.length).toBe(count) expect(result.current).toEqual(config.connectors) config._internal.connectors.setState(() => [ ...config.connectors, config._internal.connectors.setup(mock({ accounts })), ]) rerender() expect(result.current.length).toBe(count + 1) }) test('parameters: config', async () => { const { result } = await renderHook(() => useConnectors({ config }), { wrapper: ({ children }) => createElement(Fragment, { children }), }) expect(result.current).toBeDefined() }) ================================================ FILE: packages/react/src/hooks/useConnectors.ts ================================================ 'use client' import { type Config, type GetConnectorsReturnType, getConnectors, type ResolvedRegister, watchConnectors, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { useSyncExternalStore } from 'react' import { useConfig } from './useConfig.js' export type UseConnectorsParameters = ConfigParameter export type UseConnectorsReturnType = GetConnectorsReturnType /** https://wagmi.sh/react/api/hooks/useConnectors */ export function useConnectors< config extends Config = ResolvedRegister['config'], >( parameters: UseConnectorsParameters = {}, ): UseConnectorsReturnType { const config = useConfig(parameters) return useSyncExternalStore( (onChange) => watchConnectors(config, { onChange }), () => getConnectors(config), () => getConnectors(config), ) } ================================================ FILE: packages/react/src/hooks/useContractEvents.test-d.ts ================================================ import { abi, type config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { type UseContractEventsParameters, useContractEvents, } from './useContractEvents.js' test('default', () => { const result = useContractEvents({ address: '0x', abi: abi.erc20, eventName: 'Transfer', args: { from: '0x', to: '0x', }, }) if (result.data) { expectTypeOf(result.data[0]!.eventName).toEqualTypeOf<'Transfer'>() expectTypeOf(result.data[0]!.args).toEqualTypeOf<{ from?: `0x${string}` | undefined to?: `0x${string}` | undefined value?: bigint | undefined }>() } useContractEvents({ address: '0x', abi: abi.erc20, // @ts-expect-error eventName: 'Foo', args: { from: '0x', to: '0x', }, }) useContractEvents({ address: '0x', abi: abi.erc20, eventName: 'Transfer', args: { // @ts-expect-error foo: '0x', to: '0x', }, }) }) test('behavior: strict', () => { const result = useContractEvents({ address: '0x', abi: abi.erc20, strict: true, eventName: 'Transfer', args: { from: '0x', to: '0x', }, }) if (result.data) { expectTypeOf(result.data[0]!.eventName).toEqualTypeOf<'Transfer'>() expectTypeOf(result.data[0]!.args).toEqualTypeOf<{ from: `0x${string}` to: `0x${string}` value: bigint }>() expectTypeOf(result.data[0]!.args).not.toEqualTypeOf<{ from?: `0x${string}` | undefined to?: `0x${string}` | undefined value?: bigint | undefined }>() } }) test('behavior: no eventName', () => { type Result = UseContractEventsParameters< typeof abi.erc20, undefined, true, undefined, undefined, typeof config > expectTypeOf().toEqualTypeOf< | { from?: `0x${string}` | `0x${string}`[] | null | undefined to?: `0x${string}` | `0x${string}`[] | null | undefined } | { owner?: `0x${string}` | `0x${string}`[] | null | undefined spender?: `0x${string}` | `0x${string}`[] | null | undefined } | undefined >() const result = useContractEvents({ address: '0x', abi: abi.erc20, args: { from: '0x', to: '0x', }, }) if (result.data) { expectTypeOf(result.data[0]!.eventName).toEqualTypeOf< 'Transfer' | 'Approval' >() expectTypeOf(result.data[0]!.args).toEqualTypeOf< | { from?: `0x${string}` | undefined to?: `0x${string}` | undefined value?: bigint | undefined } | { owner?: `0x${string}` | undefined spender?: `0x${string}` | undefined value?: bigint | undefined } >() } }) ================================================ FILE: packages/react/src/hooks/useContractEvents.test.ts ================================================ import { connect, disconnect, readContract } from '@wagmi/core' import { abi, address, config, testClient } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { createWalletClient, erc20Abi, getAddress, http, parseEther, } from 'viem' import { expect, test, vi } from 'vitest' import { useContractEvents } from './useContractEvents.js' const connector = config.connectors[0]! test('default', async () => { const data = await connect(config, { connector }) const connectedAddress = data.accounts[0] // impersonate usdc holder account and transfer usdc to connected account await testClient.mainnet.impersonateAccount({ address: address.usdcHolder }) await testClient.mainnet.setBalance({ address: address.usdcHolder, value: 10000000000000000000000n, }) const walletClient = createWalletClient({ account: address.usdcHolder, chain: testClient.mainnet.chain, transport: http(), }) await walletClient.writeContract({ address: address.usdc, abi: abi.erc20, functionName: 'transfer', args: [connectedAddress, parseEther('100', 'gwei')], }) await walletClient.writeContract({ address: address.usdc, abi: abi.erc20, functionName: 'approve', args: [connectedAddress, parseEther('10', 'gwei')], }) await testClient.mainnet.mine({ blocks: 1 }) await testClient.mainnet.stopImpersonatingAccount({ address: address.usdcHolder, }) const balance = await readContract(config, { address: address.usdc, abi: erc20Abi, functionName: 'balanceOf', args: [connectedAddress], }) expect(balance).toBeGreaterThan(0n) const { result } = await renderHook(() => useContractEvents({ address: address.usdc, abi: abi.erc20, }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const logs = result.current.data expect(logs![0]!.eventName).toEqual('Transfer') expect(logs![0]!.args).toEqual({ from: getAddress(address.usdcHolder), to: getAddress(connectedAddress), value: parseEther('100', 'gwei'), }) expect(logs![1]!.eventName).toEqual('Approval') expect(logs![1]!.args).toEqual({ owner: getAddress(address.usdcHolder), spender: getAddress(connectedAddress), value: parseEther('10', 'gwei'), }) await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/useContractEvents.ts ================================================ 'use client' import type { Config, GetContractEventsErrorType, ResolvedRegister, } from '@wagmi/core' import type { ConfigParameter, UnionCompute } from '@wagmi/core/internal' import { type GetContractEventsData, type GetContractEventsOptions, getContractEventsQueryOptions, } from '@wagmi/core/query' import type { Abi, BlockNumber, BlockTag, ContractEventName } from 'viem' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseContractEventsParameters< abi extends Abi | readonly unknown[] = Abi, eventName extends ContractEventName | undefined = | ContractEventName | undefined, strict extends boolean | undefined = undefined, fromBlock extends BlockNumber | BlockTag | undefined = undefined, toBlock extends BlockNumber | BlockTag | undefined = undefined, config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetContractEventsData< abi, eventName, strict, fromBlock, toBlock >, > = UnionCompute< GetContractEventsOptions< abi, eventName, strict, fromBlock, toBlock, config, chainId, selectData > & ConfigParameter > export type UseContractEventsReturnType< abi extends Abi | readonly unknown[] = Abi, eventName extends ContractEventName | undefined = | ContractEventName | undefined, strict extends boolean | undefined = undefined, fromBlock extends BlockNumber | BlockTag | undefined = undefined, toBlock extends BlockNumber | BlockTag | undefined = undefined, selectData = GetContractEventsData< abi, eventName, strict, fromBlock, toBlock >, > = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useContractEvents */ export function useContractEvents< const abi extends Abi | readonly unknown[], eventName extends ContractEventName | undefined, strict extends boolean | undefined = undefined, fromBlock extends BlockNumber | BlockTag | undefined = undefined, toBlock extends BlockNumber | BlockTag | undefined = undefined, config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetContractEventsData< abi, eventName, strict, fromBlock, toBlock >, >( parameters: UseContractEventsParameters< abi, eventName, strict, fromBlock, toBlock, config, chainId, selectData > = {} as any, ): UseContractEventsReturnType< abi, eventName, strict, fromBlock, toBlock, selectData > { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getContractEventsQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useDeployContract.test-d.ts ================================================ import type { DeployContractErrorType } from '@wagmi/core' import { abi, bytecode } from '@wagmi/test' import type { Abi, Hash } from 'viem' import { expectTypeOf, test } from 'vitest' import { useDeployContract } from './useDeployContract.js' const contextValue = { foo: 'bar' } as const test('context', () => { const deployContract = useDeployContract({ mutation: { onMutate(variables) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: Abi args?: readonly unknown[] | undefined }>() return contextValue }, onError(error, variables, context) { expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: Abi args?: readonly unknown[] | undefined }>() }, onSuccess(data, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: Abi args?: readonly unknown[] | undefined }>() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: Abi args?: readonly unknown[] | undefined }>() }, }, }) expectTypeOf(deployContract.data).toEqualTypeOf() expectTypeOf( deployContract.error, ).toEqualTypeOf() expectTypeOf(deployContract.variables).toMatchTypeOf< { chainId?: number | undefined } | undefined >() expectTypeOf(deployContract.context).toEqualTypeOf< typeof contextValue | undefined >() deployContract.mutate( { abi: abi.bayc, bytecode: bytecode.bayc, args: ['Bored Ape Wagmi Club', 'BAYC', 69420n, 0n], chainId: 1, }, { onError(error, variables, context) { expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: typeof abi.bayc args: readonly [string, string, bigint, bigint] }>() }, onSuccess(data, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: typeof abi.bayc args: readonly [string, string, bigint, bigint] }>() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: typeof abi.bayc args: readonly [string, string, bigint, bigint] }>() }, }, ) }) ================================================ FILE: packages/react/src/hooks/useDeployContract.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { abi, bytecode, config, transactionHashRegex } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useDeployContract } from './useDeployContract.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const { result } = await renderHook(() => useDeployContract()) result.current.mutate({ abi: abi.bayc, bytecode: bytecode.bayc, args: ['Bored Ape Wagmi Club', 'BAYC', 69420n, 0n], }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current.data).toMatch(transactionHashRegex) await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/useDeployContract.ts ================================================ 'use client' import { useMutation } from '@tanstack/react-query' import type { Config, DeployContractErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type DeployContractData, type DeployContractMutate, type DeployContractMutateAsync, type DeployContractOptions, type DeployContractVariables, deployContractMutationOptions, } from '@wagmi/core/query' import type { Abi } from 'viem' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseDeployContractParameters< config extends Config = Config, context = unknown, > = Compute & DeployContractOptions> export type UseDeployContractReturnType< config extends Config = Config, context = unknown, > = UseMutationReturnType< DeployContractData, DeployContractErrorType, DeployContractVariables, context, DeployContractMutate, DeployContractMutateAsync > & { /** @deprecated use `mutate` instead */ deployContract: DeployContractMutate /** @deprecated use `mutateAsync` instead */ deployContractAsync: DeployContractMutateAsync } /** https://wagmi.sh/react/api/hooks/useDeployContract */ export function useDeployContract< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: UseDeployContractParameters = {}, ): UseDeployContractReturnType { const config = useConfig(parameters) const options = deployContractMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseDeployContractReturnType return { ...(mutation as Return), deployContract: mutation.mutate as Return['mutate'], deployContractAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/react/src/hooks/useDisconnect.test-d.ts ================================================ import type { Connector, DisconnectErrorType } from '@wagmi/core' import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useDisconnect } from './useDisconnect.js' const connector = config.connectors[0]! const contextValue = { foo: 'bar' } as const test('parameter', () => { expectTypeOf(useDisconnect().disconnect) .parameter(0) .toEqualTypeOf<{ connector?: Connector | undefined } | undefined>() expectTypeOf(useDisconnect().disconnect) .parameter(0) .toEqualTypeOf<{ connector?: Connector | undefined } | undefined>() }) test('context', () => { const { context, data, disconnect, error, variables } = useDisconnect({ mutation: { onMutate(variables) { expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(context).toEqualTypeOf() disconnect( { connector }, { onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/react/src/hooks/useDisconnect.test.ts ================================================ import { connect } from '@wagmi/core' import { config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { beforeEach, expect, test, vi } from 'vitest' import { useConnection } from './useConnection.js' import { useDisconnect } from './useDisconnect.js' const connector = config.connectors[0]! beforeEach(async () => { await connect(config, { connector }) }) test('default', async () => { const { result } = await renderHook(() => ({ useConnection: useConnection(), useDisconnect: useDisconnect(), })) expect(result.current.useConnection.address).toBeDefined() expect(result.current.useConnection.status).toEqual('connected') result.current.useDisconnect.mutate() await vi.waitFor(() => expect(result.current.useConnection.isDisconnected).toBeTruthy(), ) expect(result.current.useConnection.address).not.toBeDefined() expect(result.current.useConnection.status).toEqual('disconnected') }) ================================================ FILE: packages/react/src/hooks/useDisconnect.ts ================================================ 'use client' import { useMutation } from '@tanstack/react-query' import type { Connector, DisconnectErrorType } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type DisconnectData, type DisconnectMutate, type DisconnectMutateAsync, type DisconnectOptions, type DisconnectVariables, disconnectMutationOptions, } from '@wagmi/core/query' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' import { useConnections } from './useConnections.js' export type UseDisconnectParameters = Compute< ConfigParameter & DisconnectOptions > export type UseDisconnectReturnType = Compute< UseMutationReturnType< DisconnectData, DisconnectErrorType, DisconnectVariables, context, DisconnectMutate, DisconnectMutateAsync > & { /** @deprecated use `useConnections` instead */ connectors: readonly Connector[] /** @deprecated use `mutate` instead */ disconnect: DisconnectMutate /** @deprecated use `mutateAsync` instead */ disconnectAsync: DisconnectMutateAsync } > /** https://wagmi.sh/react/api/hooks/useDisconnect */ export function useDisconnect( parameters: UseDisconnectParameters = {}, ): UseDisconnectReturnType { const config = useConfig(parameters) const options = disconnectMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseDisconnectReturnType return { ...(mutation as Return), connectors: useConnections({ config }).map( (connection) => connection.connector, ), disconnect: mutation.mutate as Return['mutate'], disconnectAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/react/src/hooks/useEnsAddress.test.ts ================================================ import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useEnsAddress } from './useEnsAddress.js' test('default', async () => { const { result } = await renderHook(() => useEnsAddress({ name: 'wevm.eth', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": "0xd2135CfB216b74109775236E36d4b433F1DF507B", "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "ensAddress", { "chainId": 1, "name": "wevm.eth", }, ], "refetch": [Function], "status": "success", } `) }) ================================================ FILE: packages/react/src/hooks/useEnsAddress.ts ================================================ 'use client' import type { Config, GetEnsAddressErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetEnsAddressData, type GetEnsAddressOptions, getEnsAddressQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseEnsAddressParameters< config extends Config = Config, selectData = GetEnsAddressData, > = Compute & ConfigParameter> export type UseEnsAddressReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useEnsAddress */ export function useEnsAddress< config extends Config = ResolvedRegister['config'], selectData = GetEnsAddressData, >( parameters: UseEnsAddressParameters = {}, ): UseEnsAddressReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getEnsAddressQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useEnsAvatar.test.ts ================================================ import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useEnsAvatar } from './useEnsAvatar.js' test('default', async () => { const { result } = await renderHook(() => useEnsAvatar({ name: 'wevm.eth', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": "https://euc.li/wevm.eth", "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "ensAvatar", { "chainId": 1, "name": "wevm.eth", }, ], "refetch": [Function], "status": "success", } `) }) ================================================ FILE: packages/react/src/hooks/useEnsAvatar.ts ================================================ 'use client' import type { Config, GetEnsAvatarErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetEnsAvatarData, type GetEnsAvatarOptions, getEnsAvatarQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseEnsAvatarParameters< config extends Config = Config, selectData = GetEnsAvatarData, > = Compute & ConfigParameter> export type UseEnsAvatarReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useEnsAvatar */ export function useEnsAvatar< config extends Config = ResolvedRegister['config'], selectData = GetEnsAvatarData, >( parameters: UseEnsAvatarParameters = {}, ): UseEnsAvatarReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getEnsAvatarQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useEnsName.test.ts ================================================ import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useEnsName } from './useEnsName.js' test('default', async () => { const { result } = await renderHook(() => useEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": "wevm.eth", "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "ensName", { "address": "0xd2135CfB216b74109775236E36d4b433F1DF507B", "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) ================================================ FILE: packages/react/src/hooks/useEnsName.ts ================================================ 'use client' import type { Config, GetEnsNameErrorType, ResolvedRegister } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetEnsNameData, type GetEnsNameOptions, getEnsNameQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseEnsNameParameters< config extends Config = Config, selectData = GetEnsNameData, > = Compute & ConfigParameter> export type UseEnsNameReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useEnsName */ export function useEnsName< config extends Config = ResolvedRegister['config'], selectData = GetEnsNameData, >( parameters: UseEnsNameParameters = {}, ): UseEnsNameReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getEnsNameQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useEnsResolver.test.ts ================================================ import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useEnsResolver } from './useEnsResolver.js' test('default', async () => { const { result } = await renderHook(() => useEnsResolver({ name: 'wevm.eth', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": "0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41", "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "ensResolver", { "chainId": 1, "name": "wevm.eth", }, ], "refetch": [Function], "status": "success", } `) }) ================================================ FILE: packages/react/src/hooks/useEnsResolver.ts ================================================ 'use client' import type { Config, GetEnsResolverErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetEnsResolverData, type GetEnsResolverOptions, getEnsResolverQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseEnsResolverParameters< config extends Config = Config, selectData = GetEnsResolverData, > = Compute & ConfigParameter> export type UseEnsResolverReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useEnsResolver */ export function useEnsResolver< config extends Config = ResolvedRegister['config'], selectData = GetEnsResolverData, >( parameters: UseEnsResolverParameters = {}, ): UseEnsResolverReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getEnsResolverQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useEnsText.test.ts ================================================ import { wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useEnsText } from './useEnsText.js' test('default', async () => { const { result } = await renderHook(() => useEnsText({ key: 'com.twitter', name: 'wevm.eth', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": "wevm_dev", "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "ensText", { "chainId": 1, "key": "com.twitter", "name": "wevm.eth", }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: name: undefined -> defined', async () => { const { result, rerender } = await renderHook( (props) => useEnsText({ key: 'com.twitter', name: props?.name, }), { initialProps: { name: undefined as string | undefined } }, ) expect(result.current).toMatchInlineSnapshot(` { "data": undefined, "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "ensText", { "chainId": 1, "key": "com.twitter", "name": undefined, }, ], "refetch": [Function], "status": "pending", } `) rerender({ name: 'wevm.eth' }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": "wevm_dev", "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "ensText", { "chainId": 1, "key": "com.twitter", "name": "wevm.eth", }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: disabled when properties missing', async () => { const { result } = await renderHook(() => useEnsText()) await wait(100) await vi.waitFor(() => expect(result.current.isPending).toBeTruthy()) }) ================================================ FILE: packages/react/src/hooks/useEnsText.ts ================================================ 'use client' import type { Config, GetEnsTextErrorType, ResolvedRegister } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetEnsTextData, type GetEnsTextOptions, getEnsTextQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseEnsTextParameters< config extends Config = Config, selectData = GetEnsTextData, > = Compute & ConfigParameter> export type UseEnsTextReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useEnsText */ export function useEnsText< config extends Config = ResolvedRegister['config'], selectData = GetEnsTextData, >( parameters: UseEnsTextParameters = {}, ): UseEnsTextReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getEnsTextQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useEstimateFeesPerGas.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useEstimateFeesPerGas } from './useEstimateFeesPerGas.js' test('types', () => { const result = useEstimateFeesPerGas() expectTypeOf(result.data).toMatchTypeOf< | { gasPrice?: undefined maxFeePerGas: bigint maxPriorityFeePerGas: bigint } | undefined >() const result2 = useEstimateFeesPerGas({ type: 'legacy' }) expectTypeOf(result2.data).toMatchTypeOf< | { gasPrice: bigint maxFeePerGas?: undefined maxPriorityFeePerGas?: undefined } | undefined >() const result3 = useEstimateFeesPerGas({ type: 'eip1559' }) expectTypeOf(result3.data).toMatchTypeOf< | { gasPrice?: undefined maxFeePerGas: bigint maxPriorityFeePerGas: bigint } | undefined >() }) ================================================ FILE: packages/react/src/hooks/useEstimateFeesPerGas.test.ts ================================================ import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useEstimateFeesPerGas } from './useEstimateFeesPerGas.js' test('default', async () => { const { result } = await renderHook(() => useEstimateFeesPerGas()) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(Object.keys(result.current.data!)).toMatchInlineSnapshot(` [ "gasPrice", "maxFeePerGas", "maxPriorityFeePerGas", ] `) }) ================================================ FILE: packages/react/src/hooks/useEstimateFeesPerGas.ts ================================================ 'use client' import type { Config, EstimateFeesPerGasErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type EstimateFeesPerGasData, type EstimateFeesPerGasOptions, estimateFeesPerGasQueryOptions, } from '@wagmi/core/query' import type { FeeValuesType } from 'viem' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseEstimateFeesPerGasParameters< type extends FeeValuesType = FeeValuesType, config extends Config = Config, selectData = EstimateFeesPerGasData, > = Compute< EstimateFeesPerGasOptions & ConfigParameter > export type UseEstimateFeesPerGasReturnType< type extends FeeValuesType = FeeValuesType, selectData = EstimateFeesPerGasData, > = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useEstimateFeesPerGas */ export function useEstimateFeesPerGas< config extends Config = ResolvedRegister['config'], type extends FeeValuesType = 'eip1559', selectData = EstimateFeesPerGasData, >( parameters: UseEstimateFeesPerGasParameters = {}, ): UseEstimateFeesPerGasReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = estimateFeesPerGasQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useEstimateGas.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useEstimateGas } from './useEstimateGas.js' test('select data', () => { const result = useEstimateGas({ query: { select(data) { return data.toString() }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useEstimateGas.test.ts ================================================ import { accounts } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { type Address, parseEther } from 'viem' import { expect, test, vi } from 'vitest' import { useEstimateGas } from './useEstimateGas.js' test('default', async () => { const { result } = await renderHook(() => useEstimateGas({ account: accounts[0], to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": 21000n, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "estimateGas", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 1, "to": "0xd2135CfB216b74109775236E36d4b433F1DF507B", "value": 10000000000000000n, }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: address: undefined -> defined', async () => { const { result, rerender } = await renderHook( (props) => useEstimateGas({ account: props?.account }), { initialProps: { account: undefined as Address | undefined } }, ) expect(result.current).toMatchInlineSnapshot(` { "data": undefined, "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "estimateGas", { "account": undefined, "chainId": 1, }, ], "refetch": [Function], "status": "pending", } `) rerender({ account: accounts[0] }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": 53001n, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "estimateGas", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) ================================================ FILE: packages/react/src/hooks/useEstimateGas.ts ================================================ 'use client' import type { Config, EstimateGasErrorType, ResolvedRegister, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { type EstimateGasData, type EstimateGasOptions, estimateGasQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' import { useConnection } from './useConnection.js' export type UseEstimateGasParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = EstimateGasData, > = EstimateGasOptions & ConfigParameter export type UseEstimateGasReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useEstimateGas */ export function useEstimateGas< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = EstimateGasData, >( parameters?: UseEstimateGasParameters, ): UseEstimateGasReturnType export function useEstimateGas( parameters: UseEstimateGasParameters = {}, ): UseEstimateGasReturnType { const config = useConfig(parameters) const { address, connector } = useConnection() const chainId = useChainId({ config }) const options = estimateGasQueryOptions(config, { ...parameters, account: parameters.account ?? address, chainId: parameters.chainId ?? chainId, connector: parameters.connector ?? connector, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useEstimateMaxPriorityFeePerGas.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useEstimateMaxPriorityFeePerGas } from './useEstimateMaxPriorityFeePerGas.js' test('select data', () => { const result = useEstimateMaxPriorityFeePerGas({ query: { select(data) { return data.toString() }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useEstimateMaxPriorityFeePerGas.test.ts ================================================ import { chain, testClient } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useEstimateMaxPriorityFeePerGas } from './useEstimateMaxPriorityFeePerGas.js' test('default', async () => { await testClient.mainnet.restart() const { result } = await renderHook(() => useEstimateMaxPriorityFeePerGas()) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toBeTypeOf('bigint') expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "estimateMaxPriorityFeePerGas", { "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: chainId', async () => { await testClient.mainnet2.restart() await testClient.mainnet2.mine({ blocks: 1 }) const { result } = await renderHook(() => useEstimateMaxPriorityFeePerGas({ chainId: chain.mainnet2.id }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toBeTypeOf('bigint') expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "estimateMaxPriorityFeePerGas", { "chainId": 456, }, ], "refetch": [Function], "status": "success", } `) }) ================================================ FILE: packages/react/src/hooks/useEstimateMaxPriorityFeePerGas.ts ================================================ 'use client' import type { Config, EstimateMaxPriorityFeePerGasErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type EstimateMaxPriorityFeePerGasData, type EstimateMaxPriorityFeePerGasOptions, estimateMaxPriorityFeePerGasQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseEstimateMaxPriorityFeePerGasParameters< config extends Config = Config, selectData = EstimateMaxPriorityFeePerGasData, > = Compute< EstimateMaxPriorityFeePerGasOptions & ConfigParameter > export type UseEstimateMaxPriorityFeePerGasReturnType< selectData = EstimateMaxPriorityFeePerGasData, > = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useEstimateMaxPriorityFeePerGas */ export function useEstimateMaxPriorityFeePerGas< config extends Config = ResolvedRegister['config'], selectData = EstimateMaxPriorityFeePerGasData, >( parameters: UseEstimateMaxPriorityFeePerGasParameters< config, selectData > = {}, ): UseEstimateMaxPriorityFeePerGasReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = estimateMaxPriorityFeePerGasQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useFeeHistory.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useFeeHistory } from './useFeeHistory.js' test('select data', () => { const result = useFeeHistory({ query: { select(data) { return data.gasUsedRatio }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useFeeHistory.test.ts ================================================ import { chain, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useFeeHistory } from './useFeeHistory.js' test('default', async () => { const { result } = await renderHook(() => useFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75], }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toMatchObject({ baseFeePerGas: expect.arrayContaining([expect.any(BigInt)]), gasUsedRatio: expect.arrayContaining([expect.any(Number)]), oldestBlock: expect.any(BigInt), reward: expect.any(Array), }) expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "feeHistory", { "blockCount": 4, "chainId": 1, "rewardPercentiles": [ 25, 75, ], }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: chainId', async () => { const { result } = await renderHook(() => useFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75], chainId: chain.mainnet2.id, }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toMatchObject({ baseFeePerGas: expect.arrayContaining([expect.any(BigInt)]), gasUsedRatio: expect.arrayContaining([expect.any(Number)]), oldestBlock: expect.any(BigInt), reward: expect.any(Array), }) expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "feeHistory", { "blockCount": 4, "chainId": 456, "rewardPercentiles": [ 25, 75, ], }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: blockNumber', async () => { const { result } = await renderHook(() => useFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75], blockNumber: 18677379n, }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toMatchObject({ baseFeePerGas: expect.arrayContaining([expect.any(BigInt)]), gasUsedRatio: expect.arrayContaining([expect.any(Number)]), oldestBlock: expect.any(BigInt), reward: expect.any(Array), }) expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "feeHistory", { "blockCount": 4, "blockNumber": 18677379n, "chainId": 1, "rewardPercentiles": [ 25, 75, ], }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: blockTag', async () => { const { result } = await renderHook(() => useFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75], blockTag: 'safe', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toMatchObject({ baseFeePerGas: expect.arrayContaining([expect.any(BigInt)]), gasUsedRatio: expect.arrayContaining([expect.any(Number)]), oldestBlock: expect.any(BigInt), reward: expect.any(Array), }) expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "feeHistory", { "blockCount": 4, "blockTag": "safe", "chainId": 1, "rewardPercentiles": [ 25, 75, ], }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: blockCount: undefined -> defined', async () => { const { result, rerender } = await renderHook( (props) => useFeeHistory({ blockCount: props?.blockCount, rewardPercentiles: [25, 75], }), { initialProps: { blockCount: undefined as number | undefined } }, ) { const { data, ...rest } = result.current expect(data).toBeTypeOf('undefined') expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "feeHistory", { "blockCount": undefined, "chainId": 1, "rewardPercentiles": [ 25, 75, ], }, ], "refetch": [Function], "status": "pending", } `) } rerender({ blockCount: 4 }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toMatchObject({ baseFeePerGas: expect.arrayContaining([expect.any(BigInt)]), gasUsedRatio: expect.arrayContaining([expect.any(Number)]), oldestBlock: expect.any(BigInt), reward: expect.any(Array), }) expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "feeHistory", { "blockCount": 4, "chainId": 1, "rewardPercentiles": [ 25, 75, ], }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: rewardPercentiles: undefined -> defined', async () => { const { result, rerender } = await renderHook( (props) => useFeeHistory({ blockCount: 4, rewardPercentiles: props?.rewardPercentiles, }), { initialProps: { rewardPercentiles: undefined as number[] | undefined } }, ) { const { data, ...rest } = result.current expect(data).toBeTypeOf('undefined') expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "feeHistory", { "blockCount": 4, "chainId": 1, "rewardPercentiles": undefined, }, ], "refetch": [Function], "status": "pending", } `) } rerender({ rewardPercentiles: [25, 75] }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toMatchObject({ baseFeePerGas: expect.arrayContaining([expect.any(BigInt)]), gasUsedRatio: expect.arrayContaining([expect.any(Number)]), oldestBlock: expect.any(BigInt), reward: expect.any(Array), }) expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "feeHistory", { "blockCount": 4, "chainId": 1, "rewardPercentiles": [ 25, 75, ], }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: disabled when properties missing', async () => { const { result } = await renderHook(() => useFeeHistory()) await wait(100) await vi.waitFor(() => expect(result.current.isPending).toBeTruthy()) }) ================================================ FILE: packages/react/src/hooks/useFeeHistory.ts ================================================ 'use client' import type { Config, GetFeeHistoryErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetFeeHistoryData, type GetFeeHistoryOptions, getFeeHistoryQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseFeeHistoryParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetFeeHistoryData, > = Compute< GetFeeHistoryOptions & ConfigParameter > export type UseFeeHistoryReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useFeeHistory */ export function useFeeHistory< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetFeeHistoryData, >( parameters: UseFeeHistoryParameters = {}, ): UseFeeHistoryReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getFeeHistoryQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useGasPrice.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useGasPrice } from './useGasPrice.js' test('select data', () => { const result = useGasPrice({ query: { select(data) { return data?.toString() }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useGasPrice.test.ts ================================================ import { chain, testClient } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useGasPrice } from './useGasPrice.js' test('default', async () => { await testClient.mainnet.restart() await testClient.mainnet.setNextBlockBaseFeePerGas({ baseFeePerGas: 2_000_000_000n, }) await testClient.mainnet.mine({ blocks: 1 }) const { result } = await renderHook(() => useGasPrice()) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": 2750000000n, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "gasPrice", { "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) test.skip('parameters: chainId', async () => { await testClient.mainnet2.restart() await testClient.mainnet2.setNextBlockBaseFeePerGas({ baseFeePerGas: 1_000_000_000n, }) await testClient.mainnet2.mine({ blocks: 1 }) const { result } = await renderHook(() => useGasPrice({ chainId: chain.mainnet2.id }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": 1875000000n, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "gasPrice", { "chainId": 456, }, ], "refetch": [Function], "status": "success", } `) }) ================================================ FILE: packages/react/src/hooks/useGasPrice.ts ================================================ 'use client' import type { Config, GetGasPriceErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetGasPriceData, type GetGasPriceOptions, getGasPriceQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseGasPriceParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetGasPriceData, > = Compute< GetGasPriceOptions & ConfigParameter > export type UseGasPriceReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useGasPrice */ export function useGasPrice< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetGasPriceData, >( parameters: UseGasPriceParameters = {}, ): UseGasPriceReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getGasPriceQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useInfiniteReadContracts.test-d.ts ================================================ import { abi } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useInfiniteReadContracts } from './useInfiniteReadContracts.js' test('select data', () => { const result = useInfiniteReadContracts({ allowFailure: false, cacheKey: 'foo', contracts(pageParam) { expectTypeOf(pageParam).toEqualTypeOf() return [ { address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }, { address: '0x', abi: abi.wagmiMintExample, functionName: 'tokenURI', args: [123n], }, ] }, query: { initialPageParam: '0', getNextPageParam(lastPage, allPages, lastPageParam, allPageParams) { expectTypeOf(lastPage).toEqualTypeOf<[bigint, string]>() expectTypeOf(allPages).toEqualTypeOf<[bigint, string][]>() expectTypeOf(lastPageParam).toEqualTypeOf() expectTypeOf(allPageParams).toEqualTypeOf() return lastPageParam + 1 }, select(data) { expectTypeOf(data.pageParams[0]!).toEqualTypeOf() expectTypeOf(data.pages[0]!).toEqualTypeOf<[bigint, string]>() return data.pages[0]?.[0]! }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useInfiniteReadContracts.test.ts ================================================ import { abi, address, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useInfiniteReadContracts } from './useInfiniteReadContracts.js' test('default', async () => { const limit = 3 const { result } = await renderHook(() => useInfiniteReadContracts({ cacheKey: 'foo', contracts(pageParam) { return [...new Array(limit)].map( (_, i) => ({ address: address.shields, abi: abi.shields, functionName: 'tokenURI', args: [BigInt(pageParam + i + 1)], }) as const, ) }, query: { initialPageParam: 0, getNextPageParam(_lastPage, _allPages, lastPageParam) { return lastPageParam + limit }, select(data) { const results = [] for (const page of data.pages) { for (const response of page) { if (response.status === 'success') { const decoded = atob( response.result.replace(/(^.*base64,)/, ''), ) const json = JSON.parse(decoded) as { name: string } results.push(json.name) } else results.push('Error fetching shield') } } return results }, }, }), ) await wait(0) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current.data).toMatchInlineSnapshot(` [ "Three Shields on Pink Perfect", "Three Shields on Sky Perfect", "Three Shields on Evergreen Perfect", ] `) await result.current.fetchNextPage() await wait(0) await vi.waitFor(() => expect(result.current.hasNextPage).toBeTruthy()) expect(result.current.data).toMatchInlineSnapshot(` [ "Three Shields on Pink Perfect", "Three Shields on Sky Perfect", "Three Shields on Evergreen Perfect", "Three Shields on Hi-Vis Perfect", "Three Shields on Gray Perfect", "Everlasting: Tracery on Onyx and Pink Razor Bordure", ] `) await result.current.fetchNextPage() await wait(0) await vi.waitFor(() => expect(result.current.hasNextPage).toBeTruthy()) expect(result.current.data).toMatchInlineSnapshot(` [ "Three Shields on Pink Perfect", "Three Shields on Sky Perfect", "Three Shields on Evergreen Perfect", "Three Shields on Hi-Vis Perfect", "Three Shields on Gray Perfect", "Everlasting: Tracery on Onyx and Pink Razor Bordure", "The Book of Shields on Pink Perfect", "Menacing: Necklace on Evergreen and Hi-Vis Chief Indented", "Secured: Telescope and Stars on Ultraviolet and Sky Doppler", ] `) }, 20_000) ================================================ FILE: packages/react/src/hooks/useInfiniteReadContracts.ts ================================================ 'use client' import type { Config, ReadContractsErrorType, ResolvedRegister, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { type InfiniteReadContractsQueryFnData, type InfiniteReadContractsQueryKey, infiniteReadContractsQueryOptions, structuralSharing, } from '@wagmi/core/query' import type { ContractFunctionParameters } from 'viem' import type { InfiniteReadContractsData, InfiniteReadContractsOptions, } from '../exports/query.js' import type { InfiniteQueryParameter } from '../types/properties.js' import { type UseInfiniteQueryParameters, type UseInfiniteQueryReturnType, useInfiniteQuery, } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseInfiniteContractReadsParameters< contracts extends readonly unknown[] = readonly ContractFunctionParameters[], allowFailure extends boolean = true, config extends Config = Config, pageParam = unknown, selectData = InfiniteReadContractsData, > = InfiniteReadContractsOptions & ConfigParameter & InfiniteQueryParameter< InfiniteReadContractsQueryFnData, ReadContractsErrorType, selectData, InfiniteReadContractsData, InfiniteReadContractsQueryKey, pageParam > export type UseInfiniteContractReadsReturnType< contracts extends readonly unknown[] = readonly ContractFunctionParameters[], allowFailure extends boolean = true, selectData = InfiniteReadContractsData, > = UseInfiniteQueryReturnType /** https://wagmi.sh/react/api/hooks/useInfiniteReadContracts */ export function useInfiniteReadContracts< const contracts extends readonly unknown[], allowFailure extends boolean = true, config extends Config = ResolvedRegister['config'], pageParam = unknown, selectData = InfiniteReadContractsData, >( parameters: UseInfiniteContractReadsParameters< contracts, allowFailure, config, pageParam, selectData >, ): UseInfiniteContractReadsReturnType { const { contracts = [], query } = parameters const config = useConfig(parameters) const chainId = useChainId({ config }) const options = infiniteReadContractsQueryOptions(config, { ...parameters, chainId, contracts: contracts as UseInfiniteContractReadsParameters['contracts'], query: query as UseInfiniteQueryParameters, }) return useInfiniteQuery({ ...(query as any), ...options, initialPageParam: options.initialPageParam, structuralSharing: query.structuralSharing ?? structuralSharing, }) } ================================================ FILE: packages/react/src/hooks/usePrepareTransactionRequest.test-d.ts ================================================ import { config } from '@wagmi/test' import type { PrepareTransactionRequestReturnType } from 'viem' import { expectTypeOf, test } from 'vitest' import { usePrepareTransactionRequest } from './usePrepareTransactionRequest.js' test('select data', () => { const result = usePrepareTransactionRequest({ query: { select(data) { return data }, }, }) expectTypeOf(result.data).toMatchTypeOf< PrepareTransactionRequestReturnType | undefined >() }) test('parameters: config', () => { const result = usePrepareTransactionRequest({ config, chainId: 456, }) if (result.data) expectTypeOf(result.data.chainId).toEqualTypeOf<456>() }) ================================================ FILE: packages/react/src/hooks/usePrepareTransactionRequest.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { parseEther } from 'viem' import { expect, test, vi } from 'vitest' import { usePrepareTransactionRequest } from './usePrepareTransactionRequest.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const { result } = await renderHook(() => usePrepareTransactionRequest({ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data: { gas: _gas, gasPrice: _gasPrice, maxFeePerGas: _mfpg, maxPriorityFeePerGas: _mpfpg, nonce: _nonce, ...data } = {}, ...rest } = result.current expect(data).toMatchInlineSnapshot(` { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 1, "from": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "to": "0x70997970c51812dc3a010c7d01b50e0d17dc79c8", "type": "eip1559", "value": 1000000000000000000n, } `) expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "prepareTransactionRequest", { "chainId": 1, "to": "0x70997970c51812dc3a010c7d01b50e0d17dc79c8", "value": 1000000000000000000n, }, ], "refetch": [Function], "status": "success", } `) await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/usePrepareTransactionRequest.ts ================================================ 'use client' import type { Config, PrepareTransactionRequestErrorType, ResolvedRegister, SelectChains, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { type PrepareTransactionRequestData, type PrepareTransactionRequestOptions, prepareTransactionRequestQueryOptions, } from '@wagmi/core/query' import type { PrepareTransactionRequestRequest as viem_PrepareTransactionRequestRequest } from 'viem' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UsePrepareTransactionRequestParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] | undefined = undefined, request extends viem_PrepareTransactionRequestRequest< SelectChains[0], SelectChains[0] > = viem_PrepareTransactionRequestRequest< SelectChains[0], SelectChains[0] >, selectData = PrepareTransactionRequestData, > = PrepareTransactionRequestOptions & ConfigParameter export type UsePrepareTransactionRequestReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] | undefined = undefined, request extends viem_PrepareTransactionRequestRequest< SelectChains[0], SelectChains[0] > = viem_PrepareTransactionRequestRequest< SelectChains[0], SelectChains[0] >, selectData = PrepareTransactionRequestData, > = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/usePrepareTransactionRequest */ export function usePrepareTransactionRequest< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] | undefined = undefined, request extends viem_PrepareTransactionRequestRequest< SelectChains[0], SelectChains[0] > = viem_PrepareTransactionRequestRequest< SelectChains[0], SelectChains[0] >, selectData = PrepareTransactionRequestData, >( parameters: UsePrepareTransactionRequestParameters< config, chainId, request, selectData > = {} as any, ): UsePrepareTransactionRequestReturnType< config, chainId, request, selectData > { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = prepareTransactionRequestQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as PrepareTransactionRequestOptions) return useQuery(options) as any } ================================================ FILE: packages/react/src/hooks/useProof.test-d.ts ================================================ import type { GetProofReturnType } from 'viem' import { expectTypeOf, test } from 'vitest' import { useProof } from './useProof.js' test('select data', () => { const result = useProof({ query: { select(data) { return data }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useProof.test.ts ================================================ import { chain, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import type { Address } from 'viem' import { expect, test, vi } from 'vitest' import { useProof } from './useProof.js' test.skip('default', async () => { const { result } = await renderHook(() => useProof({ address: '0x7F0d15C7FAae65896648C8273B6d7E43f58Fa842', chainId: chain.optimism.id, storageKeys: [ '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421', ], }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect({ ...result.current, data: null }).toMatchInlineSnapshot(` { "data": null, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getProof", { "address": "0x4200000000000000000000000000000000000016", "chainId": 10, "storageKeys": [ "0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99", ], }, ], "refetch": [Function], "status": "success", } `) }) test.skip('behavior: address: undefined -> defined', async () => { const { result, rerender } = await renderHook( (props) => useProof({ address: props?.address, chainId: chain.optimism.id, storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }), { initialProps: { address: undefined as Address | undefined } }, ) expect(result.current).toMatchInlineSnapshot(` { "data": undefined, "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "getProof", { "address": undefined, "chainId": 10, "storageKeys": [ "0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99", ], }, ], "refetch": [Function], "status": "pending", } `) rerender({ address: '0x4200000000000000000000000000000000000016' }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect({ ...result.current, data: null }).toMatchInlineSnapshot(` { "data": null, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getProof", { "address": "0x4200000000000000000000000000000000000016", "chainId": 10, "storageKeys": [ "0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99", ], }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: disabled when properties missing', async () => { const { result } = await renderHook(() => useProof()) await wait(100) await vi.waitFor(() => expect(result.current.isPending).toBeTruthy()) }) ================================================ FILE: packages/react/src/hooks/useProof.ts ================================================ 'use client' import type { Config, GetProofErrorType, ResolvedRegister } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetProofData, type GetProofOptions, getProofQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseProofParameters< config extends Config = Config, selectData = GetProofData, > = Compute & ConfigParameter> export type UseProofReturnType = UseQueryReturnType< selectData, GetProofErrorType > /** https://wagmi.sh/react/api/hooks/useProof */ export function useProof< config extends Config = ResolvedRegister['config'], selectData = GetProofData, >( parameters: UseProofParameters = {}, ): UseProofReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getProofQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/usePublicClient.test-d.ts ================================================ import { chain, config } from '@wagmi/test' import type { Chain } from 'viem' import { expectTypeOf, test } from 'vitest' import { usePublicClient } from './usePublicClient.js' test('default', () => { const client = usePublicClient({ config }) expectTypeOf(client.chain).toEqualTypeOf<(typeof config)['chains'][number]>() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) test('parameters: chainId', () => { const client = usePublicClient({ config, chainId: chain.mainnet.id, }) expectTypeOf(client.chain).toEqualTypeOf() expectTypeOf(client.chain).not.toEqualTypeOf() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) test('behavior: unconfigured chain', () => { { const client = usePublicClient({ chainId: 123456 }) if (client) { expectTypeOf(client.chain).toEqualTypeOf() expectTypeOf(client.transport.type).toEqualTypeOf() } else { expectTypeOf(client).toEqualTypeOf() } } const client = usePublicClient({ config, // @ts-expect-error chainId: 123456, }) expectTypeOf(client).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/usePublicClient.test.ts ================================================ import { switchChain } from '@wagmi/core' import { config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { createElement, Fragment } from 'react' import { expect, test } from 'vitest' import { usePublicClient } from './usePublicClient.js' test('default', async () => { const { result, rerender } = await renderHook(() => usePublicClient()) expect(result.current?.chain.id).toEqual(1) await switchChain(config, { chainId: 456 }) rerender() expect(result.current?.chain.id).toEqual(456) }) test('parameters: config', async () => { const { result } = await renderHook(() => usePublicClient({ config }), { wrapper: ({ children }) => createElement(Fragment, { children }), }) expect(result.current).toBeDefined() }) test('behavior: unconfigured chain', async () => { const { result } = await renderHook(() => usePublicClient({ chainId: 123456 }), ) expect(result.current).toBeUndefined() }) ================================================ FILE: packages/react/src/hooks/usePublicClient.ts ================================================ 'use client' import { type Config, type GetPublicClientParameters, type GetPublicClientReturnType, getPublicClient, type ResolvedRegister, watchPublicClient, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector.js' import { useConfig } from './useConfig.js' export type UsePublicClientParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] | number | undefined = | config['chains'][number]['id'] | undefined, > = Compute< GetPublicClientParameters & ConfigParameter > export type UsePublicClientReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] | number | undefined = | config['chains'][number]['id'] | undefined, > = GetPublicClientReturnType /** https://wagmi.sh/react/api/hooks/usePublicClient */ export function usePublicClient< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] | number | undefined = | config['chains'][number]['id'] | undefined, >( parameters: UsePublicClientParameters = {}, ): UsePublicClientReturnType { const config = useConfig(parameters) return useSyncExternalStoreWithSelector( (onChange) => watchPublicClient(config, { onChange }), () => getPublicClient(config, parameters), () => getPublicClient(config, parameters), (x) => x, (a, b) => a?.uid === b?.uid, ) as any } ================================================ FILE: packages/react/src/hooks/useReadContract.test-d.ts ================================================ import { abi } from '@wagmi/test' import type { Address } from 'viem' import { assertType, expectTypeOf, test } from 'vitest' import { type UseReadContractParameters, type UseReadContractReturnType, useReadContract, } from './useReadContract.js' test('select data', () => { const result = useReadContract({ address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], query: { select(data) { expectTypeOf(data).toEqualTypeOf() return data?.toString() }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) test('UseReadContractParameters', () => { type Result = UseReadContractParameters expectTypeOf>().toEqualTypeOf<{ functionName?: | 'symbol' | 'name' | 'allowance' | 'balanceOf' | 'decimals' | 'totalSupply' | undefined args?: readonly [Address] | undefined }>() }) test('UseReadContractReturnType', () => { type Result = UseReadContractReturnType expectTypeOf().toEqualTypeOf() }) test('overloads', () => { const result1 = useReadContract({ address: '0x', abi: abi.viewOverloads, functionName: 'foo', }) assertType(result1.data) const result2 = useReadContract({ address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: [], }) assertType(result2.data) const result3 = useReadContract({ address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x'], }) assertType(result3.data) const result4 = useReadContract({ address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x', '0x'], }) assertType< | { foo: `0x${string}` bar: `0x${string}` } | undefined >(result4.data) }) test('deployless read (bytecode)', () => { const result = useReadContract({ code: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useReadContract.test.ts ================================================ import { QueryClientProvider } from '@tanstack/react-query' import { abi, address, bytecode, chain, config, wait } from '@wagmi/test' import { queryClient, renderHook } from '@wagmi/test/react' import { createElement } from 'react' import { expect, test, vi } from 'vitest' import { useReadContract } from './useReadContract.js' test('default', async () => { const { result } = await renderHook(() => useReadContract({ address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": 10n, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "readContract", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": [ "0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC", ], "chainId": 1, "functionName": "balanceOf", }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: chainId', async () => { const { result } = await renderHook(() => useReadContract({ address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], chainId: chain.mainnet2.id, }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": 10n, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "readContract", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": [ "0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC", ], "chainId": 456, "functionName": "balanceOf", }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: config', async () => { const { result } = await renderHook( () => useReadContract({ address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], config, }), { wrapper: ({ children }) => createElement(QueryClientProvider, { client: queryClient }, children), }, ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": 10n, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "readContract", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": [ "0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC", ], "chainId": 1, "functionName": "balanceOf", }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: deployless read (bytecode)', async () => { const { result } = await renderHook(() => useReadContract({ abi: abi.wagmiMintExample, functionName: 'name', code: bytecode.wagmiMintExample, }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current.data).toMatchInlineSnapshot(`"wagmi"`) }) test('behavior: disabled when properties missing', async () => { const { result } = await renderHook(() => useReadContract()) await wait(100) await vi.waitFor(() => expect(result.current.isPending).toBeTruthy()) }) ================================================ FILE: packages/react/src/hooks/useReadContract.ts ================================================ 'use client' import type { Config, ReadContractErrorType, ResolvedRegister, } from '@wagmi/core' import type { ConfigParameter, UnionCompute } from '@wagmi/core/internal' import { type ReadContractData, type ReadContractOptions, readContractQueryOptions, } from '@wagmi/core/query' import type { Abi, ContractFunctionArgs, ContractFunctionName } from 'viem' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseReadContractParameters< abi extends Abi | readonly unknown[] = Abi, functionName extends ContractFunctionName< abi, 'pure' | 'view' > = ContractFunctionName, args extends ContractFunctionArgs< abi, 'pure' | 'view', functionName > = ContractFunctionArgs, config extends Config = Config, selectData = ReadContractData, > = UnionCompute< ReadContractOptions & ConfigParameter > export type UseReadContractReturnType< abi extends Abi | readonly unknown[] = Abi, functionName extends ContractFunctionName< abi, 'pure' | 'view' > = ContractFunctionName, args extends ContractFunctionArgs< abi, 'pure' | 'view', functionName > = ContractFunctionArgs, selectData = ReadContractData, > = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useReadContract */ export function useReadContract< const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, const args extends ContractFunctionArgs, config extends Config = ResolvedRegister['config'], selectData = ReadContractData, >( parameters: UseReadContractParameters< abi, functionName, args, config, selectData > = {} as any, ): UseReadContractReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = readContractQueryOptions(config, { ...(parameters as any), chainId: parameters.chainId ?? chainId, }) return useQuery(options) as any } ================================================ FILE: packages/react/src/hooks/useReadContracts.test-d.ts ================================================ import { abi } from '@wagmi/test' import { assertType, expectTypeOf, test } from 'vitest' import { useReadContracts } from './useReadContracts.js' test('select data', () => { const result = useReadContracts({ allowFailure: false, contracts: [ { address: '0x', abi: abi.erc20, functionName: 'balanceOf', chainId: 1, args: ['0x'], }, { address: '0x', abi: abi.wagmiMintExample, functionName: 'tokenURI', args: [123n], }, ], query: { select(data) { expectTypeOf(data).toEqualTypeOf<[bigint, string]>() return data[0] }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) test('overloads', async () => { const result1 = useReadContracts({ allowFailure: false, contracts: [ { address: '0x', abi: abi.viewOverloads, functionName: 'foo', }, ], }) assertType<[number] | undefined>(result1.data) const result2 = useReadContracts({ allowFailure: false, contracts: [ { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: [], }, ], }) assertType<[number] | undefined>(result2.data) const result3 = useReadContracts({ allowFailure: false, contracts: [ { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x'], }, ], }) assertType<[string] | undefined>(result3.data) const result4 = useReadContracts({ allowFailure: false, contracts: [ { address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x', '0x'], }, ], }) assertType< | [ { foo: `0x${string}` bar: `0x${string}` }, ] | undefined >(result4.data) }) ================================================ FILE: packages/react/src/hooks/useReadContracts.test.ts ================================================ import { switchChain } from '@wagmi/core' import { abi, address, chain, config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useReadContracts } from './useReadContracts.js' test('default', async () => { const { result } = await renderHook(() => useReadContracts({ contracts: [ { address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }, { address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'symbol', }, ], }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": [ { "result": 10n, "status": "success", }, { "result": "WAGMI", "status": "success", }, ], "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "readContracts", { "chainId": 1, "contracts": [ { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": [ "0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC", ], "chainId": 1, "functionName": "balanceOf", }, { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "chainId": 1, "functionName": "symbol", }, ], }, ], "refetch": [Function], "status": "success", } `) }) test('multichain', async () => { const { mainnet, mainnet2 } = chain const { result } = await renderHook(() => useReadContracts({ contracts: [ { abi: abi.wagmigotchi, address: address.wagmigotchi, chainId: mainnet.id, functionName: 'love', args: ['0x27a69ffba1e939ddcfecc8c7e0f967b872bac65c'], }, { abi: abi.wagmigotchi, address: address.wagmigotchi, chainId: mainnet.id, functionName: 'love', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }, { abi: abi.wagmigotchi, address: address.wagmigotchi, chainId: mainnet.id, functionName: 'love', args: ['0xd2135CfB216b74109775236E36d4b433F1DF507B'], }, { abi: abi.wagmigotchi, address: address.wagmigotchi, chainId: mainnet2.id, functionName: 'getAlive', }, { abi: abi.mloot, address: address.mloot, chainId: mainnet2.id, functionName: 'tokenOfOwnerByIndex', args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 0n], }, // { // abi: abi.erc20, // address: address.optimism.usdc, // chainId: optimism.id, // functionName: 'symbol', // }, // { // abi: abi.erc20, // address: address.optimism.usdc, // chainId: optimism.id, // functionName: 'balanceOf', // args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], // }, ], }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 60_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": [ { "result": 2n, "status": "success", }, { "result": 1n, "status": "success", }, { "result": 0n, "status": "success", }, { "result": false, "status": "success", }, { "result": 370395n, "status": "success", }, ], "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "readContracts", { "contracts": [ { "address": "0xecb504d39723b0be0e3a9aa33d646642d1051ee1", "args": [ "0x27a69ffba1e939ddcfecc8c7e0f967b872bac65c", ], "chainId": 1, "functionName": "love", }, { "address": "0xecb504d39723b0be0e3a9aa33d646642d1051ee1", "args": [ "0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC", ], "chainId": 1, "functionName": "love", }, { "address": "0xecb504d39723b0be0e3a9aa33d646642d1051ee1", "args": [ "0xd2135CfB216b74109775236E36d4b433F1DF507B", ], "chainId": 1, "functionName": "love", }, { "address": "0xecb504d39723b0be0e3a9aa33d646642d1051ee1", "chainId": 456, "functionName": "getAlive", }, { "address": "0x1dfe7ca09e99d10835bf73044a23b73fc20623df", "args": [ "0xA0Cf798816D4b9b9866b5330EEa46a18382f251e", 0n, ], "chainId": 456, "functionName": "tokenOfOwnerByIndex", }, ], }, ], "refetch": [Function], "status": "success", } `) }, 60_000) test('behavior: all same chainId', async () => { const { mainnet, mainnet2 } = chain await switchChain(config, { chainId: mainnet2.id }) const { result } = await renderHook(() => useReadContracts({ contracts: [ { abi: abi.wagmigotchi, address: address.wagmigotchi, chainId: mainnet.id, functionName: 'love', args: ['0x27a69ffba1e939ddcfecc8c7e0f967b872bac65c'], }, { abi: abi.wagmigotchi, address: address.wagmigotchi, chainId: mainnet.id, functionName: 'love', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }, { abi: abi.wagmigotchi, address: address.wagmigotchi, chainId: mainnet.id, functionName: 'love', args: ['0xd2135CfB216b74109775236E36d4b433F1DF507B'], }, ], }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": [ { "result": 2n, "status": "success", }, { "result": 1n, "status": "success", }, { "result": 0n, "status": "success", }, ], "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "readContracts", { "contracts": [ { "address": "0xecb504d39723b0be0e3a9aa33d646642d1051ee1", "args": [ "0x27a69ffba1e939ddcfecc8c7e0f967b872bac65c", ], "chainId": 1, "functionName": "love", }, { "address": "0xecb504d39723b0be0e3a9aa33d646642d1051ee1", "args": [ "0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC", ], "chainId": 1, "functionName": "love", }, { "address": "0xecb504d39723b0be0e3a9aa33d646642d1051ee1", "args": [ "0xd2135CfB216b74109775236E36d4b433F1DF507B", ], "chainId": 1, "functionName": "love", }, ], }, ], "refetch": [Function], "status": "success", } `) }) ================================================ FILE: packages/react/src/hooks/useReadContracts.ts ================================================ 'use client' import type { Config, ReadContractsErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type ReadContractsData, type ReadContractsOptions, readContractsQueryOptions, } from '@wagmi/core/query' import { useMemo } from 'react' import type { ContractFunctionParameters } from 'viem' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseReadContractsParameters< contracts extends readonly unknown[] = readonly ContractFunctionParameters[], allowFailure extends boolean = true, config extends Config = Config, selectData = ReadContractsData, > = Compute< ReadContractsOptions & ConfigParameter > export type UseReadContractsReturnType< contracts extends readonly unknown[] = readonly ContractFunctionParameters[], allowFailure extends boolean = true, selectData = ReadContractsData, > = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useReadContracts */ export function useReadContracts< const contracts extends readonly unknown[], allowFailure extends boolean = true, config extends Config = ResolvedRegister['config'], selectData = ReadContractsData, >( parameters: UseReadContractsParameters< contracts, allowFailure, config, selectData > = {}, ): UseReadContractsReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const contractsChainId = useMemo(() => { const firstChainId = ( parameters.contracts?.[0] as { chainId?: number } | undefined )?.chainId if ( ((parameters.contracts ?? []) as { chainId?: number }[]).every( (contract) => contract.chainId === firstChainId, ) ) return firstChainId return undefined }, [parameters.contracts]) const options = readContractsQueryOptions(config, { ...parameters, chainId: contractsChainId ?? chainId, }) return useQuery(options) as any } ================================================ FILE: packages/react/src/hooks/useReconnect.test-d.ts ================================================ import type { Connector, CreateConnectorFn, ReconnectErrorType, } from '@wagmi/core' import { config } from '@wagmi/test' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' import { useReconnect } from './useReconnect.js' const connectors = [config.connectors[0]!] const contextValue = { foo: 'bar' } as const test('context', () => { const reconnect = useReconnect({ mutation: { onMutate(variables) { expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(data).toEqualTypeOf< { accounts: readonly [Address, ...Address[]] chainId: number connector: Connector }[] >() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number connector: Connector }[] | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(reconnect.data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number connector: Connector }[] | undefined >() expectTypeOf(reconnect.error).toEqualTypeOf() expectTypeOf(reconnect.variables).toEqualTypeOf< | { connectors?: readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(reconnect.context).toEqualTypeOf< typeof contextValue | undefined >() reconnect.mutate( { connectors }, { onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(data).toEqualTypeOf< { accounts: readonly [Address, ...Address[]] chainId: number connector: Connector }[] >() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number connector: Connector }[] | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/react/src/hooks/useReconnect.test.ts ================================================ import { mock } from '@wagmi/connectors' import { connect, disconnect } from '@wagmi/core' import { accounts, config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { afterEach, expect, test, vi } from 'vitest' import { useReconnect } from './useReconnect.js' const connector = config._internal.connectors.setup( mock({ accounts, features: { reconnect: true }, }), ) afterEach(async () => { if (config.state.current) await disconnect(config) }) test('default', async () => { const { result } = await renderHook(() => useReconnect()) result.current.mutate() await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current.data).toStrictEqual([]) }) test('parameters: connectors (Connector)', async () => { await connect(config, { connector }) const { result } = await renderHook(() => useReconnect()) result.current.mutate({ connectors: [connector] }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current.data).toMatchObject( expect.arrayContaining([ expect.objectContaining({ accounts: expect.any(Array), chainId: expect.any(Number), }), ]), ) }) test('parameters: connectors (CreateConnectorFn)', async () => { const connector = mock({ accounts, features: { reconnect: true }, }) await connect(config, { connector }) const { result } = await renderHook(() => useReconnect()) result.current.mutate({ connectors: [connector] }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current.data).toMatchObject( expect.arrayContaining([ expect.objectContaining({ accounts: expect.any(Array), chainId: expect.any(Number), }), ]), ) }) test("behavior: doesn't reconnect if already reconnecting", async () => { const previousStatus = config.state.status config.setState((x) => ({ ...x, status: 'reconnecting' })) const { result } = await renderHook(() => useReconnect()) await expect( result.current.mutateAsync({ connectors: [connector] }), ).resolves.toStrictEqual([]) config.setState((x) => ({ ...x, status: previousStatus })) }) ================================================ FILE: packages/react/src/hooks/useReconnect.ts ================================================ 'use client' import { useMutation } from '@tanstack/react-query' import type { Connector, ReconnectErrorType } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type ReconnectData, type ReconnectMutate, type ReconnectMutateAsync, type ReconnectOptions, type ReconnectVariables, reconnectMutationOptions, } from '@wagmi/core/query' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseReconnectParameters = Compute< ConfigParameter & ReconnectOptions > export type UseReconnectReturnType = Compute< UseMutationReturnType< ReconnectData, ReconnectErrorType, ReconnectVariables, context, ReconnectMutate, ReconnectMutateAsync > & { /** @deprecated use `useConnectors` instead */ connectors: readonly Connector[] /** @deprecated use `mutate` instead */ reconnect: ReconnectMutate /** @deprecated use `mutateAsync` instead */ reconnectAsync: ReconnectMutateAsync } > /** https://wagmi.sh/react/api/hooks/useReconnect */ export function useReconnect( parameters: UseReconnectParameters = {}, ): UseReconnectReturnType { const config = useConfig(parameters) const options = reconnectMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseReconnectReturnType return { ...(mutation as Return), connectors: config.connectors, reconnect: mutation.mutate as Return['mutate'], reconnectAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/react/src/hooks/useSendCalls.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { accounts, config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { parseEther } from 'viem' import { expect, test, vi } from 'vitest' import { useSendCalls } from './useSendCalls.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const { result } = await renderHook(() => useSendCalls()) result.current.mutate({ calls: [ { data: '0xdeadbeef', to: accounts[1], value: parseEther('1'), }, { to: accounts[2], value: parseEther('2'), }, { to: accounts[3], value: parseEther('3'), }, ], }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current.data).toMatchInlineSnapshot( ` { "id": "0xb24b52a86aa2b0bae6f1e44868c3a13d2572e766a1f6364afd93d1757839b8a1", } `, ) await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/useSendCalls.ts ================================================ 'use client' import { useMutation } from '@tanstack/react-query' import type { Config, ResolvedRegister, SendCallsErrorType } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type SendCallsData, type SendCallsMutate, type SendCallsMutateAsync, type SendCallsOptions, type SendCallsVariables, sendCallsMutationOptions, } from '@wagmi/core/query' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseSendCallsParameters< config extends Config = Config, context = unknown, > = Compute & SendCallsOptions> export type UseSendCallsReturnType< config extends Config = Config, context = unknown, > = Compute< UseMutationReturnType< SendCallsData, SendCallsErrorType, SendCallsVariables, context, SendCallsMutate, SendCallsMutateAsync > & { /** @deprecated use `mutate` instead */ sendCalls: SendCallsMutate /** @deprecated use `mutateAsync` instead */ sendCallsAsync: SendCallsMutateAsync } > /** https://wagmi.sh/react/api/hooks/useSendCalls */ export function useSendCalls< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: UseSendCallsParameters = {}, ): UseSendCallsReturnType { const config = useConfig(parameters) const options = sendCallsMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseSendCallsReturnType return { ...(mutation as Return), sendCalls: mutation.mutate as Return['mutate'], sendCallsAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/react/src/hooks/useSendCallsSync.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { accounts, config, testClient, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { parseEther } from 'viem' import { expect, test, vi } from 'vitest' import { useSendCallsSync } from './useSendCallsSync.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const { result } = await renderHook(() => useSendCallsSync()) result.current.mutate({ calls: [ { data: '0xdeadbeef', to: accounts[1], value: parseEther('1'), }, { to: accounts[2], value: parseEther('2'), }, { to: accounts[3], value: parseEther('3'), }, ], }) await wait(4_000) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy(), { timeout: 10_000, }) expect(result.current.data).toBeDefined() await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/useSendCallsSync.ts ================================================ 'use client' import { useMutation } from '@tanstack/react-query' import type { Config, ResolvedRegister, SendCallsSyncErrorType, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type SendCallsSyncData, type SendCallsSyncMutate, type SendCallsSyncMutateAsync, type SendCallsSyncOptions, type SendCallsSyncVariables, sendCallsSyncMutationOptions, } from '@wagmi/core/query' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseSendCallsSyncParameters< config extends Config = Config, context = unknown, > = Compute & SendCallsSyncOptions> export type UseSendCallsSyncReturnType< config extends Config = Config, context = unknown, > = Compute< UseMutationReturnType< SendCallsSyncData, SendCallsSyncErrorType, SendCallsSyncVariables, context, SendCallsSyncMutate, SendCallsSyncMutateAsync > & { /** @deprecated use `mutate` instead */ sendCallsSync: SendCallsSyncMutate /** @deprecated use `mutateAsync` instead */ sendCallsSyncAsync: SendCallsSyncMutateAsync } > /** https://wagmi.sh/react/api/hooks/useSendCallsSync */ export function useSendCallsSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: UseSendCallsSyncParameters = {}, ): UseSendCallsSyncReturnType { const config = useConfig(parameters) const options = sendCallsSyncMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseSendCallsSyncReturnType return { ...(mutation as Return), sendCallsSync: mutation.mutate as Return['mutate'], sendCallsSyncAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/react/src/hooks/useSendTransaction.test-d.ts ================================================ import type { SendTransactionErrorType } from '@wagmi/core' import type { Hash } from 'viem' import { expectTypeOf, test } from 'vitest' import { useSendTransaction } from './useSendTransaction.js' const contextValue = { foo: 'bar' } as const test('context', () => { const sendTransaction = useSendTransaction({ mutation: { onMutate(variables) { expectTypeOf(variables).toMatchTypeOf< { chainId?: number | undefined } | undefined >() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(sendTransaction.data).toEqualTypeOf() expectTypeOf( sendTransaction.error, ).toEqualTypeOf() expectTypeOf(sendTransaction.variables).toMatchTypeOf< { chainId?: number | undefined } | undefined >() expectTypeOf(sendTransaction.context).toEqualTypeOf< typeof contextValue | undefined >() sendTransaction.mutate( { to: '0x' }, { onError(error, variables, context) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/react/src/hooks/useSendTransaction.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { config, transactionHashRegex } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { parseEther } from 'viem' import { expect, test, vi } from 'vitest' import { useSendTransaction } from './useSendTransaction.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const { result } = await renderHook(() => useSendTransaction()) result.current.mutate({ to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current.data).toMatch(transactionHashRegex) await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/useSendTransaction.ts ================================================ 'use client' import { useMutation } from '@tanstack/react-query' import type { Config, ResolvedRegister, SendTransactionErrorType, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type SendTransactionData, type SendTransactionMutate, type SendTransactionMutateAsync, type SendTransactionOptions, type SendTransactionVariables, sendTransactionMutationOptions, } from '@wagmi/core/query' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseSendTransactionParameters< config extends Config = Config, context = unknown, > = Compute & SendTransactionOptions> export type UseSendTransactionReturnType< config extends Config = Config, context = unknown, > = Compute< UseMutationReturnType< SendTransactionData, SendTransactionErrorType, SendTransactionVariables, context, SendTransactionMutate, SendTransactionMutateAsync > & { /** @deprecated use `mutate` instead */ sendTransaction: SendTransactionMutate /** @deprecated use `mutateAsync` instead */ sendTransactionAsync: SendTransactionMutateAsync } > /** https://wagmi.sh/react/api/hooks/useSendTransaction */ export function useSendTransaction< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: UseSendTransactionParameters = {}, ): UseSendTransactionReturnType { const config = useConfig(parameters) const options = sendTransactionMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseSendTransactionReturnType return { ...(mutation as Return), sendTransaction: mutation.mutate as Return['mutate'], sendTransactionAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/react/src/hooks/useSendTransactionSync.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { config, testClient, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { parseEther } from 'viem' import { beforeEach, expect, test, vi } from 'vitest' import { useSendTransactionSync } from './useSendTransactionSync.js' const connector = config.connectors[0]! beforeEach(async () => { await disconnect(config).catch(() => {}) }) test('default', async () => { await connect(config, { connector }) const { result } = await renderHook(() => useSendTransactionSync()) result.current.mutate({ to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) await wait(2_000) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 15_000 }) expect(result.current.data).toBeDefined() await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/useSendTransactionSync.ts ================================================ 'use client' import { useMutation } from '@tanstack/react-query' import type { Config, ResolvedRegister, SendTransactionSyncErrorType, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type SendTransactionSyncData, type SendTransactionSyncMutate, type SendTransactionSyncMutateAsync, type SendTransactionSyncOptions, type SendTransactionSyncVariables, sendTransactionSyncMutationOptions, } from '@wagmi/core/query' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseSendTransactionSyncParameters< config extends Config = Config, context = unknown, > = Compute< ConfigParameter & SendTransactionSyncOptions > export type UseSendTransactionSyncReturnType< config extends Config = Config, context = unknown, > = Compute< UseMutationReturnType< SendTransactionSyncData, SendTransactionSyncErrorType, SendTransactionSyncVariables, context, SendTransactionSyncMutate, SendTransactionSyncMutateAsync > & { /** @deprecated use `mutate` instead */ sendTransactionSync: SendTransactionSyncMutate /** @deprecated use `mutateAsync` instead */ sendTransactionSyncAsync: SendTransactionSyncMutateAsync } > /** https://wagmi.sh/react/api/hooks/useSendTransactionSync */ export function useSendTransactionSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: UseSendTransactionSyncParameters = {}, ): UseSendTransactionSyncReturnType { const config = useConfig(parameters) const options = sendTransactionSyncMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseSendTransactionSyncReturnType return { ...(mutation as Return), sendTransactionSync: mutation.mutate as Return['mutate'], sendTransactionSyncAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/react/src/hooks/useShowCallsStatus.test.ts ================================================ import { connect, disconnect, sendCalls } from '@wagmi/core' import { accounts, config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { parseEther } from 'viem' import { test, vi } from 'vitest' import { useShowCallsStatus } from './useShowCallsStatus.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const { id } = await sendCalls(config, { calls: [ { data: '0xdeadbeef', to: accounts[1], value: parseEther('1'), }, { to: accounts[2], value: parseEther('2'), }, { to: accounts[3], value: parseEther('3'), }, ], }) const { result } = await renderHook(() => useShowCallsStatus()) result.current.mutate({ id }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/useShowCallsStatus.ts ================================================ 'use client' import { useMutation } from '@tanstack/react-query' import type { Config, ResolvedRegister, ShowCallsStatusErrorType, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type ShowCallsStatusData, type ShowCallsStatusMutate, type ShowCallsStatusMutateAsync, type ShowCallsStatusOptions, type ShowCallsStatusVariables, showCallsStatusMutationOptions, } from '@wagmi/core/query' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseShowCallsStatusParameters< config extends Config = Config, context = unknown, > = Compute & ShowCallsStatusOptions> export type UseShowCallsStatusReturnType = Compute< UseMutationReturnType< ShowCallsStatusData, ShowCallsStatusErrorType, ShowCallsStatusVariables, context, ShowCallsStatusMutate, ShowCallsStatusMutateAsync > & { /** @deprecated use `mutate` instead */ showCallsStatus: ShowCallsStatusMutate /** @deprecated use `mutateAsync` instead */ showCallsStatusAsync: ShowCallsStatusMutateAsync } > /** https://wagmi.sh/react/api/hooks/useShowCallsStatus */ export function useShowCallsStatus< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: UseShowCallsStatusParameters = {}, ): UseShowCallsStatusReturnType { const config = useConfig(parameters) const options = showCallsStatusMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseShowCallsStatusReturnType return { ...(mutation as Return), showCallsStatus: mutation.mutate as Return['mutate'], showCallsStatusAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/react/src/hooks/useSignMessage.test-d.ts ================================================ import type { SignMessageErrorType } from '@wagmi/core' import type { SignMessageVariables } from '@wagmi/core/query' import { expectTypeOf, test } from 'vitest' import { useSignMessage } from './useSignMessage.js' const message = 'hello world' const contextValue = { foo: 'bar' } as const test('context', () => { const signMessage = useSignMessage({ mutation: { onMutate(variables) { expectTypeOf(variables).toEqualTypeOf() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf() expectTypeOf(data).toEqualTypeOf<`0x${string}`>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf<`0x${string}` | undefined>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(signMessage.data).toEqualTypeOf<`0x${string}` | undefined>() expectTypeOf(signMessage.error).toEqualTypeOf() expectTypeOf(signMessage.variables).toEqualTypeOf< SignMessageVariables | undefined >() expectTypeOf(signMessage.context).toEqualTypeOf< typeof contextValue | undefined >() signMessage.mutate( { message }, { onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf() expectTypeOf(data).toEqualTypeOf<`0x${string}`>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf<`0x${string}` | undefined>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/react/src/hooks/useSignMessage.test.ts ================================================ import { connect, disconnect, getConnection } from '@wagmi/core' import { config, privateKey } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { recoverMessageAddress } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { expect, test, vi } from 'vitest' import { useSignMessage } from './useSignMessage.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const { result } = await renderHook(() => useSignMessage()) result.current.mutate({ message: 'foo bar baz' }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) await expect( recoverMessageAddress({ message: 'foo bar baz', signature: result.current.data!, }), ).resolves.toEqual(getConnection(config).address) await disconnect(config, { connector }) }) test('behavior: local account', async () => { const { result } = await renderHook(() => useSignMessage()) const account = privateKeyToAccount(privateKey) result.current.mutate({ account, message: 'foo bar baz' }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) await expect( recoverMessageAddress({ message: 'foo bar baz', signature: result.current.data!, }), ).resolves.toEqual(account.address) }) ================================================ FILE: packages/react/src/hooks/useSignMessage.ts ================================================ 'use client' import { useMutation } from '@tanstack/react-query' import type { SignMessageErrorType } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type SignMessageData, type SignMessageMutate, type SignMessageMutateAsync, type SignMessageOptions, type SignMessageVariables, signMessageMutationOptions, } from '@wagmi/core/query' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseSignMessageParameters = Compute< ConfigParameter & SignMessageOptions > export type UseSignMessageReturnType = Compute< UseMutationReturnType< SignMessageData, SignMessageErrorType, SignMessageVariables, context, SignMessageMutate, SignMessageMutateAsync > & { /** @deprecated use `mutate` instead */ signMessage: SignMessageMutate /** @deprecated use `mutateAsync` instead */ signMessageAsync: SignMessageMutateAsync } > /** https://wagmi.sh/react/api/hooks/useSignMessage */ export function useSignMessage( parameters: UseSignMessageParameters = {}, ): UseSignMessageReturnType { const config = useConfig(parameters) const options = signMessageMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseSignMessageReturnType return { ...(mutation as Return), signMessage: mutation.mutate as Return['mutate'], signMessageAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/react/src/hooks/useSignTransaction.test-d.ts ================================================ import type { SignTransactionErrorType } from '@wagmi/core' import type { Hash, TransactionSerializedEIP1559, TransactionSerializedEIP2930, TransactionSerializedEIP4844, TransactionSerializedEIP7702, TransactionSerializedLegacy, } from 'viem' import { expectTypeOf, test } from 'vitest' import { useSignTransaction } from './useSignTransaction.js' const contextValue = { foo: 'bar' } as const test('context', () => { const signTransaction = useSignTransaction({ mutation: { onMutate(variables) { expectTypeOf(variables).toMatchTypeOf< { chainId?: number | undefined } | undefined >() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(data).toMatchTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toMatchTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(signTransaction.data).toMatchTypeOf() expectTypeOf( signTransaction.error, ).toEqualTypeOf() expectTypeOf(signTransaction.variables).toMatchTypeOf< { chainId?: number | undefined } | undefined >() expectTypeOf(signTransaction.context).toEqualTypeOf< typeof contextValue | undefined >() signTransaction.mutate( { to: '0x' }, { onError(error, variables, context) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(data).toMatchTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toMatchTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(context).toEqualTypeOf() }, }, ) }) test('legacy', () => { const { mutateAsync } = useSignTransaction() const result1 = mutateAsync({ gasPrice: 0n }) const result2 = mutateAsync({ type: 'legacy' }) expectTypeOf(result1).toEqualTypeOf>() expectTypeOf(result2).toEqualTypeOf>() // @ts-expect-error mutateAsync({ gasPrice: 0n, maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, }) // @ts-expect-error mutateAsync({ gasPrice: 0n, maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, type: 'legacy', }) // @ts-expect-error mutateAsync({ maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, type: 'legacy', }) }) test('eip7702', () => { const { mutateAsync } = useSignTransaction() const result1 = mutateAsync({ authorizationList: [], }) const result2 = mutateAsync({ authorizationList: [], type: 'eip7702', }) expectTypeOf(result1).toEqualTypeOf>() expectTypeOf(result2).toEqualTypeOf>() }) test('eip4844', () => { const { mutateAsync } = useSignTransaction() const result1 = mutateAsync({ blobVersionedHashes: [], maxFeePerBlobGas: 0n, to: '0x0000000000000000000000000000000000000000', }) const result2 = mutateAsync({ blobVersionedHashes: [], maxFeePerBlobGas: 0n, to: '0x0000000000000000000000000000000000000000', type: 'eip4844', }) expectTypeOf(result1).toEqualTypeOf>() expectTypeOf(result2).toEqualTypeOf>() }) test('eip1559', () => { const { mutateAsync } = useSignTransaction() const result1 = mutateAsync({ maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, }) const result2 = mutateAsync({ type: 'eip1559', }) expectTypeOf(result1).toEqualTypeOf>() expectTypeOf(result2).toEqualTypeOf>() // @ts-expect-error mutateAsync({ gasPrice: 0n, maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, }) // @ts-expect-error mutateAsync({ gasPrice: 0n, maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, type: 'eip1559', }) // @ts-expect-error mutateAsync({ gasPrice: 0n, type: 'eip1559', }) }) test('eip2930', () => { const { mutateAsync } = useSignTransaction() const result1 = mutateAsync({ accessList: [], gasPrice: 0n, }) const result2 = mutateAsync({ type: 'eip2930', }) expectTypeOf(result1).toEqualTypeOf>() expectTypeOf(result2).toEqualTypeOf>() // @ts-expect-error mutateAsync({ accessList: [], gasPrice: 0n, maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, }) // @ts-expect-error mutateAsync({ accessList: [], gasPrice: 0n, maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, type: 'eip2930', }) // @ts-expect-error mutateAsync({ accessList: [], maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, type: 'eip2930', }) }) ================================================ FILE: packages/react/src/hooks/useSignTransaction.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { config, signedTransactionRegex } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { parseEther } from 'viem' import { expect, test, vi } from 'vitest' import { useSignTransaction } from './useSignTransaction.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const { result } = await renderHook(() => useSignTransaction()) result.current.mutate({ to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 5_000 }) expect(result.current.data).toMatch(signedTransactionRegex) await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/useSignTransaction.ts ================================================ 'use client' import { useMutation } from '@tanstack/react-query' import type { Config, ResolvedRegister, SelectChains, SignTransactionErrorType, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type SignTransactionData, type SignTransactionMutate, type SignTransactionMutateAsync, type SignTransactionOptions, type SignTransactionVariables, signTransactionMutationOptions, } from '@wagmi/core/query' import type { SignTransactionRequest as viem_SignTransactionRequest } from 'viem' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseSignTransactionParameters< config extends Config = Config, request extends viem_SignTransactionRequest< SelectChains[0], SelectChains[0] > = viem_SignTransactionRequest< SelectChains[0], SelectChains[0] >, context = unknown, > = Compute< ConfigParameter & SignTransactionOptions< config, config['chains'][number]['id'], request, context > > export type UseSignTransactionReturnType< config extends Config = Config, request extends viem_SignTransactionRequest< SelectChains[0], SelectChains[0] > = viem_SignTransactionRequest< SelectChains[0], SelectChains[0] >, context = unknown, > = Compute< UseMutationReturnType< SignTransactionData, SignTransactionErrorType, SignTransactionVariables, context, SignTransactionMutate, SignTransactionMutateAsync > & { /** @deprecated use `mutate` instead */ signTransaction: SignTransactionMutate /** @deprecated use `mutateAsync` instead */ signTransactionAsync: SignTransactionMutateAsync } > /** https://wagmi.sh/react/api/hooks/useSignTransaction */ export function useSignTransaction< config extends Config = ResolvedRegister['config'], request extends viem_SignTransactionRequest< SelectChains[0], SelectChains[0] > = viem_SignTransactionRequest< SelectChains[0], SelectChains[0] >, context = unknown, >( parameters: UseSignTransactionParameters = {}, ): UseSignTransactionReturnType { const config = useConfig(parameters) const options = signTransactionMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseSignTransactionReturnType return { ...(mutation as unknown as Return), signTransaction: mutation.mutate as Return['mutate'], signTransactionAsync: mutation.mutateAsync as unknown as Return['mutateAsync'], } } ================================================ FILE: packages/react/src/hooks/useSignTypedData.test-d.ts ================================================ import type { SignTypedDataErrorType, SignTypedDataReturnType, } from '@wagmi/core' import type { SignTypedDataVariables } from '@wagmi/core/query' import { typedData } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useSignTypedData } from './useSignTypedData.js' const contextValue = { foo: 'bar' } as const test('context', () => { const signTypedData = useSignTypedData({ mutation: { onMutate(variables) { expectTypeOf(variables).toMatchTypeOf() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toMatchTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toMatchTypeOf() expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(signTypedData.data).toEqualTypeOf< SignTypedDataReturnType | undefined >() expectTypeOf( signTypedData.error, ).toEqualTypeOf() expectTypeOf(signTypedData.variables).toMatchTypeOf< SignTypedDataVariables | undefined >() expectTypeOf(signTypedData.context).toEqualTypeOf< typeof contextValue | undefined >() signTypedData.mutate( { types: typedData.basic.types, primaryType: 'Person', message: { name: 'Bob', wallet: '0x', }, }, { onError(error, variables, context) { expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ types: typeof typedData.basic.types primaryType: 'Person' message: { name: string wallet: `0x${string}` } }>() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ types: typeof typedData.basic.types primaryType: 'Person' message: { name: string wallet: `0x${string}` } }>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ types: typeof typedData.basic.types primaryType: 'Person' message: { name: string wallet: `0x${string}` } }>() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/react/src/hooks/useSignTypedData.test.ts ================================================ import { connect, disconnect, getConnection } from '@wagmi/core' import { config, privateKey, typedData } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { recoverTypedDataAddress } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { expect, test, vi } from 'vitest' import { useSignTypedData } from './useSignTypedData.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const { result } = await renderHook(() => useSignTypedData()) result.current.mutate({ types: typedData.basic.types, primaryType: 'Mail', message: typedData.basic.message, }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) await expect( recoverTypedDataAddress({ types: typedData.basic.types, primaryType: 'Mail', message: typedData.basic.message, signature: result.current.data!, }), ).resolves.toEqual(getConnection(config).address) await disconnect(config, { connector }) }) test('behavior: local account', async () => { const { result } = await renderHook(() => useSignTypedData()) const account = privateKeyToAccount(privateKey) result.current.mutate({ account, types: typedData.basic.types, primaryType: 'Mail', message: typedData.basic.message, }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) await expect( recoverTypedDataAddress({ types: typedData.basic.types, primaryType: 'Mail', message: typedData.basic.message, signature: result.current.data!, }), ).resolves.toEqual(account.address) }) ================================================ FILE: packages/react/src/hooks/useSignTypedData.ts ================================================ 'use client' import { useMutation } from '@tanstack/react-query' import type { SignTypedDataErrorType } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type SignTypedDataData, type SignTypedDataMutate, type SignTypedDataMutateAsync, type SignTypedDataOptions, type SignTypedDataVariables, signTypedDataMutationOptions, } from '@wagmi/core/query' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseSignTypedDataParameters = Compute< ConfigParameter & SignTypedDataOptions > export type UseSignTypedDataReturnType = Compute< UseMutationReturnType< SignTypedDataData, SignTypedDataErrorType, SignTypedDataVariables, context, SignTypedDataMutate, SignTypedDataMutateAsync > & { /** @deprecated use `mutate` instead */ signTypedData: SignTypedDataMutate /** @deprecated use `mutateAsync` instead */ signTypedDataAsync: SignTypedDataMutateAsync } > /** https://wagmi.sh/react/api/hooks/useSignTypedData */ export function useSignTypedData( parameters: UseSignTypedDataParameters = {}, ): UseSignTypedDataReturnType { const config = useConfig(parameters) const options = signTypedDataMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseSignTypedDataReturnType return { ...(mutation as Return), signTypedData: mutation.mutate as Return['mutate'], signTypedDataAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/react/src/hooks/useSimulateContract.test-d.ts ================================================ import { abi, type config } from '@wagmi/test' import type { Address } from 'viem' import { assertType, expectTypeOf, test } from 'vitest' import { type UseSimulateContractParameters, type UseSimulateContractReturnType, useSimulateContract, } from './useSimulateContract.js' test('default', () => { const result = useSimulateContract({ address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], }) expectTypeOf(result.data).toMatchTypeOf< | { result: boolean request: { chainId?: undefined abi: readonly [ { readonly name: 'transferFrom' readonly type: 'function' readonly stateMutability: 'nonpayable' readonly inputs: readonly [ { readonly type: 'address'; readonly name: 'sender' }, { readonly type: 'address'; readonly name: 'recipient' }, { readonly type: 'uint256'; readonly name: 'amount' }, ] readonly outputs: readonly [{ type: 'bool' }] }, ] functionName: 'transferFrom' args: readonly [Address, Address, bigint] } } | undefined >() }) test('select data', () => { const result = useSimulateContract({ address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], chainId: 1, query: { select(data) { expectTypeOf(data.result).toEqualTypeOf() return data.request.args }, }, }) expectTypeOf(result.data).toEqualTypeOf< readonly [Address, Address, bigint] | undefined >() }) test('UseSimulateContractParameters', () => { type Result = UseSimulateContractParameters expectTypeOf().toMatchTypeOf<{ functionName?: 'approve' | 'transfer' | 'transferFrom' | undefined args?: readonly [Address, Address, bigint] | undefined }>() }) test('UseSimulateContractReturnType', () => { type Result = UseSimulateContractReturnType< typeof abi.erc20, 'transferFrom', ['0x', '0x', 123n], typeof config, 1 > expectTypeOf().toMatchTypeOf< | { result: boolean request: { chainId: number abi: readonly [ { readonly name: 'transferFrom' readonly type: 'function' readonly stateMutability: 'nonpayable' readonly inputs: readonly [ { readonly type: 'address'; readonly name: 'sender' }, { readonly type: 'address'; readonly name: 'recipient' }, { readonly type: 'uint256'; readonly name: 'amount' }, ] readonly outputs: readonly [{ type: 'bool' }] }, ] functionName: 'approve' | 'transfer' | 'transferFrom' args: readonly [Address, Address, bigint] } } | undefined >() }) test('overloads', () => { const result1 = useSimulateContract({ address: '0x', abi: abi.writeOverloads, functionName: 'foo', }) assertType(result1.data?.result) const result2 = useSimulateContract({ address: '0x', abi: abi.writeOverloads, functionName: 'foo', args: [], }) assertType(result2.data?.result) const result3 = useSimulateContract({ address: '0x', abi: abi.writeOverloads, functionName: 'foo', args: ['0x'], }) assertType(result3.data?.result) const result4 = useSimulateContract({ address: '0x', abi: abi.writeOverloads, functionName: 'foo', args: ['0x', '0x'], }) assertType< | { foo: `0x${string}` bar: `0x${string}` } | undefined >(result4.data?.result) }) ================================================ FILE: packages/react/src/hooks/useSimulateContract.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { abi, address, config, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useSimulateContract } from './useSimulateContract.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const { result } = await renderHook(() => useSimulateContract({ address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'mint', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": { "chainId": 1, "request": { "abi": [ { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "account": { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "type": "json-rpc", }, "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": undefined, "chainId": 1, "dataSuffix": undefined, "functionName": "mint", }, "result": undefined, }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "simulateContract", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "chainId": 1, "functionName": "mint", }, ], "refetch": [Function], "status": "success", } `) await disconnect(config, { connector }) }) test('behavior: disabled when properties missing', async () => { const { result } = await renderHook(() => useSimulateContract()) await wait(100) await vi.waitFor(() => expect(result.current.isPending).toBeTruthy()) }) ================================================ FILE: packages/react/src/hooks/useSimulateContract.ts ================================================ 'use client' import type { Config, ResolvedRegister, SimulateContractErrorType, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { type SimulateContractData, type SimulateContractOptions, simulateContractQueryOptions, } from '@wagmi/core/query' import type { Abi, ContractFunctionArgs, ContractFunctionName } from 'viem' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' import { useConnection } from './useConnection.js' export type UseSimulateContractParameters< abi extends Abi | readonly unknown[] = Abi, functionName extends ContractFunctionName< abi, 'nonpayable' | 'payable' > = ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName > = ContractFunctionArgs, config extends Config = Config, chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = SimulateContractData, > = SimulateContractOptions< abi, functionName, args, config, chainId, selectData > & ConfigParameter export type UseSimulateContractReturnType< abi extends Abi | readonly unknown[] = Abi, functionName extends ContractFunctionName< abi, 'nonpayable' | 'payable' > = ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName > = ContractFunctionArgs, config extends Config = Config, chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = SimulateContractData, > = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useSimulateContract */ export function useSimulateContract< const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, const args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName >, config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = SimulateContractData, >( parameters: UseSimulateContractParameters< abi, functionName, args, config, chainId, selectData > = {} as any, ): UseSimulateContractReturnType< abi, functionName, args, config, chainId, selectData > { const config = useConfig(parameters) const { address, connector } = useConnection() const chainId = useChainId({ config }) const options = simulateContractQueryOptions(config, { ...(parameters as any), account: parameters.account ?? address, chainId: parameters.chainId ?? chainId, connector: parameters.connector ?? connector, }) return useQuery(options) as any } ================================================ FILE: packages/react/src/hooks/useStorageAt.test-d.ts ================================================ import type { Hex } from 'viem' import { expectTypeOf, test } from 'vitest' import { useStorageAt } from './useStorageAt.js' test('select data', () => { const result = useStorageAt({ query: { select(data) { return data }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useStorageAt.test.ts ================================================ import { address, chain, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import type { Address } from 'viem' import { expect, test, vi } from 'vitest' import { useStorageAt } from './useStorageAt.js' test('default', async () => { const { result } = await renderHook(() => useStorageAt({ address: address.wagmiMintExample, slot: '0x0', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": "0x7761676d6900000000000000000000000000000000000000000000000000000a", "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getStorageAt", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "chainId": 1, "slot": "0x0", }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: blockNumber', async () => { const { result } = await renderHook(() => useStorageAt({ address: address.wagmiMintExample, blockNumber: 16280770n, slot: '0x0', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": "0x7761676d6900000000000000000000000000000000000000000000000000000a", "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getStorageAt", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "blockNumber": 16280770n, "chainId": 1, "slot": "0x0", }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: blockTag', async () => { const { result } = await renderHook(() => useStorageAt({ address: address.wagmiMintExample, blockTag: 'safe', slot: '0x0', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": "0x7761676d6900000000000000000000000000000000000000000000000000000a", "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getStorageAt", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "blockTag": "safe", "chainId": 1, "slot": "0x0", }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: chainId', async () => { const { result } = await renderHook(() => useStorageAt({ address: address.wagmiMintExample, chainId: chain.optimism.id, slot: '0x0', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": "0x0000000000000000000000000000000000000000000000000000000000000000", "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getStorageAt", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "chainId": 10, "slot": "0x0", }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: address: undefined -> defined', async () => { const { result, rerender } = await renderHook( (props) => useStorageAt({ address: props?.address, slot: '0x0', }), { initialProps: { address: undefined as Address | undefined } }, ) expect(result.current).toMatchInlineSnapshot(` { "data": undefined, "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "getStorageAt", { "address": undefined, "chainId": 1, "slot": "0x0", }, ], "refetch": [Function], "status": "pending", } `) rerender({ address: address.wagmiMintExample }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": "0x7761676d6900000000000000000000000000000000000000000000000000000a", "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getStorageAt", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "chainId": 1, "slot": "0x0", }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: disabled when properties missing', async () => { const { result } = await renderHook(() => useStorageAt()) await wait(100) await vi.waitFor(() => expect(result.current.isPending).toBeTruthy()) }) ================================================ FILE: packages/react/src/hooks/useStorageAt.ts ================================================ 'use client' import type { Config, GetStorageAtErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetStorageAtData, type GetStorageAtOptions, getStorageAtQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseStorageAtParameters< config extends Config = Config, selectData = GetStorageAtData, > = Compute & ConfigParameter> export type UseStorageAtReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useStorageAt */ export function useStorageAt< config extends Config = ResolvedRegister['config'], selectData = GetStorageAtData, >( parameters: UseStorageAtParameters = {}, ): UseStorageAtReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getStorageAtQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useSwitchChain.test-d.ts ================================================ import type { Connector, SwitchChainErrorType } from '@wagmi/core' import type { Chain } from '@wagmi/core/chains' import type { Compute, ExactPartial } from '@wagmi/core/internal' import { chain } from '@wagmi/test' import type { AddEthereumChainParameter } from 'viem' import { expectTypeOf, test } from 'vitest' import { useSwitchChain } from './useSwitchChain.js' const chainId = chain.mainnet.id const contextValue = { foo: 'bar' } as const test('context', () => { const switchChain = useSwitchChain({ mutation: { onMutate(variables) { expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() expectTypeOf(data).toEqualTypeOf>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf | undefined>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(switchChain.data).toEqualTypeOf | undefined>() expectTypeOf(switchChain.error).toEqualTypeOf() expectTypeOf(switchChain.variables).toEqualTypeOf< | { addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined } | undefined >() expectTypeOf(switchChain.context).toEqualTypeOf< typeof contextValue | undefined >() switchChain.mutate( { chainId }, { onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() expectTypeOf(data).toEqualTypeOf>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf | undefined>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/react/src/hooks/useSwitchChain.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { chain, config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useConnection } from './useConnection.js' import { useSwitchChain } from './useSwitchChain.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const { result, act } = await renderHook(() => ({ useConnection: useConnection(), useSwitchChain: useSwitchChain(), })) const chainId1 = result.current.useConnection.chainId expect(chainId1).toBeDefined() await act(() => result.current.useSwitchChain.mutate({ chainId: chain.mainnet2.id }), ) await vi.waitFor(() => expect(result.current.useSwitchChain.isSuccess).toBeTruthy(), ) const chainId2 = result.current.useConnection.chainId expect(chainId2).toBeDefined() expect(chainId1).not.toBe(chainId2) await act(() => result.current.useSwitchChain.mutate({ chainId: chain.mainnet.id }), ) await vi.waitFor(() => expect(result.current.useSwitchChain.isSuccess).toBeTruthy(), ) const chainId3 = result.current.useConnection.chainId expect(chainId3).toBeDefined() expect(chainId1).toBe(chainId3) await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/useSwitchChain.ts ================================================ 'use client' import { useMutation } from '@tanstack/react-query' import type { Config, ResolvedRegister, SwitchChainErrorType, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type SwitchChainData, type SwitchChainMutate, type SwitchChainMutateAsync, type SwitchChainOptions, type SwitchChainVariables, switchChainMutationOptions, } from '@wagmi/core/query' import type { UseMutationReturnType } from '../utils/query.js' import { useChains } from './useChains.js' import { useConfig } from './useConfig.js' export type UseSwitchChainParameters< config extends Config = Config, context = unknown, > = Compute & SwitchChainOptions> export type UseSwitchChainReturnType< config extends Config = Config, context = unknown, > = Compute< UseMutationReturnType< SwitchChainData, SwitchChainErrorType, SwitchChainVariables, context, SwitchChainMutate, SwitchChainMutateAsync > & { /** @deprecated use `useChains` instead */ chains: config['chains'] /** @deprecated use `mutate` instead */ switchChain: SwitchChainMutate /** @deprecated use `mutateAsync` instead */ switchChainAsync: SwitchChainMutateAsync } > /** https://wagmi.sh/react/api/hooks/useSwitchChain */ export function useSwitchChain< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: UseSwitchChainParameters = {}, ): UseSwitchChainReturnType { const config = useConfig(parameters) const options = switchChainMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseSwitchChainReturnType return { ...(mutation as Return), chains: useChains({ config }) as unknown as config['chains'], switchChain: mutation.mutate as Return['mutate'], switchChainAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/react/src/hooks/useSwitchConnection.test-d.ts ================================================ import type { Connector, SwitchAccountErrorType } from '@wagmi/core' import { config } from '@wagmi/test' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' import { useSwitchConnection } from './useSwitchConnection.js' const connector = config.connectors[0]! const contextValue = { foo: 'bar' } as const test('context', () => { const switchConnection = useSwitchConnection({ mutation: { onMutate(variables) { expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() expectTypeOf(data).toEqualTypeOf<{ accounts: readonly [Address, ...Address[]] chainId: number }>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(switchConnection.data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number } | undefined >() expectTypeOf( switchConnection.error, ).toEqualTypeOf() expectTypeOf(switchConnection.variables).toEqualTypeOf< { connector: Connector } | undefined >() expectTypeOf(switchConnection.context).toEqualTypeOf< typeof contextValue | undefined >() switchConnection.mutate( { connector }, { onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() expectTypeOf(data).toEqualTypeOf<{ accounts: readonly [Address, ...Address[]] chainId: number }>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/react/src/hooks/useSwitchConnection.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { config, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useConnection } from './useConnection.js' import { useSwitchConnection } from './useSwitchConnection.js' const connector1 = config.connectors[0]! const connector2 = config.connectors[1]! test('default', async () => { await connect(config, { connector: connector2 }) await connect(config, { connector: connector1 }) const { result } = await renderHook(() => ({ useConnection: useConnection(), useSwitchConnection: useSwitchConnection(), })) const address1 = result.current.useConnection.address expect(address1).toBeDefined() result.current.useSwitchConnection.mutate({ connector: connector2 }) await vi.waitFor(() => expect(result.current.useSwitchConnection.isSuccess).toBeTruthy(), ) await wait(0) const address2 = result.current.useConnection.address expect(address2).toBeDefined() expect(address1).not.toBe(address2) result.current.useSwitchConnection.mutate({ connector: connector1 }) await vi.waitFor(() => expect(result.current.useSwitchConnection.isSuccess).toBeTruthy(), ) await wait(0) const address3 = result.current.useConnection.address expect(address3).toBeDefined() expect(address1).toBe(address3) await disconnect(config, { connector: connector1 }) await disconnect(config, { connector: connector2 }) }) ================================================ FILE: packages/react/src/hooks/useSwitchConnection.ts ================================================ 'use client' import { useMutation } from '@tanstack/react-query' import type { Config, Connector, ResolvedRegister, SwitchConnectionErrorType, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type SwitchConnectionData, type SwitchConnectionMutate, type SwitchConnectionMutateAsync, type SwitchConnectionOptions, type SwitchConnectionVariables, switchConnectionMutationOptions, } from '@wagmi/core/query' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' import { useConnections } from './useConnections.js' export type UseSwitchConnectionParameters< config extends Config = Config, context = unknown, > = Compute & SwitchConnectionOptions> export type UseSwitchConnectionReturnType< config extends Config = Config, context = unknown, > = Compute< UseMutationReturnType< SwitchConnectionData, SwitchConnectionErrorType, SwitchConnectionVariables, context, SwitchConnectionMutate, SwitchConnectionMutateAsync > & { /** @deprecated use `useConnections` instead */ connectors: readonly Connector[] /** @deprecated use `mutate` instead */ switchAccount: SwitchConnectionMutate /** @deprecated use `mutateAsync` instead */ switchAccountAsync: SwitchConnectionMutateAsync /** @deprecated use `mutate` instead */ switchConnection: SwitchConnectionMutate /** @deprecated use `mutateAsync` instead */ switchConnectionAsync: SwitchConnectionMutateAsync } > /** https://wagmi.sh/react/api/hooks/useSwitchConnection */ export function useSwitchConnection< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: UseSwitchConnectionParameters = {}, ): UseSwitchConnectionReturnType { const config = useConfig(parameters) const options = switchConnectionMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseSwitchConnectionReturnType return { ...(mutation as Return), connectors: useConnections({ config }).map( (connection) => connection.connector, ), switchAccount: mutation.mutate as Return['mutate'], switchAccountAsync: mutation.mutateAsync as Return['mutateAsync'], switchConnection: mutation.mutate as Return['mutate'], switchConnectionAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/react/src/hooks/useSyncExternalStoreWithTracked.test.tsx ================================================ import { render, renderHook } from '@wagmi/test/react' import React from 'react' import * as ReactDOM from 'react-dom' import { expect, test } from 'vitest' import { useSyncExternalStoreWithTracked } from './useSyncExternalStoreWithTracked.js' function createExternalStore(initialState: state) { const listeners = new Set<() => void>() let currentState = initialState return { set(updater: (state: state) => state) { currentState = updater(currentState) ReactDOM.unstable_batchedUpdates(() => { for (const listener of listeners) { listener() } }) }, subscribe(listener: () => void) { listeners.add(listener) return () => listeners.delete(listener) }, getState() { return currentState }, } } function useExternalStore( store: ReturnType, cb: (state: any) => void, ) { const state = useSyncExternalStoreWithTracked( store.subscribe, store.getState, store.getState, ) cb(state) return state as any } test('rerenders only when the tracked value changes', async () => { const externalStore = createExternalStore({ foo: 'bar', gm: 'wagmi', isGonnaMakeIt: false, }) const renders: any[] = [] const { act } = await renderHook(() => { const { gm } = useExternalStore(externalStore, (state) => { renders.push(state) }) return gm }) act(() => { externalStore.set((x) => ({ ...x, foo: 'baz', isGonnaMakeIt: true })) }) expect(renders).toMatchInlineSnapshot(` [ { "foo": "bar", "gm": "wagmi", "isGonnaMakeIt": false, }, ] `) act(() => { externalStore.set((x) => ({ ...x, gm: 'ngmi' })) }) expect(renders).toMatchInlineSnapshot(` [ { "foo": "bar", "gm": "wagmi", "isGonnaMakeIt": false, }, { "foo": "baz", "gm": "ngmi", "isGonnaMakeIt": true, }, ] `) }) test('rerenders when all values are being tracked', async () => { const externalStore = createExternalStore({ foo: 'bar', gm: 'wagmi', isGonnaMakeIt: false, }) const renders: any[] = [] const { act } = await renderHook(() => { const { foo, gm, isGonnaMakeIt } = useExternalStore( externalStore, (state) => { renders.push(state) }, ) return { foo, gm, isGonnaMakeIt, } }) act(() => { externalStore.set((x) => ({ ...x, isGonnaMakeIt: true })) }) expect(renders).toMatchInlineSnapshot(` [ { "foo": "bar", "gm": "wagmi", "isGonnaMakeIt": false, }, { "foo": "bar", "gm": "wagmi", "isGonnaMakeIt": true, }, ] `) }) test('rerenders when no values are being tracked', async () => { const externalStore = createExternalStore({ foo: 'bar', gm: 'wagmi', isGonnaMakeIt: false, }) const renders: any[] = [] const { act } = await renderHook(() => { useExternalStore(externalStore, (state) => { renders.push(state) }) }) act(() => { externalStore.set((x) => ({ ...x, isGonnaMakeIt: true })) }) expect(renders).toMatchInlineSnapshot(` [ { "foo": "bar", "gm": "wagmi", "isGonnaMakeIt": false, }, { "foo": "bar", "gm": "wagmi", "isGonnaMakeIt": true, }, ] `) }) test('store object reference is stable across rerenders', async () => { const externalStore = createExternalStore({ foo: 'bar', gm: 'wagmi', isGonnaMakeIt: false, }) let childRenderCount = 0 const MemoComponent = React.memo((props: { store: any }) => { childRenderCount++ return
{props.store.isGonnaMakeIt}
}) const renders: any[] = [] function Test() { const store = useExternalStore(externalStore, (state) => { renders.push(state) }) const [, rerender] = React.useState(0) return ( <> ) } const screen = await render() const forceRerenderButton = screen.getByText('rerender') expect(childRenderCount).toBe(1) expect(renders.length).toBe(1) // updating parent state, child should not rerender await forceRerenderButton.click() expect(childRenderCount).toBe(1) expect(renders.length).toBe(2) // child and parent both rerender when store changes const updateExternalStoreButton = screen.getByText('update') await updateExternalStoreButton.click() expect(childRenderCount).toBe(2) expect(renders.length).toBe(3) }) test('array', async () => { const externalStore = createExternalStore(['foo']) const renders: any[] = [] const { act } = await renderHook(() => { const array = useExternalStore(externalStore, (state) => { renders.push(state) }) return array }) act(() => { externalStore.set((x) => [...x, 'bar']) }) expect(renders).toMatchInlineSnapshot(` [ [ "foo", ], [ "foo", "bar", ], ] `) act(() => { externalStore.set((x) => [...x, 'baz']) }) expect(renders).toMatchInlineSnapshot(` [ [ "foo", ], [ "foo", "bar", ], [ "foo", "bar", "baz", ], ] `) }) ================================================ FILE: packages/react/src/hooks/useSyncExternalStoreWithTracked.ts ================================================ 'use client' import { deepEqual } from '@wagmi/core/internal' import { useMemo, useRef } from 'react' import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector.js' const isPlainObject = (obj: unknown) => typeof obj === 'object' && !Array.isArray(obj) export function useSyncExternalStoreWithTracked< snapshot extends selection, selection = snapshot, >( subscribe: (onStoreChange: () => void) => () => void, getSnapshot: () => snapshot, getServerSnapshot: undefined | null | (() => snapshot) = getSnapshot, isEqual: (a: selection, b: selection) => boolean = deepEqual, ) { const trackedKeys = useRef([]) const result = useSyncExternalStoreWithSelector( subscribe, getSnapshot, getServerSnapshot, (x) => x, (a, b) => { if (isPlainObject(a) && isPlainObject(b) && trackedKeys.current.length) { for (const key of trackedKeys.current) { const equal = isEqual( (a as { [_a: string]: any })[key], (b as { [_b: string]: any })[key], ) if (!equal) return false } return true } return isEqual(a, b) }, ) return useMemo(() => { if (isPlainObject(result)) { const trackedResult = { ...result } let properties = {} for (const [key, value] of Object.entries( trackedResult as { [key: string]: any }, )) { properties = { ...properties, [key]: { configurable: false, enumerable: true, get: () => { if (!trackedKeys.current.includes(key)) { trackedKeys.current.push(key) } return value }, }, } } Object.defineProperties(trackedResult, properties) return trackedResult } return result }, [result]) } ================================================ FILE: packages/react/src/hooks/useTransaction.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useTransaction } from './useTransaction.js' test('select data', () => { const result = useTransaction({ query: { select(data) { return data?.nonce }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useTransaction.test.ts ================================================ import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useTransaction } from './useTransaction.js' test('default', async () => { const { result } = await renderHook(() => useTransaction({ hash: '0x60668ed8c2dc110d61d945a936fcd45b8f13654e5c78481c8c825d1148c7ef30', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": { "accessList": [], "blockHash": "0xd725a38b51e5ceec8c5f6c9ccfdb2cc423af993bb650af5eedca5e4be7156ba7", "blockNumber": 15189204n, "chainId": 1, "from": "0xa0cf798816d4b9b9866b5330eea46a18382f251e", "gas": 21000n, "gasPrice": 9371645552n, "hash": "0x60668ed8c2dc110d61d945a936fcd45b8f13654e5c78481c8c825d1148c7ef30", "input": "0x", "maxFeePerGas": 13644824566n, "maxPriorityFeePerGas": 1500000000n, "nonce": 86, "r": "0x40174f9a38df876c1a7ce2587848819d4082ccd6d67a88aa5cabe59bf594e14f", "s": "0x7c0c82f62a8a5a9b0e9cf30a54a72fdae8fc54b5b79ddafef0acd30e94e83872", "to": "0xd2135cfb216b74109775236e36d4b433f1df507b", "transactionIndex": 144, "type": "eip1559", "typeHex": "0x2", "v": 0n, "value": 100000000000000000n, "yParity": 0, }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "transaction", { "chainId": 1, "hash": "0x60668ed8c2dc110d61d945a936fcd45b8f13654e5c78481c8c825d1148c7ef30", }, ], "refetch": [Function], "status": "success", } `) }) ================================================ FILE: packages/react/src/hooks/useTransaction.ts ================================================ 'use client' import type { Config, GetTransactionErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetTransactionData, type GetTransactionOptions, getTransactionQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseTransactionParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetTransactionData, > = Compute< GetTransactionOptions & ConfigParameter > export type UseTransactionReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetTransactionData, > = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useTransaction */ export function useTransaction< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetTransactionData, >( parameters: UseTransactionParameters = {}, ): UseTransactionReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getTransactionQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) as any } ================================================ FILE: packages/react/src/hooks/useTransactionConfirmations.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useTransactionConfirmations } from './useTransactionConfirmations.js' test('select data', () => { const result = useTransactionConfirmations({ query: { select(data) { return data }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useTransactionConfirmations.test.ts ================================================ import { getTransactionReceipt } from '@wagmi/core' import { config, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import type { Hash } from 'viem' import { expect, test, vi } from 'vitest' import { useTransactionConfirmations } from './useTransactionConfirmations.js' test('default', async () => { const { result } = await renderHook(() => useTransactionConfirmations({ hash: '0x60668ed8c2dc110d61d945a936fcd45b8f13654e5c78481c8c825d1148c7ef30', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toBeTypeOf('bigint') expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "transactionConfirmations", { "chainId": 1, "hash": "0x60668ed8c2dc110d61d945a936fcd45b8f13654e5c78481c8c825d1148c7ef30", }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: transactionReceipt', async () => { const transactionReceipt = await getTransactionReceipt(config, { hash: '0x60668ed8c2dc110d61d945a936fcd45b8f13654e5c78481c8c825d1148c7ef30', }) const { result } = await renderHook(() => useTransactionConfirmations({ transactionReceipt, }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toBeTypeOf('bigint') expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "transactionConfirmations", { "chainId": 1, "transactionReceipt": { "blockHash": "0xd725a38b51e5ceec8c5f6c9ccfdb2cc423af993bb650af5eedca5e4be7156ba7", "blockNumber": 15189204n, "contractAddress": null, "cumulativeGasUsed": 12949744n, "effectiveGasPrice": 9371645552n, "from": "0xa0cf798816d4b9b9866b5330eea46a18382f251e", "gasUsed": 21000n, "logs": [], "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "status": "success", "to": "0xd2135cfb216b74109775236e36d4b433f1df507b", "transactionHash": "0x60668ed8c2dc110d61d945a936fcd45b8f13654e5c78481c8c825d1148c7ef30", "transactionIndex": 144, "type": "eip1559", }, }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: hash: undefined -> defined', async () => { const { result, rerender } = await renderHook( (props) => useTransactionConfirmations({ hash: props?.hash, }), { initialProps: { hash: undefined as Hash | undefined } }, ) expect(result.current).toMatchInlineSnapshot(` { "data": undefined, "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "transactionConfirmations", { "chainId": 1, "hash": undefined, }, ], "refetch": [Function], "status": "pending", } `) rerender({ hash: '0x60668ed8c2dc110d61d945a936fcd45b8f13654e5c78481c8c825d1148c7ef30', }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toBeTypeOf('bigint') expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "transactionConfirmations", { "chainId": 1, "hash": "0x60668ed8c2dc110d61d945a936fcd45b8f13654e5c78481c8c825d1148c7ef30", }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: disabled when properties missing', async () => { const { result } = await renderHook(() => useTransactionConfirmations()) await wait(100) await vi.waitFor(() => expect(result.current.isPending).toBeTruthy()) }) ================================================ FILE: packages/react/src/hooks/useTransactionConfirmations.ts ================================================ 'use client' import type { Config, GetTransactionConfirmationsErrorType, ResolvedRegister, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { type GetTransactionConfirmationsData, type GetTransactionConfirmationsOptions, getTransactionConfirmationsQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseTransactionConfirmationsParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = GetTransactionConfirmationsData, > = GetTransactionConfirmationsOptions & ConfigParameter export type UseTransactionConfirmationsReturnType< selectData = GetTransactionConfirmationsData, > = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useTransactionConfirmations */ export function useTransactionConfirmations< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = GetTransactionConfirmationsData, >( parameters: UseTransactionConfirmationsParameters< config, chainId, selectData > = {} as any, ): UseTransactionConfirmationsReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getTransactionConfirmationsQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) as any } ================================================ FILE: packages/react/src/hooks/useTransactionCount.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useTransactionCount } from './useTransactionCount.js' test('select data', () => { const result = useTransactionCount({ query: { select(data) { return data }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useTransactionCount.test.ts ================================================ import { accounts, chain, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import type { Address } from 'viem' import { expect, test, vi } from 'vitest' import { useTransactionCount } from './useTransactionCount.js' const address = accounts[0] test('default', async () => { const { result } = await renderHook(() => useTransactionCount({ address })) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toBeTypeOf('number') expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "transactionCount", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: chainId', async () => { const { result } = await renderHook(() => useTransactionCount({ address, chainId: chain.mainnet2.id }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toBeTypeOf('number') expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "transactionCount", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 456, }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: blockNumber', async () => { const { result } = await renderHook(() => useTransactionCount({ address, blockNumber: 13677382n }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toBeTypeOf('number') expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "transactionCount", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "blockNumber": 13677382n, "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: address: undefined -> defined', async () => { let address: Address | undefined const { result, rerender } = await renderHook(() => useTransactionCount({ address }), ) { const { data, ...rest } = result.current expect(data).toBeTypeOf('undefined') expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "transactionCount", { "address": undefined, "chainId": 1, }, ], "refetch": [Function], "status": "pending", } `) } address = accounts[0] rerender() await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result.current expect(data).toBeTypeOf('number') expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "transactionCount", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: disabled when properties missing', async () => { const { result } = await renderHook(() => useTransactionCount()) await wait(100) await vi.waitFor(() => expect(result.current.isPending).toBeTruthy()) }) ================================================ FILE: packages/react/src/hooks/useTransactionCount.ts ================================================ 'use client' import type { Config, GetTransactionCountErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetTransactionCountData, type GetTransactionCountOptions, getTransactionCountQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseTransactionCountParameters< config extends Config = Config, selectData = GetTransactionCountData, > = Compute< GetTransactionCountOptions & ConfigParameter > export type UseTransactionCountReturnType< selectData = GetTransactionCountData, > = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useTransactionCount */ export function useTransactionCount< config extends Config = ResolvedRegister['config'], selectData = GetTransactionCountData, >( parameters: UseTransactionCountParameters = {}, ): UseTransactionCountReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getTransactionCountQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useTransactionReceipt.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useTransactionReceipt } from './useTransactionReceipt.js' test('select data', () => { const result = useTransactionReceipt({ query: { select(data) { return data?.blockNumber }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useTransactionReceipt.test.ts ================================================ import { chain, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import type { Hash } from 'viem' import { expect, test, vi } from 'vitest' import { useTransactionReceipt } from './useTransactionReceipt.js' test('default', async () => { const { result } = await renderHook(() => useTransactionReceipt({ hash: '0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": { "blockHash": "0xb932f77cf770d1d1c8f861153eec1e990f5d56b6ffdb4ac06aef3cca51ef37d4", "blockNumber": 16280769n, "contractAddress": null, "cumulativeGasUsed": 21000n, "effectiveGasPrice": 33427926161n, "from": "0x043022ef9fca1066024d19d681e2ccf44ff90de3", "gasUsed": 21000n, "logs": [], "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "status": "success", "to": "0x318a5fb4f1604fc46375a1db9a9018b6e423b345", "transactionHash": "0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871", "transactionIndex": 0, "type": "legacy", }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getTransactionReceipt", { "chainId": 1, "hash": "0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871", }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: chainId', async () => { const { result } = await renderHook(() => useTransactionReceipt({ chainId: chain.mainnet2.id, hash: '0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": { "blockHash": "0xb932f77cf770d1d1c8f861153eec1e990f5d56b6ffdb4ac06aef3cca51ef37d4", "blockNumber": 16280769n, "contractAddress": null, "cumulativeGasUsed": 21000n, "effectiveGasPrice": 33427926161n, "from": "0x043022ef9fca1066024d19d681e2ccf44ff90de3", "gasUsed": 21000n, "logs": [], "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "status": "success", "to": "0x318a5fb4f1604fc46375a1db9a9018b6e423b345", "transactionHash": "0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871", "transactionIndex": 0, "type": "legacy", }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getTransactionReceipt", { "chainId": 456, "hash": "0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871", }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: hash: undefined -> defined', async () => { const { result, rerender } = await renderHook( (props) => useTransactionReceipt({ hash: props?.hash, }), { initialProps: { hash: undefined as Hash | undefined } }, ) expect(result.current).toMatchInlineSnapshot(` { "data": undefined, "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "getTransactionReceipt", { "chainId": 1, "hash": undefined, }, ], "refetch": [Function], "status": "pending", } `) rerender({ hash: '0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871', }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": { "blockHash": "0xb932f77cf770d1d1c8f861153eec1e990f5d56b6ffdb4ac06aef3cca51ef37d4", "blockNumber": 16280769n, "contractAddress": null, "cumulativeGasUsed": 21000n, "effectiveGasPrice": 33427926161n, "from": "0x043022ef9fca1066024d19d681e2ccf44ff90de3", "gasUsed": 21000n, "logs": [], "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "status": "success", "to": "0x318a5fb4f1604fc46375a1db9a9018b6e423b345", "transactionHash": "0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871", "transactionIndex": 0, "type": "legacy", }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getTransactionReceipt", { "chainId": 1, "hash": "0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871", }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: disabled when properties missing', async () => { const { result } = await renderHook(() => useTransactionReceipt()) await wait(100) await vi.waitFor(() => expect(result.current.isPending).toBeTruthy()) }) ================================================ FILE: packages/react/src/hooks/useTransactionReceipt.ts ================================================ 'use client' import type { Config, GetTransactionReceiptErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetTransactionReceiptData, type GetTransactionReceiptOptions, getTransactionReceiptQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseTransactionReceiptParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetTransactionReceiptData, > = Compute< GetTransactionReceiptOptions & ConfigParameter > export type UseTransactionReceiptReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetTransactionReceiptData, > = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useTransactionReceipt */ export function useTransactionReceipt< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetTransactionReceiptData, >( parameters: UseTransactionReceiptParameters = {}, ): UseTransactionReceiptReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = getTransactionReceiptQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) as any } ================================================ FILE: packages/react/src/hooks/useVerifyMessage.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useVerifyMessage } from './useVerifyMessage.js' test('select data', () => { const result = useVerifyMessage({ query: { select(data) { return data }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useVerifyMessage.test.ts ================================================ import { chain, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import type { Hex } from 'viem' import { expect, test, vi } from 'vitest' import { useVerifyMessage } from './useVerifyMessage.js' const address = '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266' test('default', async () => { const { result } = await renderHook(() => useVerifyMessage({ address, message: 'This is a test message for viem!', signature: '0xc4c7f2820177020d66d5fd00d084cdd3f575a868c059c29a2d7f23398d04819709a14f83d98b446dda539ca5dcb87d75aa3340eb15e66d67606850622a3420f61b', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": true, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "verifyMessage", { "address": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", "chainId": 1, "message": "This is a test message for viem!", "signature": "0xc4c7f2820177020d66d5fd00d084cdd3f575a868c059c29a2d7f23398d04819709a14f83d98b446dda539ca5dcb87d75aa3340eb15e66d67606850622a3420f61b", }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: chainId', async () => { const { result } = await renderHook(() => useVerifyMessage({ chainId: chain.mainnet2.id, address, message: 'This is a test message for viem!', signature: '0xc4c7f2820177020d66d5fd00d084cdd3f575a868c059c29a2d7f23398d04819709a14f83d98b446dda539ca5dcb87d75aa3340eb15e66d67606850622a3420f61b', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": true, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "verifyMessage", { "address": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", "chainId": 456, "message": "This is a test message for viem!", "signature": "0xc4c7f2820177020d66d5fd00d084cdd3f575a868c059c29a2d7f23398d04819709a14f83d98b446dda539ca5dcb87d75aa3340eb15e66d67606850622a3420f61b", }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: blockNumber', async () => { const { result } = await renderHook(() => useVerifyMessage({ blockNumber: 12345678n, address, message: 'This is a test message for viem!', signature: '0xc4c7f2820177020d66d5fd00d084cdd3f575a868c059c29a2d7f23398d04819709a14f83d98b446dda539ca5dcb87d75aa3340eb15e66d67606850622a3420f61b', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": true, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "verifyMessage", { "address": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", "blockNumber": 12345678n, "chainId": 1, "message": "This is a test message for viem!", "signature": "0xc4c7f2820177020d66d5fd00d084cdd3f575a868c059c29a2d7f23398d04819709a14f83d98b446dda539ca5dcb87d75aa3340eb15e66d67606850622a3420f61b", }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: blockTag', async () => { const { result } = await renderHook(() => useVerifyMessage({ blockTag: 'pending', address, message: 'This is a test message for viem!', signature: '0xc4c7f2820177020d66d5fd00d084cdd3f575a868c059c29a2d7f23398d04819709a14f83d98b446dda539ca5dcb87d75aa3340eb15e66d67606850622a3420f61b', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": true, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "verifyMessage", { "address": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", "blockTag": "pending", "chainId": 1, "message": "This is a test message for viem!", "signature": "0xc4c7f2820177020d66d5fd00d084cdd3f575a868c059c29a2d7f23398d04819709a14f83d98b446dda539ca5dcb87d75aa3340eb15e66d67606850622a3420f61b", }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: signature: undefined -> defined', async () => { const { result, rerender } = await renderHook( (props) => useVerifyMessage({ address, message: 'This is a test message for viem!', signature: props?.signature, }), { initialProps: { signature: undefined as Hex | undefined } }, ) expect(result.current).toMatchInlineSnapshot(` { "data": undefined, "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "verifyMessage", { "address": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", "chainId": 1, "message": "This is a test message for viem!", "signature": undefined, }, ], "refetch": [Function], "status": "pending", } `) rerender({ signature: '0xc4c7f2820177020d66d5fd00d084cdd3f575a868c059c29a2d7f23398d04819709a14f83d98b446dda539ca5dcb87d75aa3340eb15e66d67606850622a3420f61b', }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": true, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "verifyMessage", { "address": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266", "chainId": 1, "message": "This is a test message for viem!", "signature": "0xc4c7f2820177020d66d5fd00d084cdd3f575a868c059c29a2d7f23398d04819709a14f83d98b446dda539ca5dcb87d75aa3340eb15e66d67606850622a3420f61b", }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: disabled when properties missing', async () => { const { result } = await renderHook(() => useVerifyMessage()) await wait(100) await vi.waitFor(() => expect(result.current.isPending).toBeTruthy()) }) ================================================ FILE: packages/react/src/hooks/useVerifyMessage.ts ================================================ 'use client' import type { Config, ResolvedRegister, VerifyMessageErrorType, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type VerifyMessageData, type VerifyMessageOptions, verifyMessageQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseVerifyMessageParameters< config extends Config = Config, selectData = VerifyMessageData, > = Compute & ConfigParameter> export type UseVerifyMessageReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useVerifyMessage */ export function useVerifyMessage< config extends Config = ResolvedRegister['config'], selectData = VerifyMessageData, >( parameters: UseVerifyMessageParameters = {}, ): UseVerifyMessageReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = verifyMessageQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useVerifyTypedData.test-d.ts ================================================ import { typedData } from '@wagmi/test' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' import { type UseVerifyTypedDataParameters, useVerifyTypedData, } from './useVerifyTypedData.js' test('select data', () => { const result = useVerifyTypedData({ query: { select(data) { return data }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) test('UseReadContractParameters', () => { type Result = UseVerifyTypedDataParameters< typeof typedData.basic.types, 'Mail' > expectTypeOf>().toEqualTypeOf<{ primaryType?: 'Mail' | 'Person' message?: { from: { name: string wallet: Address } to: { name: string wallet: Address } contents: string } }>() }) test('primaryType', async () => { useVerifyTypedData({ address: '0x', ...typedData.basic, primaryType: 'Mail', signature: '0x', }) useVerifyTypedData({ address: '0x', ...typedData.basic, // @ts-expect-error primaryType: 'foobarbaz', signature: '0x', }) }) ================================================ FILE: packages/react/src/hooks/useVerifyTypedData.test.ts ================================================ import { typedData, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import type { Hex } from 'viem' import { expect, test, vi } from 'vitest' import { useVerifyTypedData } from './useVerifyTypedData.js' const smartAccountAddress = '0x3FCf42e10CC70Fe75A62EB3aDD6D305Aa840d145' const notDeployedAddress = '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef' test('valid signature', async () => { const { result } = await renderHook(() => useVerifyTypedData({ ...typedData.basic, primaryType: 'Mail', address: smartAccountAddress, signature: '0x79d756d805073dc97b7bc885b0d56ddf319a2599530fe1e178c2a7de5be88980068d24f20a79b318ea0a84d33ae06f93db77e4235e5d9eeb8b1d7a63922ada3e1c', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": true, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "verifyTypedData", { "address": "0x3FCf42e10CC70Fe75A62EB3aDD6D305Aa840d145", "chainId": 1, "domain": { "chainId": 1, "name": "Ether Mail", "verifyingContract": "0x0000000000000000000000000000000000000000", "version": "1", }, "message": { "contents": "Hello, Bob!", "from": { "name": "Cow", "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", }, "to": { "name": "Bob", "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", }, }, "primaryType": "Mail", "signature": "0x79d756d805073dc97b7bc885b0d56ddf319a2599530fe1e178c2a7de5be88980068d24f20a79b318ea0a84d33ae06f93db77e4235e5d9eeb8b1d7a63922ada3e1c", "types": { "Mail": [ { "name": "from", "type": "Person", }, { "name": "to", "type": "Person", }, { "name": "contents", "type": "string", }, ], "Person": [ { "name": "name", "type": "string", }, { "name": "wallet", "type": "address", }, ], }, }, ], "refetch": [Function], "status": "success", } `) }) test('invalid signature', async () => { const { result } = await renderHook(() => useVerifyTypedData({ ...typedData.basic, primaryType: 'Mail', address: smartAccountAddress, signature: '0xdead', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": false, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "verifyTypedData", { "address": "0x3FCf42e10CC70Fe75A62EB3aDD6D305Aa840d145", "chainId": 1, "domain": { "chainId": 1, "name": "Ether Mail", "verifyingContract": "0x0000000000000000000000000000000000000000", "version": "1", }, "message": { "contents": "Hello, Bob!", "from": { "name": "Cow", "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", }, "to": { "name": "Bob", "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", }, }, "primaryType": "Mail", "signature": "0xdead", "types": { "Mail": [ { "name": "from", "type": "Person", }, { "name": "to", "type": "Person", }, { "name": "contents", "type": "string", }, ], "Person": [ { "name": "name", "type": "string", }, { "name": "wallet", "type": "address", }, ], }, }, ], "refetch": [Function], "status": "success", } `) }) test('account not deployed', async () => { const { result } = await renderHook(() => useVerifyTypedData({ ...typedData.basic, primaryType: 'Mail', address: notDeployedAddress, signature: '0x79d756d805073dc97b7bc885b0d56ddf319a2599530fe1e178c2a7de5be88980068d24f20a79b318ea0a84d33ae06f93db77e4235e5d9eeb8b1d7a63922ada3e1c', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": false, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "verifyTypedData", { "address": "0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef", "chainId": 1, "domain": { "chainId": 1, "name": "Ether Mail", "verifyingContract": "0x0000000000000000000000000000000000000000", "version": "1", }, "message": { "contents": "Hello, Bob!", "from": { "name": "Cow", "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", }, "to": { "name": "Bob", "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", }, }, "primaryType": "Mail", "signature": "0x79d756d805073dc97b7bc885b0d56ddf319a2599530fe1e178c2a7de5be88980068d24f20a79b318ea0a84d33ae06f93db77e4235e5d9eeb8b1d7a63922ada3e1c", "types": { "Mail": [ { "name": "from", "type": "Person", }, { "name": "to", "type": "Person", }, { "name": "contents", "type": "string", }, ], "Person": [ { "name": "name", "type": "string", }, { "name": "wallet", "type": "address", }, ], }, }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: signature: undefined -> defined', async () => { const { result, rerender } = await renderHook( (props) => useVerifyTypedData({ ...typedData.basic, primaryType: 'Mail', address: smartAccountAddress, signature: props?.signature, }), { initialProps: { signature: undefined as Hex | undefined } }, ) expect(result.current).toMatchInlineSnapshot(` { "data": undefined, "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "verifyTypedData", { "address": "0x3FCf42e10CC70Fe75A62EB3aDD6D305Aa840d145", "chainId": 1, "domain": { "chainId": 1, "name": "Ether Mail", "verifyingContract": "0x0000000000000000000000000000000000000000", "version": "1", }, "message": { "contents": "Hello, Bob!", "from": { "name": "Cow", "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", }, "to": { "name": "Bob", "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", }, }, "primaryType": "Mail", "signature": undefined, "types": { "Mail": [ { "name": "from", "type": "Person", }, { "name": "to", "type": "Person", }, { "name": "contents", "type": "string", }, ], "Person": [ { "name": "name", "type": "string", }, { "name": "wallet", "type": "address", }, ], }, }, ], "refetch": [Function], "status": "pending", } `) rerender({ signature: '0x79d756d805073dc97b7bc885b0d56ddf319a2599530fe1e178c2a7de5be88980068d24f20a79b318ea0a84d33ae06f93db77e4235e5d9eeb8b1d7a63922ada3e1c', }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current).toMatchInlineSnapshot(` { "data": true, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "verifyTypedData", { "address": "0x3FCf42e10CC70Fe75A62EB3aDD6D305Aa840d145", "chainId": 1, "domain": { "chainId": 1, "name": "Ether Mail", "verifyingContract": "0x0000000000000000000000000000000000000000", "version": "1", }, "message": { "contents": "Hello, Bob!", "from": { "name": "Cow", "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", }, "to": { "name": "Bob", "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", }, }, "primaryType": "Mail", "signature": "0x79d756d805073dc97b7bc885b0d56ddf319a2599530fe1e178c2a7de5be88980068d24f20a79b318ea0a84d33ae06f93db77e4235e5d9eeb8b1d7a63922ada3e1c", "types": { "Mail": [ { "name": "from", "type": "Person", }, { "name": "to", "type": "Person", }, { "name": "contents", "type": "string", }, ], "Person": [ { "name": "name", "type": "string", }, { "name": "wallet", "type": "address", }, ], }, }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: disabled when properties missing', async () => { const { result } = await renderHook(() => useVerifyTypedData()) await wait(100) await vi.waitFor(() => expect(result.current.isPending).toBeTruthy()) }) ================================================ FILE: packages/react/src/hooks/useVerifyTypedData.ts ================================================ 'use client' import type { Config, ResolvedRegister, VerifyTypedDataErrorType, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { type VerifyTypedDataData, type VerifyTypedDataOptions, verifyTypedDataQueryOptions, } from '@wagmi/core/query' import type { TypedData } from 'viem' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseVerifyTypedDataParameters< typedData extends TypedData | Record = TypedData, primaryType extends keyof typedData | 'EIP712Domain' = keyof typedData, config extends Config = Config, selectData = VerifyTypedDataData, > = VerifyTypedDataOptions & ConfigParameter export type UseVerifyTypedDataReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useVerifyTypedData */ export function useVerifyTypedData< const typedData extends TypedData | Record, primaryType extends keyof typedData | 'EIP712Domain', config extends Config = ResolvedRegister['config'], selectData = VerifyTypedDataData, >( parameters: UseVerifyTypedDataParameters< typedData, primaryType, config, selectData > = {} as any, ): UseVerifyTypedDataReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = verifyTypedDataQueryOptions(config, { ...(parameters as any), chainId: parameters.chainId ?? chainId, }) return useQuery(options) as any } ================================================ FILE: packages/react/src/hooks/useWaitForCallsStatus.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { accounts, config, testClient, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { parseEther } from 'viem' import { expect, test, vi } from 'vitest' import { useSendCalls } from './useSendCalls.js' import { useWaitForCallsStatus } from './useWaitForCallsStatus.js' const connector = config.connectors[0]! test('default', async () => { await disconnect(config, { connector }).catch(() => {}) await connect(config, { connector }) const useSendCalls_render = await renderHook(() => useSendCalls()) const useWaitForCallsStatus_render = await renderHook(() => useWaitForCallsStatus({ id: useSendCalls_render.result.current.data?.id }), ) useSendCalls_render.result.current.mutate({ calls: [ { data: '0xdeadbeef', to: accounts[1], value: parseEther('1'), }, { to: accounts[2], value: parseEther('2'), }, { to: accounts[3], value: parseEther('3'), }, ], }) await vi.waitUntil(() => useSendCalls_render.result.current.isSuccess, { timeout: 10_000, }) expect(useWaitForCallsStatus_render.result.current.fetchStatus).toBe('idle') useWaitForCallsStatus_render.rerender() expect(useWaitForCallsStatus_render.result.current.fetchStatus).toBe( 'fetching', ) await wait(1_000) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitUntil( () => useWaitForCallsStatus_render.result.current.isSuccess, { timeout: 10_000 }, ) expect(useWaitForCallsStatus_render.result.current.data?.status).toBe( 'success', ) expect( useWaitForCallsStatus_render.result.current.data?.receipts?.map((x) => ({ ...x, blockHash: undefined, transactionHash: undefined, })), ).toMatchInlineSnapshot( ` [ { "blockHash": undefined, "blockNumber": 23535881n, "gasUsed": 21160n, "logs": [], "status": "success", "transactionHash": undefined, }, { "blockHash": undefined, "blockNumber": 23535881n, "gasUsed": 21000n, "logs": [], "status": "success", "transactionHash": undefined, }, { "blockHash": undefined, "blockNumber": 23535881n, "gasUsed": 21000n, "logs": [], "status": "success", "transactionHash": undefined, }, ] `, ) await testClient.mainnet.mine({ blocks: 1 }) await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/useWaitForCallsStatus.ts ================================================ 'use client' import type { Config, ResolvedRegister, WaitForCallsStatusErrorType, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type WaitForCallsStatusData, type WaitForCallsStatusOptions, waitForCallsStatusQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useConfig } from './useConfig.js' import { useConnection } from './useConnection.js' export type UseWaitForCallsStatusParameters< config extends Config = Config, selectData = WaitForCallsStatusData, > = Compute & ConfigParameter> export type UseWaitForCallsStatusReturnType< selectData = WaitForCallsStatusData, > = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useWaitForCallsStatus */ export function useWaitForCallsStatus< config extends Config = ResolvedRegister['config'], selectData = WaitForCallsStatusData, >( parameters: UseWaitForCallsStatusParameters, ): UseWaitForCallsStatusReturnType { const config = useConfig(parameters) const { connector } = useConnection({ config }) const options = waitForCallsStatusQueryOptions(config, { ...parameters, connector: parameters.connector ?? connector, }) return useQuery(options) } ================================================ FILE: packages/react/src/hooks/useWaitForTransactionReceipt.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useWaitForTransactionReceipt } from './useWaitForTransactionReceipt.js' test('select data', () => { const result = useWaitForTransactionReceipt({ query: { select(data) { return data?.blockNumber }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/react/src/hooks/useWaitForTransactionReceipt.test.ts ================================================ import { wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useWaitForTransactionReceipt } from './useWaitForTransactionReceipt.js' test('default', async () => { const { result } = await renderHook(() => useWaitForTransactionReceipt({ hash: '0x60668ed8c2dc110d61d945a936fcd45b8f13654e5c78481c8c825d1148c7ef30', }), ) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result).toMatchInlineSnapshot(` { "current": { "data": { "blockHash": "0xd725a38b51e5ceec8c5f6c9ccfdb2cc423af993bb650af5eedca5e4be7156ba7", "blockNumber": 15189204n, "chainId": 1, "contractAddress": null, "cumulativeGasUsed": 12949744n, "effectiveGasPrice": 9371645552n, "from": "0xa0cf798816d4b9b9866b5330eea46a18382f251e", "gasUsed": 21000n, "logs": [], "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "status": "success", "to": "0xd2135cfb216b74109775236e36d4b433f1df507b", "transactionHash": "0x60668ed8c2dc110d61d945a936fcd45b8f13654e5c78481c8c825d1148c7ef30", "transactionIndex": 144, "type": "eip1559", }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "waitForTransactionReceipt", { "chainId": 1, "hash": "0x60668ed8c2dc110d61d945a936fcd45b8f13654e5c78481c8c825d1148c7ef30", }, ], "refetch": [Function], "status": "success", }, } `) }) test('disabled when hash is undefined', async () => { const { result } = await renderHook(() => useWaitForTransactionReceipt({ hash: undefined }), ) await wait(100) await vi.waitFor(() => expect(result.current.isPending).toBeTruthy()) }) ================================================ FILE: packages/react/src/hooks/useWaitForTransactionReceipt.ts ================================================ 'use client' import type { Config, ResolvedRegister, WaitForTransactionReceiptErrorType, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type WaitForTransactionReceiptData, type WaitForTransactionReceiptOptions, waitForTransactionReceiptQueryOptions, } from '@wagmi/core/query' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseWaitForTransactionReceiptParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = WaitForTransactionReceiptData, > = Compute< WaitForTransactionReceiptOptions & ConfigParameter > export type UseWaitForTransactionReceiptReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = WaitForTransactionReceiptData, > = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useWaitForTransactionReceipt */ export function useWaitForTransactionReceipt< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = WaitForTransactionReceiptData, >( parameters: UseWaitForTransactionReceiptParameters< config, chainId, selectData > = {}, ): UseWaitForTransactionReceiptReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = waitForTransactionReceiptQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, }) return useQuery(options) as any } ================================================ FILE: packages/react/src/hooks/useWalletClient.test-d.ts ================================================ import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useWalletClient } from './useWalletClient.js' test('parameters: config', async () => { const client = useWalletClient({ config }) expectTypeOf(client.data?.chain?.id!).toEqualTypeOf<1 | 456 | 10>() const client2 = useWalletClient({ config, chainId: 1 }) expectTypeOf(client2.data?.chain?.id!).toEqualTypeOf<1>() }) ================================================ FILE: packages/react/src/hooks/useWalletClient.test.tsx ================================================ import { connect, disconnect } from '@wagmi/core' import { config } from '@wagmi/test' import { render, renderHook } from '@wagmi/test/react' import * as React from 'react' import { expect, test, vi } from 'vitest' import { useConnect } from './useConnect.js' import { useConnection } from './useConnection.js' import { useConnectors } from './useConnectors.js' import { useDisconnect } from './useDisconnect.js' import { useSwitchChain } from './useSwitchChain.js' import { useWalletClient } from './useWalletClient.js' // Almost identical implementation to `useConnectorClient` (except for return type) // Should update both in tandem const connector = config.connectors[0]! test('default', async () => { const { result } = await renderHook(() => useWalletClient()) await vi.waitFor(() => expect(result.current.isPending).toBeTruthy()) expect(result.current).toMatchInlineSnapshot(` { "data": undefined, "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "walletClient", { "chainId": 1, }, ], "refetch": [Function], "status": "pending", } `) }) test('behavior: connected on mount', async () => { await connect(config, { connector }) const { result } = await renderHook(() => useWalletClient()) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) const { data, queryKey: _, ...rest } = result.current expect(data).toMatchObject( expect.objectContaining({ account: expect.any(Object), chain: expect.any(Object), }), ) expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": true, "refetch": [Function], "status": "success", } `) await disconnect(config, { connector }) }) test('behavior: connect and disconnect', async () => { const { result } = await renderHook(() => ({ useConnect: useConnect(), useConnectors: useConnectors(), useWalletClient: useWalletClient(), useDisconnect: useDisconnect(), })) expect(result.current.useWalletClient.data).not.toBeDefined() result.current.useConnect.connect({ connector: result.current.useConnectors[0]!, }) await vi.waitFor(() => expect(result.current.useWalletClient.data).toBeDefined(), ) result.current.useDisconnect.disconnect() await vi.waitFor(() => expect(result.current.useWalletClient.data).not.toBeDefined(), ) }) test('behavior: switch chains', async () => { await connect(config, { connector }) const { act, result } = await renderHook(() => ({ useWalletClient: useWalletClient(), useSwitchChain: useSwitchChain(), })) expect(result.current.useWalletClient.data).not.toBeDefined() await vi.waitFor(() => expect(result.current.useWalletClient.data).toBeDefined(), ) await act(() => result.current.useSwitchChain.switchChain({ chainId: 456 })) await vi.waitUntil(() => result.current.useSwitchChain.isSuccess, { timeout: 10_000, }) await act(() => result.current.useSwitchChain.reset()) await vi.waitUntil(() => result.current.useWalletClient.isSuccess, { timeout: 10_000, }) expect(result.current.useWalletClient.data?.chain.id).toEqual(456) await act(() => result.current.useSwitchChain.switchChain({ chainId: 1 })) await vi.waitUntil(() => result.current.useSwitchChain.isSuccess, { timeout: 10_000, }) await vi.waitUntil(() => result.current.useWalletClient.isSuccess, { timeout: 10_000, }) expect(result.current.useWalletClient.data?.chain.id).toEqual(1) await disconnect(config, { connector }) }) test('behavior: re-render does not invalidate query', async () => { await disconnect(config, { connector }) const screen = await render() await screen.getByTestId('connect').click() await vi.waitFor(async () => { await expect .element(screen.getByTestId('address')) .toHaveTextContent('0x95132632579b073D12a6673e18Ab05777a6B86f8') await expect.element(screen.getByTestId('client')).toBeVisible() await expect.element(screen.getByTestId('child-client')).toBeVisible() await expect .element(screen.getByTestId('render-count')) .toHaveTextContent('1') }) const initialClient = screen.getByTestId('child-client') await screen.getByTestId('rerender').click() await vi.waitFor(() => expect.element(screen.getByTestId('render-count')).toHaveTextContent('2'), ) await expect .element(screen.getByTestId('child-client').element()) .toEqual(initialClient.element()) }) function Parent() { const [renderCount, setRenderCount] = React.useState(1) const { connect } = useConnect() const connectors = useConnectors() const { address } = useConnection() const { data } = useWalletClient() return ( <>
{address}
{data?.uid}
) } function Child(props: { renderCount: number }) { const { renderCount } = props const { data } = useWalletClient() return (
{data?.uid} {renderCount}
) } ================================================ FILE: packages/react/src/hooks/useWalletClient.ts ================================================ 'use client' // Almost identical implementation to `useConnectorClient` (except for return type) // Should update both in tandem import { useQueryClient } from '@tanstack/react-query' import type { Config, GetWalletClientErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetWalletClientData, type GetWalletClientOptions, getWalletClientQueryOptions, } from '@wagmi/core/query' import { useEffect, useRef } from 'react' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' import { useConnection } from './useConnection.js' export type UseWalletClientParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetWalletClientData, > = Compute< GetWalletClientOptions & ConfigParameter > export type UseWalletClientReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetWalletClientData, > = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useWalletClient */ export function useWalletClient< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetWalletClientData, >( parameters: UseWalletClientParameters = {}, ): UseWalletClientReturnType { const config = useConfig(parameters) const chainId = useChainId({ config }) const { address, connector } = useConnection({ config }) const options = getWalletClientQueryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, connector: parameters.connector ?? connector, query: parameters.query as any, }) const addressRef = useRef(address) const queryClient = useQueryClient() // biome-ignore lint/correctness/useExhaustiveDependencies: `queryKey` not required useEffect(() => { const previousAddress = addressRef.current if (!address && previousAddress) { // remove when account is disconnected queryClient.removeQueries({ queryKey: options.queryKey }) addressRef.current = undefined } else if (address !== previousAddress) { // invalidate when address changes queryClient.invalidateQueries({ queryKey: options.queryKey }) addressRef.current = address } }, [address, queryClient]) return useQuery(options) as any } ================================================ FILE: packages/react/src/hooks/useWatchAsset.test-d.ts ================================================ import type { WatchAssetErrorType } from '@wagmi/core' import type { WatchAssetVariables } from '@wagmi/core/query' import { expectTypeOf, test } from 'vitest' import { useWatchAsset } from './useWatchAsset.js' const tokenInfo = { address: '0x0000000000000000000000000000000000000000', symbol: 'NULL', decimals: 18, } const contextValue = { foo: 'bar' } as const test('context', () => { const watchAsset = useWatchAsset({ mutation: { onMutate(variables) { expectTypeOf(variables).toEqualTypeOf() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf() expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(watchAsset.data).toEqualTypeOf() expectTypeOf(watchAsset.error).toEqualTypeOf() expectTypeOf(watchAsset.variables).toEqualTypeOf< WatchAssetVariables | undefined >() expectTypeOf(watchAsset.context).toEqualTypeOf< typeof contextValue | undefined >() watchAsset.mutate( { type: 'ERC20', options: tokenInfo }, { onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf() expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/react/src/hooks/useWatchAsset.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useWatchAsset } from './useWatchAsset.js' const connector = config.connectors[0]! const tokenInfo = { address: '0x0000000000000000000000000000000000000000', symbol: 'NULL', decimals: 18, } test('default', async () => { await connect(config, { connector }) const { result } = await renderHook(() => useWatchAsset()) result.current.mutate({ type: 'ERC20', options: tokenInfo }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current.data).toEqual(true) await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/useWatchAsset.ts ================================================ 'use client' import { useMutation } from '@tanstack/react-query' import type { WatchAssetErrorType } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type WatchAssetData, type WatchAssetMutate, type WatchAssetMutateAsync, type WatchAssetOptions, type WatchAssetVariables, watchAssetMutationOptions, } from '@wagmi/core/query' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseWatchAssetParameters = Compute< ConfigParameter & WatchAssetOptions > export type UseWatchAssetReturnType = Compute< UseMutationReturnType< WatchAssetData, WatchAssetErrorType, WatchAssetVariables, context, WatchAssetMutate, WatchAssetMutateAsync > & { /** @deprecated use `mutate` instead */ watchAsset: WatchAssetMutate /** @deprecated use `mutateAsync` instead */ watchAssetAsync: WatchAssetMutateAsync } > /** https://wagmi.sh/react/api/hooks/useWatchAsset */ export function useWatchAsset( parameters: UseWatchAssetParameters = {}, ): UseWatchAssetReturnType { const config = useConfig(parameters) const options = watchAssetMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseWatchAssetReturnType return { ...(mutation as Return), watchAsset: mutation.mutate as Return['mutate'], watchAssetAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/react/src/hooks/useWatchBlockNumber.test-d.ts ================================================ import { createConfig } from '@wagmi/core' import { http, webSocket } from 'viem' import { mainnet, optimism } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { type UseWatchBlockNumberParameters, useWatchBlockNumber, } from './useWatchBlockNumber.js' test('default', () => { useWatchBlockNumber({ poll: false, onBlockNumber() {}, }) }) test('differing transports', () => { const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: webSocket(), }, }) type Result = UseWatchBlockNumberParameters< typeof config, typeof mainnet.id | typeof optimism.id > expectTypeOf().toEqualTypeOf() useWatchBlockNumber({ config, poll: false, onBlockNumber() {}, }) type Result2 = UseWatchBlockNumberParameters expectTypeOf().toEqualTypeOf() useWatchBlockNumber({ config, chainId: mainnet.id, poll: true, onBlockNumber() {}, }) useWatchBlockNumber({ config, chainId: mainnet.id, // @ts-expect-error poll: false, onBlockNumber() {}, }) type Result3 = UseWatchBlockNumberParameters< typeof config, typeof optimism.id > expectTypeOf().toEqualTypeOf() useWatchBlockNumber({ config, chainId: optimism.id, poll: true, onBlockNumber() {}, }) useWatchBlockNumber({ config, chainId: optimism.id, poll: false, onBlockNumber() {}, }) }) ================================================ FILE: packages/react/src/hooks/useWatchBlockNumber.test.ts ================================================ import { testClient, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useWatchBlockNumber } from './useWatchBlockNumber.js' test('default', async () => { const blockNumbers: bigint[] = [] renderHook(() => useWatchBlockNumber({ onBlockNumber(blockNumber) { blockNumbers.push(blockNumber) }, }), ) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitUntil(() => blockNumbers.length === 3, { timeout: 10_000 }) expect(blockNumbers.length).toBe(3) }) test('behavior: does not resubscribe when onBlockNumber changes', async () => { const blockNumbers: bigint[] = [] let callbackCallCount = 0 const { rerender } = await renderHook( (props) => useWatchBlockNumber({ onBlockNumber: props?.callback, }), { initialProps: { callback: (blockNumber: bigint) => { callbackCallCount++ blockNumbers.push(blockNumber) }, }, }, ) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitUntil(() => blockNumbers.length >= 1, { timeout: 10_000 }) // Rerender with new callback references multiple times rerender({ callback: (blockNumber: bigint) => { callbackCallCount++ blockNumbers.push(blockNumber) }, }) rerender({ callback: (blockNumber: bigint) => { callbackCallCount++ blockNumbers.push(blockNumber) }, }) rerender({ callback: (blockNumber: bigint) => { callbackCallCount++ blockNumbers.push(blockNumber) }, }) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitUntil(() => blockNumbers.length >= 2, { timeout: 10_000 }) rerender({ callback: (blockNumber: bigint) => { callbackCallCount++ blockNumbers.push(blockNumber) }, }) // If resubscribing happened, we'd see duplicate block numbers or // emitOnBegin behavior. We should only have 2 blocks total. expect(blockNumbers.length).toBe(2) expect(callbackCallCount).toBe(2) }) test('behavior: uses latest callback after rerender', async () => { const blockNumbers1: bigint[] = [] const blockNumbers2: bigint[] = [] const { rerender } = await renderHook( (props) => useWatchBlockNumber({ onBlockNumber: props?.callback, }), { initialProps: { callback: (blockNumber: bigint) => blockNumbers1.push(blockNumber), }, }, ) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitUntil(() => blockNumbers1.length >= 1, { timeout: 10_000 }) rerender({ callback: (blockNumber) => blockNumbers2.push(blockNumber), }) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitUntil(() => blockNumbers2.length >= 1, { timeout: 10_000 }) expect(blockNumbers1.length).toBe(1) expect(blockNumbers2.length).toBeGreaterThanOrEqual(1) }) ================================================ FILE: packages/react/src/hooks/useWatchBlockNumber.ts ================================================ 'use client' import { type Config, type ResolvedRegister, type WatchBlockNumberParameters, watchBlockNumber, } from '@wagmi/core' import type { ConfigParameter, EnabledParameter, UnionCompute, UnionExactPartial, } from '@wagmi/core/internal' import { useEffect, useRef } from 'react' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseWatchBlockNumberParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = UnionCompute< UnionExactPartial> & ConfigParameter & EnabledParameter > export type UseWatchBlockNumberReturnType = void /** https://wagmi.sh/react/api/hooks/useWatchBlockNumber */ export function useWatchBlockNumber< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], >( parameters: UseWatchBlockNumberParameters = {} as any, ): UseWatchBlockNumberReturnType { const { enabled = true, onBlockNumber, config: _, ...rest } = parameters const config = useConfig(parameters) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId const onBlockNumberRef = useRef(onBlockNumber) const onErrorRef = useRef(rest.onError) onBlockNumberRef.current = onBlockNumber onErrorRef.current = rest.onError // TODO(react@19): cleanup // biome-ignore lint/correctness/useExhaustiveDependencies: `rest` changes every render so only including properties in dependency array useEffect(() => { if (!enabled) return if (!onBlockNumberRef.current) return return watchBlockNumber(config, { ...(rest as any), chainId, onBlockNumber: (blockNumber, prevBlockNumber) => onBlockNumberRef.current?.(blockNumber, prevBlockNumber), onError: (error) => onErrorRef.current?.(error), }) }, [ chainId, config, enabled, /// rest.emitMissed, rest.emitOnBegin, rest.poll, rest.pollingInterval, rest.syncConnectedChain, ]) } ================================================ FILE: packages/react/src/hooks/useWatchBlocks.test-d.ts ================================================ import { createConfig } from '@wagmi/core' import { http, webSocket } from 'viem' import { mainnet, optimism } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { type UseWatchBlocksParameters, useWatchBlocks, } from './useWatchBlocks.js' test('default', () => { useWatchBlocks({ poll: false, onBlock() {}, }) }) test('differing transports', () => { const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: webSocket(), }, }) type Result = UseWatchBlocksParameters< false, 'latest', typeof config, typeof mainnet.id | typeof optimism.id > expectTypeOf().toEqualTypeOf() useWatchBlocks({ config, poll: false, onBlock() {}, }) type Result2 = UseWatchBlocksParameters< false, 'latest', typeof config, typeof mainnet.id > expectTypeOf().toEqualTypeOf() useWatchBlocks({ config, chainId: mainnet.id, poll: true, onBlock() {}, }) type Result3 = UseWatchBlocksParameters< false, 'latest', typeof config, typeof optimism.id > expectTypeOf().toEqualTypeOf() useWatchBlocks({ config, chainId: optimism.id, poll: true, onBlock() {}, }) useWatchBlocks({ config, chainId: optimism.id, poll: false, onBlock() {}, }) }) ================================================ FILE: packages/react/src/hooks/useWatchBlocks.test.ts ================================================ import { testClient, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import type { Block } from 'viem' import { expect, test, vi } from 'vitest' import { useWatchBlocks } from './useWatchBlocks.js' test('default', async () => { const blocks: Block[] = [] await renderHook(() => useWatchBlocks({ onBlock(block) { blocks.push(block) }, }), ) await testClient.mainnet.mine({ blocks: 1 }) await wait(500) await testClient.mainnet.mine({ blocks: 1 }) await wait(500) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitUntil(() => blocks.length === 3, { timeout: 10_000 }) expect(blocks.length).toBe(3) }) test('behavior: uses latest callback after rerender', async () => { const blocks1: Block[] = [] const blocks2: Block[] = [] const { rerender } = await renderHook( (props) => useWatchBlocks({ onBlock: props?.callback, }), { initialProps: { callback: (block: Block) => blocks1.push(block), }, }, ) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitUntil(() => blocks1.length >= 1, { timeout: 10_000 }) rerender({ callback: (block) => blocks2.push(block), }) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitUntil(() => blocks2.length >= 1, { timeout: 10_000 }) expect(blocks1.length).toBe(1) expect(blocks2.length).toBeGreaterThanOrEqual(1) }) ================================================ FILE: packages/react/src/hooks/useWatchBlocks.ts ================================================ 'use client' import { type Config, type ResolvedRegister, type WatchBlocksParameters, watchBlocks, } from '@wagmi/core' import type { ConfigParameter, EnabledParameter, UnionCompute, UnionExactPartial, } from '@wagmi/core/internal' import { useEffect, useRef } from 'react' import type { BlockTag } from 'viem' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseWatchBlocksParameters< includeTransactions extends boolean = false, blockTag extends BlockTag = 'latest', config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = UnionCompute< UnionExactPartial< WatchBlocksParameters > & ConfigParameter & EnabledParameter > export type UseWatchBlocksReturnType = void /** https://wagmi.sh/react/hooks/useWatchBlocks */ export function useWatchBlocks< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], includeTransactions extends boolean = false, blockTag extends BlockTag = 'latest', >( parameters: UseWatchBlocksParameters< includeTransactions, blockTag, config, chainId > = {} as any, ): UseWatchBlocksReturnType { const { enabled = true, onBlock, config: _, ...rest } = parameters const config = useConfig(parameters) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId const onBlockRef = useRef(onBlock) const onErrorRef = useRef(rest.onError) onBlockRef.current = onBlock onErrorRef.current = rest.onError // TODO(react@19): cleanup // biome-ignore lint/correctness/useExhaustiveDependencies: `rest` changes every render so only including properties in dependency array useEffect(() => { if (!enabled) return if (!onBlockRef.current) return return watchBlocks(config, { ...(rest as any), chainId, onBlock: (block, prevBlock) => onBlockRef.current?.(block as any, prevBlock as any), onError: (error) => onErrorRef.current?.(error), }) }, [ chainId, config, enabled, /// rest.blockTag, rest.emitMissed, rest.emitOnBegin, rest.includeTransactions, rest.poll, rest.pollingInterval, rest.syncConnectedChain, ]) } ================================================ FILE: packages/react/src/hooks/useWatchContractEvent.test-d.ts ================================================ import { createConfig, http, webSocket } from '@wagmi/core' import { mainnet, optimism } from '@wagmi/core/chains' import { abi } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { type UseWatchContractEventParameters, useWatchContractEvent, } from './useWatchContractEvent.js' test('default', () => { useWatchContractEvent({ address: '0x', abi: abi.erc20, eventName: 'Transfer', poll: false, args: { from: '0x', to: '0x', }, onLogs(logs) { expectTypeOf(logs[0]!.eventName).toEqualTypeOf<'Transfer'>() expectTypeOf(logs[0]!.args).toEqualTypeOf<{ from?: `0x${string}` | undefined to?: `0x${string}` | undefined value?: bigint | undefined }>() }, }) }) test('behavior: no eventName', () => { useWatchContractEvent({ address: '0x', abi: abi.erc20, args: { // TODO: Figure out why this is not working // @ts-ignore from: '0x', to: '0x', }, onLogs(logs) { expectTypeOf(logs[0]!.eventName).toEqualTypeOf<'Transfer' | 'Approval'>() expectTypeOf(logs[0]!.args).toEqualTypeOf< | { from?: `0x${string}` | undefined to?: `0x${string}` | undefined value?: bigint | undefined } | { owner?: `0x${string}` | undefined spender?: `0x${string}` | undefined value?: bigint | undefined } >() }, }) }) test('differing transports', () => { const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: webSocket(), }, }) type Result = UseWatchContractEventParameters< typeof abi.erc20, 'Transfer' | 'Approval', true, typeof config, typeof mainnet.id | typeof optimism.id > expectTypeOf().toEqualTypeOf() useWatchContractEvent({ config, poll: false, address: '0x', abi: abi.erc20, onLogs() {}, }) type Result2 = UseWatchContractEventParameters< typeof abi.erc20, 'Transfer' | 'Approval', true, typeof config, typeof mainnet.id > expectTypeOf().toEqualTypeOf() useWatchContractEvent({ config, chainId: mainnet.id, poll: true, address: '0x', abi: abi.erc20, onLogs() {}, }) type Result3 = UseWatchContractEventParameters< typeof abi.erc20, 'Transfer' | 'Approval', true, typeof config, typeof optimism.id > expectTypeOf().toEqualTypeOf() useWatchContractEvent({ config, chainId: optimism.id, poll: true, address: '0x', abi: abi.erc20, onLogs() {}, }) useWatchContractEvent({ config, chainId: optimism.id, poll: false, address: '0x', abi: abi.erc20, onLogs() {}, }) }) ================================================ FILE: packages/react/src/hooks/useWatchContractEvent.test.ts ================================================ import { connect, disconnect, readContract, writeContract } from '@wagmi/core' import { abi, accounts, address, config, testClient, transactionHashRegex, wait, } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { createWalletClient, erc20Abi, http, parseEther } from 'viem' import type { WatchEventOnLogsParameter } from 'viem/actions' import { expect, test, vi } from 'vitest' import { useWatchContractEvent } from './useWatchContractEvent.js' const connector = config.connectors[0]! test('default', async () => { const data = await connect(config, { connector }) const connectedAddress = data.accounts[0] // impersonate usdc holder account and transfer usdc to connected account await testClient.mainnet.impersonateAccount({ address: address.usdcHolder }) await testClient.mainnet.setBalance({ address: address.usdcHolder, value: 10000000000000000000000n, }) await createWalletClient({ account: address.usdcHolder, chain: testClient.mainnet.chain, transport: http(), }).writeContract({ address: address.usdc, abi: abi.erc20, functionName: 'transfer', args: [connectedAddress, parseEther('10', 'gwei')], }) await testClient.mainnet.mine({ blocks: 1 }) await testClient.mainnet.stopImpersonatingAccount({ address: address.usdcHolder, }) const balance = await readContract(config, { address: address.usdc, abi: erc20Abi, functionName: 'balanceOf', args: [connectedAddress], }) expect(balance).toBeGreaterThan(0n) // start watching transfer events let logs: WatchEventOnLogsParameter = [] renderHook(() => useWatchContractEvent({ address: address.usdc, abi: abi.erc20, eventName: 'Transfer', onLogs(next) { logs = logs.concat(next) }, }), ) await writeContract(config, { address: address.usdc, abi: abi.erc20, functionName: 'transfer', args: [accounts[1], parseEther('1', 'gwei')], }) await writeContract(config, { address: address.usdc, abi: abi.erc20, functionName: 'transfer', args: [accounts[3], parseEther('1', 'gwei')], }) await testClient.mainnet.mine({ blocks: 1 }) await testClient.mainnet.mine({ blocks: 1 }) await wait(1000) // wait for events to be emitted expect(logs.length).toBe(2) expect(logs[0]?.transactionHash).toMatch(transactionHashRegex) await disconnect(config, { connector }) await wait(500) }) test('behavior: uses latest callback after rerender', async () => { await connect(config, { connector }) let logs1: WatchEventOnLogsParameter = [] let logs2: WatchEventOnLogsParameter = [] const { rerender } = await renderHook( (props) => useWatchContractEvent({ address: address.usdc, abi: abi.erc20, eventName: 'Transfer', onLogs: props?.callback, }), { initialProps: { callback: (next: WatchEventOnLogsParameter) => { logs1 = logs1.concat(next) }, }, }, ) await writeContract(config, { address: address.usdc, abi: abi.erc20, functionName: 'transfer', args: [accounts[1], parseEther('0.001', 'gwei')], }) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitUntil(() => logs1.length >= 1, { timeout: 10_000 }) rerender({ callback: (next) => { logs2 = logs2.concat(next) }, }) await writeContract(config, { address: address.usdc, abi: abi.erc20, functionName: 'transfer', args: [accounts[1], parseEther('0.001', 'gwei')], }) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitUntil(() => logs2.length >= 1, { timeout: 10_000 }) expect(logs1.length).toBe(1) expect(logs2.length).toBeGreaterThanOrEqual(1) await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/useWatchContractEvent.ts ================================================ 'use client' import { type Config, deepEqual, type ResolvedRegister, type WatchContractEventParameters, watchContractEvent, } from '@wagmi/core' import type { ConfigParameter, EnabledParameter, UnionCompute, UnionExactPartial, } from '@wagmi/core/internal' import { useEffect, useRef } from 'react' import type { Abi, ContractEventName } from 'viem' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseWatchContractEventParameters< abi extends Abi | readonly unknown[] = Abi, eventName extends ContractEventName = ContractEventName, strict extends boolean | undefined = undefined, config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = UnionCompute< UnionExactPartial< WatchContractEventParameters > & ConfigParameter & EnabledParameter > export type UseWatchContractEventReturnType = void /** https://wagmi.sh/react/api/hooks/useWatchContractEvent */ export function useWatchContractEvent< const abi extends Abi | readonly unknown[], eventName extends ContractEventName, strict extends boolean | undefined = undefined, config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], >( parameters: UseWatchContractEventParameters< abi, eventName, strict, config, chainId > = {} as any, ): UseWatchContractEventReturnType { const { enabled = true, onLogs, config: _, ...rest } = parameters const config = useConfig(parameters) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId const onLogsRef = useRef(onLogs) const onErrorRef = useRef(rest.onError) onLogsRef.current = onLogs onErrorRef.current = rest.onError const abiRef = useRef(rest.abi) const addressRef = useRef(rest.address) const argsRef = useRef(rest.args) if (!abiRef.current || !deepEqual(abiRef.current, rest.abi)) abiRef.current = rest.abi if (!addressRef.current || !deepEqual(addressRef.current, rest.address)) addressRef.current = rest.address if (!argsRef.current || !deepEqual(argsRef.current, rest.args)) argsRef.current = rest.args // TODO(react@19): cleanup // biome-ignore lint/correctness/useExhaustiveDependencies: `rest` changes every render so only including properties in dependency array useEffect(() => { if (!enabled) return if (!onLogsRef.current) return return watchContractEvent(config, { ...(rest as any), chainId, onLogs: (logs) => onLogsRef.current?.(logs as any), onError: (error) => onErrorRef.current?.(error), }) }, [ chainId, config, enabled, /// abiRef.current, addressRef.current, argsRef.current, rest.batch, rest.eventName, rest.fromBlock, rest.poll, rest.pollingInterval, rest.strict, rest.syncConnectedChain, ]) } ================================================ FILE: packages/react/src/hooks/useWatchPendingTransactions.test-d.ts ================================================ import { createConfig } from '@wagmi/core' import { http, webSocket } from 'viem' import { mainnet, optimism } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { type UseWatchPendingTransactionsParameters, useWatchPendingTransactions, } from './useWatchPendingTransactions.js' test('default', () => { useWatchPendingTransactions({ poll: false, onTransactions() {}, }) }) test('differing transports', () => { const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: webSocket(), }, }) type Result = UseWatchPendingTransactionsParameters< typeof config, typeof mainnet.id | typeof optimism.id > expectTypeOf().toEqualTypeOf() useWatchPendingTransactions({ config, poll: false, onTransactions() {}, }) type Result2 = UseWatchPendingTransactionsParameters< typeof config, typeof mainnet.id > expectTypeOf().toEqualTypeOf() useWatchPendingTransactions({ config, chainId: mainnet.id, poll: true, onTransactions() {}, }) type Result3 = UseWatchPendingTransactionsParameters< typeof config, typeof optimism.id > expectTypeOf().toEqualTypeOf() useWatchPendingTransactions({ config, chainId: optimism.id, poll: true, onTransactions() {}, }) useWatchPendingTransactions({ config, chainId: optimism.id, poll: false, onTransactions() {}, }) }) ================================================ FILE: packages/react/src/hooks/useWatchPendingTransactions.test.ts ================================================ import { connect, disconnect, sendTransaction } from '@wagmi/core' import { accounts, config, testClient, transactionHashRegex, wait, } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { parseEther } from 'viem' import type { OnTransactionsParameter } from 'viem/actions' import { expect, test, vi } from 'vitest' import { useWatchPendingTransactions } from './useWatchPendingTransactions.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) let transactions: OnTransactionsParameter = [] renderHook(() => useWatchPendingTransactions({ onTransactions(next) { transactions = [...transactions, ...next] }, }), ) await wait(1000) await sendTransaction(config, { to: accounts[1], value: parseEther('1'), }) await wait(200) await sendTransaction(config, { to: accounts[3], value: parseEther('1'), }) await wait(200) await testClient.mainnet.mine({ blocks: 1 }) expect(transactions.length).toBe(2) expect(transactions[0]).toMatch(transactionHashRegex) await disconnect(config, { connector }) }) test('behavior: uses latest callback after rerender', async () => { await connect(config, { connector }) let transactions1: OnTransactionsParameter = [] let transactions2: OnTransactionsParameter = [] const { rerender } = await renderHook( (props) => useWatchPendingTransactions({ onTransactions: props?.callback, }), { initialProps: { callback: (next: OnTransactionsParameter) => { transactions1 = [...transactions1, ...next] }, }, }, ) await wait(1000) await sendTransaction(config, { to: accounts[1], value: parseEther('0.001'), }) await vi.waitUntil(() => transactions1.length >= 1, { timeout: 10_000 }) await testClient.mainnet.mine({ blocks: 1 }) rerender({ callback: (next) => { transactions2 = [...transactions2, ...next] }, }) await sendTransaction(config, { to: accounts[1], value: parseEther('0.001'), }) await vi.waitUntil(() => transactions2.length >= 1, { timeout: 10_000 }) await testClient.mainnet.mine({ blocks: 1 }) expect(transactions1.length).toBe(1) expect(transactions2.length).toBeGreaterThanOrEqual(1) await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/useWatchPendingTransactions.ts ================================================ 'use client' import { type Config, type ResolvedRegister, type WatchPendingTransactionsParameters, watchPendingTransactions, } from '@wagmi/core' import type { ConfigParameter, EnabledParameter, UnionCompute, UnionExactPartial, } from '@wagmi/core/internal' import { useEffect, useRef } from 'react' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseWatchPendingTransactionsParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = UnionCompute< UnionExactPartial> & ConfigParameter & EnabledParameter > export type UseWatchPendingTransactionsReturnType = void /** https://wagmi.sh/react/api/hooks/useWatchPendingTransactions */ export function useWatchPendingTransactions< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], >( parameters: UseWatchPendingTransactionsParameters< config, chainId > = {} as any, ): UseWatchPendingTransactionsReturnType { const { enabled = true, onTransactions, config: _, ...rest } = parameters const config = useConfig(parameters) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId const onTransactionsRef = useRef(onTransactions) const onErrorRef = useRef(rest.onError) onTransactionsRef.current = onTransactions onErrorRef.current = rest.onError // TODO(react@19): cleanup // biome-ignore lint/correctness/useExhaustiveDependencies: `rest` changes every render so only including properties in dependency array useEffect(() => { if (!enabled) return if (!onTransactionsRef.current) return return watchPendingTransactions(config, { ...(rest as any), chainId, onTransactions: (transactions) => onTransactionsRef.current?.(transactions), onError: (error) => onErrorRef.current?.(error), }) }, [ chainId, config, enabled, /// rest.batch, rest.poll, rest.pollingInterval, rest.syncConnectedChain, ]) } ================================================ FILE: packages/react/src/hooks/useWriteContract.test-d.ts ================================================ import { createConfig, http, type WriteContractErrorType } from '@wagmi/core' import { base } from '@wagmi/core/chains' import { abi } from '@wagmi/test' import type { Abi, Address, Hash } from 'viem' import { expectTypeOf, test } from 'vitest' import { useSimulateContract } from './useSimulateContract.js' import { useWriteContract } from './useWriteContract.js' const contextValue = { foo: 'bar' } as const test('context', () => { const writeContract = useWriteContract({ mutation: { onMutate(variables) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: Abi functionName: string args?: readonly unknown[] | undefined }>() return contextValue }, onError(error, variables, context) { expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: Abi functionName: string args?: readonly unknown[] | undefined }>() }, onSuccess(data, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: Abi functionName: string args?: readonly unknown[] | undefined }>() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: Abi functionName: string args?: readonly unknown[] | undefined }>() }, }, }) expectTypeOf(writeContract.data).toEqualTypeOf() expectTypeOf( writeContract.error, ).toEqualTypeOf() expectTypeOf(writeContract.variables).toMatchTypeOf< { chainId?: number | undefined } | undefined >() expectTypeOf(writeContract.context).toEqualTypeOf< typeof contextValue | undefined >() writeContract.mutate( { address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], chainId: 1, }, { onError(error, variables, context) { expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: typeof abi.erc20 functionName: 'transferFrom' args: readonly [Address, Address, bigint] }>() }, onSuccess(data, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() expectTypeOf(variables.functionName).toEqualTypeOf<'transferFrom'>() expectTypeOf(variables.args).toEqualTypeOf< readonly [Address, Address, bigint] >() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: typeof abi.erc20 functionName: 'transferFrom' args: readonly [Address, Address, bigint] }>() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: typeof abi.erc20 functionName: 'transferFrom' args: readonly [Address, Address, bigint] }>() }, }, ) }) test('useSimulateContract', () => { const { data } = useSimulateContract({ address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], chainId: 1, }) const { writeContract } = useWriteContract() const request = data?.request if (request) writeContract(request) }) // https://github.com/wevm/wagmi/issues/3981 test('gh#3981', () => { const config = createConfig({ chains: [base], transports: { [base.id]: http(), }, }) const abi = [ { type: 'function', name: 'example1', inputs: [ { name: 'exampleName', type: 'address', internalType: 'address' }, ], outputs: [], stateMutability: 'payable', }, { type: 'function', name: 'example2', inputs: [ { name: 'exampleName', type: 'address', internalType: 'address' }, ], outputs: [], stateMutability: 'nonpayable', }, ] as const const { writeContract } = useWriteContract({ config }) writeContract({ abi, address: '0x...', functionName: 'example1', args: ['0x...'], value: 123n, }) writeContract({ abi, address: '0x...', functionName: 'example2', args: ['0x...'], // @ts-expect-error value: 123n, }) }) ================================================ FILE: packages/react/src/hooks/useWriteContract.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { abi, address, config } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { expect, test, vi } from 'vitest' import { useWriteContract } from './useWriteContract.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const { result } = await renderHook(() => useWriteContract()) result.current.mutate({ abi: abi.wagmiMintExample, address: address.wagmiMintExample, functionName: 'mint', }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 10_000 }) expect(result.current.data).toBeDefined() await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/useWriteContract.ts ================================================ 'use client' import { useMutation } from '@tanstack/react-query' import type { Config, ResolvedRegister, WriteContractErrorType, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { type WriteContractData, type WriteContractMutate, type WriteContractMutateAsync, type WriteContractOptions, type WriteContractVariables, writeContractMutationOptions, } from '@wagmi/core/query' import type { Abi } from 'viem' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseWriteContractParameters< config extends Config = Config, context = unknown, > = ConfigParameter & WriteContractOptions export type UseWriteContractReturnType< config extends Config = Config, context = unknown, > = UseMutationReturnType< WriteContractData, WriteContractErrorType, WriteContractVariables< Abi, string, readonly unknown[], config, config['chains'][number]['id'] >, context, WriteContractMutate, WriteContractMutateAsync > & { /** @deprecated use `mutate` instead */ writeContract: WriteContractMutate /** @deprecated use `mutateAsync` instead */ writeContractAsync: WriteContractMutateAsync } /** https://wagmi.sh/react/api/hooks/useWriteContract */ export function useWriteContract< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: UseWriteContractParameters = {}, ): UseWriteContractReturnType { const config = useConfig(parameters) const options = writeContractMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseWriteContractReturnType return { ...(mutation as Return), writeContract: mutation.mutate as Return['mutate'], writeContractAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/react/src/hooks/useWriteContractSync.test-d.ts ================================================ import type { WriteContractSyncErrorType } from '@wagmi/core' import { abi } from '@wagmi/test' import type { Abi, TransactionReceipt } from 'viem' import { expectTypeOf, test } from 'vitest' import { useWriteContractSync } from './useWriteContractSync.js' const contextValue = { foo: 'bar' } as const test('context', () => { const writeContractSync = useWriteContractSync({ mutation: { onMutate(variables) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: Abi functionName: string args?: readonly unknown[] | undefined }>() return contextValue }, onError(error, _variables, context) { expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, _variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, _variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(writeContractSync.data).toEqualTypeOf< TransactionReceipt | undefined >() expectTypeOf( writeContractSync.error, ).toEqualTypeOf() expectTypeOf(writeContractSync.context).toEqualTypeOf< typeof contextValue | undefined >() writeContractSync.mutate({ address: '0x', abi: abi.wagmiMintExample, functionName: 'mint', chainId: 1, }) }) ================================================ FILE: packages/react/src/hooks/useWriteContractSync.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { abi, address, config, testClient, wait } from '@wagmi/test' import { renderHook } from '@wagmi/test/react' import { beforeEach, expect, test, vi } from 'vitest' import { useWriteContractSync } from './useWriteContractSync.js' const connector = config.connectors[0]! beforeEach(async () => { await disconnect(config).catch(() => {}) }) test('default', async () => { await connect(config, { connector }) const { result } = await renderHook(() => useWriteContractSync()) result.current.mutate({ abi: abi.wagmiMintExample, address: address.wagmiMintExample, functionName: 'mint', }) await wait(4_000) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitUntil(() => result.current.isSuccess, { timeout: 15_000 }) expect(result.current.data).toBeDefined() expect(result.current.data?.status).toBe('success') expect(result.current.data?.blockNumber).toBeDefined() await disconnect(config, { connector }) }) ================================================ FILE: packages/react/src/hooks/useWriteContractSync.ts ================================================ 'use client' import { useMutation } from '@tanstack/react-query' import type { Config, ResolvedRegister, WriteContractSyncErrorType, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { type WriteContractSyncData, type WriteContractSyncMutate, type WriteContractSyncMutateAsync, type WriteContractSyncOptions, type WriteContractSyncVariables, writeContractSyncMutationOptions, } from '@wagmi/core/query' import type { Abi } from 'viem' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseWriteContractSyncParameters< config extends Config = Config, context = unknown, > = ConfigParameter & WriteContractSyncOptions export type UseWriteContractSyncReturnType< config extends Config = Config, context = unknown, > = UseMutationReturnType< WriteContractSyncData, WriteContractSyncErrorType, WriteContractSyncVariables< Abi, string, readonly unknown[], config, config['chains'][number]['id'] >, context, WriteContractSyncMutate, WriteContractSyncMutateAsync > & { /** @deprecated use `mutate` instead */ writeContractSync: WriteContractSyncMutate /** @deprecated use `mutateAsync` instead */ writeContractSyncAsync: WriteContractSyncMutateAsync } /** https://wagmi.sh/react/api/hooks/useWriteContractSync */ export function useWriteContractSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: UseWriteContractSyncParameters = {}, ): UseWriteContractSyncReturnType { const config = useConfig(parameters) const options = writeContractSyncMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseWriteContractSyncReturnType return { ...(mutation as Return), writeContractSync: mutation.mutate as Return['mutate'], writeContractSyncAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/react/src/hydrate.ts ================================================ 'use client' import { hydrate, type ResolvedRegister, type State } from '@wagmi/core' import { type ReactElement, useEffect, useRef } from 'react' export type HydrateProps = { config: ResolvedRegister['config'] initialState?: State | undefined reconnectOnMount?: boolean | undefined } export function Hydrate(parameters: React.PropsWithChildren) { const { children, config, initialState, reconnectOnMount = true } = parameters const { onMount } = hydrate(config, { initialState, reconnectOnMount, }) // Hydrate for non-SSR if (!config._internal.ssr) onMount() // Hydrate for SSR const active = useRef(true) // biome-ignore lint/correctness/useExhaustiveDependencies: `queryKey` not required useEffect(() => { if (!active.current) return if (!config._internal.ssr) return onMount() return () => { active.current = false } }, []) return children as ReactElement } ================================================ FILE: packages/react/src/tempo/AGENTS.md ================================================ # Agent Guidelines Agent guidance for `wagmi/tempo` Hooks. > **Communication Style**: Be brief, concise. Maximize information density, minimize tokens. Incomplete sentences acceptable when clear. Remove filler words. Prioritize clarity over grammar. ## Wagmi Hooks When generating Wagmi hooks (in `hooks/`), follow these guidelines. An example of a generated hook set can be found in `hooks/fee.ts`. ### Source of Truth - **All hooks must be based on their corresponding Wagmi actions** from `@wagmi/core/tempo` (`packages/core/src/tempo/`) - Wagmi hooks are React hooks that wrap Wagmi actions with TanStack Query's `useQuery` and `useMutation` - If the Wagmi action is unclear or missing, implement the Wagmi action first ### Documentation Requirements All hooks **must include comprehensive TSDoc** with: 1. **Function description** - What the hook does 2. **`@example` block** - Complete working example showing: - Required imports (hook imports) - React component usage - Hook usage with realistic parameters - Expected return value handling (if applicable) 3. **@param parameters** - Parameters description 4. **`@returns` tag** - Description of the return value Example: ```typescript /** * Hook for getting the user's default fee token. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data, isLoading } = Hooks.fee.useUserToken({ * account: '0x20c...0055', * }) * if (isLoading) return
Loading...
* return
Token: {data?.address}
* } * ``` * * @param parameters - Parameters. * @returns Query result with token address and ID. */ ``` ### Query Hooks For read-only hooks that fetch data: - Use `useQuery` from `../../utils/query.js` - Use `useConfig` and `useChainId` from `../../hooks/(useChainId|useConfig).js` - Call the corresponding action's `queryOptions` function - All parameters should be optional. Use `ExactPartial` to make all query parameters optional - Support optional `query` parameter for TanStack Query options - Default `parameters` to `{}` only if all parameters are truly optional (no required non-reactive parameters like `token`, `role`, etc.) ```typescript export function useMyAction< config extends Config = ResolvedRegister['config'], selectData = myAction.ReturnValue, >(parameters: useMyAction.Parameters = {}): useMyAction.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = myAction.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) } ``` ### Mutation Hooks For state-changing hooks, both variants must be implemented: **1. Standard Variant** ```typescript export function useMyAction< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useMyAction.Parameters = {}, ): useMyAction.ReturnValue { const { mutation = {} } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return myAction(config, variables) }, mutationKey: ['myAction'], }) } ``` **2. Sync Variant (`use*Sync`)** ```typescript export function useMyActionSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useMyActionSync.Parameters = {}, ): useMyActionSync.ReturnValue { const { mutation = {} } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return myActionSync(config, variables) }, mutationKey: ['myActionSync'], }) } ``` ### Watch Hooks For event watching hooks: - Call the corresponding action's watch function inside `useEffect` - All parameters should be optional using `ExactPartial` - Include an `enabled` parameter (defaults to `true`) to control whether the watcher is active - Check if all required properties (like the callback) are defined before setting up the watcher - Include all optional properties for `rest` in the dependency array (e.g. `rest.foo`, `rest.bar`, `rest.baz`) - Return the unwatch function from the `useEffect` for cleanup All watch hooks must include comprehensive JSDoc with: 1. **Function description** - What events the hook watches for 2. **`@example` block** - Complete working example showing hook usage in a React component 3. **`@param` tag** - Parameters description ```typescript /** * Hook for watching TIP20 token mint events. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.token.useWatchMint({ * onMint(args) { * console.log('Mint:', args) * }, * }) * return
Watching for mints...
* } * ``` * * @param parameters - Parameters. */ export function useWatchMyEvent< config extends Config = ResolvedRegister['config'], >(parameters: useWatchMyEvent.Parameters = {}) { const { enabled = true, onMyEvent, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId useEffect(() => { if (!enabled) return if (!onMyEvent) return return Actions.watchMyEvent(config, { ...rest, chainId, onMyEvent, }) }, [config, enabled, onMyEvent, rest.foo, rest.bar, rest.baz]) } export declare namespace useWatchMyEvent { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } ``` ### Namespace Properties #### Query Hooks All query hooks must include the following components: ```typescript export function useMyAction< config extends Config = ResolvedRegister['config'], selectData = myAction.ReturnValue, >(parameters: useMyAction.Parameters = {}): useMyAction.ReturnValue { ... } export declare namespace useMyAction { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = myAction.ReturnValue, > = ConfigParameter & QueryParameter< myAction.ReturnValue, myAction.ErrorType, selectData, myAction.QueryKey > & ExactPartial> export type ReturnValue = UseQueryReturnType } ``` **Note:** Use `ExactPartial` to make all query parameters optional. This ensures that reactive parameters can be undefined initially and populated later for proper reactivity. #### Watch Hooks All watch hooks must include the following components: ```typescript export function useWatchMyEvent< config extends Config = ResolvedRegister['config'], >(parameters: useWatchMyEvent.Parameters = {}) { ... } export declare namespace useWatchMyEvent { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } ``` **Note:** Watch hooks don't have a return value - they set up event listeners in a `useEffect` and automatically clean up when the component unmounts or dependencies change. #### Mutation Hooks All mutation hooks must include the following components: ```typescript export function useMyAction< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useMyAction.Parameters = {}, ): useMyAction.ReturnValue { ... } export declare namespace useMyAction { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< myAction.ReturnValue, myAction.ErrorType, myAction.Parameters, context > | undefined } type ReturnValue< config extends Config = Config, context = unknown, > = UseMutationResult< myAction.ReturnValue, myAction.ErrorType, myAction.Parameters, context > } export declare namespace useMyActionSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< myActionSync.ReturnValue, myActionSync.ErrorType, myActionSync.Parameters, context > | undefined } type ReturnValue< config extends Config = Config, context = unknown, > = UseMutationResult< myActionSync.ReturnValue, myActionSync.ErrorType, myActionSync.Parameters, context > } ``` ### Testing Tests should be co-located with hooks in `myNamespace.test.ts` files. **Important**: Wagmi hook tests should follow the same test flows as the corresponding Wagmi action tests in `@wagmi/core/tempo`. This includes: - Setting up the same initial state (creating tokens, granting roles, minting tokens, etc.) - Testing the same behaviors and edge cases - Using the same test data and assertions where applicable The main difference is that hooks use React rendering patterns with `renderHook`, and mutation hooks don't require explicit `account` parameters in `mutateAsync` calls since they use the connector's account. See `hooks/fee.test.ts` for a comprehensive example of test patterns and structure. #### Test Structure Organize tests by hook name with a default test case. Use namespace imports for cleaner code when importing hooks: ```typescript import { type Address } from 'viem' import { describe, expect, test, vi } from 'vitest' import { useConnect } from 'wagmi' import { accounts, config, renderHook } from '@wagmi/test/tempo' import * as myNamespace from './myNamespace.js' // Query hooks describe('useMyAction', () => { test('default', async () => { const { result } = await renderHook(() => myNamespace.useMyAction({ account: account.address }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) expect(result.current.data).toBeDefined() // Additional assertions... }) test('reactivity: account parameter', async () => { const { result, rerender } = await renderHook( (props) => myNamespace.useMyAction({ account: props?.account }), { initialProps: { account: undefined as Address | undefined } }, ) await vi.waitFor(() => result.current.fetchStatus === 'fetching') // Should be disabled when account is undefined expect(result.current.data).toBeUndefined() expect(result.current.isPending).toBe(true) // expect(result.current.isEnabled).toBe(false) // TODO: Disabled until @tanstack/react-query bumped to latest // Set account rerender({ account: account.address }) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) // Should now be enabled and have data expect(result.current.isEnabled).toBe(true) expect(result.current.data).toBeDefined() // Additional assertions... }) }) // Mutation hooks describe('useMyAction', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), myAction: myNamespace.useMyAction(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Include any necessary setup from the corresponding Wagmi action test // e.g., create tokens, grant roles, etc. using the action's mutateAsync const hash = await result.current.myAction.mutateAsync({ // ... mutation parameters (no account parameter needed) }) expect(hash).toBeDefined() await vi.waitFor(() => expect(result.current.myAction.isSuccess).toBeTruthy(), ) }) }) describe('useMyActionSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), myAction: myNamespace.useMyActionSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Include any necessary setup from the corresponding Wagmi action test const data = await result.current.myAction.mutateAsync({ // ... mutation parameters (no account parameter needed) }) expect(data).toBeDefined() await vi.waitFor(() => expect(result.current.myAction.isSuccess).toBeTruthy(), ) }) }) // Watch hooks describe('useWatchMyEvent', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), createSync: myNamespace.useCreateSync(), // ... any other setup hooks needed })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Include any necessary setup (e.g., create token, grant roles) const events: any[] = [] await renderHook(() => myNamespace.useWatchMyEvent({ // ... parameters onMyEvent(args) { events.push(args) }, }), ) // Trigger the event by calling a sync action // e.g., await connectResult.current.myActionSync.mutateAsync({ ... }) await vi.waitUntil(() => events.length >= 1) expect(events.length).toBeGreaterThanOrEqual(1) expect(events[0]?.someField).toBe(expectedValue) }) }) ``` ================================================ FILE: packages/react/src/tempo/Connectors.test.ts ================================================ import { KeyManager, webAuthn } from '@wagmi/core/tempo' import { renderHook } from '@wagmi/test/tempo' import { describe, expect, test, vi } from 'vitest' import { cdp } from 'vitest/browser' import { useConnect, useConnection, useDisconnect } from 'wagmi' async function setupWebAuthn() { const client = cdp() await client.send('WebAuthn.enable') const result = await client.send('WebAuthn.addVirtualAuthenticator', { options: { protocol: 'ctap2', transport: 'internal', hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true, }, }) return async () => { const client = cdp() await client.send('WebAuthn.removeVirtualAuthenticator', { authenticatorId: result.authenticatorId, }) await client.send('WebAuthn.disable') } } test('connect', async (context) => { const cleanup = await setupWebAuthn() context.onTestFinished(async () => await cleanup()) const { result } = await renderHook(() => ({ useConnection: useConnection(), useConnect: useConnect(), })) expect(result.current.useConnection.address).not.toBeDefined() expect(result.current.useConnection.status).toEqual('disconnected') result.current.useConnect.mutate({ capabilities: { type: 'sign-up', label: 'Test Account' }, connector: webAuthn({ keyManager: KeyManager.localStorage(), }), }) await vi.waitFor(() => expect(result.current.useConnection.isConnected).toBeTruthy(), ) expect(result.current.useConnection.address).toBeDefined() expect(result.current.useConnection.address).toMatch(/^0x[a-fA-F0-9]{40}$/) expect(result.current.useConnection.status).toEqual('connected') }) describe('capabilities.sign', () => { test('sign-up + sign (create path)', async (context) => { const cleanup = await setupWebAuthn() context.onTestFinished(async () => await cleanup()) const connector = webAuthn({ keyManager: KeyManager.localStorage(), }) const { result } = await renderHook(() => ({ useConnection: useConnection(), useConnect: useConnect(), })) const hash = '0x0000000000000000000000000000000000000000000000000000000000000001' const connectResult = await result.current.useConnect.mutateAsync({ capabilities: { type: 'sign-up', label: 'Create+Sign', sign: { hash } }, connector, withCapabilities: true, }) await vi.waitFor(() => expect(result.current.useConnection.isConnected).toBeTruthy(), ) expect(result.current.useConnection.address).toBeDefined() expect(result.current.useConnection.address).toMatch(/^0x[a-fA-F0-9]{40}$/) expect(connectResult.accounts[0]?.capabilities.signature).toBeDefined() expect(connectResult.accounts[0]?.capabilities.signature).toMatch(/^0x/) }) test('discover path: disconnect then reconnect with sign', async (context) => { const cleanup = await setupWebAuthn() context.onTestFinished(async () => await cleanup()) const connector = webAuthn({ keyManager: KeyManager.localStorage(), }) const { result } = await renderHook(() => ({ useConnection: useConnection(), useConnect: useConnect(), useDisconnect: useDisconnect(), })) await result.current.useConnect.mutateAsync({ capabilities: { type: 'sign-up', label: 'Discover Test' }, connector, }) await vi.waitFor(() => expect(result.current.useConnection.isConnected).toBeTruthy(), ) const address = result.current.useConnection.address expect(address).toBeDefined() await result.current.useDisconnect.mutateAsync({}) await vi.waitFor(() => expect(result.current.useConnection.isConnected).toBeFalsy(), ) const hash = '0x0000000000000000000000000000000000000000000000000000000000000001' const connectResult = await result.current.useConnect.mutateAsync({ capabilities: { sign: { hash }, }, connector, withCapabilities: true, }) await vi.waitFor(() => expect(result.current.useConnection.isConnected).toBeTruthy(), ) expect(result.current.useConnection.address).toBeDefined() expect(result.current.useConnection.address).toMatch(/^0x[a-fA-F0-9]{40}$/) expect(connectResult.accounts[0]?.capabilities.signature).toBeDefined() expect(connectResult.accounts[0]?.capabilities.signature).toMatch(/^0x/) }) test('sign skips access key provisioning (with grantAccessKey)', async (context) => { const cleanup = await setupWebAuthn() context.onTestFinished(async () => await cleanup()) const connector = webAuthn({ grantAccessKey: true, keyManager: KeyManager.localStorage(), }) const { result } = await renderHook(() => ({ useConnection: useConnection(), useConnect: useConnect(), useDisconnect: useDisconnect(), })) await result.current.useConnect.mutateAsync({ capabilities: { type: 'sign-up', label: 'Grant Test' }, connector, }) await vi.waitFor(() => expect(result.current.useConnection.isConnected).toBeTruthy(), ) await result.current.useDisconnect.mutateAsync({}) await vi.waitFor(() => expect(result.current.useConnection.isConnected).toBeFalsy(), ) const hash = '0x0000000000000000000000000000000000000000000000000000000000000002' const connectResult = await result.current.useConnect.mutateAsync({ capabilities: { sign: { hash }, }, connector, withCapabilities: true, }) await vi.waitFor(() => expect(result.current.useConnection.isConnected).toBeTruthy(), ) expect(result.current.useConnection.address).toBeDefined() expect(connectResult.accounts[0]?.capabilities.signature).toBeDefined() expect(connectResult.accounts[0]?.capabilities.signature).toMatch(/^0x/) }) }) ================================================ FILE: packages/react/src/tempo/hooks/amm.test.ts ================================================ import { accounts, addresses, config, renderHook } from '@wagmi/test/tempo' import { type Address, parseUnits } from 'viem' import { describe, expect, test, vi } from 'vitest' import { useConnect } from '../../hooks/useConnect.js' import * as hooks from './amm.js' import * as tokenHooks from './token.js' const account = accounts[0] describe('usePool', () => { test('default', async () => { const { result } = await renderHook(() => hooks.usePool({ userToken: addresses.alphaUsd, validatorToken: '0x20c0000000000000000000000000000000000001', }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy(), { timeout: 10_000, }) expect(result.current.data).toMatchInlineSnapshot(` { "reserveUserToken": 0n, "reserveValidatorToken": 0n, "totalSupply": 0n, } `) }) test('reactivity: token parameters', async () => { const { result, rerender } = await renderHook( (props) => hooks.usePool({ userToken: props?.userToken, validatorToken: props?.validatorToken, }), { initialProps: { userToken: undefined as Address | undefined, validatorToken: undefined as Address | undefined, }, }, ) await vi.waitFor(() => expect(result.current.fetchStatus).toBe('idle')) // Should be disabled when tokens are undefined expect(result.current.data).toBeUndefined() expect(result.current.isPending).toBe(true) // expect(result.current.isEnabled).toBe(false) // Set tokens rerender({ userToken: addresses.alphaUsd, validatorToken: '0x20c0000000000000000000000000000000000001', }) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) // Should now be enabled and have data // expect(result.current.isEnabled).toBe(true) expect(result.current.data).toBeDefined() }) }) describe('useLiquidityBalance', () => { test('default', async () => { const { result } = await renderHook(() => hooks.useLiquidityBalance({ address: account.address, userToken: addresses.alphaUsd, validatorToken: '0x20c0000000000000000000000000000000000001', }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy(), { timeout: 10_000, }) expect(result.current.data).toMatchInlineSnapshot('0n') }) test('reactivity: poolId and address parameters', async () => { const { result, rerender } = await renderHook( (props) => hooks.useLiquidityBalance({ userToken: props?.userToken, validatorToken: props?.validatorToken, address: props?.address, }), { initialProps: { userToken: undefined as Address | undefined, validatorToken: undefined as Address | undefined, address: undefined as Address | undefined, }, }, ) await vi.waitFor(() => expect(result.current.fetchStatus).toBe('idle')) // Should be disabled when parameters are undefined expect(result.current.data).toBeUndefined() expect(result.current.isPending).toBe(true) // expect(result.current.isEnabled).toBe(false) // Set parameters rerender({ userToken: addresses.alphaUsd, validatorToken: '0x20c0000000000000000000000000000000000001', address: account.address, }) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) // Should now be enabled and have data // expect(result.current.isEnabled).toBe(true) expect(result.current.data).toBeDefined() }) }) describe('useMintSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: tokenHooks.useCreateSync(), grantRolesSync: tokenHooks.useGrantRolesSync(), mintTokenSync: tokenHooks.useMintSync(), mintSync: hooks.useMintSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token for testing const { token } = await result.current.createSync.mutateAsync({ name: 'Test Token', symbol: 'TEST', currency: 'USD', }) // Grant issuer role to mint tokens await result.current.grantRolesSync.mutateAsync({ token, roles: ['issuer'], to: account.address, }) // Mint some tokens to account await result.current.mintTokenSync.mutateAsync({ to: account.address, amount: parseUnits('1000', 6), token, }) // Add liquidity to pool const data = await result.current.mintSync.mutateAsync({ userTokenAddress: token, validatorTokenAddress: addresses.alphaUsd, validatorTokenAmount: parseUnits('100', 6), to: account.address, }) await vi.waitFor(() => expect(result.current.mintSync.isSuccess).toBeTruthy(), ) expect(data.receipt).toBeDefined() expect(data.amountValidatorToken).toBe(parseUnits('100', 6)) }) }) describe.skip('useBurnSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: tokenHooks.useCreateSync(), grantRolesSync: tokenHooks.useGrantRolesSync(), mintTokenSync: tokenHooks.useMintSync(), mintSync: hooks.useMintSync(), burnSync: hooks.useBurnSync(), transferSync: tokenHooks.useTransferSync(), getLiquidityBalance: hooks.useLiquidityBalance, })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token for testing const { token } = await result.current.createSync.mutateAsync({ name: 'Test Token 5', symbol: 'TEST5', currency: 'USD', }) // Grant issuer role to mint tokens await result.current.grantRolesSync.mutateAsync({ token, roles: ['issuer'], to: account.address, }) // Mint some tokens to account await result.current.mintTokenSync.mutateAsync({ to: account.address, amount: parseUnits('1000', 6), token, }) // Add liquidity to pool await result.current.mintSync.mutateAsync({ userTokenAddress: token, validatorTokenAddress: addresses.alphaUsd, validatorTokenAmount: parseUnits('100', 6), to: account.address, }) // TODO(TEMPO-1183): Remove this janky fix to get some user token in the pool await result.current.transferSync.mutateAsync({ to: '0x30D861999070Ae03B9548501DBd573E11A9f59Ee', amount: 600n, token: token, feeToken: token, }) // Get LP balance before burn const { result: balanceResult } = await renderHook(() => result.current.getLiquidityBalance({ userToken: token, validatorToken: addresses.alphaUsd, address: account.address, }), ) await vi.waitFor(() => expect(balanceResult.current.isSuccess).toBeTruthy()) const lpBalanceBefore = balanceResult.current.data! // Burn half of LP tokens const data = await result.current.burnSync.mutateAsync({ userToken: token, validatorToken: addresses.alphaUsd, liquidity: lpBalanceBefore / 2n, to: account.address, }) await vi.waitFor(() => expect(result.current.burnSync.isSuccess).toBeTruthy(), ) expect(data.receipt).toBeDefined() expect(data.liquidity).toBe(lpBalanceBefore / 2n) }) }) describe.skip('useRebalanceSwapSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: tokenHooks.useCreateSync(), grantRolesSync: tokenHooks.useGrantRolesSync(), mintTokenSync: tokenHooks.useMintSync(), mintSync: hooks.useMintSync(), transferSync: tokenHooks.useTransferSync(), rebalanceSwapSync: hooks.useRebalanceSwapSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token for testing const { token } = await result.current.createSync.mutateAsync({ name: 'Test Token 6', symbol: 'TEST6', currency: 'USD', }) // Grant issuer role to mint tokens await result.current.grantRolesSync.mutateAsync({ token, roles: ['issuer'], to: account.address, }) // Mint some tokens to account await result.current.mintTokenSync.mutateAsync({ to: account.address, amount: parseUnits('1000', 6), token, }) // Add liquidity to pool await result.current.mintSync.mutateAsync({ userTokenAddress: token, validatorTokenAddress: addresses.alphaUsd, validatorTokenAmount: parseUnits('100', 6), to: account.address, }) // TODO(TEMPO-1183): Remove this janky fix to get some user token in the pool await result.current.transferSync.mutateAsync({ to: '0x30D861999070Ae03B9548501DBd573E11A9f59Ee', amount: 600n, token: token, feeToken: token, }) const account2 = accounts[1] // Perform rebalance swap const data = await result.current.rebalanceSwapSync.mutateAsync({ userToken: token, validatorToken: addresses.alphaUsd, amountOut: 100n, to: account2.address, }) await vi.waitFor(() => expect(result.current.rebalanceSwapSync.isSuccess).toBeTruthy(), ) expect(data.receipt).toBeDefined() expect(data.amountOut).toBe(100n) expect(data.swapper).toBe(account.address) }) }) describe.skip('useWatchRebalanceSwap', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), createSync: tokenHooks.useCreateSync(), grantRolesSync: tokenHooks.useGrantRolesSync(), mintTokenSync: tokenHooks.useMintSync(), mintSync: hooks.useMintSync(), transferSync: tokenHooks.useTransferSync(), rebalanceSwapSync: hooks.useRebalanceSwapSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token for testing const { token } = await connectResult.current.createSync.mutateAsync({ name: 'Test Token 3', symbol: 'TEST3', currency: 'USD', }) // Grant issuer role to mint tokens await connectResult.current.grantRolesSync.mutateAsync({ token, roles: ['issuer'], to: account.address, }) // Mint some tokens to account await connectResult.current.mintTokenSync.mutateAsync({ to: account.address, amount: parseUnits('1000', 6), token, }) // Add liquidity to pool await connectResult.current.mintSync.mutateAsync({ userTokenAddress: token, validatorTokenAddress: addresses.alphaUsd, validatorTokenAmount: parseUnits('100', 6), to: account.address, }) // TODO(TEMPO-1183): Remove this janky fix to get some user token in the pool await connectResult.current.transferSync.mutateAsync({ to: '0x30D861999070Ae03B9548501DBd573E11A9f59Ee', amount: 600n, token: token, feeToken: token, }) const events: any[] = [] await renderHook(() => hooks.useWatchRebalanceSwap({ onRebalanceSwap(args) { events.push(args) }, }), ) const account2 = accounts[1] // Perform rebalance swap await connectResult.current.rebalanceSwapSync.mutateAsync({ userToken: token, validatorToken: addresses.alphaUsd, amountOut: 100n, to: account2.address, }) await vi.waitUntil(() => events.length >= 1) expect(events.length).toBeGreaterThanOrEqual(1) expect(events[0]?.userToken.toLowerCase()).toBe(token.toLowerCase()) expect(events[0]?.validatorToken.toLowerCase()).toBe( addresses.alphaUsd.toLowerCase(), ) expect(events[0]?.amountOut).toBe(100n) }) }) describe('useWatchMint', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), createSync: tokenHooks.useCreateSync(), grantRolesSync: tokenHooks.useGrantRolesSync(), mintTokenSync: tokenHooks.useMintSync(), mintSync: hooks.useMintSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token for testing const { token } = await connectResult.current.createSync.mutateAsync({ name: 'Test Token 2', symbol: 'TEST2', currency: 'USD', }) // Grant issuer role to mint tokens await connectResult.current.grantRolesSync.mutateAsync({ token, roles: ['issuer'], to: account.address, }) // Mint some tokens to account await connectResult.current.mintTokenSync.mutateAsync({ to: account.address, amount: parseUnits('1000', 6), token, }) const events: any[] = [] await renderHook(() => hooks.useWatchMint({ onMint(args) { events.push(args) }, }), ) // Add liquidity to pool await connectResult.current.mintSync.mutateAsync({ userTokenAddress: token, validatorTokenAddress: addresses.alphaUsd, validatorTokenAmount: parseUnits('100', 6), to: account.address, }) await vi.waitUntil(() => events.length >= 1) expect(events.length).toBeGreaterThanOrEqual(1) expect(events[0]?.userToken.toLowerCase()).toBe(token.toLowerCase()) expect(events[0]?.validatorToken.toLowerCase()).toBe( addresses.alphaUsd.toLowerCase(), ) expect(events[0]?.amountValidatorToken).toBe(parseUnits('100', 6)) }) }) describe.skip('useWatchBurn', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), createSync: tokenHooks.useCreateSync(), grantRolesSync: tokenHooks.useGrantRolesSync(), mintTokenSync: tokenHooks.useMintSync(), mintSync: hooks.useMintSync(), burnSync: hooks.useBurnSync(), transferSync: tokenHooks.useTransferSync(), getLiquidityBalance: hooks.useLiquidityBalance, })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token for testing const { token } = await connectResult.current.createSync.mutateAsync({ name: 'Test Token 4', symbol: 'TEST4', currency: 'USD', }) // Grant issuer role to mint tokens await connectResult.current.grantRolesSync.mutateAsync({ token, roles: ['issuer'], to: account.address, }) // Mint some tokens to account await connectResult.current.mintTokenSync.mutateAsync({ to: account.address, amount: parseUnits('1000', 6), token, }) // Add liquidity to pool await connectResult.current.mintSync.mutateAsync({ userTokenAddress: token, validatorTokenAddress: addresses.alphaUsd, validatorTokenAmount: parseUnits('100', 6), to: account.address, }) // TODO(TEMPO-1183): Remove this janky fix to get some user token in the pool await connectResult.current.transferSync.mutateAsync({ to: '0x30D861999070Ae03B9548501DBd573E11A9f59Ee', amount: 600n, token: token, feeToken: token, }) // Get LP balance const { result: balanceResult } = await renderHook(() => connectResult.current.getLiquidityBalance({ userToken: token, validatorToken: addresses.alphaUsd, address: account.address, }), ) await vi.waitFor(() => expect(balanceResult.current.isSuccess).toBeTruthy()) const lpBalance = balanceResult.current.data! const events: any[] = [] await renderHook(() => hooks.useWatchBurn({ onBurn(args) { events.push(args) }, }), ) // Burn LP tokens await connectResult.current.burnSync.mutateAsync({ userToken: token, validatorToken: addresses.alphaUsd, liquidity: lpBalance / 2n, to: account.address, }) await vi.waitUntil(() => events.length >= 1) expect(events.length).toBeGreaterThanOrEqual(1) expect(events[0]?.userToken.toLowerCase()).toBe(token.toLowerCase()) expect(events[0]?.validatorToken.toLowerCase()).toBe( addresses.alphaUsd.toLowerCase(), ) expect(events[0]?.liquidity).toBe(lpBalance / 2n) }) }) ================================================ FILE: packages/react/src/tempo/hooks/amm.ts ================================================ import type { UseMutationResult } from '@tanstack/react-query' import type { Config, ResolvedRegister } from '@wagmi/core' import type { ConfigParameter, ExactPartial, UnionCompute, } from '@wagmi/core/internal' import { Actions } from '@wagmi/core/tempo' import { useEffect } from 'react' import { useChainId } from '../../hooks/useChainId.js' import { useConfig } from '../../hooks/useConfig.js' import { type UseMutationParameters, type UseQueryReturnType, useMutation, useQuery, } from '../../utils/query.js' import type { QueryParameter } from '../utils.js' /** * Hook for getting the reserves for a liquidity pool. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data, isLoading } = Hooks.amm.usePool({ * userToken: '0x...', * validatorToken: '0x...', * }) * * if (isLoading) return
Loading...
* return ( *
* User Token Reserve: {data?.reserveUserToken.toString()} * Validator Token Reserve: {data?.reserveValidatorToken.toString()} *
* ) * } * ``` * * @param parameters - Parameters. * @returns Query result with the pool reserves. */ export function usePool< config extends Config = ResolvedRegister['config'], selectData = Actions.amm.getPool.ReturnValue, >( parameters: usePool.Parameters = {}, ): usePool.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.amm.getPool.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace usePool { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.amm.getPool.ReturnValue, > = ConfigParameter & QueryParameter< Actions.amm.getPool.ReturnValue, Actions.amm.getPool.ErrorType, selectData, Actions.amm.getPool.QueryKey > & ExactPartial> export type ReturnValue = UseQueryReturnType } /** * Hook for getting the LP token balance for an account in a specific pool. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data: poolId } = Hooks.amm.usePoolId({ * userToken: '0x...', * validatorToken: '0x...', * }) * * const { data, isLoading } = Hooks.amm.useLiquidityBalance({ * poolId, * address: '0x20c...0055', * }) * * if (isLoading) return
Loading...
* return
LP Balance: {data?.toString()}
* } * ``` * * @param parameters - Parameters. * @returns Query result with the LP token balance. */ export function useLiquidityBalance< config extends Config = ResolvedRegister['config'], selectData = Actions.amm.getLiquidityBalance.ReturnValue, >( parameters: useLiquidityBalance.Parameters = {}, ): useLiquidityBalance.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.amm.getLiquidityBalance.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace useLiquidityBalance { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.amm.getLiquidityBalance.ReturnValue, > = ConfigParameter & QueryParameter< Actions.amm.getLiquidityBalance.ReturnValue, Actions.amm.getLiquidityBalance.ErrorType, selectData, Actions.amm.getLiquidityBalance.QueryKey > & ExactPartial> export type ReturnValue< selectData = Actions.amm.getLiquidityBalance.ReturnValue, > = UseQueryReturnType } /** * Hook for performing a rebalance swap from validator token to user token. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.amm.useRebalanceSwap() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useRebalanceSwap< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useRebalanceSwap.Parameters = {}, ): useRebalanceSwap.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.amm.rebalanceSwap(config, variables as never) }, mutationKey: ['rebalanceSwap'], }) as never } export declare namespace useRebalanceSwap { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.amm.rebalanceSwap.ReturnValue, Actions.amm.rebalanceSwap.ErrorType, Actions.amm.rebalanceSwap.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.amm.rebalanceSwap.ReturnValue, Actions.amm.rebalanceSwap.ErrorType, Actions.amm.rebalanceSwap.Parameters, context > } /** * Hook for performing a rebalance swap from validator token to user token. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.amm.useRebalanceSwapSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useRebalanceSwapSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useRebalanceSwapSync.Parameters = {}, ): useRebalanceSwapSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.amm.rebalanceSwapSync(config, variables as never) }, mutationKey: ['rebalanceSwapSync'], }) as never } export declare namespace useRebalanceSwapSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.amm.rebalanceSwapSync.ReturnValue, Actions.amm.rebalanceSwapSync.ErrorType, Actions.amm.rebalanceSwapSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.amm.rebalanceSwapSync.ReturnValue, Actions.amm.rebalanceSwapSync.ErrorType, Actions.amm.rebalanceSwapSync.Parameters, context > } /** * Hook for adding liquidity to a pool. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.amm.useMint() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useMint< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useMint.Parameters = {}, ): useMint.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.amm.mint(config, variables as never) }, mutationKey: ['mint'], }) as never } export declare namespace useMint { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.amm.mint.ReturnValue, Actions.amm.mint.ErrorType, Actions.amm.mint.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.amm.mint.ReturnValue, Actions.amm.mint.ErrorType, Actions.amm.mint.Parameters, context > } /** * Hook for adding liquidity to a pool. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.amm.useMintSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useMintSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useMintSync.Parameters = {}, ): useMintSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.amm.mintSync(config, variables as never) }, mutationKey: ['mintSync'], }) as never } export declare namespace useMintSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.amm.mintSync.ReturnValue, Actions.amm.mintSync.ErrorType, Actions.amm.mintSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.amm.mintSync.ReturnValue, Actions.amm.mintSync.ErrorType, Actions.amm.mintSync.Parameters, context > } /** * Hook for removing liquidity from a pool. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.amm.useBurn() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useBurn< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useBurn.Parameters = {}, ): useBurn.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.amm.burn(config, variables as never) }, mutationKey: ['burn'], }) as never } export declare namespace useBurn { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.amm.burn.ReturnValue, Actions.amm.burn.ErrorType, Actions.amm.burn.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.amm.burn.ReturnValue, Actions.amm.burn.ErrorType, Actions.amm.burn.Parameters, context > } /** * Hook for removing liquidity from a pool. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.amm.useBurnSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useBurnSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useBurnSync.Parameters = {}, ): useBurnSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.amm.burnSync(config, variables as never) }, mutationKey: ['burnSync'], }) as never } export declare namespace useBurnSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.amm.burnSync.ReturnValue, Actions.amm.burnSync.ErrorType, Actions.amm.burnSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.amm.burnSync.ReturnValue, Actions.amm.burnSync.ErrorType, Actions.amm.burnSync.Parameters, context > } /** * Hook for watching rebalance swap events. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.amm.useWatchRebalanceSwap({ * onRebalanceSwap(args) { * console.log('Rebalance swap:', args) * }, * }) * * return
Watching for rebalance swaps...
* } * ``` * * @param parameters - Parameters. */ export function useWatchRebalanceSwap< config extends Config = ResolvedRegister['config'], >(parameters: useWatchRebalanceSwap.Parameters = {}) { const { enabled = true, onRebalanceSwap, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onRebalanceSwap) return return Actions.amm.watchRebalanceSwap(config, { ...rest, chainId, onRebalanceSwap, }) }, [ config, enabled, chainId, onRebalanceSwap, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, rest.userToken, rest.validatorToken, ]) } export declare namespace useWatchRebalanceSwap { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } /** * Hook for watching liquidity mint events. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.amm.useWatchMint({ * onMint(args) { * console.log('Liquidity added:', args) * }, * }) * * return
Watching for liquidity additions...
* } * ``` * * @param parameters - Parameters. */ export function useWatchMint< config extends Config = ResolvedRegister['config'], >(parameters: useWatchMint.Parameters = {}) { const { enabled = true, onMint, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onMint) return return Actions.amm.watchMint(config, { ...rest, chainId, onMint, }) }, [ config, enabled, chainId, onMint, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, rest.sender, rest.userToken, rest.validatorToken, ]) } export declare namespace useWatchMint { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } /** * Hook for watching liquidity burn events. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.amm.useWatchBurn({ * onBurn(args) { * console.log('Liquidity removed:', args) * }, * }) * * return
Watching for liquidity removals...
* } * ``` * * @param parameters - Parameters. */ export function useWatchBurn< config extends Config = ResolvedRegister['config'], >(parameters: useWatchBurn.Parameters = {}) { const { enabled = true, onBurn, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onBurn) return return Actions.amm.watchBurn(config, { ...rest, chainId, onBurn, }) }, [ config, enabled, chainId, onBurn, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, rest.userToken, rest.validatorToken, ]) } export declare namespace useWatchBurn { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } ================================================ FILE: packages/react/src/tempo/hooks/dex.test.ts ================================================ import { Actions } from '@wagmi/core/tempo' import { accounts, addresses, config, renderHook, setupTokenPair, } from '@wagmi/test/tempo' import { type Address, isAddress, parseUnits } from 'viem' import { Tick } from 'viem/tempo' import { describe, expect, test, vi } from 'vitest' import { useConnect } from '../../hooks/useConnect.js' import * as dex from './dex.js' const account = accounts[0] const account2 = accounts[1] describe('useBuy', () => { test('default', async () => { const { base, quote } = await setupTokenPair() const { result } = await renderHook(() => dex.useBuySync()) // Place ask order to create liquidity await Actions.dex.placeSync(config, { token: base, amount: parseUnits('500', 6), type: 'sell', tick: Tick.fromPrice('1.001'), }) // Buy base tokens with quote tokens const { receipt } = await result.current.mutateAsync({ tokenIn: quote, tokenOut: base, amountOut: parseUnits('100', 6), maxAmountIn: parseUnits('150', 6), }) expect(receipt).toBeDefined() expect(receipt.status).toBe('success') await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) }) test('behavior: respects maxAmountIn', async () => { const { base, quote } = await setupTokenPair() const { result } = await renderHook(() => dex.useBuySync()) // Place ask order at high price await Actions.dex.placeSync(config, { token: base, amount: parseUnits('500', 6), type: 'sell', tick: Tick.fromPrice('1.01'), // 1% above peg }) // Try to buy with insufficient maxAmountIn - should fail await expect( result.current.mutateAsync({ tokenIn: quote, tokenOut: base, amountOut: parseUnits('100', 6), maxAmountIn: parseUnits('50', 6), // Way too low for 1% premium }), ).rejects.toThrow('The contract function "swapExactAmountOut" reverted') }) test('behavior: fails with insufficient liquidity', async () => { const { base, quote } = await setupTokenPair() const { result } = await renderHook(() => dex.useBuySync()) // Don't place any orders - no liquidity // Try to buy - should fail due to no liquidity await expect( result.current.mutateAsync({ tokenIn: quote, tokenOut: base, amountOut: parseUnits('100', 6), maxAmountIn: parseUnits('150', 6), }), ).rejects.toThrow('The contract function "swapExactAmountOut" reverted') }) }) describe('useCancel', () => { test('default', async () => { const { base, quote } = await setupTokenPair() const { result } = await renderHook(() => ({ place: dex.usePlaceSync(), cancel: dex.useCancelSync(), })) // Place a bid order const { orderId } = await result.current.place.mutateAsync({ token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) // Check initial DEX balance (should be 0) const dexBalanceBefore = await Actions.dex.getBalance(config, { account: account.address, token: quote, }) expect(dexBalanceBefore).toBe(0n) // Cancel the order const { receipt, orderId: returnedOrderId } = await result.current.cancel.mutateAsync({ orderId, }) expect(receipt).toBeDefined() expect(receipt.status).toBe('success') expect(returnedOrderId).toBe(orderId) await vi.waitFor(() => expect(result.current.cancel.isSuccess).toBeTruthy()) // Check DEX balance after cancel - tokens should be refunded to internal balance const dexBalanceAfter = await Actions.dex.getBalance(config, { account: account.address, token: quote, }) expect(dexBalanceAfter).toBeGreaterThan(0n) }) test('behavior: only maker can cancel', async () => { const { base } = await setupTokenPair() const { result } = await renderHook(() => ({ connect: useConnect(), place: dex.usePlaceSync(), cancel: dex.useCancelSync(), })) // Account places order const { orderId } = await result.current.place.mutateAsync({ token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) // Transfer gas to account2 await Actions.token.transferSync(config, { to: account2.address, amount: parseUnits('1', 6), token: addresses.alphaUsd, }) // Use a different account via the connector await result.current.connect.connectAsync({ connector: config.connectors[1]!, }) // Account2 tries to cancel - should fail await expect( result.current.cancel.mutateAsync({ orderId, }), ).rejects.toThrow('The contract function "cancel" reverted') }) test('behavior: cannot cancel non-existent order', async () => { await setupTokenPair() const { result } = await renderHook(() => dex.useCancelSync()) // Try to cancel an order that doesn't exist await expect( result.current.mutateAsync({ orderId: 999n, }), ).rejects.toThrow('The contract function "cancel" reverted') }) }) describe('useCreatePair', () => { test('default', async () => { await setupTokenPair() // This ensures connection const { result } = await renderHook(() => dex.useCreatePairSync()) const { token: baseToken } = await Actions.token.createSync(config, { name: 'Test Base Token', symbol: 'BASE', currency: 'USD', admin: account, }) const { receipt, ...resultData } = await result.current.mutateAsync({ base: baseToken, }) expect(receipt).toBeDefined() expect(receipt.status).toBe('success') const { key, ...rest } = resultData expect(key).toBeDefined() expect(rest).toEqual( expect.objectContaining({ base: expect.toSatisfy(isAddress), quote: expect.toSatisfy(isAddress), }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) }) }) describe('useBalance', () => { test('default', async () => { const { base, quote } = await setupTokenPair() const { result, rerender } = await renderHook( (props) => dex.useBalance({ account: props?.account, token: quote }), { initialProps: { account: undefined as Address | undefined } }, ) await vi.waitFor(() => expect(result.current.fetchStatus).toBe('idle')) // Verify initial state (disabled/pending when account missing) expect(result.current.status).toBe('pending') // Set account and rerender rerender({ account: accounts[0].address }) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) // Initial balance should be 0 expect(result.current.data).toBe(0n) // Place and cancel order to create internal balance const { orderId } = await Actions.dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.0005'), }) await Actions.dex.cancelSync(config, { orderId, }) // Trigger refetch and verify updated balance const { data } = await result.current.refetch() expect(data).toBeGreaterThan(0n) }) test('behavior: check different account', async () => { const { quote } = await setupTokenPair() const { result } = await renderHook(() => dex.useBalance({ account: account2.address, token: quote }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) // Check account2's balance (should be 0) expect(result.current.data).toBe(0n) }) test('behavior: balances are per-token', async () => { const { base, quote } = await setupTokenPair() // Create balance in quote token const { orderId } = await Actions.dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) await Actions.dex.cancelSync(config, { orderId }) const { result } = await renderHook(() => ({ quote: dex.useBalance({ account: account.address, token: quote }), base: dex.useBalance({ account: account.address, token: base }), })) await vi.waitUntil( () => result.current.base.isSuccess && result.current.quote.isSuccess, { timeout: 50_000, }, ) // Check quote balance (should have refunded tokens) expect(result.current.quote.data).toBeGreaterThan(0n) // Check base balance (should still be 0) expect(result.current.base.data).toBe(0n) }) }) describe('useBuyQuote', () => { test('default', async () => { const { base, quote } = await setupTokenPair() // Place ask orders to create liquidity await Actions.dex.placeSync(config, { token: base, amount: parseUnits('500', 6), type: 'sell', tick: Tick.fromPrice('1.001'), }) const { result } = await renderHook(() => dex.useBuyQuote({ tokenIn: quote, tokenOut: base, amountOut: parseUnits('100', 6), }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) expect(result.current.data).toBeGreaterThan(0n) // Should be approximately 100 * 1.001 = 100.1 expect(result.current.data).toBeGreaterThan(parseUnits('100', 6)) }) test('behavior: fails with no liquidity', async () => { const { base, quote } = await setupTokenPair() // No orders placed - no liquidity const { result } = await renderHook(() => dex.useBuyQuote({ tokenIn: quote, tokenOut: base, amountOut: parseUnits('100', 6), }), ) await vi.waitUntil(() => result.current.isError, { timeout: 50_000, }) expect(result.current.error?.message).toContain('InsufficientLiquidity') }) }) describe('useOrder', () => { test('default', async () => { const { base } = await setupTokenPair() // Place an order to get an order ID const { orderId } = await Actions.dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) const { result } = await renderHook(() => dex.useOrder({ orderId, }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) const order = result.current.data! expect(order.maker).toBe(account.address) expect(order.isBid).toBe(true) expect(order.tick).toBe(Tick.fromPrice('1.001')) expect(order.amount).toBe(parseUnits('100', 6)) expect(order.remaining).toBe(parseUnits('100', 6)) expect(order.isFlip).toBe(false) }) test('behavior: returns flip order details', async () => { const { base } = await setupTokenPair() // Place a flip order const { orderId } = await Actions.dex.placeFlipSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), flipTick: Tick.fromPrice('1.002'), }) const { result } = await renderHook(() => dex.useOrder({ orderId, }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) const order = result.current.data! expect(order.maker).toBe(account.address) expect(order.isBid).toBe(true) expect(order.tick).toBe(Tick.fromPrice('1.001')) expect(order.amount).toBe(parseUnits('100', 6)) expect(order.isFlip).toBe(true) expect(order.flipTick).toBe(Tick.fromPrice('1.002')) }) test('behavior: fails for non-existent order', async () => { await setupTokenPair() const { result } = await renderHook(() => dex.useOrder({ orderId: 999n, }), ) await vi.waitUntil(() => result.current.isError, { timeout: 50_000, }) expect(result.current.error?.message).toContain('OrderDoesNotExist') }) }) describe('useOrderbook', () => { test('default', async () => { const { base, quote } = await setupTokenPair() const { result } = await renderHook(() => dex.useOrderbook({ base, quote, }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) const book = result.current.data! expect(book.base).toBe(base) expect(book.quote).toBe(quote) expect(book.bestBidTick).toBeDefined() expect(book.bestAskTick).toBeDefined() }) test('behavior: shows best bid and ask after orders placed', async () => { const { base, quote } = await setupTokenPair() const bidTick = Tick.fromPrice('0.999') const askTick = Tick.fromPrice('1.001') // Place a bid order await Actions.dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: bidTick, }) // Place an ask order await Actions.dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'sell', tick: askTick, }) const { result } = await renderHook(() => dex.useOrderbook({ base, quote, }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) const book = result.current.data! expect(book.bestBidTick).toBe(bidTick) expect(book.bestAskTick).toBe(askTick) }) }) describe('useTickLevel', () => { test('default', async () => { const { base } = await setupTokenPair() const tick = Tick.fromPrice('1.001') // Place an order to create liquidity at this tick const { orderId } = await Actions.dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick, }) const { result } = await renderHook(() => dex.useTickLevel({ base, tick, isBid: true, }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) const level = result.current.data! expect(level.head).toBe(orderId) // head should be our order expect(level.tail).toBe(orderId) // tail should also be our order (only one) expect(level.totalLiquidity).toBeGreaterThan(0n) }) test('behavior: empty price level', async () => { const { base } = await setupTokenPair() const tick = Tick.fromPrice('1.001') // Query a tick with no orders const { result } = await renderHook(() => dex.useTickLevel({ base, tick, isBid: true, }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) const level = result.current.data! expect(level.head).toBe(0n) expect(level.tail).toBe(0n) expect(level.totalLiquidity).toBe(0n) }) }) describe('useSellQuote', () => { test('default', async () => { const { base, quote } = await setupTokenPair() // Place bid orders to create liquidity await Actions.dex.placeSync(config, { token: base, amount: parseUnits('500', 6), type: 'buy', tick: Tick.fromPrice('0.999'), }) const { result } = await renderHook(() => dex.useSellQuote({ tokenIn: base, tokenOut: quote, amountIn: parseUnits('100', 6), }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) expect(result.current.data).toBeGreaterThan(0n) // Should be approximately 100 * 0.999 = 99.9 expect(result.current.data).toBeLessThan(parseUnits('100', 6)) }) test('behavior: fails with no liquidity', async () => { const { base, quote } = await setupTokenPair() // Quote should fail with no liquidity const { result } = await renderHook(() => dex.useSellQuote({ tokenIn: base, tokenOut: quote, amountIn: parseUnits('100', 6), }), ) await vi.waitUntil(() => result.current.isError, { timeout: 50_000, }) expect(result.current.error?.message).toContain('InsufficientLiquidity') }) }) describe('usePlace', () => { test('default', async () => { const { base } = await setupTokenPair() const { result } = await renderHook(() => dex.usePlaceSync()) // Place a sell order const { receipt, orderId, token, ...resultData } = await result.current.mutateAsync({ token: base, amount: parseUnits('100', 6), type: 'sell', tick: Tick.fromPrice('1.001'), }) expect(receipt).toBeDefined() expect(receipt.status).toBe('success') expect(orderId).toBeGreaterThan(0n) expect(token).toBe(base) expect(resultData).toMatchInlineSnapshot(` { "amount": 100000000n, "flipTick": 0, "isBid": false, "isFlipOrder": false, "maker": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", "tick": 100, } `) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) // Place a buy order const { receipt: receipt2, orderId: orderId2, token: token2, ...result2 } = await result.current.mutateAsync({ token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) expect(receipt2.status).toBe('success') expect(orderId2).toBeGreaterThan(0n) expect(token2).toBe(base) expect(result2).toMatchInlineSnapshot(` { "amount": 100000000n, "flipTick": 0, "isBid": true, "isFlipOrder": false, "maker": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", "tick": 100, } `) }) }) describe('usePlaceFlip', () => { test('default', async () => { const { base } = await setupTokenPair() const { result } = await renderHook(() => dex.usePlaceFlipSync()) // Place a flip bid order const { receipt, orderId, token, ...resultData } = await result.current.mutateAsync({ token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), flipTick: Tick.fromPrice('1.002'), }) expect(receipt).toBeDefined() expect(receipt.status).toBe('success') expect(orderId).toBeGreaterThan(0n) expect(token).toBe(base) expect(resultData.flipTick).toBe(Tick.fromPrice('1.002')) expect(resultData).toMatchInlineSnapshot(` { "amount": 100000000n, "flipTick": 200, "isBid": true, "isFlipOrder": true, "maker": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", "tick": 100, } `) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) }) }) describe('useSell', () => { test('default', async () => { const { base, quote } = await setupTokenPair() const { result } = await renderHook(() => dex.useSellSync()) // Place bid order to create liquidity await Actions.dex.placeSync(config, { token: base, amount: parseUnits('500', 6), type: 'buy', tick: Tick.fromPrice('0.999'), }) // Sell base tokens const { receipt } = await result.current.mutateAsync({ tokenIn: base, tokenOut: quote, amountIn: parseUnits('100', 6), minAmountOut: parseUnits('50', 6), }) expect(receipt).toBeDefined() expect(receipt.status).toBe('success') await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) }) test('behavior: respects minAmountOut', async () => { const { base, quote } = await setupTokenPair() const { result } = await renderHook(() => dex.useSellSync()) // Place bid order at low price await Actions.dex.placeSync(config, { token: base, amount: parseUnits('500', 6), type: 'buy', tick: Tick.fromPrice('0.99'), // 1% below peg }) // Try to sell with too high minAmountOut - should fail await expect( result.current.mutateAsync({ tokenIn: base, tokenOut: quote, amountIn: parseUnits('100', 6), minAmountOut: parseUnits('150', 6), // Way too high }), ).rejects.toThrow('The contract function "swapExactAmountIn" reverted') }) test('behavior: fails with insufficient liquidity', async () => { const { base, quote } = await setupTokenPair() const { result } = await renderHook(() => dex.useSellSync()) // No orders - no liquidity // Try to sell - should fail await expect( result.current.mutateAsync({ tokenIn: base, tokenOut: quote, amountIn: parseUnits('100', 6), minAmountOut: parseUnits('50', 6), }), ).rejects.toThrow('The contract function "swapExactAmountIn" reverted') }) }) describe('useWatchFlipOrderPlaced', () => { test('default', async () => { const { base } = await setupTokenPair() const { result } = await renderHook(() => dex.usePlaceFlipSync()) const events: any[] = [] await renderHook(() => dex.useWatchFlipOrderPlaced({ onFlipOrderPlaced(args) { events.push(args) }, }), ) // Place flip order to trigger event await result.current.mutateAsync({ token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), flipTick: Tick.fromPrice('1.002'), }) await vi.waitUntil(() => events.length >= 1) expect(events.length).toBeGreaterThanOrEqual(1) expect(events[0]?.flipTick).toBe(Tick.fromPrice('1.002')) expect(events[0]?.tick).toBe(Tick.fromPrice('1.001')) expect(events[0]?.isBid).toBe(true) expect(events[0]?.amount).toBe(parseUnits('100', 6)) }) }) describe('useWatchOrderCancelled', () => { test('default', async () => { const { base } = await setupTokenPair() // Place order first const { orderId } = await Actions.dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) const events: any[] = [] await renderHook(() => dex.useWatchOrderCancelled({ onOrderCancelled(args) { events.push(args) }, }), ) // Cancel order to trigger event await Actions.dex.cancelSync(config, { orderId, }) await vi.waitUntil(() => events.length >= 1) expect(events.length).toBeGreaterThanOrEqual(1) expect(events[0]?.orderId).toBe(orderId) }) test('behavior: filter by orderId', async () => { const { base } = await setupTokenPair() // Place two orders const { orderId: orderId1 } = await Actions.dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) const { orderId: orderId2 } = await Actions.dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) const events: any[] = [] await renderHook(() => dex.useWatchOrderCancelled({ orderId: orderId1, // Filter for only orderId1 onOrderCancelled(args) { events.push(args) }, }), ) // Cancel orderId1 (should be captured) await Actions.dex.cancelSync(config, { orderId: orderId1, }) // Cancel orderId2 (should NOT be captured due to filter) await Actions.dex.cancelSync(config, { orderId: orderId2, }) await vi.waitUntil(() => events.length >= 1, { timeout: 2000 }) // Should only receive 1 event (for orderId1) expect(events.length).toBe(1) expect(events[0]?.orderId).toBe(orderId1) }) }) describe('useWatchOrderFilled', () => { test('default', async () => { const { base, quote } = await setupTokenPair() // Place a sell order to create liquidity const { orderId } = await Actions.dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'sell', tick: Tick.fromPrice('1.001'), }) const events: any[] = [] await renderHook(() => dex.useWatchOrderFilled({ onOrderFilled(args) { events.push(args) }, }), ) // Buy from the order to trigger a fill await Actions.dex.buySync(config, { tokenIn: quote, tokenOut: base, amountOut: parseUnits('50', 6), maxAmountIn: parseUnits('100', 6), }) await vi.waitUntil(() => events.length >= 1) expect(events.length).toBeGreaterThanOrEqual(1) expect(events[0]?.orderId).toBe(orderId) expect(events[0]?.maker).toBe(accounts[0].address) expect(events[0]?.taker).toBe(accounts[0].address) expect(events[0]?.amountFilled).toBeGreaterThan(0n) }) test('behavior: filter by orderId', async () => { const { base, quote } = await setupTokenPair() // Place two sell orders const { orderId: orderId1 } = await Actions.dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'sell', tick: Tick.fromPrice('1.001'), }) const { orderId: orderId2 } = await Actions.dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'sell', tick: Tick.fromPrice('1.002'), }) const events: any[] = [] await renderHook(() => dex.useWatchOrderFilled({ orderId: orderId1, // Filter for only orderId1 onOrderFilled(args) { events.push(args) }, }), ) // Buy enough to fill orderId1 only (cheaper price first) await Actions.dex.buySync(config, { tokenIn: quote, tokenOut: base, amountOut: parseUnits('50', 6), maxAmountIn: parseUnits('100', 6), }) await vi.waitUntil(() => events.length >= 1, { timeout: 2000 }) // Should only receive 1 event (for orderId1) expect(events.length).toBe(1) expect(events[0]?.orderId).toBe(orderId1) // Suppress unused variable warning void orderId2 }) }) describe('useWatchOrderPlaced', () => { test('default', async () => { const { base } = await setupTokenPair() const events: any[] = [] await renderHook(() => dex.useWatchOrderPlaced({ onOrderPlaced(args) { events.push(args) }, }), ) // Place first order await Actions.dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) // Place second order await Actions.dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'sell', tick: Tick.fromPrice('0.999'), }) await vi.waitUntil(() => events.length >= 2) expect(events.length).toBeGreaterThanOrEqual(2) expect(events[0]?.isBid).toBe(true) expect(events[0]?.amount).toBe(parseUnits('100', 6)) expect(events[1]?.isBid).toBe(false) expect(events[1]?.amount).toBe(parseUnits('100', 6)) }) test('behavior: filter by token', async () => { const { base } = await setupTokenPair() const { base: base2 } = await setupTokenPair() const events: any[] = [] await renderHook(() => dex.useWatchOrderPlaced({ token: base, // Filter for only base token onOrderPlaced(args) { events.push(args) }, }), ) // Place order on base (should be captured) await Actions.dex.placeSync(config, { token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) // Place order on base2 (should NOT be captured due to filter) await Actions.dex.placeSync(config, { token: base2, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) await vi.waitUntil(() => events.length >= 1, { timeout: 2000 }) // Should only receive 1 event (for base token) expect(events.length).toBe(1) expect(events[0]?.token.toLowerCase()).toBe(base.toLowerCase()) }) }) describe('useWithdraw', () => { test('default', async () => { const { base, quote } = await setupTokenPair() const { result } = await renderHook(() => ({ place: dex.usePlaceSync(), cancel: dex.useCancelSync(), withdraw: dex.useWithdrawSync(), })) // Create internal balance const { orderId } = await result.current.place.mutateAsync({ token: base, amount: parseUnits('100', 6), type: 'buy', tick: Tick.fromPrice('1.001'), }) await result.current.cancel.mutateAsync({ orderId }) // Get DEX balance const dexBalance = await Actions.dex.getBalance(config, { account: account.address, token: quote, }) expect(dexBalance).toBeGreaterThan(0n) // Get wallet balance before withdraw const walletBalanceBefore = await Actions.token.getBalance(config, { token: quote, account: account.address, }) // Withdraw from DEX const { receipt } = await result.current.withdraw.mutateAsync({ token: quote, amount: dexBalance, }) expect(receipt).toBeDefined() expect(receipt.status).toBe('success') await vi.waitFor(() => expect(result.current.withdraw.isSuccess).toBeTruthy(), ) // Check DEX balance is now 0 const dexBalanceAfter = await Actions.dex.getBalance(config, { account: account.address, token: quote, }) expect(dexBalanceAfter).toBe(0n) // Check wallet balance increased const walletBalanceAfter = await Actions.token.getBalance(config, { token: quote, account: account.address, }) expect(walletBalanceAfter).toBeGreaterThan(walletBalanceBefore) }) }) ================================================ FILE: packages/react/src/tempo/hooks/dex.ts ================================================ import type { UseMutationResult } from '@tanstack/react-query' import type { Config, ResolvedRegister } from '@wagmi/core' import type { ConfigParameter, ExactPartial, UnionCompute, } from '@wagmi/core/internal' import { Actions } from '@wagmi/core/tempo' import { useEffect } from 'react' import { useChainId } from '../../hooks/useChainId.js' import { useConfig } from '../../hooks/useConfig.js' import { type UseMutationParameters, type UseQueryReturnType, useMutation, useQuery, } from '../../utils/query.js' import type { QueryParameter } from '../utils.js' /** * Hook for buying a specific amount of tokens. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.dex.useBuy() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useBuy< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useBuy.Parameters = {}, ): useBuy.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.dex.buy(config, variables as never) }, mutationKey: ['buy'], }) as never } export declare namespace useBuy { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.dex.buy.ReturnValue, Actions.dex.buy.ErrorType, Actions.dex.buy.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.dex.buy.ReturnValue, Actions.dex.buy.ErrorType, Actions.dex.buy.Parameters, context > } /** * Hook for buying a specific amount of tokens. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.dex.useBuySync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useBuySync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useBuySync.Parameters = {}, ): useBuySync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.dex.buySync(config, variables as never) }, mutationKey: ['buySync'], }) as never } export declare namespace useBuySync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.dex.buySync.ReturnValue, Actions.dex.buySync.ErrorType, Actions.dex.buySync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.dex.buySync.ReturnValue, Actions.dex.buySync.ErrorType, Actions.dex.buySync.Parameters, context > } /** * Hook for canceling an order from the orderbook. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.dex.useCancel() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useCancel< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useCancel.Parameters = {}, ): useCancel.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.dex.cancel(config, variables as never) }, mutationKey: ['cancel'], }) as never } export declare namespace useCancel { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.dex.cancel.ReturnValue, Actions.dex.cancel.ErrorType, Actions.dex.cancel.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.dex.cancel.ReturnValue, Actions.dex.cancel.ErrorType, Actions.dex.cancel.Parameters, context > } /** * Hook for canceling an order from the orderbook. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.dex.useCancelSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useCancelSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useCancelSync.Parameters = {}, ): useCancelSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.dex.cancelSync(config, variables as never) }, mutationKey: ['cancelSync'], }) as never } export declare namespace useCancelSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.dex.cancelSync.ReturnValue, Actions.dex.cancelSync.ErrorType, Actions.dex.cancelSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.dex.cancelSync.ReturnValue, Actions.dex.cancelSync.ErrorType, Actions.dex.cancelSync.Parameters, context > } /** * Hook for cancelling a stale order from the orderbook. * * A stale order is one where the owner's balance or allowance has dropped * below the order amount. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.dex.useCancelStale() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useCancelStale< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useCancelStale.Parameters = {}, ): useCancelStale.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.dex.cancelStale(config, variables as never) }, mutationKey: ['cancelStale'], }) as never } export declare namespace useCancelStale { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.dex.cancelStale.ReturnValue, Actions.dex.cancelStale.ErrorType, Actions.dex.cancelStale.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.dex.cancelStale.ReturnValue, Actions.dex.cancelStale.ErrorType, Actions.dex.cancelStale.Parameters, context > } /** * Hook for cancelling a stale order and waiting for confirmation. * * A stale order is one where the owner's balance or allowance has dropped * below the order amount. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.dex.useCancelStaleSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useCancelStaleSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useCancelStaleSync.Parameters = {}, ): useCancelStaleSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.dex.cancelStaleSync(config, variables as never) }, mutationKey: ['cancelStaleSync'], }) as never } export declare namespace useCancelStaleSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.dex.cancelStaleSync.ReturnValue, Actions.dex.cancelStaleSync.ErrorType, Actions.dex.cancelStaleSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.dex.cancelStaleSync.ReturnValue, Actions.dex.cancelStaleSync.ErrorType, Actions.dex.cancelStaleSync.Parameters, context > } /** * Hook for creating a new trading pair on the DEX. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.dex.useCreatePair() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useCreatePair< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useCreatePair.Parameters = {}, ): useCreatePair.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.dex.createPair(config, variables as never) }, mutationKey: ['createPair'], }) as never } export declare namespace useCreatePair { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.dex.createPair.ReturnValue, Actions.dex.createPair.ErrorType, Actions.dex.createPair.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.dex.createPair.ReturnValue, Actions.dex.createPair.ErrorType, Actions.dex.createPair.Parameters, context > } /** * Hook for creating a new trading pair on the DEX. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.dex.useCreatePairSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useCreatePairSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useCreatePairSync.Parameters = {}, ): useCreatePairSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.dex.createPairSync(config, variables as never) }, mutationKey: ['createPairSync'], }) as never } export declare namespace useCreatePairSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.dex.createPairSync.ReturnValue, Actions.dex.createPairSync.ErrorType, Actions.dex.createPairSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.dex.createPairSync.ReturnValue, Actions.dex.createPairSync.ErrorType, Actions.dex.createPairSync.Parameters, context > } /** * Hook for getting a user's token balance on the DEX. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data, isLoading } = Hooks.dex.useBalance({ * account: '0x...', * token: '0x20c...11', * }) * * if (isLoading) return
Loading...
* return
Balance: {data}
* } * ``` * * @param parameters - Parameters. * @returns Query result with the user's token balance on the DEX. */ export function useBalance< config extends Config = ResolvedRegister['config'], selectData = Actions.dex.getBalance.ReturnValue, >( parameters: useBalance.Parameters, ): useBalance.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.dex.getBalance.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace useBalance { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.dex.getBalance.ReturnValue, > = ConfigParameter & QueryParameter< Actions.dex.getBalance.ReturnValue, Actions.dex.getBalance.ErrorType, selectData, Actions.dex.getBalance.QueryKey > & ExactPartial> export type ReturnValue = UseQueryReturnType } /** * Hook for getting the quote for buying a specific amount of tokens. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data, isLoading } = Hooks.dex.useBuyQuote({ * amountOut: parseUnits('100', 6), * tokenIn: '0x20c...11', * tokenOut: '0x20c...20', * }) * * if (isLoading) return
Loading...
* return
Required Input: {data}
* } * ``` * * @param parameters - Parameters. * @returns Query result with the amount of tokenIn needed. */ export function useBuyQuote< config extends Config = ResolvedRegister['config'], selectData = Actions.dex.getBuyQuote.ReturnValue, >( parameters: useBuyQuote.Parameters, ): useBuyQuote.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.dex.getBuyQuote.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace useBuyQuote { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.dex.getBuyQuote.ReturnValue, > = ConfigParameter & QueryParameter< Actions.dex.getBuyQuote.ReturnValue, Actions.dex.getBuyQuote.ErrorType, selectData, Actions.dex.getBuyQuote.QueryKey > & ExactPartial> export type ReturnValue = UseQueryReturnType } /** * Hook for getting an order's details from the orderbook. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data, isLoading } = Hooks.dex.useOrder({ * orderId: 123n, * }) * * if (isLoading) return
Loading...
* return
Order: {JSON.stringify(data)}
* } * ``` * * @param parameters - Parameters. * @returns Query result with the order details. */ export function useOrder< config extends Config = ResolvedRegister['config'], selectData = Actions.dex.getOrder.ReturnValue, >( parameters: useOrder.Parameters, ): useOrder.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.dex.getOrder.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace useOrder { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.dex.getOrder.ReturnValue, > = ConfigParameter & QueryParameter< Actions.dex.getOrder.ReturnValue, Actions.dex.getOrder.ErrorType, selectData, Actions.dex.getOrder.QueryKey > & ExactPartial> export type ReturnValue = UseQueryReturnType } /** * Hook for getting orderbook information for a trading pair. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data, isLoading } = Hooks.dex.useOrderbook({ * base: '0x20c...11', * quote: '0x20c...20', * }) * * if (isLoading) return
Loading...
* return
Orderbook: {JSON.stringify(data)}
* } * ``` * * @param parameters - Parameters. * @returns Query result with the orderbook information. */ export function useOrderbook< config extends Config = ResolvedRegister['config'], selectData = Actions.dex.getOrderbook.ReturnValue, >( parameters: useOrderbook.Parameters, ): useOrderbook.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.dex.getOrderbook.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace useOrderbook { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.dex.getOrderbook.ReturnValue, > = ConfigParameter & QueryParameter< Actions.dex.getOrderbook.ReturnValue, Actions.dex.getOrderbook.ErrorType, selectData, Actions.dex.getOrderbook.QueryKey > & ExactPartial> export type ReturnValue = UseQueryReturnType } /** * Hook for getting the tick level information at a specific tick. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * import { Tick } from 'viem/tempo' * * function App() { * const { data, isLoading } = Hooks.dex.useTickLevel({ * base: '0x20c...11', * tick: Tick.fromPrice('1.001'), * isBid: true, * }) * * if (isLoading) return
Loading...
* return
Tick Level: {JSON.stringify(data)}
* } * ``` * * @param parameters - Parameters. * @returns Query result with the tick level information. */ export function useTickLevel< config extends Config = ResolvedRegister['config'], selectData = Actions.dex.getTickLevel.ReturnValue, >( parameters: useTickLevel.Parameters, ): useTickLevel.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.dex.getTickLevel.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace useTickLevel { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.dex.getTickLevel.ReturnValue, > = ConfigParameter & QueryParameter< Actions.dex.getTickLevel.ReturnValue, Actions.dex.getTickLevel.ErrorType, selectData, Actions.dex.getTickLevel.QueryKey > & ExactPartial> export type ReturnValue = UseQueryReturnType } /** * Hook for getting the quote for selling a specific amount of tokens. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data, isLoading } = Hooks.dex.useSellQuote({ * amountIn: parseUnits('100', 6), * tokenIn: '0x20c...11', * tokenOut: '0x20c...20', * }) * * if (isLoading) return
Loading...
* return
Expected Output: {data}
* } * ``` * * @param parameters - Parameters. * @returns Query result with the amount of tokenOut received. */ export function useSellQuote< config extends Config = ResolvedRegister['config'], selectData = Actions.dex.getSellQuote.ReturnValue, >( parameters: useSellQuote.Parameters, ): useSellQuote.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.dex.getSellQuote.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace useSellQuote { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.dex.getSellQuote.ReturnValue, > = ConfigParameter & QueryParameter< Actions.dex.getSellQuote.ReturnValue, Actions.dex.getSellQuote.ErrorType, selectData, Actions.dex.getSellQuote.QueryKey > & ExactPartial> export type ReturnValue = UseQueryReturnType } /** * Hook for placing a limit order on the orderbook. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.dex.usePlace() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function usePlace< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: usePlace.Parameters = {}, ): usePlace.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.dex.place(config, variables as never) }, mutationKey: ['place'], }) as never } export declare namespace usePlace { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.dex.place.ReturnValue, Actions.dex.place.ErrorType, Actions.dex.place.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.dex.place.ReturnValue, Actions.dex.place.ErrorType, Actions.dex.place.Parameters, context > } /** * Hook for placing a flip order that automatically flips when filled. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.dex.usePlaceFlip() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function usePlaceFlip< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: usePlaceFlip.Parameters = {}, ): usePlaceFlip.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.dex.placeFlip(config, variables as never) }, mutationKey: ['placeFlip'], }) as never } export declare namespace usePlaceFlip { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.dex.placeFlip.ReturnValue, Actions.dex.placeFlip.ErrorType, Actions.dex.placeFlip.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.dex.placeFlip.ReturnValue, Actions.dex.placeFlip.ErrorType, Actions.dex.placeFlip.Parameters, context > } /** * Hook for placing a flip order that automatically flips when filled. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.dex.usePlaceFlipSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function usePlaceFlipSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: usePlaceFlipSync.Parameters = {}, ): usePlaceFlipSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.dex.placeFlipSync(config, variables as never) }, mutationKey: ['placeFlipSync'], }) as never } export declare namespace usePlaceFlipSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.dex.placeFlipSync.ReturnValue, Actions.dex.placeFlipSync.ErrorType, Actions.dex.placeFlipSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.dex.placeFlipSync.ReturnValue, Actions.dex.placeFlipSync.ErrorType, Actions.dex.placeFlipSync.Parameters, context > } /** * Hook for placing a limit order on the orderbook. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.dex.usePlaceSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function usePlaceSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: usePlaceSync.Parameters = {}, ): usePlaceSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.dex.placeSync(config, variables as never) }, mutationKey: ['placeSync'], }) as never } export declare namespace usePlaceSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.dex.placeSync.ReturnValue, Actions.dex.placeSync.ErrorType, Actions.dex.placeSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.dex.placeSync.ReturnValue, Actions.dex.placeSync.ErrorType, Actions.dex.placeSync.Parameters, context > } /** * Hook for selling a specific amount of tokens. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.dex.useSell() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useSell< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useSell.Parameters = {}, ): useSell.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.dex.sell(config, variables as never) }, mutationKey: ['sell'], }) as never } export declare namespace useSell { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.dex.sell.ReturnValue, Actions.dex.sell.ErrorType, Actions.dex.sell.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.dex.sell.ReturnValue, Actions.dex.sell.ErrorType, Actions.dex.sell.Parameters, context > } /** * Hook for selling a specific amount of tokens. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.dex.useSellSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useSellSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useSellSync.Parameters = {}, ): useSellSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.dex.sellSync(config, variables as never) }, mutationKey: ['sellSync'], }) as never } export declare namespace useSellSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.dex.sellSync.ReturnValue, Actions.dex.sellSync.ErrorType, Actions.dex.sellSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.dex.sellSync.ReturnValue, Actions.dex.sellSync.ErrorType, Actions.dex.sellSync.Parameters, context > } /** * Hook for withdrawing tokens from the DEX to the caller's wallet. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.dex.useWithdraw() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useWithdraw< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useWithdraw.Parameters = {}, ): useWithdraw.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.dex.withdraw(config, variables as never) }, mutationKey: ['withdraw'], }) as never } export declare namespace useWithdraw { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.dex.withdraw.ReturnValue, Actions.dex.withdraw.ErrorType, Actions.dex.withdraw.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.dex.withdraw.ReturnValue, Actions.dex.withdraw.ErrorType, Actions.dex.withdraw.Parameters, context > } /** * Hook for withdrawing tokens from the DEX to the caller's wallet. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.dex.useWithdrawSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useWithdrawSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useWithdrawSync.Parameters = {}, ): useWithdrawSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.dex.withdrawSync(config, variables as never) }, mutationKey: ['withdrawSync'], }) as never } export declare namespace useWithdrawSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.dex.withdrawSync.ReturnValue, Actions.dex.withdrawSync.ErrorType, Actions.dex.withdrawSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.dex.withdrawSync.ReturnValue, Actions.dex.withdrawSync.ErrorType, Actions.dex.withdrawSync.Parameters, context > } /** * Hook for watching flip order placement events on the DEX. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.dex.useWatchFlipOrderPlaced({ * onFlipOrderPlaced(args) { * console.log('Flip order placed:', args) * }, * }) * * return
Watching for flip order placements...
* } * ``` * * @param parameters - Parameters. */ export function useWatchFlipOrderPlaced< config extends Config = ResolvedRegister['config'], >(parameters: useWatchFlipOrderPlaced.Parameters = {}) { const { enabled = true, onFlipOrderPlaced, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onFlipOrderPlaced) return return Actions.dex.watchFlipOrderPlaced(config, { ...rest, chainId, onFlipOrderPlaced, }) }, [ config, enabled, chainId, onFlipOrderPlaced, rest.fromBlock, rest.maker, rest.onError, rest.poll, rest.pollingInterval, rest.token, ]) } export declare namespace useWatchFlipOrderPlaced { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } /** * Hook for watching order cancellation events on the DEX. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.dex.useWatchOrderCancelled({ * onOrderCancelled(args) { * console.log('Order cancelled:', args) * }, * }) * * return
Watching for order cancellations...
* } * ``` * * @param parameters - Parameters. */ export function useWatchOrderCancelled< config extends Config = ResolvedRegister['config'], >(parameters: useWatchOrderCancelled.Parameters = {}) { const { enabled = true, onOrderCancelled, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onOrderCancelled) return return Actions.dex.watchOrderCancelled(config, { ...rest, chainId, onOrderCancelled, }) }, [ config, enabled, chainId, onOrderCancelled, rest.fromBlock, rest.onError, rest.orderId, rest.poll, rest.pollingInterval, ]) } export declare namespace useWatchOrderCancelled { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } /** * Hook for watching order filled events on the DEX. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.dex.useWatchOrderFilled({ * onOrderFilled(args) { * console.log('Order filled:', args) * }, * }) * * return
Watching for order fills...
* } * ``` * * @param parameters - Parameters. */ export function useWatchOrderFilled< config extends Config = ResolvedRegister['config'], >(parameters: useWatchOrderFilled.Parameters = {}) { const { enabled = true, onOrderFilled, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onOrderFilled) return return Actions.dex.watchOrderFilled(config, { ...rest, chainId, onOrderFilled, }) }, [ config, enabled, chainId, onOrderFilled, rest.fromBlock, rest.maker, rest.onError, rest.orderId, rest.poll, rest.pollingInterval, rest.taker, ]) } export declare namespace useWatchOrderFilled { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } /** * Hook for watching order placement events on the DEX. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.dex.useWatchOrderPlaced({ * onOrderPlaced(args) { * console.log('Order placed:', args) * }, * }) * * return
Watching for order placements...
* } * ``` * * @param parameters - Parameters. */ export function useWatchOrderPlaced< config extends Config = ResolvedRegister['config'], >(parameters: useWatchOrderPlaced.Parameters = {}) { const { enabled = true, onOrderPlaced, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onOrderPlaced) return return Actions.dex.watchOrderPlaced(config, { ...rest, chainId, onOrderPlaced, }) }, [ config, enabled, chainId, onOrderPlaced, rest.fromBlock, rest.maker, rest.onError, rest.poll, rest.pollingInterval, rest.token, ]) } export declare namespace useWatchOrderPlaced { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } ================================================ FILE: packages/react/src/tempo/hooks/faucet.ts ================================================ import type { UseMutationResult } from '@tanstack/react-query' import type { Config, ResolvedRegister } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { Actions } from '@wagmi/core/tempo' import { useConfig } from '../../hooks/useConfig.js' import { type UseMutationParameters, useMutation } from '../../utils/query.js' /** * Hook for funding an account with an initial amount of set token(s) * on Tempo's testnet. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.faucet.useFund() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useFund< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useFund.Parameters = {}, ): useFund.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.faucet.fund(config, variables) }, mutationKey: ['fund'], }) } export declare namespace useFund { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.faucet.fund.ReturnValue, Actions.faucet.fund.ErrorType, Actions.faucet.fund.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.faucet.fund.ReturnValue, Actions.faucet.fund.ErrorType, Actions.faucet.fund.Parameters, context > } /** * Hook for funding an account with an initial amount of set token(s) * on Tempo's testnet. Returns the transaction receipts. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.faucet.useFundSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useFundSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useFundSync.Parameters = {}, ): useFundSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.faucet.fundSync(config, variables) }, mutationKey: ['fundSync'], }) } export declare namespace useFundSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.faucet.fundSync.ReturnValue, Actions.faucet.fundSync.ErrorType, Actions.faucet.fundSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.faucet.fundSync.ReturnValue, Actions.faucet.fundSync.ErrorType, Actions.faucet.fundSync.Parameters, context > } ================================================ FILE: packages/react/src/tempo/hooks/fee.test.ts ================================================ import { accounts, config, renderHook } from '@wagmi/test/tempo' import type { Address } from 'viem' import { describe, expect, test, vi } from 'vitest' import { useConnect } from '../../hooks/useConnect.js' import { useSetUserToken, useSetUserTokenSync, useUserToken } from './fee.js' describe('useUserToken', () => { test('default', async () => { const { result, rerender } = await renderHook( (props) => useUserToken({ account: props?.account }), { initialProps: { account: undefined as Address | undefined } }, ) await vi.waitFor(() => expect(result.current.fetchStatus).toBe('idle')) expect(result.current).toMatchInlineSnapshot(` { "data": undefined, "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "getUserToken", { "account": undefined, "chainId": 1337, }, ], "refetch": [Function], "status": "pending", } `) rerender({ account: accounts[0].address }) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy(), { timeout: 10_000, }) expect(result.current).toMatchInlineSnapshot(` { "data": { "address": "0x20C0000000000000000000000000000000000001", "id": 1n, }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getUserToken", { "account": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", "chainId": 1337, }, ], "refetch": [Function], "status": "success", } `) }) }) describe('useSetUserToken', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), setUserToken: useSetUserToken(), })) await result.current.connect.connectAsync({ connector: config.connectors[0]!, }) const hash = await result.current.setUserToken.mutateAsync({ token: '0x20C0000000000000000000000000000000000001', }) expect(hash).toBeDefined() await vi.waitFor(() => expect(result.current.setUserToken.isSuccess).toBeTruthy(), ) }) }) describe('useSetUserTokenSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), setUserToken: useSetUserTokenSync(), })) await result.current.connect.connectAsync({ connector: config.connectors[0]!, }) const data = await result.current.setUserToken.mutateAsync({ token: '0x20C0000000000000000000000000000000000001', }) expect(data).toBeDefined() await vi.waitFor(() => expect(result.current.setUserToken.isSuccess).toBeTruthy(), ) }) }) ================================================ FILE: packages/react/src/tempo/hooks/fee.ts ================================================ import type { UseMutationResult } from '@tanstack/react-query' import type { Config, ResolvedRegister } from '@wagmi/core' import type { ConfigParameter, ExactPartial, UnionCompute, } from '@wagmi/core/internal' import { Actions } from '@wagmi/core/tempo' import { useEffect } from 'react' import { useChainId } from '../../hooks/useChainId.js' import { useConfig } from '../../hooks/useConfig.js' import { type UseMutationParameters, type UseQueryReturnType, useMutation, useQuery, } from '../../utils/query.js' import type { QueryParameter } from '../utils.js' /** * Hook for getting the user's default fee token. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data, isLoading } = Hooks.fee.useUserToken({ * account: '0x20c...0055', * }) * * if (isLoading) return
Loading...
* return
Token: {data?.address}
* } * ``` * * @param parameters - Parameters. * @returns Query result with token address and ID. */ export function useUserToken< config extends Config = ResolvedRegister['config'], selectData = Actions.fee.getUserToken.ReturnValue, >( parameters: useUserToken.Parameters, ): useUserToken.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.fee.getUserToken.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace useUserToken { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.fee.getUserToken.ReturnValue, > = ConfigParameter & QueryParameter< Actions.fee.getUserToken.ReturnValue, Actions.fee.getUserToken.ErrorType, selectData, Actions.fee.getUserToken.QueryKey > & ExactPartial> export type ReturnValue = UseQueryReturnType } /** * Hook for setting the user's default fee token. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.fee.useSetUserToken() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useSetUserToken< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useSetUserToken.Parameters = {}, ): useSetUserToken.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.fee.setUserToken(config, variables as never) }, mutationKey: ['setUserToken'], }) as never } export declare namespace useSetUserToken { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.fee.setUserToken.ReturnValue, Actions.fee.setUserToken.ErrorType, Actions.fee.setUserToken.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.fee.setUserToken.ReturnValue, Actions.fee.setUserToken.ErrorType, Actions.fee.setUserToken.Parameters, context > } /** * Hook for setting the user's default fee token. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.fee.useSetUserTokenSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useSetUserTokenSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useSetUserTokenSync.Parameters = {}, ): useSetUserTokenSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.fee.setUserTokenSync(config, variables as never) }, mutationKey: ['setUserTokenSync'], }) as never } export declare namespace useSetUserTokenSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.fee.setUserTokenSync.ReturnValue, Actions.fee.setUserTokenSync.ErrorType, Actions.fee.setUserTokenSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.fee.setUserTokenSync.ReturnValue, Actions.fee.setUserTokenSync.ErrorType, Actions.fee.setUserTokenSync.Parameters, context > } /** * Hook for watching user token set events. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.fee.useWatchSetUserToken({ * onUserTokenSet(args) { * console.log('User token set:', args) * }, * }) * * return
Watching for user token changes...
* } * ``` * * @param parameters - Parameters. */ export function useWatchSetUserToken< config extends Config = ResolvedRegister['config'], >(parameters: useWatchSetUserToken.Parameters = {}) { const { enabled = true, onUserTokenSet, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onUserTokenSet) return return Actions.fee.watchSetUserToken(config, { ...rest, chainId, onUserTokenSet, }) }, [ config, enabled, chainId, onUserTokenSet, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, ]) } export declare namespace useWatchSetUserToken { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } ================================================ FILE: packages/react/src/tempo/hooks/index.ts ================================================ /** biome-ignore-all lint/performance/noReExportAll: entrypoint */ // biome-ignore lint/performance/noBarrelFile: stable export * as amm from './amm.js' export * as dex from './dex.js' export * as faucet from './faucet.js' export * as fee from './fee.js' export * as nonce from './nonce.js' export * as policy from './policy.js' export * as reward from './reward.js' export * as token from './token.js' ================================================ FILE: packages/react/src/tempo/hooks/nonce.test.ts ================================================ import { accounts, renderHook, restart } from '@wagmi/test/tempo' import type { Address } from 'viem' import { beforeEach, describe, expect, test, vi } from 'vitest' import * as nonce from './nonce.js' import * as token from './token.js' const account = accounts[0] const account2 = accounts[1] beforeEach(async () => { await restart() }) describe('useNonce', () => { test('default', async () => { const { result, rerender } = await renderHook( (props) => nonce.useNonce({ account: props?.account, nonceKey: props?.nonceKey, }), { initialProps: { account: undefined as Address | undefined, nonceKey: undefined as bigint | undefined, }, }, ) await vi.waitFor(() => expect(result.current.fetchStatus).toBe('idle')) // Should be disabled when account is undefined expect(result.current.data).toBeUndefined() expect(result.current.isPending).toBe(true) // expect(result.current.isEnabled).toBe(false) // Set account and nonceKey rerender({ account: account.address, nonceKey: 1n }) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy(), { timeout: 10_000, }) // Should now be enabled and have data // expect(result.current.isEnabled).toBe(true) expect(result.current.data).toBe(0n) }) test('reactivity: account parameter', async () => { const { result, rerender } = await renderHook( (props) => nonce.useNonce({ account: props?.account, nonceKey: 1n }), { initialProps: { account: undefined as Address | undefined } }, ) await vi.waitFor(() => expect(result.current.fetchStatus).toBe('idle')) // Should be disabled when account is undefined // expect(result.current.isEnabled).toBe(false) // Set account rerender({ account: account.address }) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy(), { timeout: 10_000, }) // expect(result.current.isEnabled).toBe(true) expect(result.current.data).toBe(0n) }) test('reactivity: nonceKey parameter', async () => { const { result, rerender } = await renderHook( (props) => nonce.useNonce({ account: account.address, nonceKey: props?.nonceKey, }), { initialProps: { nonceKey: undefined as bigint | undefined } }, ) await vi.waitFor(() => expect(result.current.fetchStatus).toBe('idle')) // Should be disabled when nonceKey is undefined // expect(result.current.isEnabled).toBe(false) // Set nonceKey rerender({ nonceKey: 1n }) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy(), { timeout: 10_000, }) // expect(result.current.isEnabled).toBe(true) expect(result.current.data).toBe(0n) }) }) describe('useWatchNonceIncremented', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ transferSync: token.useTransferSync(), })) const events: any[] = [] await renderHook(() => nonce.useWatchNonceIncremented({ onNonceIncremented(args) { events.push(args) }, args: { account: account.address, nonceKey: 5n, }, }), ) // Have to manually set nonce because eth_FillTransaction does not support nonce keys await connectResult.current.transferSync.mutateAsync({ to: account2.address, amount: 1n, token: 1n, nonceKey: 5n, nonce: 0, }) await connectResult.current.transferSync.mutateAsync({ to: account2.address, amount: 1n, token: 1n, nonceKey: 5n, nonce: 1, }) await vi.waitUntil(() => events.length >= 2) expect(events).toHaveLength(2) expect(events[0]?.account).toBe(account.address) expect(events[0]?.nonceKey).toBe(5n) expect(events[0]?.newNonce).toBe(1n) expect(events[1]?.newNonce).toBe(2n) }) }) ================================================ FILE: packages/react/src/tempo/hooks/nonce.ts ================================================ import type { Config, ResolvedRegister } from '@wagmi/core' import type { ConfigParameter, ExactPartial, UnionCompute, } from '@wagmi/core/internal' import { Actions } from '@wagmi/core/tempo' import { useEffect } from 'react' import { useChainId } from '../../hooks/useChainId.js' import { useConfig } from '../../hooks/useConfig.js' import { type UseQueryReturnType, useQuery } from '../../utils/query.js' import type { QueryParameter } from '../utils.js' /** * Hook for getting the nonce for an account and nonce key. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data, isLoading } = Hooks.nonce.useNonce({ * account: '0x...', * nonceKey: 1n, * }) * * if (isLoading) return
Loading...
* return
Nonce: {data?.toString()}
* } * ``` * * @param parameters - Parameters. * @returns Query result with nonce value. */ export function useNonce< config extends Config = ResolvedRegister['config'], selectData = Actions.nonce.getNonce.ReturnValue, >( parameters: useNonce.Parameters = {}, ): useNonce.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.nonce.getNonce.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace useNonce { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.nonce.getNonce.ReturnValue, > = ConfigParameter & QueryParameter< Actions.nonce.getNonce.ReturnValue, Actions.nonce.getNonce.ErrorType, selectData, Actions.nonce.getNonce.QueryKey > & ExactPartial> export type ReturnValue = UseQueryReturnType } /** * Hook for watching nonce incremented events. * * @deprecated This function has been deprecated post-AllegroModerato. It will be removed in a future version. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.nonce.useWatchNonceIncremented({ * onNonceIncremented(args, log) { * console.log('Nonce incremented:', args) * }, * }) * * return
Watching for nonce increments...
* } * ``` * * @param parameters - Parameters. */ export function useWatchNonceIncremented< config extends Config = ResolvedRegister['config'], >(parameters: useWatchNonceIncremented.Parameters = {}) { const { enabled = true, onNonceIncremented, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onNonceIncremented) return return Actions.nonce.watchNonceIncremented(config, { ...rest, chainId, onNonceIncremented, }) }, [ config, enabled, chainId, onNonceIncremented, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, ]) } export declare namespace useWatchNonceIncremented { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } ================================================ FILE: packages/react/src/tempo/hooks/policy.test.ts ================================================ import { Actions } from '@wagmi/core/tempo' import { accounts, config, queryClient, renderHook } from '@wagmi/test/tempo' import type { Address } from 'viem' import { describe, expect, test, vi } from 'vitest' import { useConnect } from '../../hooks/useConnect.js' import * as policy from './policy.js' const account = accounts[0] const account2 = accounts[1] describe('useCreate', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: policy.useCreateSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // create whitelist policy const { receipt, ...createResult } = await result.current.createSync.mutateAsync({ type: 'whitelist', }) expect(receipt).toBeDefined() expect(createResult).toMatchInlineSnapshot(` { "policyId": 2n, "policyType": 0, "updater": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", } `) const { policyId } = createResult // verify policy was created const data = await Actions.policy.getData(config, { policyId, }) expect(data.admin).toBe(account.address) expect(data.type).toBe('whitelist') }) test('behavior: blacklist', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: policy.useCreateSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // create blacklist policy const { receipt: blacklistReceipt, ...blacklistResult } = await result.current.createSync.mutateAsync({ type: 'blacklist', }) expect(blacklistReceipt).toBeDefined() expect(blacklistResult).toMatchInlineSnapshot(` { "policyId": 3n, "policyType": 1, "updater": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", } `) const { policyId } = blacklistResult // verify policy was created const data = await Actions.policy.getData(config, { policyId, }) expect(data.admin).toBe(account.address) expect(data.type).toBe('blacklist') }) }) describe('useSetAdmin', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: policy.useCreateSync(), setAdminSync: policy.useSetAdminSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // create policy const { policyId } = await result.current.createSync.mutateAsync({ type: 'whitelist', }) // set new admin const { receipt: setAdminReceipt, ...setAdminResult } = await result.current.setAdminSync.mutateAsync({ policyId, admin: account2.address, }) expect(setAdminReceipt).toBeDefined() expect(setAdminResult).toMatchInlineSnapshot(` { "admin": "0x8C8d35429F74ec245F8Ef2f4Fd1e551cFF97d650", "policyId": 4n, "updater": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", } `) { // verify new admin const data = await Actions.policy.getData(config, { policyId }) expect(data.admin).toBe(account2.address) } }) }) describe('useModifyWhitelist', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: policy.useCreateSync(), modifyWhitelistSync: policy.useModifyWhitelistSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // create whitelist policy const { policyId } = await result.current.createSync.mutateAsync({ type: 'whitelist', }) // verify account2 is not authorized { const isAuthorized = await Actions.policy.isAuthorized(config, { policyId, user: account2.address, }) expect(isAuthorized).toBe(false) } // add account2 to whitelist const { receipt: addReceipt, ...addResult } = await result.current.modifyWhitelistSync.mutateAsync({ policyId, address: account2.address, allowed: true, }) expect(addReceipt).toBeDefined() expect(addResult).toMatchInlineSnapshot(` { "account": "0x8C8d35429F74ec245F8Ef2f4Fd1e551cFF97d650", "allowed": true, "policyId": 5n, "updater": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", } `) // verify account2 is authorized { const isAuthorized = await Actions.policy.isAuthorized(config, { policyId, user: account2.address, }) expect(isAuthorized).toBe(true) } // remove account2 from whitelist const { receipt: removeReceipt, ...removeResult } = await result.current.modifyWhitelistSync.mutateAsync({ policyId, address: account2.address, allowed: false, }) expect(removeReceipt).toBeDefined() expect(removeResult).toMatchInlineSnapshot(` { "account": "0x8C8d35429F74ec245F8Ef2f4Fd1e551cFF97d650", "allowed": false, "policyId": 5n, "updater": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", } `) // verify account2 is no longer authorized { const isAuthorized = await Actions.policy.isAuthorized(config, { policyId, user: account2.address, }) expect(isAuthorized).toBe(false) } }) }) describe('useModifyBlacklist', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: policy.useCreateSync(), modifyBlacklistSync: policy.useModifyBlacklistSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // create blacklist policy const { policyId } = await result.current.createSync.mutateAsync({ type: 'blacklist', }) // verify account2 is authorized (not blacklisted) { const isAuthorized = await Actions.policy.isAuthorized(config, { policyId, user: account2.address, }) expect(isAuthorized).toBe(true) } // add account2 to blacklist const { receipt: addBlacklistReceipt, ...addBlacklistResult } = await result.current.modifyBlacklistSync.mutateAsync({ policyId, address: account2.address, restricted: true, }) expect(addBlacklistReceipt).toBeDefined() expect(addBlacklistResult).toMatchInlineSnapshot(` { "account": "0x8C8d35429F74ec245F8Ef2f4Fd1e551cFF97d650", "policyId": 6n, "restricted": true, "updater": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", } `) // verify account2 is not authorized (blacklisted) { const isAuthorized = await Actions.policy.isAuthorized(config, { policyId, user: account2.address, }) expect(isAuthorized).toBe(false) } // remove account2 from blacklist const removeResult = await result.current.modifyBlacklistSync.mutateAsync({ policyId, address: account2.address, restricted: false, }) expect(removeResult.receipt).toBeDefined() expect(removeResult.policyId).toBe(policyId) expect(removeResult.account).toBe(account2.address) expect(removeResult.restricted).toBe(false) expect(removeResult.updater).toBe(account.address) // verify account2 is authorized again { const isAuthorized = await Actions.policy.isAuthorized(config, { policyId, user: account2.address, }) expect(isAuthorized).toBe(true) } }) }) describe('useData', () => { test('default', async () => { const { result: setupResult } = await renderHook(() => ({ connect: useConnect(), createSync: policy.useCreateSync(), })) await setupResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // create policy const { policyId } = await setupResult.current.createSync.mutateAsync({ type: 'whitelist', }) { // get policy data const { result } = await renderHook(() => policy.useData({ policyId })) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) expect(result.current.data?.admin).toBe(account.address) expect(result.current.data?.type).toBe('whitelist') } }) test('behavior: blacklist', async () => { const { result: setupResult } = await renderHook(() => ({ connect: useConnect(), createSync: policy.useCreateSync(), })) await setupResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // create blacklist policy const { policyId } = await setupResult.current.createSync.mutateAsync({ type: 'blacklist', }) { // get policy data const { result } = await renderHook(() => policy.useData({ policyId })) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) expect(result.current.data?.admin).toBe(account.address) expect(result.current.data?.type).toBe('blacklist') } }) test('reactivity: policyId parameter', async () => { const { result: setupResult } = await renderHook(() => ({ connect: useConnect(), createSync: policy.useCreateSync(), })) await setupResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create policy const { policyId } = await setupResult.current.createSync.mutateAsync({ type: 'whitelist', }) // Query with undefined policyId initially const { result, rerender } = await renderHook( (props) => policy.useData({ policyId: props?.policyId }), { initialProps: { policyId: undefined as bigint | undefined } }, ) await vi.waitFor(() => expect(result.current.fetchStatus).toBe('idle')) // Should be disabled when policyId is undefined expect(result.current.data).toBeUndefined() expect(result.current.isPending).toBe(true) // expect(result.current.isEnabled).toBe(false) // Set policyId rerender({ policyId }) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) // Should now be enabled and have data // expect(result.current.isEnabled).toBe(true) expect(result.current.data?.admin).toBe(account.address) expect(result.current.data?.type).toBe('whitelist') }) describe('queryOptions', () => { test('default', async () => { const { result: setupResult } = await renderHook(() => ({ connect: useConnect(), createSync: policy.useCreateSync(), })) await setupResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // create policy const { policyId } = await setupResult.current.createSync.mutateAsync({ type: 'whitelist', }) const options = Actions.policy.getData.queryOptions(config, { policyId }) const data = await queryClient.fetchQuery(options) expect(data.admin).toBe(account.address) expect(data.type).toBe('whitelist') }) }) }) describe('useIsAuthorized', () => { test('special policy: always-reject (policyId 0)', async () => { const { result } = await renderHook(() => policy.useIsAuthorized({ policyId: 0n, user: account.address, }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) expect(result.current.data).toBe(false) }) test('special policy: always-allow (policyId 1)', async () => { const { result } = await renderHook(() => policy.useIsAuthorized({ policyId: 1n, user: account.address, }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) expect(result.current.data).toBe(true) }) test('reactivity: policyId and user parameters', async () => { const { result: setupResult } = await renderHook(() => ({ connect: useConnect(), createSync: policy.useCreateSync(), modifyWhitelistSync: policy.useModifyWhitelistSync(), })) await setupResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create whitelist policy const { policyId } = await setupResult.current.createSync.mutateAsync({ type: 'whitelist', }) // Add account2 to whitelist await setupResult.current.modifyWhitelistSync.mutateAsync({ policyId, address: account2.address, allowed: true, }) // Query with undefined parameters initially const { result, rerender } = await renderHook( (props) => policy.useIsAuthorized({ policyId: props?.policyId, user: props?.user, }), { initialProps: { policyId: undefined as bigint | undefined, user: undefined as Address | undefined, }, }, ) await vi.waitFor(() => expect(result.current.fetchStatus).toBe('idle')) // Should be disabled when parameters are undefined expect(result.current.data).toBeUndefined() expect(result.current.isPending).toBe(true) // expect(result.current.isEnabled).toBe(false) // Set parameters rerender({ policyId, user: account2.address }) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) // Should now be enabled and have data // expect(result.current.isEnabled).toBe(true) expect(result.current.data).toBe(true) }) describe('queryOptions', () => { test('default', async () => { const options = Actions.policy.isAuthorized.queryOptions(config, { policyId: 1n, user: account.address, }) const isAuthorized = await queryClient.fetchQuery(options) expect(isAuthorized).toBe(true) }) }) }) describe('useWatchCreate', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), createSync: policy.useCreateSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) const events: any[] = [] await renderHook(() => policy.useWatchCreate({ onPolicyCreated(args) { events.push(args) }, }), ) // Create policy await connectResult.current.createSync.mutateAsync({ type: 'whitelist', }) await vi.waitUntil(() => events.length >= 1) expect(events.length).toBeGreaterThanOrEqual(1) expect(events[0]?.policyId).toBeDefined() expect(events[0]?.updater).toBe(account.address) expect(events[0]?.type).toBe('whitelist') }) }) describe('useWatchAdminUpdated', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), createSync: policy.useCreateSync(), setAdminSync: policy.useSetAdminSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create policy const { policyId } = await connectResult.current.createSync.mutateAsync({ type: 'whitelist', }) const events: any[] = [] await renderHook(() => policy.useWatchAdminUpdated({ onAdminUpdated(args) { events.push(args) }, }), ) // Set new admin await connectResult.current.setAdminSync.mutateAsync({ policyId, admin: account2.address, }) await vi.waitUntil(() => events.some((e) => e.admin === account2.address)) const event = events.find((e) => e.admin === account2.address) expect(event).toBeDefined() expect(event?.policyId).toBe(policyId) expect(event?.updater).toBe(account.address) }) }) describe('useWatchWhitelistUpdated', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), createSync: policy.useCreateSync(), modifyWhitelistSync: policy.useModifyWhitelistSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create whitelist policy const { policyId } = await connectResult.current.createSync.mutateAsync({ type: 'whitelist', }) const events: any[] = [] await renderHook(() => policy.useWatchWhitelistUpdated({ onWhitelistUpdated(args) { events.push(args) }, }), ) // Add address to whitelist await connectResult.current.modifyWhitelistSync.mutateAsync({ policyId, address: account2.address, allowed: true, }) // Remove address from whitelist await connectResult.current.modifyWhitelistSync.mutateAsync({ policyId, address: account2.address, allowed: false, }) await vi.waitUntil(() => events.length >= 2) expect(events.length).toBeGreaterThanOrEqual(2) expect(events[0]?.policyId).toBe(policyId) expect(events[0]?.updater).toBe(account.address) expect(events[0]?.account).toBe(account2.address) expect(events[0]?.allowed).toBe(true) expect(events[1]?.allowed).toBe(false) }) }) describe('useWatchBlacklistUpdated', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), createSync: policy.useCreateSync(), modifyBlacklistSync: policy.useModifyBlacklistSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create blacklist policy const { policyId } = await connectResult.current.createSync.mutateAsync({ type: 'blacklist', }) const events: any[] = [] await renderHook(() => policy.useWatchBlacklistUpdated({ onBlacklistUpdated(args) { events.push(args) }, }), ) // Add address to blacklist await connectResult.current.modifyBlacklistSync.mutateAsync({ policyId, address: account2.address, restricted: true, }) // Remove address from blacklist await connectResult.current.modifyBlacklistSync.mutateAsync({ policyId, address: account2.address, restricted: false, }) await vi.waitUntil(() => events.length >= 2) expect(events.length).toBeGreaterThanOrEqual(2) expect(events[0]?.policyId).toBe(policyId) expect(events[0]?.updater).toBe(account.address) expect(events[0]?.account).toBe(account2.address) expect(events[0]?.restricted).toBe(true) expect(events[1]?.restricted).toBe(false) }) }) ================================================ FILE: packages/react/src/tempo/hooks/policy.ts ================================================ import type { UseMutationResult } from '@tanstack/react-query' import type { Config, ResolvedRegister } from '@wagmi/core' import type { ConfigParameter, ExactPartial, UnionCompute, } from '@wagmi/core/internal' import { Actions } from '@wagmi/core/tempo' import { useEffect } from 'react' import { useChainId } from '../../hooks/useChainId.js' import { useConfig } from '../../hooks/useConfig.js' import { type UseMutationParameters, type UseQueryReturnType, useMutation, useQuery, } from '../../utils/query.js' import type { QueryParameter } from '../utils.js' /** * Hook for creating a new policy. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.policy.useCreate() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useCreate< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useCreate.Parameters = {}, ): useCreate.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.policy.create(config, variables as never) }, mutationKey: ['create'], }) as never } export declare namespace useCreate { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.policy.create.ReturnValue, Actions.policy.create.ErrorType, Actions.policy.create.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.policy.create.ReturnValue, Actions.policy.create.ErrorType, Actions.policy.create.Parameters, context > } /** * Hook for creating a new policy. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.policy.useCreateSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useCreateSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useCreateSync.Parameters = {}, ): useCreateSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.policy.createSync(config, variables as never) }, mutationKey: ['createSync'], }) as never } export declare namespace useCreateSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.policy.createSync.ReturnValue, Actions.policy.createSync.ErrorType, Actions.policy.createSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.policy.createSync.ReturnValue, Actions.policy.createSync.ErrorType, Actions.policy.createSync.Parameters, context > } /** * Hook for setting the admin for a policy. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.policy.useSetAdmin() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useSetAdmin< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useSetAdmin.Parameters = {}, ): useSetAdmin.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.policy.setAdmin(config, variables as never) }, mutationKey: ['setAdmin'], }) as never } export declare namespace useSetAdmin { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.policy.setAdmin.ReturnValue, Actions.policy.setAdmin.ErrorType, Actions.policy.setAdmin.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.policy.setAdmin.ReturnValue, Actions.policy.setAdmin.ErrorType, Actions.policy.setAdmin.Parameters, context > } /** * Hook for setting the admin for a policy. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.policy.useSetAdminSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useSetAdminSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useSetAdminSync.Parameters = {}, ): useSetAdminSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.policy.setAdminSync(config, variables as never) }, mutationKey: ['setAdminSync'], }) as never } export declare namespace useSetAdminSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.policy.setAdminSync.ReturnValue, Actions.policy.setAdminSync.ErrorType, Actions.policy.setAdminSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.policy.setAdminSync.ReturnValue, Actions.policy.setAdminSync.ErrorType, Actions.policy.setAdminSync.Parameters, context > } /** * Hook for modifying a policy whitelist. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.policy.useModifyWhitelist() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useModifyWhitelist< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useModifyWhitelist.Parameters = {}, ): useModifyWhitelist.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.policy.modifyWhitelist(config, variables as never) }, mutationKey: ['modifyWhitelist'], }) as never } export declare namespace useModifyWhitelist { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.policy.modifyWhitelist.ReturnValue, Actions.policy.modifyWhitelist.ErrorType, Actions.policy.modifyWhitelist.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.policy.modifyWhitelist.ReturnValue, Actions.policy.modifyWhitelist.ErrorType, Actions.policy.modifyWhitelist.Parameters, context > } /** * Hook for modifying a policy whitelist. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.policy.useModifyWhitelistSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useModifyWhitelistSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useModifyWhitelistSync.Parameters = {}, ): useModifyWhitelistSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.policy.modifyWhitelistSync(config, variables as never) }, mutationKey: ['modifyWhitelistSync'], }) as never } export declare namespace useModifyWhitelistSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.policy.modifyWhitelistSync.ReturnValue, Actions.policy.modifyWhitelistSync.ErrorType, Actions.policy.modifyWhitelistSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.policy.modifyWhitelistSync.ReturnValue, Actions.policy.modifyWhitelistSync.ErrorType, Actions.policy.modifyWhitelistSync.Parameters, context > } /** * Hook for modifying a policy blacklist. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.policy.useModifyBlacklist() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useModifyBlacklist< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useModifyBlacklist.Parameters = {}, ): useModifyBlacklist.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.policy.modifyBlacklist(config, variables as never) }, mutationKey: ['modifyBlacklist'], }) as never } export declare namespace useModifyBlacklist { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.policy.modifyBlacklist.ReturnValue, Actions.policy.modifyBlacklist.ErrorType, Actions.policy.modifyBlacklist.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.policy.modifyBlacklist.ReturnValue, Actions.policy.modifyBlacklist.ErrorType, Actions.policy.modifyBlacklist.Parameters, context > } /** * Hook for modifying a policy blacklist. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.policy.useModifyBlacklistSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useModifyBlacklistSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useModifyBlacklistSync.Parameters = {}, ): useModifyBlacklistSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.policy.modifyBlacklistSync(config, variables as never) }, mutationKey: ['modifyBlacklistSync'], }) as never } export declare namespace useModifyBlacklistSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.policy.modifyBlacklistSync.ReturnValue, Actions.policy.modifyBlacklistSync.ErrorType, Actions.policy.modifyBlacklistSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.policy.modifyBlacklistSync.ReturnValue, Actions.policy.modifyBlacklistSync.ErrorType, Actions.policy.modifyBlacklistSync.Parameters, context > } /** * Hook for getting policy data. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data, isLoading } = Hooks.policy.useData({ * policyId: 2n, * }) * * if (isLoading) return
Loading...
* return
Admin: {data?.admin}
* } * ``` * * @param parameters - Parameters. * @returns Query result with policy data. */ export function useData< config extends Config = ResolvedRegister['config'], selectData = Actions.policy.getData.ReturnValue, >( parameters: useData.Parameters = {}, ): useData.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.policy.getData.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace useData { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.policy.getData.ReturnValue, > = ConfigParameter & QueryParameter< Actions.policy.getData.ReturnValue, Actions.policy.getData.ErrorType, selectData, Actions.policy.getData.QueryKey > & ExactPartial> export type ReturnValue = UseQueryReturnType } /** * Hook for checking if a user is authorized by a policy. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data, isLoading } = Hooks.policy.useIsAuthorized({ * policyId: 2n, * user: '0x...', * }) * * if (isLoading) return
Loading...
* return
Authorized: {data ? 'Yes' : 'No'}
* } * ``` * * @param parameters - Parameters. * @returns Query result with authorization status. */ export function useIsAuthorized< config extends Config = ResolvedRegister['config'], selectData = Actions.policy.isAuthorized.ReturnValue, >( parameters: useIsAuthorized.Parameters = {}, ): useIsAuthorized.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.policy.isAuthorized.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace useIsAuthorized { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.policy.isAuthorized.ReturnValue, > = ConfigParameter & QueryParameter< Actions.policy.isAuthorized.ReturnValue, Actions.policy.isAuthorized.ErrorType, selectData, Actions.policy.isAuthorized.QueryKey > & ExactPartial> export type ReturnValue< selectData = Actions.policy.isAuthorized.ReturnValue, > = UseQueryReturnType } /** * Hook for watching policy creation events. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.policy.useWatchCreate({ * onPolicyCreated(args) { * console.log('Policy created:', args) * }, * }) * * return
Watching for policy creation...
* } * ``` * * @param parameters - Parameters. */ export function useWatchCreate< config extends Config = ResolvedRegister['config'], >(parameters: useWatchCreate.Parameters = {}) { const { enabled = true, onPolicyCreated, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onPolicyCreated) return return Actions.policy.watchCreate(config, { ...rest, chainId, onPolicyCreated, }) }, [ config, enabled, chainId, onPolicyCreated, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, ]) } export declare namespace useWatchCreate { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } /** * Hook for watching policy admin update events. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.policy.useWatchAdminUpdated({ * onAdminUpdated(args) { * console.log('Policy admin updated:', args) * }, * }) * * return
Watching for admin updates...
* } * ``` * * @param parameters - Parameters. */ export function useWatchAdminUpdated< config extends Config = ResolvedRegister['config'], >(parameters: useWatchAdminUpdated.Parameters = {}) { const { enabled = true, onAdminUpdated, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onAdminUpdated) return return Actions.policy.watchAdminUpdated(config, { ...rest, chainId, onAdminUpdated, }) }, [ config, enabled, chainId, onAdminUpdated, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, ]) } export declare namespace useWatchAdminUpdated { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } /** * Hook for watching whitelist update events. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.policy.useWatchWhitelistUpdated({ * onWhitelistUpdated(args) { * console.log('Whitelist updated:', args) * }, * }) * * return
Watching for whitelist updates...
* } * ``` * * @param parameters - Parameters. */ export function useWatchWhitelistUpdated< config extends Config = ResolvedRegister['config'], >(parameters: useWatchWhitelistUpdated.Parameters = {}) { const { enabled = true, onWhitelistUpdated, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onWhitelistUpdated) return return Actions.policy.watchWhitelistUpdated(config, { ...rest, chainId, onWhitelistUpdated, }) }, [ config, enabled, chainId, onWhitelistUpdated, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, ]) } export declare namespace useWatchWhitelistUpdated { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } /** * Hook for watching blacklist update events. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.policy.useWatchBlacklistUpdated({ * onBlacklistUpdated(args) { * console.log('Blacklist updated:', args) * }, * }) * * return
Watching for blacklist updates...
* } * ``` * * @param parameters - Parameters. */ export function useWatchBlacklistUpdated< config extends Config = ResolvedRegister['config'], >(parameters: useWatchBlacklistUpdated.Parameters = {}) { const { enabled = true, onBlacklistUpdated, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onBlacklistUpdated) return return Actions.policy.watchBlacklistUpdated(config, { ...rest, chainId, onBlacklistUpdated, }) }, [ config, enabled, chainId, onBlacklistUpdated, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, ]) } export declare namespace useWatchBlacklistUpdated { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } ================================================ FILE: packages/react/src/tempo/hooks/reward.test.ts ================================================ import { getConnection } from '@wagmi/core' import { config, renderHook, setupToken } from '@wagmi/test/tempo' import type { Address } from 'viem' import { parseUnits } from 'viem' import { describe, expect, test, vi } from 'vitest' import { useConnect } from '../../hooks/useConnect.js' import * as rewardHooks from './reward.js' import * as tokenHooks from './token.js' describe('useGetGlobalRewardPerToken', () => { test('default', async () => { const { token } = await setupToken() const { result } = await renderHook(() => rewardHooks.useGetGlobalRewardPerToken({ token, }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) expect(result.current.data).toBe(0n) }) test('reactivity: token parameter', async () => { const { result, rerender } = await renderHook( (props) => rewardHooks.useGetGlobalRewardPerToken({ token: props?.token, }), { initialProps: { token: undefined as Address | undefined, }, }, ) await vi.waitFor(() => expect(result.current.fetchStatus).toBe('idle')) // Should be disabled when token is undefined expect(result.current.data).toBeUndefined() expect(result.current.isPending).toBe(true) // expect(result.current.isEnabled).toBe(false) // Setup token const { token } = await setupToken() // Set token rerender({ token }) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) // Should now be enabled and have data // expect(result.current.isEnabled).toBe(true) expect(result.current.data).toBe(0n) }) }) describe('useUserRewardInfo', () => { test('default', async () => { const { token } = await setupToken() const account = getConnection(config).address const { result } = await renderHook(() => rewardHooks.useUserRewardInfo({ token, account, }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) expect(result.current.data?.rewardRecipient).toBeDefined() expect(result.current.data?.rewardPerToken).toBeDefined() expect(result.current.data?.rewardBalance).toBeDefined() }) test('reactivity: account and token parameters', async () => { const { result, rerender } = await renderHook( (props) => rewardHooks.useUserRewardInfo({ token: props?.token, account: props?.account, }), { initialProps: { token: undefined as Address | undefined, account: undefined as Address | undefined, }, }, ) await vi.waitFor(() => expect(result.current.fetchStatus).toBe('idle')) // Should be disabled when both token and account are undefined expect(result.current.data).toBeUndefined() expect(result.current.isPending).toBe(true) // expect(result.current.isEnabled).toBe(false) // Setup token (this also connects the account) const { token } = await setupToken() // Set token only (account still undefined) rerender({ token, account: undefined }) await vi.waitFor(() => expect(result.current.fetchStatus).toBe('idle')) // Should still be disabled when account is undefined expect(result.current.data).toBeUndefined() expect(result.current.isPending).toBe(true) // expect(result.current.isEnabled).toBe(false) // Get account from config (already connected by setupToken) const account = getConnection(config).address // Set both token and account rerender({ token, account }) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) // Should now be enabled and have data // expect(result.current.isEnabled).toBe(true) expect(result.current.data?.rewardRecipient).toBeDefined() expect(result.current.data?.rewardPerToken).toBeDefined() expect(result.current.data?.rewardBalance).toBeDefined() }) }) describe('useSetRecipientSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), setRecipient: rewardHooks.useSetRecipientSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) const { token } = await setupToken() await result.current.setRecipient.mutateAsync({ recipient: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', token, }) await vi.waitFor(() => expect(result.current.setRecipient.isSuccess).toBeTruthy(), ) }) }) describe('useWatchRewardDistributed', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), grantRolesSync: tokenHooks.useGrantRolesSync(), mintSync: tokenHooks.useMintSync(), setRecipientSync: rewardHooks.useSetRecipientSync(), distributeSync: rewardHooks.useDistributeSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) const { token: tokenAddr } = await setupToken() const account = getConnection(config).address await connectResult.current.grantRolesSync.mutateAsync({ token: tokenAddr, roles: ['issuer'], to: account!, }) const rewardAmount = parseUnits('100', 6) await connectResult.current.mintSync.mutateAsync({ token: tokenAddr, to: account!, amount: rewardAmount, }) await connectResult.current.setRecipientSync.mutateAsync({ token: tokenAddr, recipient: account!, }) const events: any[] = [] await renderHook(() => rewardHooks.useWatchRewardDistributed({ token: tokenAddr, onRewardDistributed(args) { events.push(args) }, }), ) await connectResult.current.distributeSync.mutateAsync({ token: tokenAddr, amount: rewardAmount, }) await vi.waitUntil(() => events.length >= 1) expect(events.length).toBeGreaterThanOrEqual(1) expect(events[0]?.amount).toBe(rewardAmount) expect(events[0]?.funder).toBe(account) }) }) describe('useWatchRewardRecipientSet', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), setRecipientSync: rewardHooks.useSetRecipientSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) const { token: tokenAddr } = await setupToken() const account = getConnection(config).address const events: any[] = [] await renderHook(() => rewardHooks.useWatchRewardRecipientSet({ token: tokenAddr, onRewardRecipientSet(args) { events.push(args) }, }), ) await connectResult.current.setRecipientSync.mutateAsync({ token: tokenAddr, recipient: account!, }) await vi.waitUntil(() => events.length >= 1) expect(events.length).toBeGreaterThanOrEqual(1) expect(events[0]?.holder).toBe(account) expect(events[0]?.recipient).toBe(account) }) }) ================================================ FILE: packages/react/src/tempo/hooks/reward.ts ================================================ import type { UseMutationResult } from '@tanstack/react-query' import type { Config, ResolvedRegister } from '@wagmi/core' import type { ConfigParameter, ExactPartial, UnionCompute, } from '@wagmi/core/internal' import { Actions } from '@wagmi/core/tempo' import { useEffect } from 'react' import { useChainId } from '../../hooks/useChainId.js' import { useConfig } from '../../hooks/useConfig.js' import { type UseMutationParameters, type UseQueryReturnType, useMutation, useQuery, } from '../../utils/query.js' import type { QueryParameter } from '../utils.js' /** * Hook for claiming accumulated rewards. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate: claim } = Hooks.reward.useClaim() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useClaim< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useClaim.Parameters = {}, ): useClaim.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.reward.claim(config, variables as never) }, mutationKey: ['claim'], }) as never } export declare namespace useClaim { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.reward.claim.ReturnValue, Actions.reward.claim.ErrorType, Actions.reward.claim.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.reward.claim.ReturnValue, Actions.reward.claim.ErrorType, Actions.reward.claim.Parameters, context > } /** * Hook for claiming accumulated rewards and waiting for confirmation. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate: claimSync } = Hooks.reward.useClaimSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useClaimSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useClaimSync.Parameters = {}, ): useClaimSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.reward.claimSync(config, variables as never) }, mutationKey: ['claimSync'], }) as never } export declare namespace useClaimSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.reward.claimSync.ReturnValue, Actions.reward.claimSync.ErrorType, Actions.reward.claimSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.reward.claimSync.ReturnValue, Actions.reward.claimSync.ErrorType, Actions.reward.claimSync.Parameters, context > } /** * Hook for getting the global reward per token value. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data, isLoading } = Hooks.reward.useGetGlobalRewardPerToken({ * token: '0x20c0000000000000000000000000000000000001', * }) * * if (isLoading) return
Loading...
* return
Value: {data?.toString()}
* } * ``` * * @param parameters - Parameters. * @returns Query result with global reward per token value. */ export function useGetGlobalRewardPerToken< config extends Config = ResolvedRegister['config'], selectData = Actions.reward.getGlobalRewardPerToken.ReturnValue, >( parameters: useGetGlobalRewardPerToken.Parameters = {}, ): useGetGlobalRewardPerToken.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.reward.getGlobalRewardPerToken.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace useGetGlobalRewardPerToken { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.reward.getGlobalRewardPerToken.ReturnValue, > = ConfigParameter & QueryParameter< Actions.reward.getGlobalRewardPerToken.ReturnValue, Actions.reward.getGlobalRewardPerToken.ErrorType, selectData, Actions.reward.getGlobalRewardPerToken.QueryKey > & ExactPartial> export type ReturnValue< selectData = Actions.reward.getGlobalRewardPerToken.ReturnValue, > = UseQueryReturnType } /** * Hook for getting the reward information for a specific account. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data, isLoading } = Hooks.reward.useUserRewardInfo({ * token: '0x20c0000000000000000000000000000000000001', * account: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', * }) * * if (isLoading) return
Loading...
* return ( *
*
Recipient: {data?.rewardRecipient}
*
Reward per token: {data?.rewardPerToken.toString()}
*
Reward balance: {data?.rewardBalance.toString()}
*
* ) * } * ``` * * @param parameters - Parameters. * @returns Query result with reward information (recipient, rewardPerToken, rewardBalance). */ export function useUserRewardInfo< config extends Config = ResolvedRegister['config'], selectData = Actions.reward.getUserRewardInfo.ReturnValue, >( parameters: useUserRewardInfo.Parameters = {}, ): useUserRewardInfo.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.reward.getUserRewardInfo.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace useUserRewardInfo { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.reward.getUserRewardInfo.ReturnValue, > = ConfigParameter & QueryParameter< Actions.reward.getUserRewardInfo.ReturnValue, Actions.reward.getUserRewardInfo.ErrorType, selectData, Actions.reward.getUserRewardInfo.QueryKey > & ExactPartial> export type ReturnValue< selectData = Actions.reward.getUserRewardInfo.ReturnValue, > = UseQueryReturnType } /** * Hook for setting the reward recipient for a token holder. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate: setRecipient } = Hooks.reward.useSetRecipient() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useSetRecipient< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useSetRecipient.Parameters = {}, ): useSetRecipient.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.reward.setRecipient(config, variables as never) }, mutationKey: ['setRecipient'], }) as never } export declare namespace useSetRecipient { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.reward.setRecipient.ReturnValue, Actions.reward.setRecipient.ErrorType, Actions.reward.setRecipient.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.reward.setRecipient.ReturnValue, Actions.reward.setRecipient.ErrorType, Actions.reward.setRecipient.Parameters, context > } /** * Hook for setting the reward recipient and waiting for confirmation. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate: setRecipientSync } = Hooks.reward.useSetRecipientSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useSetRecipientSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useSetRecipientSync.Parameters = {}, ): useSetRecipientSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.reward.setRecipientSync(config, variables as never) }, mutationKey: ['setRecipientSync'], }) as never } export declare namespace useSetRecipientSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.reward.setRecipientSync.ReturnValue, Actions.reward.setRecipientSync.ErrorType, Actions.reward.setRecipientSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.reward.setRecipientSync.ReturnValue, Actions.reward.setRecipientSync.ErrorType, Actions.reward.setRecipientSync.Parameters, context > } /** * Hook for distributing rewards. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate: distribute } = Hooks.reward.useDistribute() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useDistribute< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useDistribute.Parameters = {}, ): useDistribute.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.reward.distribute(config, variables as never) }, mutationKey: ['distribute'], }) as never } export declare namespace useDistribute { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.reward.distribute.ReturnValue, Actions.reward.distribute.ErrorType, Actions.reward.distribute.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.reward.distribute.ReturnValue, Actions.reward.distribute.ErrorType, Actions.reward.distribute.Parameters, context > } /** * Hook for distributing rewards and waiting for confirmation. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate: distributeSync } = Hooks.reward.useDistributeSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useDistributeSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useDistributeSync.Parameters = {}, ): useDistributeSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.reward.distributeSync(config, variables as never) }, mutationKey: ['distributeSync'], }) as never } export declare namespace useDistributeSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.reward.distributeSync.ReturnValue, Actions.reward.distributeSync.ErrorType, Actions.reward.distributeSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.reward.distributeSync.ReturnValue, Actions.reward.distributeSync.ErrorType, Actions.reward.distributeSync.Parameters, context > } /** * Hook for watching reward distributed events. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.reward.useWatchRewardDistributed({ * token: '0x20c0000000000000000000000000000000000001', * onRewardDistributed(args) { * console.log('Reward distributed:', args) * }, * }) * * return
Watching for reward distributed events...
* } * ``` * * @param parameters - Parameters. */ export function useWatchRewardDistributed< config extends Config = ResolvedRegister['config'], >(parameters: useWatchRewardDistributed.Parameters = {}) { const { enabled = true, onRewardDistributed, token, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onRewardDistributed) return if (!token) return return Actions.reward.watchRewardDistributed(config, { ...rest, chainId, onRewardDistributed, token, }) }, [ config, enabled, chainId, token, onRewardDistributed, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, ]) } export declare namespace useWatchRewardDistributed { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } /** * Hook for watching reward recipient set events. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.reward.useWatchRewardRecipientSet({ * token: '0x20c0000000000000000000000000000000000001', * onRewardRecipientSet(args) { * console.log('Reward recipient set:', args) * }, * }) * * return
Watching for reward recipient set events...
* } * ``` * * @param parameters - Parameters. */ export function useWatchRewardRecipientSet< config extends Config = ResolvedRegister['config'], >(parameters: useWatchRewardRecipientSet.Parameters = {}) { const { enabled = true, onRewardRecipientSet, token, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onRewardRecipientSet) return if (!token) return return Actions.reward.watchRewardRecipientSet(config, { ...rest, chainId, onRewardRecipientSet, token, }) }, [ config, enabled, chainId, token, onRewardRecipientSet, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, ]) } export declare namespace useWatchRewardRecipientSet { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } ================================================ FILE: packages/react/src/tempo/hooks/token.test.ts ================================================ import { accounts, addresses, config, renderHook } from '@wagmi/test/tempo' import { type Address, parseUnits } from 'viem' import { describe, expect, test, vi } from 'vitest' import { useConnect } from '../../hooks/useConnect.js' import * as hooks from './token.js' const account = accounts[0] const account2 = accounts[1] describe('useGetAllowance', () => { test('default', async () => { const { result } = await renderHook(() => hooks.useGetAllowance({ account: account.address, spender: account2.address, token: addresses.alphaUsd, }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy(), { timeout: 5000, }) expect(result.current.data).toBeDefined() expect(typeof result.current.data).toBe('bigint') }) test('reactivity: account parameter', async () => { const { result, rerender } = await renderHook( (props) => hooks.useGetAllowance({ account: props?.account, spender: props?.spender, token: addresses.alphaUsd, }), { initialProps: { account: undefined as Address | undefined, spender: undefined as Address | undefined, }, }, ) await vi.waitFor(() => expect(result.current.fetchStatus).toBe('idle')) // Should be disabled when account or spender is undefined expect(result.current.data).toBeUndefined() expect(result.current.isPending).toBe(true) // expect(result.current.isEnabled).toBe(false) // Set account but not spender rerender({ account: account.address, spender: undefined }) await vi.waitFor(() => expect(result.current.fetchStatus).toBe('idle')) // Still disabled when spender is undefined // expect(result.current.isEnabled).toBe(false) // Set spender rerender({ account: account.address, spender: account2.address }) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) // Should now be enabled and have data // expect(result.current.isEnabled).toBe(true) expect(result.current.data).toBeDefined() expect(typeof result.current.data).toBe('bigint') }) }) describe('useGetBalance', () => { test('default', async () => { const { result } = await renderHook(() => hooks.useGetBalance({ account: account.address, token: addresses.alphaUsd, }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) expect(result.current.data).toBeDefined() expect(typeof result.current.data).toBe('bigint') expect(result.current.data).toBeGreaterThan(0n) }) test('reactivity: account parameter', async () => { const { result, rerender } = await renderHook( (props) => hooks.useGetBalance({ account: props?.account, token: addresses.alphaUsd, }), { initialProps: { account: undefined as Address | undefined, }, }, ) await vi.waitFor(() => expect(result.current.fetchStatus).toBe('idle')) // Should be disabled when account is undefined expect(result.current.data).toBeUndefined() expect(result.current.isPending).toBe(true) // expect(result.current.isEnabled).toBe(false) // Set account rerender({ account: account.address }) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) // Should now be enabled and have data // expect(result.current.isEnabled).toBe(true) expect(result.current.data).toBeDefined() expect(typeof result.current.data).toBe('bigint') expect(result.current.data).toBeGreaterThan(0n) }) }) describe('useGetMetadata', () => { test('default', async () => { const { result } = await renderHook(() => hooks.useGetMetadata({ token: addresses.alphaUsd, }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) expect(result.current.data).toBeDefined() expect(result.current.data?.name).toBeDefined() expect(result.current.data?.symbol).toBeDefined() expect(result.current.data?.decimals).toBeDefined() }) }) describe('useGetRoleAdmin', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a token where we're the admin const createData = await connectResult.current.createSync.mutateAsync({ currency: 'USD', name: 'GetRoleAdmin Hook Test', symbol: 'GRAHTEST', }) const { result } = await renderHook(() => hooks.useGetRoleAdmin({ token: createData.token, role: 'issuer', }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) expect(result.current.data).toBeDefined() expect(typeof result.current.data).toBe('string') }) }) describe('useHasRole', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a token where we're the admin const createData = await connectResult.current.createSync.mutateAsync({ currency: 'USD', name: 'HasRole Hook Test', symbol: 'HRHTEST', }) const { result } = await renderHook(() => hooks.useHasRole({ account: account.address, token: createData.token, role: 'defaultAdmin', }), ) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) expect(result.current.data).toBe(true) }) test('reactivity: account parameter', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a token where we're the admin const createData = await connectResult.current.createSync.mutateAsync({ currency: 'USD', name: 'HasRole Hook Reactivity Test', symbol: 'HRHRTEST', }) const { result, rerender } = await renderHook( (props) => hooks.useHasRole({ account: props?.account, token: createData.token, role: 'defaultAdmin', }), { initialProps: { account: undefined as Address | undefined, }, }, ) await vi.waitFor(() => expect(result.current.fetchStatus).toBe('idle')) // Should be disabled when account is undefined expect(result.current.data).toBeUndefined() expect(result.current.isPending).toBe(true) // expect(result.current.isEnabled).toBe(false) // Set account rerender({ account: account.address }) await vi.waitFor(() => expect(result.current.isSuccess).toBeTruthy()) // Should now be enabled and have data // expect(result.current.isEnabled).toBe(true) expect(result.current.data).toBe(true) }) }) describe('useApproveSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), approve: hooks.useApproveSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) const data = await result.current.approve.mutateAsync({ spender: account2.address, amount: parseUnits('100', 6), token: addresses.alphaUsd, }) expect(data).toBeDefined() expect(data.receipt).toBeDefined() await vi.waitFor(() => expect(result.current.approve.isSuccess).toBeTruthy(), ) }) }) describe('useBurnSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), grantRolesSync: hooks.useGrantRolesSync(), mintSync: hooks.useMintSync(), burn: hooks.useBurnSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await result.current.createSync.mutateAsync({ currency: 'USD', name: 'Burnable Hook Token Sync', symbol: 'BURNHOOKSYNC', }) // Grant issuer role await result.current.grantRolesSync.mutateAsync({ token: tokenAddr, roles: ['issuer'], to: account.address, }) // Mint some tokens await result.current.mintSync.mutateAsync({ token: tokenAddr, to: account.address, amount: parseUnits('1000', 6), }) const data = await result.current.burn.mutateAsync({ token: tokenAddr, amount: parseUnits('1', 6), }) expect(data).toBeDefined() expect(data.receipt).toBeDefined() await vi.waitFor(() => expect(result.current.burn.isSuccess).toBeTruthy()) }) }) describe('useChangeTransferPolicySync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), changeTransferPolicy: hooks.useChangeTransferPolicySync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await result.current.createSync.mutateAsync({ currency: 'USD', name: 'Policy Hook Token Sync', symbol: 'POLICYHOOKSYNC', }) const data = await result.current.changeTransferPolicy.mutateAsync({ token: tokenAddr, policyId: 0n, }) expect(data).toBeDefined() expect(data.receipt).toBeDefined() await vi.waitFor(() => expect(result.current.changeTransferPolicy.isSuccess).toBeTruthy(), ) }) }) describe('useCreateSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), create: hooks.useCreateSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) const data = await result.current.create.mutateAsync({ name: 'Hook Test Token Sync', symbol: 'HOOKTESTSYNC', currency: 'USD', }) expect(data).toBeDefined() expect(data.receipt).toBeDefined() expect(data.token).toBeDefined() expect(data.name).toBe('Hook Test Token Sync') await vi.waitFor(() => expect(result.current.create.isSuccess).toBeTruthy()) }) }) describe('useUpdateQuoteTokenSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), prepareUpdateQuoteTokenSync: hooks.usePrepareUpdateQuoteTokenSync(), updateQuoteToken: hooks.useUpdateQuoteTokenSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create quote token const { token: quoteToken } = await result.current.createSync.mutateAsync({ currency: 'USD', name: 'Finalize Quote Hook Sync', symbol: 'FQHOOKSYNC', }) // Create main token const { token: tokenAddr } = await result.current.createSync.mutateAsync({ currency: 'USD', name: 'Finalize Main Hook Sync', symbol: 'FMHOOKSYNC', }) // Prepare quote token update first await result.current.prepareUpdateQuoteTokenSync.mutateAsync({ token: tokenAddr, quoteToken, }) const data = await result.current.updateQuoteToken.mutateAsync({ token: tokenAddr, }) expect(data).toBeDefined() expect(data.receipt).toBeDefined() await vi.waitFor(() => expect(result.current.updateQuoteToken.isSuccess).toBeTruthy(), ) }) }) describe('useGrantRoles', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), grantRoles: hooks.useGrantRoles(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await result.current.createSync.mutateAsync({ currency: 'USD', name: 'Grant Hook Token', symbol: 'GRANTHOOK', }) const hash = await result.current.grantRoles.mutateAsync({ token: tokenAddr, roles: ['issuer'], to: account2.address, }) expect(hash).toBeDefined() await vi.waitFor(() => expect(result.current.grantRoles.isSuccess).toBeTruthy(), ) }) }) describe('useGrantRolesSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), grantRoles: hooks.useGrantRolesSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await result.current.createSync.mutateAsync({ currency: 'USD', name: 'Grant Hook Token Sync', symbol: 'GRANTHOOKSYNC', }) const data = await result.current.grantRoles.mutateAsync({ token: tokenAddr, roles: ['issuer'], to: account2.address, }) expect(data).toBeDefined() expect(data.receipt).toBeDefined() expect(data.value).toBeDefined() await vi.waitFor(() => expect(result.current.grantRoles.isSuccess).toBeTruthy(), ) }) }) describe('useMintSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), grantRolesSync: hooks.useGrantRolesSync(), mint: hooks.useMintSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await result.current.createSync.mutateAsync({ currency: 'USD', name: 'Mint Hook Token Sync', symbol: 'MINTHOOKSYNC', }) // Grant issuer role await result.current.grantRolesSync.mutateAsync({ token: tokenAddr, roles: ['issuer'], to: account.address, }) const data = await result.current.mint.mutateAsync({ token: tokenAddr, to: account.address, amount: parseUnits('100', 6), }) expect(data).toBeDefined() expect(data.receipt).toBeDefined() await vi.waitFor(() => expect(result.current.mint.isSuccess).toBeTruthy()) }) }) describe('usePauseSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), grantRolesSync: hooks.useGrantRolesSync(), pause: hooks.usePauseSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await result.current.createSync.mutateAsync({ currency: 'USD', name: 'Pause Hook Token Sync', symbol: 'PAUSEHOOKSYNC', }) // Grant pause role await result.current.grantRolesSync.mutateAsync({ token: tokenAddr, roles: ['pause'], to: account.address, }) const data = await result.current.pause.mutateAsync({ token: tokenAddr, }) expect(data).toBeDefined() expect(data.receipt).toBeDefined() await vi.waitFor(() => expect(result.current.pause.isSuccess).toBeTruthy()) }) }) describe('useRenounceRolesSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), grantRolesSync: hooks.useGrantRolesSync(), renounceRoles: hooks.useRenounceRolesSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await result.current.createSync.mutateAsync({ currency: 'USD', name: 'Renounce Hook Token Sync', symbol: 'RENOUNCEHOOKSYNC', }) // Grant issuer role to ourselves await result.current.grantRolesSync.mutateAsync({ token: tokenAddr, roles: ['issuer'], to: account.address, }) const data = await result.current.renounceRoles.mutateAsync({ token: tokenAddr, roles: ['issuer'], }) expect(data).toBeDefined() expect(data.receipt).toBeDefined() expect(data.value).toBeDefined() await vi.waitFor(() => expect(result.current.renounceRoles.isSuccess).toBeTruthy(), ) }) }) describe('useRevokeRolesSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), grantRolesSync: hooks.useGrantRolesSync(), revokeRoles: hooks.useRevokeRolesSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await result.current.createSync.mutateAsync({ currency: 'USD', name: 'Revoke Hook Token Sync', symbol: 'REVOKEHOOKSYNC', }) // Grant issuer role to account2 await result.current.grantRolesSync.mutateAsync({ token: tokenAddr, roles: ['issuer'], to: account2.address, }) const data = await result.current.revokeRoles.mutateAsync({ token: tokenAddr, roles: ['issuer'], from: account2.address, }) expect(data).toBeDefined() expect(data.receipt).toBeDefined() expect(data.value).toBeDefined() await vi.waitFor(() => expect(result.current.revokeRoles.isSuccess).toBeTruthy(), ) }) }) describe('useSetRoleAdminSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), setRoleAdmin: hooks.useSetRoleAdminSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await result.current.createSync.mutateAsync({ currency: 'USD', name: 'Role Admin Hook Token Sync', symbol: 'ROLEADMINHOOKSYNC', }) const data = await result.current.setRoleAdmin.mutateAsync({ token: tokenAddr, role: 'issuer', adminRole: 'pause', }) expect(data).toBeDefined() expect(data.receipt).toBeDefined() await vi.waitFor(() => expect(result.current.setRoleAdmin.isSuccess).toBeTruthy(), ) }) }) describe('useSetSupplyCapSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), setSupplyCap: hooks.useSetSupplyCapSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await result.current.createSync.mutateAsync({ currency: 'USD', name: 'Supply Cap Hook Token Sync', symbol: 'SUPPLYCAPHOOKSYNC', }) const data = await result.current.setSupplyCap.mutateAsync({ token: tokenAddr, supplyCap: parseUnits('1000000', 6), }) expect(data).toBeDefined() expect(data.receipt).toBeDefined() await vi.waitFor(() => expect(result.current.setSupplyCap.isSuccess).toBeTruthy(), ) }) }) describe('useTransferSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), transfer: hooks.useTransferSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) const data = await result.current.transfer.mutateAsync({ to: account2.address, amount: parseUnits('1', 6), token: addresses.alphaUsd, }) expect(data).toBeDefined() expect(data.receipt).toBeDefined() await vi.waitFor(() => expect(result.current.transfer.isSuccess).toBeTruthy(), ) }) }) describe('useUnpauseSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), grantRolesSync: hooks.useGrantRolesSync(), pauseSync: hooks.usePauseSync(), unpause: hooks.useUnpauseSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await result.current.createSync.mutateAsync({ currency: 'USD', name: 'Unpause Hook Token Sync', symbol: 'UNPAUSEHOOKSYNC', }) // Grant pause and unpause roles await result.current.grantRolesSync.mutateAsync({ token: tokenAddr, roles: ['pause', 'unpause'], to: account.address, }) // First pause it await result.current.pauseSync.mutateAsync({ token: tokenAddr, }) const data = await result.current.unpause.mutateAsync({ token: tokenAddr, }) expect(data).toBeDefined() expect(data.receipt).toBeDefined() await vi.waitFor(() => expect(result.current.unpause.isSuccess).toBeTruthy(), ) }) }) describe('usePrepareUpdateQuoteTokenSync', () => { test('default', async () => { const { result } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), prepareUpdateQuoteToken: hooks.usePrepareUpdateQuoteTokenSync(), })) await result.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create quote token const { token: quoteToken } = await result.current.createSync.mutateAsync({ currency: 'USD', name: 'Update Quote Hook Sync', symbol: 'UQHOOKSYNC', }) // Create main token const { token: tokenAddr } = await result.current.createSync.mutateAsync({ currency: 'USD', name: 'Update Main Hook Sync', symbol: 'UMHOOKSYNC', }) const data = await result.current.prepareUpdateQuoteToken.mutateAsync({ token: tokenAddr, quoteToken, }) expect(data).toBeDefined() expect(data.receipt).toBeDefined() await vi.waitFor(() => expect(result.current.prepareUpdateQuoteToken.isSuccess).toBeTruthy(), ) }) }) describe('useWatchAdminRole', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), setRoleAdminSync: hooks.useSetRoleAdminSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await connectResult.current.createSync.mutateAsync({ currency: 'USD', name: 'Watch Admin Role Hook Token', symbol: 'WATCHADMINHOOK', }) const events: any[] = [] await renderHook(() => hooks.useWatchAdminRole({ token: tokenAddr, onRoleAdminUpdated(args) { events.push(args) }, }), ) // Trigger event by setting a role admin await connectResult.current.setRoleAdminSync.mutateAsync({ token: tokenAddr, role: 'issuer', adminRole: 'pause', }) await vi.waitUntil(() => events.length >= 1) expect(events.length).toBeGreaterThanOrEqual(1) expect(events[0]).toBeDefined() }) }) describe('useWatchApprove', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), approveSync: hooks.useApproveSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) const events: any[] = [] await renderHook(() => hooks.useWatchApprove({ onApproval(args) { events.push(args) }, token: addresses.alphaUsd, }), ) // Trigger approval event await connectResult.current.approveSync.mutateAsync({ spender: account2.address, amount: parseUnits('50', 6), token: addresses.alphaUsd, }) await vi.waitUntil(() => events.length >= 1) expect(events.length).toBeGreaterThanOrEqual(1) expect(events[0]?.owner).toBe(account.address) expect(events[0]?.spender).toBe(account2.address) expect(events[0]?.amount).toBe(parseUnits('50', 6)) }) }) describe('useWatchBurn', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), grantRolesSync: hooks.useGrantRolesSync(), mintSync: hooks.useMintSync(), burnSync: hooks.useBurnSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await connectResult.current.createSync.mutateAsync({ currency: 'USD', name: 'Watch Burn Hook Token', symbol: 'WATCHBURNHOOK', }) // Grant issuer role and mint tokens await connectResult.current.grantRolesSync.mutateAsync({ token: tokenAddr, roles: ['issuer'], to: account.address, }) await connectResult.current.mintSync.mutateAsync({ token: tokenAddr, to: account.address, amount: parseUnits('1000', 6), }) const events: any[] = [] await renderHook(() => hooks.useWatchBurn({ token: tokenAddr, onBurn(args) { events.push(args) }, }), ) // Trigger burn event await connectResult.current.burnSync.mutateAsync({ token: tokenAddr, amount: parseUnits('10', 6), }) await vi.waitUntil(() => events.length >= 1) expect(events.length).toBeGreaterThanOrEqual(1) expect(events[0]?.from).toBe(account.address) expect(events[0]?.amount).toBe(parseUnits('10', 6)) }) }) describe('useWatchCreate', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) const events: any[] = [] await renderHook(() => hooks.useWatchCreate({ onTokenCreated(args) { events.push(args) }, }), ) // Trigger token creation event await connectResult.current.createSync.mutateAsync({ name: 'Watch Create Hook Token', symbol: 'WATCHCREATEHOOK', currency: 'USD', }) await vi.waitUntil(() => events.length >= 1) expect(events.length).toBeGreaterThanOrEqual(1) expect(events[0]?.name).toBe('Watch Create Hook Token') expect(events[0]?.symbol).toBe('WATCHCREATEHOOK') expect(events[0]?.currency).toBe('USD') expect(events[0]?.admin).toBe(account.address) }) }) describe('useWatchMint', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), grantRolesSync: hooks.useGrantRolesSync(), mintSync: hooks.useMintSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await connectResult.current.createSync.mutateAsync({ currency: 'USD', name: 'Watch Mint Hook Token', symbol: 'WATCHMINTHOOK', }) // Grant issuer role await connectResult.current.grantRolesSync.mutateAsync({ token: tokenAddr, roles: ['issuer'], to: account.address, }) const events: any[] = [] await renderHook(() => hooks.useWatchMint({ token: tokenAddr, onMint(args) { events.push(args) }, }), ) // Trigger mint event await connectResult.current.mintSync.mutateAsync({ token: tokenAddr, to: account.address, amount: parseUnits('100', 6), }) await vi.waitUntil(() => events.length >= 1) expect(events.length).toBeGreaterThanOrEqual(1) expect(events[0]?.to).toBe(account.address) expect(events[0]?.amount).toBe(parseUnits('100', 6)) }) }) describe('useWatchRole', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), grantRolesSync: hooks.useGrantRolesSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create a new token const { token: tokenAddr } = await connectResult.current.createSync.mutateAsync({ currency: 'USD', name: 'Watch Role Hook Token', symbol: 'WATCHROLEHOOK', }) const events: any[] = [] await renderHook(() => hooks.useWatchRole({ token: tokenAddr, onRoleUpdated(args) { events.push(args) }, }), ) // Trigger role update event by granting a role await connectResult.current.grantRolesSync.mutateAsync({ token: tokenAddr, roles: ['issuer'], to: account2.address, }) await vi.waitUntil(() => events.some((e) => e.account === account2.address)) const event = events.find((e) => e.account === account2.address) expect(event).toBeDefined() expect(event?.hasRole).toBe(true) expect(event?.type).toBe('granted') }) }) describe('useWatchTransfer', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), transferSync: hooks.useTransferSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) const events: any[] = [] await renderHook(() => hooks.useWatchTransfer({ onTransfer(args) { events.push(args) }, token: addresses.alphaUsd, }), ) // Trigger transfer event await connectResult.current.transferSync.mutateAsync({ to: account2.address, amount: parseUnits('5', 6), token: addresses.alphaUsd, }) await vi.waitUntil(() => events.length >= 1) expect(events.length).toBeGreaterThanOrEqual(1) expect(events[0]?.from).toBe(account.address) expect(events[0]?.to).toBe(account2.address) expect(events[0]?.amount).toBe(parseUnits('5', 6)) }) }) describe('useWatchUpdateQuoteToken', () => { test('default', async () => { const { result: connectResult } = await renderHook(() => ({ connect: useConnect(), createSync: hooks.useCreateSync(), prepareUpdateQuoteTokenSync: hooks.usePrepareUpdateQuoteTokenSync(), })) await connectResult.current.connect.mutateAsync({ connector: config.connectors[0]!, }) // Create quote token const { token: quoteToken } = await connectResult.current.createSync.mutateAsync({ currency: 'USD', name: 'Watch Quote Hook Token', symbol: 'WATCHQUOTEHOOK', }) // Create main token const { token: tokenAddr } = await connectResult.current.createSync.mutateAsync({ currency: 'USD', name: 'Watch Main Hook Token', symbol: 'WATCHMAINHOOK', }) const events: any[] = [] await renderHook(() => hooks.useWatchUpdateQuoteToken({ token: tokenAddr, onUpdateQuoteToken(args) { events.push(args) }, }), ) // Trigger prepare update quote token event await connectResult.current.prepareUpdateQuoteTokenSync.mutateAsync({ token: tokenAddr, quoteToken, }) await vi.waitUntil(() => events.length >= 1) expect(events.length).toBeGreaterThanOrEqual(1) expect(events[0]?.nextQuoteToken).toBe(quoteToken) expect(events[0]?.updater).toBe(account.address) expect(events[0]?.completed).toBe(false) }) }) describe.todo('useBurnBlocked') describe.todo('useBurnBlockedSync') ================================================ FILE: packages/react/src/tempo/hooks/token.ts ================================================ import type { UseMutationResult } from '@tanstack/react-query' import type { Config, ResolvedRegister } from '@wagmi/core' import type { ConfigParameter, ExactPartial, UnionCompute, } from '@wagmi/core/internal' import { Actions } from '@wagmi/core/tempo' import { useEffect } from 'react' import { useChainId } from '../../hooks/useChainId.js' import { useConfig } from '../../hooks/useConfig.js' import { type UseMutationParameters, type UseQueryReturnType, useMutation, useQuery, } from '../../utils/query.js' import type { QueryParameter } from '../utils.js' /** * Hook for approving a spender to transfer TIP20 tokens. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useApprove() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useApprove< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useApprove.Parameters = {}, ): useApprove.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.approve(config, variables as never) }, mutationKey: ['approve'], }) as never } export declare namespace useApprove { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.approve.ReturnValue, Actions.token.approve.ErrorType, Actions.token.approve.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.approve.ReturnValue, Actions.token.approve.ErrorType, Actions.token.approve.Parameters, context > } /** * Hook for approving a spender to transfer TIP20 tokens. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useApproveSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useApproveSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useApproveSync.Parameters = {}, ): useApproveSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.approveSync(config, variables as never) }, mutationKey: ['approveSync'], }) as never } export declare namespace useApproveSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.approveSync.ReturnValue, Actions.token.approveSync.ErrorType, Actions.token.approveSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.approveSync.ReturnValue, Actions.token.approveSync.ErrorType, Actions.token.approveSync.Parameters, context > } /** * Hook for burning TIP20 tokens from the caller's balance. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useBurn() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useBurn< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useBurn.Parameters = {}, ): useBurn.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.burn(config, variables as never) }, mutationKey: ['burn'], }) as never } export declare namespace useBurn { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.burn.ReturnValue, Actions.token.burn.ErrorType, Actions.token.burn.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.burn.ReturnValue, Actions.token.burn.ErrorType, Actions.token.burn.Parameters, context > } /** * Hook for burning TIP20 tokens from the caller's balance. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useBurnSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useBurnSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useBurnSync.Parameters = {}, ): useBurnSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.burnSync(config, variables as never) }, mutationKey: ['burnSync'], }) as never } export declare namespace useBurnSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.burnSync.ReturnValue, Actions.token.burnSync.ErrorType, Actions.token.burnSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.burnSync.ReturnValue, Actions.token.burnSync.ErrorType, Actions.token.burnSync.Parameters, context > } /** * Hook for burning TIP20 tokens from a blocked address. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useBurnBlocked() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useBurnBlocked< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useBurnBlocked.Parameters = {}, ): useBurnBlocked.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.burnBlocked(config, variables as never) }, mutationKey: ['burnBlocked'], }) as never } export declare namespace useBurnBlocked { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.burnBlocked.ReturnValue, Actions.token.burnBlocked.ErrorType, Actions.token.burnBlocked.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.burnBlocked.ReturnValue, Actions.token.burnBlocked.ErrorType, Actions.token.burnBlocked.Parameters, context > } /** * Hook for burning TIP20 tokens from a blocked address. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useBurnBlockedSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useBurnBlockedSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useBurnBlockedSync.Parameters = {}, ): useBurnBlockedSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.burnBlockedSync(config, variables as never) }, mutationKey: ['burnBlockedSync'], }) as never } export declare namespace useBurnBlockedSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.burnBlockedSync.ReturnValue, Actions.token.burnBlockedSync.ErrorType, Actions.token.burnBlockedSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.burnBlockedSync.ReturnValue, Actions.token.burnBlockedSync.ErrorType, Actions.token.burnBlockedSync.Parameters, context > } /** * Hook for changing the transfer policy ID for a TIP20 token. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useChangeTransferPolicy() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useChangeTransferPolicy< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useChangeTransferPolicy.Parameters = {}, ): useChangeTransferPolicy.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.changeTransferPolicy(config, variables as never) }, mutationKey: ['changeTransferPolicy'], }) as never } export declare namespace useChangeTransferPolicy { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.changeTransferPolicy.ReturnValue, Actions.token.changeTransferPolicy.ErrorType, Actions.token.changeTransferPolicy.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.changeTransferPolicy.ReturnValue, Actions.token.changeTransferPolicy.ErrorType, Actions.token.changeTransferPolicy.Parameters, context > } /** * Hook for changing the transfer policy ID for a TIP20 token. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useChangeTransferPolicySync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useChangeTransferPolicySync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useChangeTransferPolicySync.Parameters = {}, ): useChangeTransferPolicySync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.changeTransferPolicySync(config, variables as never) }, mutationKey: ['changeTransferPolicySync'], }) as never } export declare namespace useChangeTransferPolicySync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.changeTransferPolicySync.ReturnValue, Actions.token.changeTransferPolicySync.ErrorType, Actions.token.changeTransferPolicySync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.changeTransferPolicySync.ReturnValue, Actions.token.changeTransferPolicySync.ErrorType, Actions.token.changeTransferPolicySync.Parameters, context > } /** * Hook for creating a new TIP20 token. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useCreate() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useCreate< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useCreate.Parameters = {}, ): useCreate.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.create(config, variables as never) }, mutationKey: ['create'], }) as never } export declare namespace useCreate { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.create.ReturnValue, Actions.token.create.ErrorType, Actions.token.create.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.create.ReturnValue, Actions.token.create.ErrorType, Actions.token.create.Parameters, context > } /** * Hook for creating a new TIP20 token. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useCreateSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useCreateSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useCreateSync.Parameters = {}, ): useCreateSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.createSync(config, variables as never) }, mutationKey: ['createSync'], }) as never } export declare namespace useCreateSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.createSync.ReturnValue, Actions.token.createSync.ErrorType, Actions.token.createSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.createSync.ReturnValue, Actions.token.createSync.ErrorType, Actions.token.createSync.Parameters, context > } /** * Hook for updating the quote token for a TIP20 token. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useUpdateQuoteToken() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useUpdateQuoteToken< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useUpdateQuoteToken.Parameters = {}, ): useUpdateQuoteToken.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.updateQuoteToken(config, variables as never) }, mutationKey: ['updateQuoteToken'], }) as never } export declare namespace useUpdateQuoteToken { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.updateQuoteToken.ReturnValue, Actions.token.updateQuoteToken.ErrorType, Actions.token.updateQuoteToken.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.updateQuoteToken.ReturnValue, Actions.token.updateQuoteToken.ErrorType, Actions.token.updateQuoteToken.Parameters, context > } /** * Hook for updating the quote token for a TIP20 token. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useUpdateQuoteTokenSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useUpdateQuoteTokenSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useUpdateQuoteTokenSync.Parameters = {}, ): useUpdateQuoteTokenSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.updateQuoteTokenSync(config, variables as never) }, mutationKey: ['updateQuoteTokenSync'], }) as never } export declare namespace useUpdateQuoteTokenSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.updateQuoteTokenSync.ReturnValue, Actions.token.updateQuoteTokenSync.ErrorType, Actions.token.updateQuoteTokenSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.updateQuoteTokenSync.ReturnValue, Actions.token.updateQuoteTokenSync.ErrorType, Actions.token.updateQuoteTokenSync.Parameters, context > } /** * Hook for getting TIP20 token allowance. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data, isLoading } = Hooks.token.useGetAllowance({ * account: '0x...', * spender: '0x...', * }) * * if (isLoading) return
Loading...
* return
Allowance: {data?.toString()}
* } * ``` * * @param parameters - Parameters. * @returns Query result with token allowance. */ export function useGetAllowance< config extends Config = ResolvedRegister['config'], selectData = Actions.token.getAllowance.ReturnValue, >( parameters: useGetAllowance.Parameters = {}, ): useGetAllowance.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.token.getAllowance.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace useGetAllowance { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.token.getAllowance.ReturnValue, > = ConfigParameter & QueryParameter< Actions.token.getAllowance.ReturnValue, Actions.token.getAllowance.ErrorType, selectData, Actions.token.getAllowance.QueryKey > & ExactPartial> export type ReturnValue = UseQueryReturnType } /** * Hook for getting TIP20 token balance for an address. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data, isLoading } = Hooks.token.useGetBalance({ * account: '0x...', * }) * * if (isLoading) return
Loading...
* return
Balance: {data?.toString()}
* } * ``` * * @param parameters - Parameters. * @returns Query result with token balance. */ export function useGetBalance< config extends Config = ResolvedRegister['config'], selectData = Actions.token.getBalance.ReturnValue, >( parameters: useGetBalance.Parameters = {}, ): useGetBalance.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.token.getBalance.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace useGetBalance { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.token.getBalance.ReturnValue, > = ConfigParameter & QueryParameter< Actions.token.getBalance.ReturnValue, Actions.token.getBalance.ErrorType, selectData, Actions.token.getBalance.QueryKey > & ExactPartial> export type ReturnValue = UseQueryReturnType } /** * Hook for getting TIP20 token metadata. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data, isLoading } = Hooks.token.useGetMetadata({ * token: '0x...', * }) * * if (isLoading) return
Loading...
* return
{data?.name} ({data?.symbol})
* } * ``` * * @param parameters - Parameters. * @returns Query result with token metadata. */ export function useGetMetadata< config extends Config = ResolvedRegister['config'], selectData = Actions.token.getMetadata.ReturnValue, >( parameters: useGetMetadata.Parameters = {}, ): useGetMetadata.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.token.getMetadata.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace useGetMetadata { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.token.getMetadata.ReturnValue, > = ConfigParameter & QueryParameter< Actions.token.getMetadata.ReturnValue, Actions.token.getMetadata.ErrorType, selectData, Actions.token.getMetadata.QueryKey > & ExactPartial> export type ReturnValue = UseQueryReturnType } /** * Hook for getting the admin role for a specific role in a TIP20 token. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data, isLoading } = Hooks.token.useGetRoleAdmin({ * role: 'issuer', * token: '0x...', * }) * * if (isLoading) return
Loading...
* return
Admin Role: {data}
* } * ``` * * @param parameters - Parameters. * @returns Query result with admin role hash. */ export function useGetRoleAdmin< config extends Config = ResolvedRegister['config'], selectData = Actions.token.getRoleAdmin.ReturnValue, >( parameters: useGetRoleAdmin.Parameters, ): useGetRoleAdmin.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.token.getRoleAdmin.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace useGetRoleAdmin { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.token.getRoleAdmin.ReturnValue, > = ConfigParameter & QueryParameter< Actions.token.getRoleAdmin.ReturnValue, Actions.token.getRoleAdmin.ErrorType, selectData, Actions.token.getRoleAdmin.QueryKey > & ExactPartial> export type ReturnValue = UseQueryReturnType } /** * Hook for granting roles for a TIP20 token. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useGrantRoles() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useGrantRoles< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useGrantRoles.Parameters = {}, ): useGrantRoles.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.grantRoles(config, variables as never) }, mutationKey: ['grantRoles'], }) as never } export declare namespace useGrantRoles { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.grantRoles.ReturnValue, Actions.token.grantRoles.ErrorType, Actions.token.grantRoles.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.grantRoles.ReturnValue, Actions.token.grantRoles.ErrorType, Actions.token.grantRoles.Parameters, context > } /** * Hook for granting roles for a TIP20 token. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useGrantRolesSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useGrantRolesSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useGrantRolesSync.Parameters = {}, ): useGrantRolesSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.grantRolesSync(config, variables as never) }, mutationKey: ['grantRolesSync'], }) as never } export declare namespace useGrantRolesSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.grantRolesSync.ReturnValue, Actions.token.grantRolesSync.ErrorType, Actions.token.grantRolesSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.grantRolesSync.ReturnValue, Actions.token.grantRolesSync.ErrorType, Actions.token.grantRolesSync.Parameters, context > } /** * Hook for checking if an account has a specific role for a TIP20 token. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { data, isLoading } = Hooks.token.useHasRole({ * account: '0x...', * role: 'issuer', * token: '0x...', * }) * * if (isLoading) return
Loading...
* return
Has Role: {data ? 'Yes' : 'No'}
* } * ``` * * @param parameters - Parameters. * @returns Query result with boolean indicating if account has role. */ export function useHasRole< config extends Config = ResolvedRegister['config'], selectData = Actions.token.hasRole.ReturnValue, >( parameters: useHasRole.Parameters, ): useHasRole.ReturnValue { const config = useConfig(parameters) const chainId = useChainId({ config }) const options = Actions.token.hasRole.queryOptions(config, { ...parameters, chainId: parameters.chainId ?? chainId, } as never) return useQuery(options) as never } export declare namespace useHasRole { export type Parameters< config extends Config = ResolvedRegister['config'], selectData = Actions.token.hasRole.ReturnValue, > = ConfigParameter & QueryParameter< Actions.token.hasRole.ReturnValue, Actions.token.hasRole.ErrorType, selectData, Actions.token.hasRole.QueryKey > & ExactPartial> export type ReturnValue = UseQueryReturnType } /** * Hook for minting TIP20 tokens to an address. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useMint() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useMint< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useMint.Parameters = {}, ): useMint.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.mint(config, variables as never) }, mutationKey: ['mint'], }) as never } export declare namespace useMint { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.mint.ReturnValue, Actions.token.mint.ErrorType, Actions.token.mint.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.mint.ReturnValue, Actions.token.mint.ErrorType, Actions.token.mint.Parameters, context > } /** * Hook for minting TIP20 tokens to an address. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useMintSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useMintSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useMintSync.Parameters = {}, ): useMintSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.mintSync(config, variables as never) }, mutationKey: ['mintSync'], }) as never } export declare namespace useMintSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.mintSync.ReturnValue, Actions.token.mintSync.ErrorType, Actions.token.mintSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.mintSync.ReturnValue, Actions.token.mintSync.ErrorType, Actions.token.mintSync.Parameters, context > } /** * Hook for pausing a TIP20 token. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.usePause() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function usePause< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: usePause.Parameters = {}, ): usePause.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.pause(config, variables as never) }, mutationKey: ['pause'], }) as never } export declare namespace usePause { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.pause.ReturnValue, Actions.token.pause.ErrorType, Actions.token.pause.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.pause.ReturnValue, Actions.token.pause.ErrorType, Actions.token.pause.Parameters, context > } /** * Hook for pausing a TIP20 token. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.usePauseSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function usePauseSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: usePauseSync.Parameters = {}, ): usePauseSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.pauseSync(config, variables as never) }, mutationKey: ['pauseSync'], }) as never } export declare namespace usePauseSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.pauseSync.ReturnValue, Actions.token.pauseSync.ErrorType, Actions.token.pauseSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.pauseSync.ReturnValue, Actions.token.pauseSync.ErrorType, Actions.token.pauseSync.Parameters, context > } /** * Hook for renouncing roles for a TIP20 token. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useRenounceRoles() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useRenounceRoles< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useRenounceRoles.Parameters = {}, ): useRenounceRoles.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.renounceRoles(config, variables as never) }, mutationKey: ['renounceRoles'], }) as never } export declare namespace useRenounceRoles { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.renounceRoles.ReturnValue, Actions.token.renounceRoles.ErrorType, Actions.token.renounceRoles.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.renounceRoles.ReturnValue, Actions.token.renounceRoles.ErrorType, Actions.token.renounceRoles.Parameters, context > } /** * Hook for renouncing roles for a TIP20 token. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useRenounceRolesSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useRenounceRolesSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useRenounceRolesSync.Parameters = {}, ): useRenounceRolesSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.renounceRolesSync(config, variables as never) }, mutationKey: ['renounceRolesSync'], }) as never } export declare namespace useRenounceRolesSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.renounceRolesSync.ReturnValue, Actions.token.renounceRolesSync.ErrorType, Actions.token.renounceRolesSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.renounceRolesSync.ReturnValue, Actions.token.renounceRolesSync.ErrorType, Actions.token.renounceRolesSync.Parameters, context > } /** * Hook for revoking roles for a TIP20 token. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useRevokeRoles() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useRevokeRoles< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useRevokeRoles.Parameters = {}, ): useRevokeRoles.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.revokeRoles(config, variables as never) }, mutationKey: ['revokeRoles'], }) as never } export declare namespace useRevokeRoles { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.revokeRoles.ReturnValue, Actions.token.revokeRoles.ErrorType, Actions.token.revokeRoles.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.revokeRoles.ReturnValue, Actions.token.revokeRoles.ErrorType, Actions.token.revokeRoles.Parameters, context > } /** * Hook for revoking roles for a TIP20 token. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useRevokeRolesSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useRevokeRolesSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useRevokeRolesSync.Parameters = {}, ): useRevokeRolesSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.revokeRolesSync(config, variables as never) }, mutationKey: ['revokeRolesSync'], }) as never } export declare namespace useRevokeRolesSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.revokeRolesSync.ReturnValue, Actions.token.revokeRolesSync.ErrorType, Actions.token.revokeRolesSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.revokeRolesSync.ReturnValue, Actions.token.revokeRolesSync.ErrorType, Actions.token.revokeRolesSync.Parameters, context > } /** * Hook for setting the admin role for a specific role in a TIP20 token. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useSetRoleAdmin() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useSetRoleAdmin< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useSetRoleAdmin.Parameters = {}, ): useSetRoleAdmin.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.setRoleAdmin(config, variables as never) }, mutationKey: ['setRoleAdmin'], }) as never } export declare namespace useSetRoleAdmin { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.setRoleAdmin.ReturnValue, Actions.token.setRoleAdmin.ErrorType, Actions.token.setRoleAdmin.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.setRoleAdmin.ReturnValue, Actions.token.setRoleAdmin.ErrorType, Actions.token.setRoleAdmin.Parameters, context > } /** * Hook for setting the admin role for a specific role in a TIP20 token. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useSetRoleAdminSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useSetRoleAdminSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useSetRoleAdminSync.Parameters = {}, ): useSetRoleAdminSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.setRoleAdminSync(config, variables as never) }, mutationKey: ['setRoleAdminSync'], }) as never } export declare namespace useSetRoleAdminSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.setRoleAdminSync.ReturnValue, Actions.token.setRoleAdminSync.ErrorType, Actions.token.setRoleAdminSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.setRoleAdminSync.ReturnValue, Actions.token.setRoleAdminSync.ErrorType, Actions.token.setRoleAdminSync.Parameters, context > } /** * Hook for setting the supply cap for a TIP20 token. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useSetSupplyCap() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useSetSupplyCap< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useSetSupplyCap.Parameters = {}, ): useSetSupplyCap.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.setSupplyCap(config, variables as never) }, mutationKey: ['setSupplyCap'], }) as never } export declare namespace useSetSupplyCap { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.setSupplyCap.ReturnValue, Actions.token.setSupplyCap.ErrorType, Actions.token.setSupplyCap.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.setSupplyCap.ReturnValue, Actions.token.setSupplyCap.ErrorType, Actions.token.setSupplyCap.Parameters, context > } /** * Hook for setting the supply cap for a TIP20 token. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useSetSupplyCapSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useSetSupplyCapSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useSetSupplyCapSync.Parameters = {}, ): useSetSupplyCapSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.setSupplyCapSync(config, variables as never) }, mutationKey: ['setSupplyCapSync'], }) as never } export declare namespace useSetSupplyCapSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.setSupplyCapSync.ReturnValue, Actions.token.setSupplyCapSync.ErrorType, Actions.token.setSupplyCapSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.setSupplyCapSync.ReturnValue, Actions.token.setSupplyCapSync.ErrorType, Actions.token.setSupplyCapSync.Parameters, context > } /** * Hook for transferring TIP20 tokens to another address. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useTransfer() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useTransfer< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useTransfer.Parameters = {}, ): useTransfer.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.transfer(config, variables as never) }, mutationKey: ['transfer'], }) as never } export declare namespace useTransfer { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.transfer.ReturnValue, Actions.token.transfer.ErrorType, Actions.token.transfer.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.transfer.ReturnValue, Actions.token.transfer.ErrorType, Actions.token.transfer.Parameters, context > } /** * Hook for transferring TIP20 tokens to another address. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useTransferSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useTransferSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useTransferSync.Parameters = {}, ): useTransferSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.transferSync(config, variables as never) }, mutationKey: ['transferSync'], }) as never } export declare namespace useTransferSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.transferSync.ReturnValue, Actions.token.transferSync.ErrorType, Actions.token.transferSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.transferSync.ReturnValue, Actions.token.transferSync.ErrorType, Actions.token.transferSync.Parameters, context > } /** * Hook for unpausing a TIP20 token. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useUnpause() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useUnpause< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useUnpause.Parameters = {}, ): useUnpause.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.unpause(config, variables as never) }, mutationKey: ['unpause'], }) as never } export declare namespace useUnpause { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.unpause.ReturnValue, Actions.token.unpause.ErrorType, Actions.token.unpause.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.unpause.ReturnValue, Actions.token.unpause.ErrorType, Actions.token.unpause.Parameters, context > } /** * Hook for unpausing a TIP20 token. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.useUnpauseSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function useUnpauseSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useUnpauseSync.Parameters = {}, ): useUnpauseSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.unpauseSync(config, variables as never) }, mutationKey: ['unpauseSync'], }) as never } export declare namespace useUnpauseSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.unpauseSync.ReturnValue, Actions.token.unpauseSync.ErrorType, Actions.token.unpauseSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.unpauseSync.ReturnValue, Actions.token.unpauseSync.ErrorType, Actions.token.unpauseSync.Parameters, context > } /** * Hook for preparing the quote token update for a TIP20 token. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.usePrepareUpdateQuoteToken() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function usePrepareUpdateQuoteToken< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: usePrepareUpdateQuoteToken.Parameters = {}, ): usePrepareUpdateQuoteToken.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.prepareUpdateQuoteToken(config, variables as never) }, mutationKey: ['prepareUpdateQuoteToken'], }) as never } export declare namespace usePrepareUpdateQuoteToken { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.prepareUpdateQuoteToken.ReturnValue, Actions.token.prepareUpdateQuoteToken.ErrorType, Actions.token.prepareUpdateQuoteToken.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.prepareUpdateQuoteToken.ReturnValue, Actions.token.prepareUpdateQuoteToken.ErrorType, Actions.token.prepareUpdateQuoteToken.Parameters, context > } /** * Hook for preparing the quote token update for a TIP20 token. * * Note: This is a synchronous hook that waits for the transaction * to be included on a block before returning a response. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * const { mutate, isPending } = Hooks.token.usePrepareUpdateQuoteTokenSync() * * return ( * * ) * } * ``` * * @param parameters - Parameters. * @returns Mutation result. */ export function usePrepareUpdateQuoteTokenSync< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: usePrepareUpdateQuoteTokenSync.Parameters = {}, ): usePrepareUpdateQuoteTokenSync.ReturnType { const { mutation } = parameters const config = useConfig(parameters) return useMutation({ ...mutation, async mutationFn(variables) { return Actions.token.prepareUpdateQuoteTokenSync( config, variables as never, ) }, mutationKey: ['prepareUpdateQuoteTokenSync'], }) as never } export declare namespace usePrepareUpdateQuoteTokenSync { type Parameters< config extends Config = Config, context = unknown, > = ConfigParameter & { mutation?: | UseMutationParameters< Actions.token.prepareUpdateQuoteTokenSync.ReturnValue, Actions.token.prepareUpdateQuoteTokenSync.ErrorType, Actions.token.prepareUpdateQuoteTokenSync.Parameters, context > | undefined } type ReturnType< config extends Config = Config, context = unknown, > = UseMutationResult< Actions.token.prepareUpdateQuoteTokenSync.ReturnValue, Actions.token.prepareUpdateQuoteTokenSync.ErrorType, Actions.token.prepareUpdateQuoteTokenSync.Parameters, context > } /** * Hook for watching TIP20 token role admin updates. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.token.useWatchAdminRole({ * onRoleAdminUpdated(args) { * console.log('Role admin updated:', args) * }, * }) * * return
Watching for role admin updates...
* } * ``` * * @param parameters - Parameters. */ export function useWatchAdminRole< config extends Config = ResolvedRegister['config'], >(parameters: useWatchAdminRole.Parameters = {}) { const { enabled = true, onRoleAdminUpdated, token, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onRoleAdminUpdated) return if (!token) return return Actions.token.watchAdminRole(config, { ...rest, chainId, onRoleAdminUpdated, token, }) }, [ config, enabled, chainId, token, onRoleAdminUpdated, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, ]) } export declare namespace useWatchAdminRole { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } /** * Hook for watching TIP20 token approval events. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.token.useWatchApprove({ * onApproval(args) { * console.log('Approval:', args) * }, * }) * * return
Watching for approvals...
* } * ``` * * @param parameters - Parameters. */ export function useWatchApprove< config extends Config = ResolvedRegister['config'], >(parameters: useWatchApprove.Parameters = {}) { const { enabled = true, onApproval, token, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onApproval) return if (!token) return return Actions.token.watchApprove(config, { ...rest, chainId, onApproval, token, }) }, [ config, enabled, chainId, token, onApproval, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, ]) } export declare namespace useWatchApprove { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } /** * Hook for watching TIP20 token burn events. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.token.useWatchBurn({ * onBurn(args) { * console.log('Burn:', args) * }, * }) * * return
Watching for burns...
* } * ``` * * @param parameters - Parameters. */ export function useWatchBurn< config extends Config = ResolvedRegister['config'], >(parameters: useWatchBurn.Parameters = {}) { const { enabled = true, onBurn, token, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onBurn) return if (!token) return return Actions.token.watchBurn(config, { ...rest, chainId, onBurn, token, }) }, [ config, enabled, chainId, token, onBurn, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, ]) } export declare namespace useWatchBurn { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } /** * Hook for watching new TIP20 tokens created. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.token.useWatchCreate({ * onTokenCreated(args) { * console.log('Token created:', args) * }, * }) * * return
Watching for token creations...
* } * ``` * * @param parameters - Parameters. */ export function useWatchCreate< config extends Config = ResolvedRegister['config'], >(parameters: useWatchCreate.Parameters = {}) { const { enabled = true, onTokenCreated, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onTokenCreated) return return Actions.token.watchCreate(config, { ...rest, chainId, onTokenCreated, }) }, [ config, enabled, chainId, onTokenCreated, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, ]) } export declare namespace useWatchCreate { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } /** * Hook for watching TIP20 token mint events. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.token.useWatchMint({ * onMint(args) { * console.log('Mint:', args) * }, * }) * * return
Watching for mints...
* } * ``` * * @param parameters - Parameters. */ export function useWatchMint< config extends Config = ResolvedRegister['config'], >(parameters: useWatchMint.Parameters = {}) { const { enabled = true, onMint, token, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onMint) return if (!token) return return Actions.token.watchMint(config, { ...rest, chainId, onMint, token, }) }, [ config, enabled, chainId, token, onMint, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, ]) } export declare namespace useWatchMint { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } /** * Hook for watching TIP20 token role membership updates. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.token.useWatchRole({ * onRoleUpdated(args) { * console.log('Role updated:', args) * }, * }) * * return
Watching for role updates...
* } * ``` * * @param parameters - Parameters. */ export function useWatchRole< config extends Config = ResolvedRegister['config'], >(parameters: useWatchRole.Parameters = {}) { const { enabled = true, onRoleUpdated, token, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onRoleUpdated) return if (!token) return return Actions.token.watchRole(config, { ...rest, chainId, onRoleUpdated, token, }) }, [ config, enabled, chainId, token, onRoleUpdated, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, ]) } export declare namespace useWatchRole { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } /** * Hook for watching TIP20 token transfer events. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.token.useWatchTransfer({ * onTransfer(args) { * console.log('Transfer:', args) * }, * }) * * return
Watching for transfers...
* } * ``` * * @param parameters - Parameters. */ export function useWatchTransfer< config extends Config = ResolvedRegister['config'], >(parameters: useWatchTransfer.Parameters = {}) { const { enabled = true, onTransfer, token, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onTransfer) return if (!token) return return Actions.token.watchTransfer(config, { ...rest, chainId, onTransfer, token, }) }, [ config, enabled, chainId, token, onTransfer, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, ]) } export declare namespace useWatchTransfer { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } /** * Hook for watching TIP20 token quote token update events. * * @example * ```tsx * import { Hooks } from 'wagmi/tempo' * * function App() { * Hooks.token.useWatchUpdateQuoteToken({ * onUpdateQuoteToken(args) { * if (args.completed) * console.log('quote token update completed:', args.newQuoteToken) * else * console.log('quote token update proposed:', args.newQuoteToken) * }, * }) * * return
Watching for quote token updates...
* } * ``` * * @param parameters - Parameters. */ export function useWatchUpdateQuoteToken< config extends Config = ResolvedRegister['config'], >(parameters: useWatchUpdateQuoteToken.Parameters = {}) { const { enabled = true, onUpdateQuoteToken, token, ...rest } = parameters const config = useConfig({ config: parameters.config }) const configChainId = useChainId({ config }) const chainId = parameters.chainId ?? configChainId // biome-ignore lint/correctness/useExhaustiveDependencies: rest.x is explicitly listed useEffect(() => { if (!enabled) return if (!onUpdateQuoteToken) return if (!token) return return Actions.token.watchUpdateQuoteToken(config, { ...rest, chainId, onUpdateQuoteToken, token, }) }, [ config, enabled, chainId, token, onUpdateQuoteToken, rest.fromBlock, rest.onError, rest.poll, rest.pollingInterval, ]) } export declare namespace useWatchUpdateQuoteToken { type Parameters = UnionCompute< ExactPartial> & ConfigParameter & { enabled?: boolean | undefined } > } ================================================ FILE: packages/react/src/tempo/utils.ts ================================================ import type * as Query from '@tanstack/react-query' import type { UnionLooseOmit } from '@wagmi/core/internal' export type QueryParameter< queryFnData = unknown, error = Query.DefaultError, data = queryFnData, queryKey extends Query.QueryKey = Query.QueryKey, > = { query?: | UnionLooseOmit< Query.UseQueryOptions, 'queryKey' | 'queryFn' > | undefined } ================================================ FILE: packages/react/src/types/properties.ts ================================================ import type { DefaultError, QueryKey } from '@tanstack/react-query' import type { Omit } from '@wagmi/core/internal' import type { UseInfiniteQueryParameters } from '../utils/query.js' export type InfiniteQueryParameter< queryFnData = unknown, error = DefaultError, data = queryFnData, queryData = queryFnData, queryKey extends QueryKey = QueryKey, pageParam = unknown, > = { query: Omit< UseInfiniteQueryParameters< queryFnData, error, data, queryData, queryKey, pageParam >, 'queryFn' | 'queryHash' | 'queryKey' | 'queryKeyHashFn' | 'throwOnError' > } ================================================ FILE: packages/react/src/utils/getVersion.test.ts ================================================ import { expect, test } from 'vitest' import { getVersion } from './getVersion.js' test('default', () => { expect(getVersion()).toMatchInlineSnapshot(`"wagmi@x.y.z"`) }) ================================================ FILE: packages/react/src/utils/getVersion.ts ================================================ import { version } from '../version.js' export const getVersion = () => `wagmi@${version}` ================================================ FILE: packages/react/src/utils/query.ts ================================================ import { type DefaultError, type MutateFunction, type QueryKey, useInfiniteQuery as tanstack_useInfiniteQuery, useQuery as tanstack_useQuery, type UseInfiniteQueryOptions, type UseInfiniteQueryResult, type UseMutationOptions, type UseMutationResult, type UseQueryOptions, type UseQueryResult, useMutation, } from '@tanstack/react-query' import type { Compute, ExactPartial, Omit, UnionStrictOmit, } from '@wagmi/core/internal' import { hashFn } from '@wagmi/core/query' export { useMutation } export type UseMutationParameters< data = unknown, error = Error, variables = void, context = unknown, > = Compute< Omit< UseMutationOptions, context>, 'mutationFn' | 'mutationKey' | 'throwOnError' > > export type UseMutationReturnType< data = unknown, error = Error, variables = void, context = unknown, mutate = MutateFunction, mutateAsync = MutateFunction, > = Compute< UnionStrictOmit< UseMutationResult, 'mutate' | 'mutateAsync' > & { mutate: mutate mutateAsync: mutateAsync } > //////////////////////////////////////////////////////////////////////////////// // Adding some basic customization. // Ideally we don't have this function, but `import('@tanstack/react-query').useQuery` currently has some quirks where it is super hard to // pass down the inferred `initialData` type because of it's discriminated overload in the on `useQuery`. export function useQuery( parameters: UseQueryParameters & { queryKey: QueryKey }, ): UseQueryReturnType { const result = tanstack_useQuery({ ...(parameters as any), queryKeyHashFn: hashFn, // for bigint support }) as UseQueryReturnType result.queryKey = parameters.queryKey return result } export type UseQueryParameters< queryFnData = unknown, error = DefaultError, data = queryFnData, queryKey extends QueryKey = QueryKey, > = Compute< ExactPartial< Omit, 'initialData'> > & { // Fix `initialData` type initialData?: | UseQueryOptions['initialData'] | undefined } > export type UseQueryReturnType = Compute< UseQueryResult & { queryKey: QueryKey } > //////////////////////////////////////////////////////////////////////////////// // Adding some basic customization. export function useInfiniteQuery< queryFnData, error, data, queryKey extends QueryKey, >( parameters: UseInfiniteQueryParameters & { queryKey: QueryKey }, ): UseInfiniteQueryReturnType { const result = tanstack_useInfiniteQuery({ ...(parameters as any), queryKeyHashFn: hashFn, // for bigint support }) as UseInfiniteQueryReturnType result.queryKey = parameters.queryKey return result } export type UseInfiniteQueryParameters< queryFnData = unknown, error = DefaultError, data = queryFnData, queryData = queryFnData, queryKey extends QueryKey = QueryKey, pageParam = unknown, > = Compute< Omit< UseInfiniteQueryOptions< queryFnData, error, data, queryData, queryKey, pageParam >, 'initialData' > & { // Fix `initialData` type initialData?: | UseInfiniteQueryOptions< queryFnData, error, data, queryKey >['initialData'] | undefined } > export type UseInfiniteQueryReturnType< data = unknown, error = DefaultError, > = UseInfiniteQueryResult & { queryKey: QueryKey } ================================================ FILE: packages/react/src/version.ts ================================================ export const version = '3.5.0' ================================================ FILE: packages/react/test/setup.ts ================================================ import { vi } from 'vitest' // Make dates stable across runs Date.now = vi.fn(() => new Date(Date.UTC(2023, 1, 1)).valueOf()) vi.mock('../src/version.ts', () => { return { version: 'x.y.z' } }) vi.mock('../../core/src/version.ts', () => { return { version: 'x.y.z' } }) ================================================ FILE: packages/react/tsconfig.build.json ================================================ { "extends": "../../tsconfig.base.json", "include": ["src/**/*.ts"], "exclude": ["src/**/*.test.ts", "src/**/*.test-d.ts"], "compilerOptions": { "sourceMap": true } } ================================================ FILE: packages/react/tsconfig.json ================================================ { "extends": "./tsconfig.build.json", "compilerOptions": { "jsx": "preserve", "types": ["@vitest/browser-playwright"] }, "include": ["src/**/*.ts", "src/**/*.tsx", "test/**/*.ts", "test/**/*.tsx"], "exclude": [] } ================================================ FILE: packages/register-tests/react/package.json ================================================ { "name": "react-register", "private": true, "type": "module", "scripts": { "check:types": "tsc --noEmit" }, "dependencies": { "@tanstack/react-query": "catalog:", "react": "catalog:", "wagmi": "workspace:*" }, "devDependencies": { "@types/react": "catalog:" } } ================================================ FILE: packages/register-tests/react/src/config.ts ================================================ import { type Address, http } from 'viem' import { createConfig, createConnector, mock } from 'wagmi' import { celo, mainnet, optimism, zkSync } from 'wagmi/chains' export const config = createConfig({ chains: [celo, mainnet, optimism, zkSync], connectors: [mock({ accounts: ['0x'] }), foo()], transports: { [celo.id]: http(), [mainnet.id]: http(), [optimism.id]: http(), [zkSync.id]: http(), }, }) export type ChainId = | typeof celo.id | typeof mainnet.id | typeof optimism.id | typeof zkSync.id declare module 'wagmi' { interface Register { config: typeof config } } export function foo() { type Properties = { // TODO(v3): Make `withCapabilities: true` default behavior connect(parameters?: { chainId?: number | undefined isReconnecting?: boolean | undefined capabilities?: { signInWithEthereum?: { nonce: string } | undefined } withCapabilities?: withCapabilities | boolean | undefined }): Promise<{ accounts: withCapabilities extends true ? readonly { capabilities: { signInWithEthereum: { message: string signature: string } } }[] : readonly Address[] chainId: number }> } return createConnector((_config) => ({}) as never) } ================================================ FILE: packages/register-tests/react/src/createUseSimulateContract.test-d.ts ================================================ import { abi, config as testConfig } from '@wagmi/test' import { test } from 'vitest' import { celo, mainnet, optimism } from 'wagmi/chains' import { createUseSimulateContract } from 'wagmi/codegen' const useSimulateErc20 = createUseSimulateContract({ abi: abi.erc20, }) test('chain formatters', () => { useSimulateErc20({ feeCurrency: '0x', }) useSimulateErc20({ chainId: celo.id, feeCurrency: '0x', }) useSimulateErc20({ chainId: mainnet.id, // @ts-expect-error feeCurrency: '0x', }) useSimulateErc20({ chainId: optimism.id, // @ts-expect-error feeCurrency: '0x', }) }) test('parameters: config', async () => { useSimulateErc20({ config: testConfig, // @ts-expect-error feeCurrency: '0x', }) }) ================================================ FILE: packages/register-tests/react/src/createUseWriteContract.test-d.ts ================================================ import { abi, config } from '@wagmi/test' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' import { celo, mainnet, optimism } from 'wagmi/chains' import { createUseWriteContract } from 'wagmi/codegen' const useWriteErc20 = createUseWriteContract({ abi: abi.erc20, }) test('chain formatters', () => { const { mutate } = useWriteErc20() const shared = { address: '0x', functionName: 'transferFrom', args: ['0x', '0x', 123n], } as const mutate({ ...shared, feeCurrency: '0x', }) type Result = Parameters< typeof mutate< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof celo.id > >[0] expectTypeOf().toEqualTypeOf< `0x${string}` | undefined >() mutate({ ...shared, chainId: celo.id, feeCurrency: '0x', }) mutate({ ...shared, chainId: mainnet.id, // @ts-expect-error feeCurrency: '0x', }) mutate({ ...shared, chainId: optimism.id, // @ts-expect-error feeCurrency: '0x', }) }) test('parameters: config', async () => { const { mutate } = useWriteErc20({ config }) mutate({ address: '0x', functionName: 'transferFrom', args: ['0x', '0x', 123n], // @ts-expect-error feeCurrency: '0x', }) }) ================================================ FILE: packages/register-tests/react/src/useBlock.test-d.ts ================================================ import type { Hex } from 'viem' import { expectTypeOf, test } from 'vitest' import { useBlock } from 'wagmi' import { celo } from 'wagmi/chains' test('chain formatters', () => { const result = useBlock() if (result.data) expectTypeOf(result.data.difficulty).toEqualTypeOf() if (result.data?.chainId === celo.id) { expectTypeOf(result.data.difficulty).toEqualTypeOf() expectTypeOf(result.data.gasLimit).toEqualTypeOf() expectTypeOf(result.data.mixHash).toEqualTypeOf() expectTypeOf(result.data.nonce).toEqualTypeOf<`0x${string}`>() expectTypeOf(result.data.uncles).toEqualTypeOf() } const result2 = useBlock({ chainId: celo.id }) if (result2.data) { expectTypeOf(result2.data.difficulty).toEqualTypeOf() expectTypeOf(result2.data.gasLimit).toEqualTypeOf() expectTypeOf(result2.data.mixHash).toEqualTypeOf() expectTypeOf(result2.data.nonce).toEqualTypeOf<`0x${string}`>() expectTypeOf(result2.data.uncles).toEqualTypeOf() } }) ================================================ FILE: packages/register-tests/react/src/useChainId.test-d.ts ================================================ import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useChainId } from 'wagmi' import type { ChainId } from './config.js' test('default', async () => { const chainId = useChainId() expectTypeOf(chainId).toEqualTypeOf() }) test('parameters: config', async () => { const chainId = useChainId({ config }) expectTypeOf(chainId).toEqualTypeOf<1 | 456 | 10>() }) ================================================ FILE: packages/register-tests/react/src/useChains.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useChains } from 'wagmi' import type { celo, optimism, zkSync } from 'wagmi/chains' test('default', () => { const chains = useChains() expectTypeOf(chains[0]).toEqualTypeOf() expectTypeOf(chains[2]).toEqualTypeOf() expectTypeOf(chains[3]).toEqualTypeOf() }) ================================================ FILE: packages/register-tests/react/src/useClient.test-d.ts ================================================ import { type chain, config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useClient } from 'wagmi' import { mainnet } from 'wagmi/chains' import type { ChainId } from './config.js' test('default', () => { const client = useClient() expectTypeOf(client.chain.id).toEqualTypeOf() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) test('parameters: config', () => { const client = useClient({ config }) expectTypeOf(client.chain.id).toEqualTypeOf< (typeof config)['chains'][number]['id'] >() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) test('parameters: chainId', () => { const client = useClient({ config, chainId: mainnet.id, }) expectTypeOf(client.chain).toEqualTypeOf() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) test('behavior: unconfigured chain', () => { const client = useClient({ config, // @ts-expect-error chainId: 123456, }) expectTypeOf(client).toEqualTypeOf() }) ================================================ FILE: packages/register-tests/react/src/useConfig.test-d.ts ================================================ import { config as testConfig } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { type Config, useConfig } from 'wagmi' import type { config } from './config.js' test('default', async () => { const result = useConfig() expectTypeOf(result).not.toEqualTypeOf() expectTypeOf(result).toEqualTypeOf() }) test('parameters: config', async () => { const result = useConfig({ config: testConfig }) expectTypeOf(result).not.toEqualTypeOf() expectTypeOf(result).toEqualTypeOf() }) ================================================ FILE: packages/register-tests/react/src/useConnect.test-d.ts ================================================ import type { Address, Hex } from 'viem' import { expectTypeOf, test } from 'vitest' import { useConnect, useConnectors } from 'wagmi' test('infers connect parameters', () => { const connect = useConnect() const connectors = useConnectors() const connector = connectors[0]! as (typeof connectors)[number] connect.mutate({ connector, foo: 'bar', }) connect.mutate({ connector: connectors[1], // @ts-expect-error foo: 'bar', }) connect.mutate({ connector, capabilities: { signInWithEthereum: { nonce: 'foobarbaz', }, }, }) connect.mutate({ connector: connectors[0], // @ts-expect-error capabilities: { signInWithEthereum: { nonce: 'foobarbaz', }, }, }) if (connect.variables && 'foo' in connect.variables) expectTypeOf(connect.variables?.foo).toEqualTypeOf() if (connect.variables && 'capabilities' in connect.variables) expectTypeOf( connect.variables?.capabilities?.signInWithEthereum, ).toEqualTypeOf<{ nonce: string } | undefined>() connect.mutate( { connector, foo: 'bar', withCapabilities: true, }, { onSuccess(data, _variables, _context) { expectTypeOf(data.accounts).toEqualTypeOf< readonly [ { address: Address capabilities: | { foo: { bar: Hex } } | { signInWithEthereum: { message: string signature: string } } }, ...{ address: Address capabilities: | { foo: { bar: Hex } } | { signInWithEthereum: { message: string signature: string } } }[], ] >() }, onSettled(data, _error, _variables, _context) { expectTypeOf(data?.accounts).toEqualTypeOf< | readonly [ { address: Address capabilities: | { foo: { bar: Hex } } | { signInWithEthereum: { message: string signature: string } } }, ...{ address: Address capabilities: | { foo: { bar: Hex } } | { signInWithEthereum: { message: string signature: string } } }[], ] | undefined >() }, }, ) ;(async () => { await connect.mutateAsync({ connector, foo: 'bar', withCapabilities: true, }) const res = await connect.mutateAsync({ connector, capabilities: { signInWithEthereum: { nonce: 'foobarbaz', }, }, withCapabilities: true, }) expectTypeOf(res.accounts).toEqualTypeOf< readonly [ { address: Address capabilities: | { foo: { bar: Hex } } | { signInWithEthereum: { message: string signature: string } } }, ...{ address: Address capabilities: | { foo: { bar: Hex } } | { signInWithEthereum: { message: string signature: string } } }[], ] >() })() }) ================================================ FILE: packages/register-tests/react/src/useConnection.test-d.ts ================================================ import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useConnection } from 'wagmi' import type { ChainId } from './config.js' test('default', () => { const result = useConnection() if (result.chain) expectTypeOf(result.chain.id).toEqualTypeOf() }) test('parameters: config', () => { const result = useConnection({ config }) if (result.chain) expectTypeOf(result.chain.id).toEqualTypeOf<1 | 10 | 456>() }) ================================================ FILE: packages/register-tests/react/src/usePrepareTransactionRequest.test-d.ts ================================================ import { config as testConfig } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { usePrepareTransactionRequest } from 'wagmi' import { celo, mainnet, optimism } from 'wagmi/chains' test('chain formatters', () => { const { data } = usePrepareTransactionRequest({ feeCurrency: '0x', }) if (data && data.chainId === celo.id) { expectTypeOf(data.feeCurrency).toEqualTypeOf<`0x${string}` | undefined>() } const { data: data2 } = usePrepareTransactionRequest({ chainId: celo.id, feeCurrency: '0x', }) if (data2) { expectTypeOf(data2.chainId).toEqualTypeOf(celo.id) expectTypeOf(data2.feeCurrency).toEqualTypeOf<`0x${string}` | undefined>() } usePrepareTransactionRequest({ chainId: mainnet.id, // @ts-expect-error feeCurrency: '0x', }) usePrepareTransactionRequest({ chainId: optimism.id, // @ts-expect-error feeCurrency: '0x', }) }) test('parameters: config', async () => { usePrepareTransactionRequest({ config: testConfig, // @ts-expect-error feeCurrency: '0x', }) }) ================================================ FILE: packages/register-tests/react/src/usePublicClient.ts ================================================ import { type chain, config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { usePublicClient } from 'wagmi' import { mainnet } from 'wagmi/chains' import type { ChainId } from './config.js' test('default', () => { const client = usePublicClient() expectTypeOf(client.chain.id).toEqualTypeOf() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) test('parameters: config', () => { const client = usePublicClient({ config }) expectTypeOf(client.chain.id).toEqualTypeOf< (typeof config)['chains'][number]['id'] >() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) test('parameters: chainId', () => { const client = usePublicClient({ config, chainId: mainnet.id, }) expectTypeOf(client.chain).toEqualTypeOf() expectTypeOf(client.transport.type).toEqualTypeOf<'http'>() }) test('behavior: unconfigured chain', () => { const client = usePublicClient({ config, // @ts-expect-error chainId: 123456, }) expectTypeOf(client).toEqualTypeOf() }) ================================================ FILE: packages/register-tests/react/src/useReadContract.test-d.ts ================================================ import { abi } from '@wagmi/test' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' import { useReadContract } from 'wagmi' import type { ChainId } from './config.js' test('UseReadContractParameters', () => { type Result = NonNullable< Parameters>[0] > expectTypeOf().toMatchTypeOf<{ functionName?: | 'symbol' | 'name' | 'allowance' | 'balanceOf' | 'decimals' | 'totalSupply' | undefined args?: readonly [Address] | undefined chainId?: ChainId | undefined }>() const result = useReadContract({ address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], query: { select(data) { expectTypeOf(data).toEqualTypeOf() return data?.toString() }, }, }) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/register-tests/react/src/useReadContracts.test-d.ts ================================================ import type { abi } from '@wagmi/test' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' import type { useReadContracts } from 'wagmi' import type { ChainId } from './config.js' test('UseReadContractsParameters', () => { type Result = NonNullable< Parameters< typeof useReadContracts< [ { abi: typeof abi.erc20 functionName: 'balanceOf' address: Address args: readonly [Address] }, ] > >[0] >['contracts'] expectTypeOf().toMatchTypeOf< | readonly [ { abi?: typeof abi.erc20 | undefined functionName?: | 'approve' | 'symbol' | 'name' | 'allowance' | 'balanceOf' | 'decimals' | 'totalSupply' | 'transfer' | 'transferFrom' | undefined address?: Address | undefined args?: readonly [Address] | undefined chainId?: ChainId | undefined }, ] | undefined >() }) ================================================ FILE: packages/register-tests/react/src/useSendTransaction.test-d.ts ================================================ import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useSendTransaction } from 'wagmi' import { celo, mainnet, optimism } from 'wagmi/chains' import type { ChainId } from './config.js' test('chain formatters', () => { const { mutate } = useSendTransaction() mutate( { to: '0x', feeCurrency: '0x', }, { onSuccess(_data, variables) { expectTypeOf(variables.chainId).toEqualTypeOf() }, }, ) type Result = Parameters>[0] expectTypeOf().toEqualTypeOf< `0x${string}` | undefined >() mutate({ chainId: celo.id, to: '0x', feeCurrency: '0x', }) mutate({ chainId: mainnet.id, to: '0x', // @ts-expect-error feeCurrency: '0x', }) mutate({ chainId: optimism.id, to: '0x', // @ts-expect-error feeCurrency: '0x', }) }) test('parameters: config', async () => { const { mutate } = useSendTransaction({ config }) mutate({ to: '0x', // @ts-expect-error feeCurrency: '0x', }) }) ================================================ FILE: packages/register-tests/react/src/useSimulateContract.test-d.ts ================================================ import { type abi, config as testConfig } from '@wagmi/test' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' import { type UseSimulateContractParameters, useSimulateContract } from 'wagmi' import { celo, mainnet, optimism } from 'wagmi/chains' import type { SimulateContractOptions } from 'wagmi/query' import type { ChainId, config } from './config.js' test('chain formatters', () => { const { data } = useSimulateContract({ feeCurrency: '0x', }) if (data && data.chainId === celo.id) { expectTypeOf(data.request.feeCurrency).toEqualTypeOf< `0x${string}` | undefined >() } const { data: data2 } = useSimulateContract({ chainId: celo.id, feeCurrency: '0x', }) if (data2) { expectTypeOf(data2.request.feeCurrency).toEqualTypeOf< `0x${string}` | undefined >() } useSimulateContract({ chainId: mainnet.id, // @ts-expect-error feeCurrency: '0x', }) useSimulateContract({ chainId: optimism.id, // @ts-expect-error feeCurrency: '0x', }) }) test('UseSimulateContractParameters', () => { type Result = UseSimulateContractParameters< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config > const res = {} as Result expectTypeOf(res.functionName).toEqualTypeOf< 'approve' | 'transfer' | 'transferFrom' | undefined >() if (res.args) { expectTypeOf(res.args[0]).toEqualTypeOf
() expectTypeOf(res.args[1]).toEqualTypeOf
() expectTypeOf(res.args[2]).toEqualTypeOf() } expectTypeOf(res.chainId).toEqualTypeOf() type Result2 = UseSimulateContractParameters< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config, typeof celo.id > const res2 = {} as Result2 expectTypeOf(res2.chainId).toEqualTypeOf() expectTypeOf(res2.feeCurrency).toEqualTypeOf<`0x${string}` | undefined>() type Result3 = UseSimulateContractParameters< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config, typeof celo.id > expectTypeOf(({} as Result3).chainId).toEqualTypeOf() type Result4 = SimulateContractOptions< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config, typeof celo.id > expectTypeOf().toEqualTypeOf() }) test('parameters: config', async () => { useSimulateContract({ config: testConfig, // @ts-expect-error feeCurrency: '0x', }) }) ================================================ FILE: packages/register-tests/react/src/useSwitchChain.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useSwitchChain } from 'wagmi' import { mainnet } from 'wagmi/chains' import type { ChainId } from './config.js' test('default', () => { const { mutate } = useSwitchChain() mutate( { chainId: 1 }, { onSuccess(data) { expectTypeOf(data).toEqualTypeOf(mainnet) }, }, ) type Result = Parameters[0] expectTypeOf().toEqualTypeOf() }) ================================================ FILE: packages/register-tests/react/src/useTransaction.test-d.ts ================================================ import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useTransaction } from 'wagmi' import { celo } from 'wagmi/chains' test('chain formatters', () => { const result = useTransaction() if (result.data?.chainId === celo.id) { expectTypeOf(result.data.feeCurrency).toEqualTypeOf<`0x${string}` | null>() } const result2 = useTransaction({ chainId: celo.id }) expectTypeOf(result2.data?.feeCurrency).toEqualTypeOf< `0x${string}` | null | undefined >() }) test('parameters: config', async () => { const result = useTransaction({ config }) if (result.data && 'feeCurrency' in result.data) expectTypeOf(result.data.feeCurrency).toEqualTypeOf() }) ================================================ FILE: packages/register-tests/react/src/useTransactionConfirmations.test-d.ts ================================================ import { config as testConfig } from '@wagmi/test' import { test } from 'vitest' import { useTransactionConfirmations } from 'wagmi' import { mainnet, zkSync } from 'wagmi/chains' const transactionReceipt = { blockHash: '0x', blockNumber: 1n, contractAddress: '0x', cumulativeGasUsed: 1n, effectiveGasPrice: 1n, from: '0x', gasUsed: 1n, logsBloom: '0x', status: 'success', to: '0x', transactionHash: '0x', transactionIndex: 1, type: 'eip1559', } as const test('chain formatters', async () => { useTransactionConfirmations({ transactionReceipt: { ...transactionReceipt, l1BatchNumber: 1n, l1BatchTxIndex: 1n, logs: [], l2ToL1Logs: [], }, }) useTransactionConfirmations({ chainId: zkSync.id, transactionReceipt: { ...transactionReceipt, l1BatchNumber: 1n, l1BatchTxIndex: 1n, logs: [], l2ToL1Logs: [], }, }) useTransactionConfirmations({ chainId: mainnet.id, transactionReceipt: { ...transactionReceipt, // @ts-expect-error l1BatchNumber: 1n, l1BatchTxIndex: 1n, logs: [], l2ToL1Logs: [], }, }) }) test('parameters: config', async () => { useTransactionConfirmations({ config: testConfig, transactionReceipt: { ...transactionReceipt, // @ts-expect-error l1BatchNumber: 1n, }, }) }) ================================================ FILE: packages/register-tests/react/src/useTransactionReceipt.test-d.ts ================================================ import { config } from '@wagmi/test' import type { ZkSyncL2ToL1Log, ZkSyncLog } from 'viem/zksync' import { expectTypeOf, test } from 'vitest' import { useTransactionReceipt } from 'wagmi' import { zkSync } from 'wagmi/chains' test('chain formatters', () => { const result = useTransactionReceipt() if (result.data?.chainId === zkSync.id) { expectTypeOf(result.data.l1BatchNumber).toEqualTypeOf() expectTypeOf(result.data.l1BatchTxIndex).toEqualTypeOf() expectTypeOf(result.data.logs).toEqualTypeOf() expectTypeOf(result.data.l2ToL1Logs).toEqualTypeOf() } const result2 = useTransactionReceipt({ chainId: zkSync.id }) if (result2.data) { expectTypeOf(result2.data.l1BatchNumber).toEqualTypeOf() expectTypeOf(result2.data.l1BatchTxIndex).toEqualTypeOf() expectTypeOf(result2.data.logs).toEqualTypeOf() expectTypeOf(result2.data.l2ToL1Logs).toEqualTypeOf() } }) test('parameters: config', async () => { const result = useTransactionReceipt({ config }) if (result.data && 'l1BatchNumber' in result.data) expectTypeOf(result.data.l1BatchNumber).toEqualTypeOf() }) ================================================ FILE: packages/register-tests/react/src/useWaitForTransactionReceipt.test-d.ts ================================================ import { config } from '@wagmi/test' import type { ZkSyncL2ToL1Log, ZkSyncLog } from 'viem/zksync' import { expectTypeOf, test } from 'vitest' import { useWaitForTransactionReceipt } from 'wagmi' import { zkSync } from 'wagmi/chains' test('chain formatters', () => { const result = useWaitForTransactionReceipt() if (result.data?.chainId === zkSync.id) { expectTypeOf(result.data.l1BatchNumber).toEqualTypeOf() expectTypeOf(result.data.l1BatchTxIndex).toEqualTypeOf() expectTypeOf(result.data.logs).toEqualTypeOf() expectTypeOf(result.data.l2ToL1Logs).toEqualTypeOf() } const result2 = useWaitForTransactionReceipt({ chainId: zkSync.id }) if (result2.data) { expectTypeOf(result2.data.l1BatchNumber).toEqualTypeOf() expectTypeOf(result2.data.l1BatchTxIndex).toEqualTypeOf() expectTypeOf(result2.data.logs).toEqualTypeOf() expectTypeOf(result2.data.l2ToL1Logs).toEqualTypeOf() } }) test('parameters: config', async () => { const result = useWaitForTransactionReceipt({ config }) if (result.data && 'l1BatchNumber' in result.data) expectTypeOf(result.data.l1BatchNumber).toEqualTypeOf() }) ================================================ FILE: packages/register-tests/react/src/useWriteContract.test-d.ts ================================================ import { abi, config } from '@wagmi/test' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' import { useWriteContract } from 'wagmi' import { celo, mainnet, optimism } from 'wagmi/chains' test('chain formatters', () => { const { mutate } = useWriteContract() const shared = { address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], } as const mutate({ ...shared, feeCurrency: '0x', }) type Result = Parameters< typeof mutate< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof celo.id > >[0] expectTypeOf().toEqualTypeOf< `0x${string}` | undefined >() mutate({ ...shared, chainId: celo.id, feeCurrency: '0x', }) mutate({ ...shared, chainId: mainnet.id, // @ts-expect-error feeCurrency: '0x', }) mutate({ ...shared, chainId: optimism.id, // @ts-expect-error feeCurrency: '0x', }) }) test('parameters: config', async () => { const { mutate } = useWriteContract({ config }) mutate({ address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], // @ts-expect-error feeCurrency: '0x', }) }) ================================================ FILE: packages/register-tests/react/tsconfig.json ================================================ { "extends": "../../../tsconfig.base.json", "include": ["src/**/*.ts"], "exclude": [] } ================================================ FILE: packages/register-tests/solid/package.json ================================================ { "name": "solid-register", "private": true, "type": "module", "scripts": { "check:types": "tsc --noEmit" }, "dependencies": { "@tanstack/solid-query": "catalog:", "@wagmi/solid": "workspace:*", "solid-js": "catalog:" } } ================================================ FILE: packages/register-tests/solid/src/config.ts ================================================ import { createConfig, createConnector, mock } from '@wagmi/solid' import { celo, mainnet, optimism, zkSync } from '@wagmi/solid/chains' import { type Address, http } from 'viem' export const config = createConfig({ chains: [celo, mainnet, optimism, zkSync], connectors: [mock({ accounts: ['0x'] }), foo()], transports: { [celo.id]: http(), [mainnet.id]: http(), [optimism.id]: http(), [zkSync.id]: http(), }, }) export type ChainId = | typeof celo.id | typeof mainnet.id | typeof optimism.id | typeof zkSync.id declare module '@wagmi/solid' { interface Register { config: typeof config } } export function foo() { type Properties = { // TODO(v3): Make `withCapabilities: true` default behavior connect(parameters?: { chainId?: number | undefined isReconnecting?: boolean | undefined capabilities?: { signInWithEthereum?: { nonce: string } | undefined } withCapabilities?: withCapabilities | boolean | undefined }): Promise<{ accounts: withCapabilities extends true ? readonly { capabilities: { signInWithEthereum: { message: string signature: string } } }[] : readonly Address[] chainId: number }> } return createConnector((_config) => ({}) as never) } ================================================ FILE: packages/register-tests/solid/src/useChainId.test-d.ts ================================================ import { useChainId } from '@wagmi/solid' import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import type { ChainId } from './config.js' test('default', async () => { const chainId = useChainId() expectTypeOf(chainId()).toEqualTypeOf() }) test('parameters: config', async () => { const chainId = useChainId(() => ({ config })) expectTypeOf(chainId()).toEqualTypeOf<1 | 456 | 10>() }) ================================================ FILE: packages/register-tests/solid/src/useChains.test-d.ts ================================================ import { useChains } from '@wagmi/solid' import type { celo, mainnet, optimism, zkSync } from '@wagmi/solid/chains' import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' test('default', () => { const chains = useChains() expectTypeOf(chains()).toEqualTypeOf< readonly [typeof celo, typeof mainnet, typeof optimism, typeof zkSync] >() }) test('parameters: config', () => { const chains = useChains(() => ({ config })) expectTypeOf(chains()).toEqualTypeOf<(typeof config)['chains']>() }) ================================================ FILE: packages/register-tests/solid/src/useClient.test-d.ts ================================================ import { useClient } from '@wagmi/solid' import { mainnet } from '@wagmi/solid/chains' import { type chain, config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import type { ChainId } from './config.js' test('default', () => { const client = useClient() expectTypeOf(client().chain.id).toEqualTypeOf() expectTypeOf(client().transport.type).toEqualTypeOf<'http'>() }) test('parameters: config', () => { const client = useClient(() => ({ config })) expectTypeOf(client().chain.id).toEqualTypeOf< (typeof config)['chains'][number]['id'] >() expectTypeOf(client().transport.type).toEqualTypeOf<'http'>() }) test('parameters: chainId', () => { const client = useClient(() => ({ config, chainId: mainnet.id, })) expectTypeOf(client().chain).toEqualTypeOf() expectTypeOf(client().transport.type).toEqualTypeOf<'http'>() }) test('behavior: unconfigured chain', () => { const client = useClient( // @ts-expect-error chainId 123456 is not configured () => ({ config, chainId: 123456, }), ) expectTypeOf(client()).toEqualTypeOf() }) ================================================ FILE: packages/register-tests/solid/src/useConfig.test-d.ts ================================================ import { type Config, useConfig } from '@wagmi/solid' import { config as testConfig } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import type { config } from './config.js' test('default', async () => { const result = useConfig() expectTypeOf(result()).not.toEqualTypeOf() expectTypeOf(result()).toEqualTypeOf() }) test('parameters: config', async () => { const result = useConfig(() => ({ config: testConfig })) expectTypeOf(result()).not.toEqualTypeOf() expectTypeOf(result()).toEqualTypeOf() }) ================================================ FILE: packages/register-tests/solid/src/useConnect.test-d.ts ================================================ import { useConnect, useConnectors } from '@wagmi/solid' import type { Address, Hex } from 'viem' import { expectTypeOf, test } from 'vitest' test('infers connect parameters', () => { const connect = useConnect() const connectors = useConnectors() const connector = connectors()[0]! as ReturnType[number] connect.mutate({ connector, foo: 'bar', }) connect.mutate({ connector: connectors()[1], // @ts-expect-error foo: 'bar', }) connect.mutate({ connector, capabilities: { signInWithEthereum: { nonce: 'foobarbaz', }, }, }) connect.mutate({ connector: connectors()[0], // @ts-expect-error capabilities: { signInWithEthereum: { nonce: 'foobarbaz', }, }, }) connect.mutate( { connector, foo: 'bar', withCapabilities: true, }, { onSuccess(data, _variables, _context) { expectTypeOf(data.accounts).toEqualTypeOf< readonly [ { address: Address capabilities: | { foo: { bar: Hex } } | { signInWithEthereum: { message: string signature: string } } }, ...{ address: Address capabilities: | { foo: { bar: Hex } } | { signInWithEthereum: { message: string signature: string } } }[], ] >() }, onSettled(data, _error, _variables, _context) { expectTypeOf(data?.accounts).toEqualTypeOf< | readonly [ { address: Address capabilities: | { foo: { bar: Hex } } | { signInWithEthereum: { message: string signature: string } } }, ...{ address: Address capabilities: | { foo: { bar: Hex } } | { signInWithEthereum: { message: string signature: string } } }[], ] | undefined >() }, }, ) ;(async () => { await connect.mutateAsync({ connector, foo: 'bar', withCapabilities: true, }) const res = await connect.mutateAsync({ connector, capabilities: { signInWithEthereum: { nonce: 'foobarbaz', }, }, withCapabilities: true, }) expectTypeOf(res.accounts).toEqualTypeOf< readonly [ { address: Address capabilities: | { foo: { bar: Hex } } | { signInWithEthereum: { message: string signature: string } } }, ...{ address: Address capabilities: | { foo: { bar: Hex } } | { signInWithEthereum: { message: string signature: string } } }[], ] >() })() }) ================================================ FILE: packages/register-tests/solid/src/useConnection.test-d.ts ================================================ import { useConnection } from '@wagmi/solid' import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import type { ChainId } from './config.js' test('default', () => { const result = useConnection() const connection = result() if (connection.chain) expectTypeOf(connection.chain.id).toEqualTypeOf() }) test('parameters: config', async () => { const result = useConnection(() => ({ config })) const connection = result() if (connection.chain) expectTypeOf(connection.chain.id).toEqualTypeOf<1 | 10 | 456>() }) ================================================ FILE: packages/register-tests/solid/src/useSwitchChain.test-d.ts ================================================ import { useSwitchChain } from '@wagmi/solid' import { mainnet } from '@wagmi/solid/chains' import { expectTypeOf, test } from 'vitest' import type { ChainId } from './config.js' test('default', () => { const switchChain = useSwitchChain() switchChain.mutate( { chainId: 1 }, { onSuccess(data) { expectTypeOf(data).toEqualTypeOf(mainnet) }, }, ) type Result = Parameters<(typeof switchChain)['mutate']>[0] expectTypeOf().toEqualTypeOf() }) ================================================ FILE: packages/register-tests/solid/tsconfig.json ================================================ { "extends": "../../../tsconfig.base.json", "include": ["src/**/*.ts"], "exclude": [] } ================================================ FILE: packages/register-tests/vue/package.json ================================================ { "name": "vue-register", "private": true, "type": "module", "scripts": { "check:types": "tsc --noEmit" }, "dependencies": { "@tanstack/vue-query": "catalog:", "@wagmi/vue": "workspace:*", "vue": "catalog:" } } ================================================ FILE: packages/register-tests/vue/src/config.ts ================================================ import { createConfig, mock } from '@wagmi/vue' import { celo, mainnet, optimism, zkSync } from '@wagmi/vue/chains' import { http } from 'viem' export const config = createConfig({ chains: [celo, mainnet, optimism, zkSync], connectors: [mock({ accounts: ['0x'] })], transports: { [celo.id]: http(), [mainnet.id]: http(), [optimism.id]: http(), [zkSync.id]: http(), }, }) export type ChainId = | typeof celo.id | typeof mainnet.id | typeof optimism.id | typeof zkSync.id declare module '@wagmi/vue' { interface Register { config: typeof config } } ================================================ FILE: packages/register-tests/vue/src/useChainId.test-d.ts ================================================ import { config } from '@wagmi/test' import { useChainId } from '@wagmi/vue' import { expectTypeOf, test } from 'vitest' import type { ChainId } from './config.js' test('default', async () => { const chainId = useChainId() expectTypeOf(chainId.value).toEqualTypeOf() }) test('parameters: config', async () => { const chainId = useChainId({ config }) expectTypeOf(chainId.value).toEqualTypeOf<1 | 456 | 10>() }) ================================================ FILE: packages/register-tests/vue/src/useChains.test-d.ts ================================================ import { useChains } from '@wagmi/vue' import type { celo, optimism, zkSync } from '@wagmi/vue/chains' import { expectTypeOf, test } from 'vitest' test('default', () => { const chains = useChains() expectTypeOf(chains.value[0]).toEqualTypeOf() expectTypeOf(chains.value[2]).toEqualTypeOf() expectTypeOf(chains.value[3]).toEqualTypeOf() }) ================================================ FILE: packages/register-tests/vue/src/useClient.test-d.ts ================================================ import { type chain, config } from '@wagmi/test' import { useClient } from '@wagmi/vue' import { mainnet } from '@wagmi/vue/chains' import { expectTypeOf, test } from 'vitest' import type { ChainId } from './config.js' test('default', () => { const client = useClient() expectTypeOf(client.value.chain.id).toEqualTypeOf() expectTypeOf(client.value.transport.type).toEqualTypeOf<'http'>() }) test('parameters: config', () => { const client = useClient({ config }) expectTypeOf(client.value.chain.id).toEqualTypeOf< (typeof config)['chains'][number]['id'] >() expectTypeOf(client.value.transport.type).toEqualTypeOf<'http'>() }) test('parameters: chainId', () => { const client = useClient({ config, chainId: mainnet.id, }) expectTypeOf(client.value.chain).toEqualTypeOf() expectTypeOf(client.value.transport.type).toEqualTypeOf<'http'>() }) test('behavior: unconfigured chain', () => { const client = useClient({ config, // @ts-expect-error chainId: 123456, }) expectTypeOf(client.value).toEqualTypeOf() }) ================================================ FILE: packages/register-tests/vue/src/useConfig.test-d.ts ================================================ import { config as testConfig } from '@wagmi/test' import { type Config, useConfig } from '@wagmi/vue' import { expectTypeOf, test } from 'vitest' import type { config } from './config.js' test('default', async () => { const result = useConfig() expectTypeOf(result).not.toEqualTypeOf() expectTypeOf(result).toEqualTypeOf() }) test('parameters: config', async () => { const result = useConfig({ config: testConfig }) expectTypeOf(result).not.toEqualTypeOf() expectTypeOf(result).toEqualTypeOf() }) ================================================ FILE: packages/register-tests/vue/src/useConnect.test-d.ts ================================================ import { useConnect, useConnectors } from '@wagmi/vue' import type { Address, Hex } from 'viem' import { expectTypeOf, test } from 'vitest' test('infers connect parameters', () => { const connect = useConnect() const connectors = useConnectors() const connector = connectors.value[0]! expectTypeOf(connect.variables.value?.foo).toEqualTypeOf() connect.mutate({ connector, foo: 'bar', }) connect.mutate( { connector, foo: 'bar', withCapabilities: true, }, { onSuccess(data, _variables, _context) { expectTypeOf(data.accounts).toEqualTypeOf< readonly [ { address: Address capabilities: { foo: { bar: Hex } } }, ...{ address: Address capabilities: { foo: { bar: Hex } } }[], ] >() }, onSettled(data, _error, _variables, _context) { expectTypeOf(data?.accounts).toEqualTypeOf< | readonly [ { address: Address capabilities: { foo: { bar: Hex } } }, ...{ address: Address capabilities: { foo: { bar: Hex } } }[], ] | undefined >() }, }, ) ;(async () => { const res = await connect.mutateAsync({ connector, foo: 'bar', withCapabilities: true, }) expectTypeOf(res.accounts).toEqualTypeOf< readonly [ { address: Address capabilities: { foo: { bar: Hex } } }, ...{ address: Address capabilities: { foo: { bar: Hex } } }[], ] >() })() }) ================================================ FILE: packages/register-tests/vue/src/useConnection.test-d.ts ================================================ import { config } from '@wagmi/test' import { useConnection } from '@wagmi/vue' import { expectTypeOf, test } from 'vitest' import type { ChainId } from './config.js' test('default', () => { const result = useConnection() if (result.chain.value) expectTypeOf(result.chain.value.id).toEqualTypeOf() }) test('parameters: config', async () => { const result = useConnection({ config }) if (result.chain.value) expectTypeOf(result.chain.value.id).toEqualTypeOf<1 | 10 | 456>() }) ================================================ FILE: packages/register-tests/vue/src/useReadContract.test-d.ts ================================================ import type { abi } from '@wagmi/test' import type { useReadContract } from '@wagmi/vue' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' import type { DeepUnwrapRef } from '../../../vue/src/types/ref.js' import type { ChainId } from './config.js' test('UseReadContractParameters', () => { type Result = DeepUnwrapRef< NonNullable< Parameters< typeof useReadContract >[0] > > expectTypeOf().toMatchTypeOf<{ functionName?: | 'symbol' | 'name' | 'allowance' | 'balanceOf' | 'decimals' | 'totalSupply' | undefined args?: readonly [Address] | undefined chainId?: ChainId | undefined }>() }) ================================================ FILE: packages/register-tests/vue/src/useSendTransaction.test-d.ts ================================================ import { config } from '@wagmi/test' import { useSendTransaction } from '@wagmi/vue' import { celo, mainnet, optimism } from '@wagmi/vue/chains' import { expectTypeOf, test } from 'vitest' import type { ChainId } from './config.js' test('chain formatters', () => { const { mutate } = useSendTransaction() mutate( { to: '0x', feeCurrency: '0x', }, { onSuccess(_data, variables) { expectTypeOf(variables.chainId).toEqualTypeOf() }, }, ) type Result = Parameters>[0] expectTypeOf().toEqualTypeOf< `0x${string}` | undefined >() mutate({ chainId: celo.id, to: '0x', feeCurrency: '0x', }) mutate({ chainId: mainnet.id, to: '0x', // @ts-expect-error feeCurrency: '0x', }) mutate({ chainId: optimism.id, to: '0x', // @ts-expect-error feeCurrency: '0x', }) }) test('parameters: config', async () => { const { mutate } = useSendTransaction({ config }) mutate({ to: '0x', // @ts-expect-error feeCurrency: '0x', }) }) ================================================ FILE: packages/register-tests/vue/src/useSimulateContract.test-d.ts ================================================ import type { abi } from '@wagmi/test' import { type UseSimulateContractParameters, useSimulateContract, } from '@wagmi/vue' import { celo, mainnet, optimism } from '@wagmi/vue/chains' import type { SimulateContractOptions } from '@wagmi/vue/query' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' import type { ChainId, config } from './config.js' test('chain formatters', () => { const { data } = useSimulateContract({ feeCurrency: '0x', }) if (data.value && data.value.chainId === celo.id) { expectTypeOf(data.value.request.feeCurrency).toEqualTypeOf< `0x${string}` | undefined >() } const { data: data2 } = useSimulateContract({ chainId: celo.id, feeCurrency: '0x', }) if (data2.value) { expectTypeOf(data2.value.request.feeCurrency).toEqualTypeOf< `0x${string}` | undefined >() } useSimulateContract({ chainId: mainnet.id, // @ts-expect-error feeCurrency: '0x', }) useSimulateContract({ chainId: optimism.id, // @ts-expect-error feeCurrency: '0x', }) }) test('UseSimulateContractParameters', () => { type Result = UseSimulateContractParameters< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config > const res = {} as Result expectTypeOf(res.value?.functionName).toEqualTypeOf< 'approve' | 'transfer' | 'transferFrom' | undefined >() if (res.value?.args) { expectTypeOf(res.value.args[0]).toEqualTypeOf
() expectTypeOf(res.value.args[1]).toEqualTypeOf
() expectTypeOf(res.value.args[2]).toEqualTypeOf() } expectTypeOf(res.value?.chainId).toEqualTypeOf() type Result2 = UseSimulateContractParameters< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config, typeof celo.id > expectTypeOf(({} as Result2).value?.chainId).toEqualTypeOf< ChainId | undefined >() type Result3 = UseSimulateContractParameters< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config, typeof celo.id > expectTypeOf(({} as Result3).value?.chainId).toEqualTypeOf< ChainId | undefined >() type Result4 = SimulateContractOptions< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof config, typeof celo.id > expectTypeOf().toEqualTypeOf() }) ================================================ FILE: packages/register-tests/vue/src/useSwitchChain.test-d.ts ================================================ import { useSwitchChain } from '@wagmi/vue' import { mainnet } from '@wagmi/vue/chains' import { expectTypeOf, test } from 'vitest' import type { ChainId } from './config.js' test('default', () => { const switchChain = useSwitchChain() switchChain.switchChain( { chainId: 1 }, { onSuccess(data) { expectTypeOf(data).toEqualTypeOf(mainnet) }, }, ) type Result = Parameters<(typeof switchChain)['switchChain']>[0] expectTypeOf().toEqualTypeOf() }) ================================================ FILE: packages/register-tests/vue/src/useTransaction.test-d.ts ================================================ import { config } from '@wagmi/test' import { useTransaction } from '@wagmi/vue' import { celo } from '@wagmi/vue/chains' import { expectTypeOf, test } from 'vitest' test('chain formatters', () => { const result = useTransaction() if (result.data?.value?.chainId === celo.id) { expectTypeOf(result.data.value.feeCurrency).toEqualTypeOf< `0x${string}` | null >() } const result2 = useTransaction({ chainId: celo.id }) expectTypeOf(result2.data?.value?.feeCurrency).toEqualTypeOf< `0x${string}` | null | undefined >() }) test('parameters: config', async () => { const result = useTransaction({ config }) if (result.data && 'feeCurrency' in result.data) expectTypeOf(result.data.feeCurrency).toEqualTypeOf() }) ================================================ FILE: packages/register-tests/vue/src/useTransactionReceipt.test-d.ts ================================================ import { config } from '@wagmi/test' import { useTransactionReceipt } from '@wagmi/vue' import { zkSync } from '@wagmi/vue/chains' import type { ZkSyncL2ToL1Log, ZkSyncLog } from 'viem/zksync' import { expectTypeOf, test } from 'vitest' test('chain formatters', () => { const result = useTransactionReceipt() if (result.data?.value?.chainId === zkSync.id) { expectTypeOf(result.data.value.l1BatchNumber).toEqualTypeOf() expectTypeOf(result.data.value.l1BatchTxIndex).toEqualTypeOf< bigint | null >() expectTypeOf(result.data.value.logs).toEqualTypeOf() expectTypeOf(result.data.value.l2ToL1Logs).toEqualTypeOf< ZkSyncL2ToL1Log[] >() } const result2 = useTransactionReceipt({ chainId: zkSync.id }) if (result2.data.value) { expectTypeOf(result2.data.value.l1BatchNumber).toEqualTypeOf< bigint | null >() expectTypeOf(result2.data.value.l1BatchTxIndex).toEqualTypeOf< bigint | null >() expectTypeOf(result2.data.value.logs).toEqualTypeOf() expectTypeOf(result2.data.value.l2ToL1Logs).toEqualTypeOf< ZkSyncL2ToL1Log[] >() } }) test('parameters: config', async () => { const result = useTransactionReceipt({ config }) if (result.data && 'l1BatchNumber' in result.data) expectTypeOf(result.data.l1BatchNumber).toEqualTypeOf() }) ================================================ FILE: packages/register-tests/vue/src/useWaitForTransaction.test-d.ts ================================================ import { config } from '@wagmi/test' import { useWaitForTransactionReceipt } from '@wagmi/vue' import { zkSync } from '@wagmi/vue/chains' import type { ZkSyncL2ToL1Log, ZkSyncLog } from 'viem/zksync' import { expectTypeOf, test } from 'vitest' test('chain formatters', () => { const result = useWaitForTransactionReceipt() if (result.data?.value?.chainId === zkSync.id) { expectTypeOf(result.data.value.l1BatchNumber).toEqualTypeOf() expectTypeOf(result.data.value.l1BatchTxIndex).toEqualTypeOf< bigint | null >() expectTypeOf(result.data.value.logs).toEqualTypeOf() expectTypeOf(result.data.value.l2ToL1Logs).toEqualTypeOf< ZkSyncL2ToL1Log[] >() } const result2 = useWaitForTransactionReceipt({ chainId: zkSync.id }) if (result2.data.value) { expectTypeOf(result2.data.value.l1BatchNumber).toEqualTypeOf< bigint | null >() expectTypeOf(result2.data.value.l1BatchTxIndex).toEqualTypeOf< bigint | null >() expectTypeOf(result2.data.value.logs).toEqualTypeOf() expectTypeOf(result2.data.value.l2ToL1Logs).toEqualTypeOf< ZkSyncL2ToL1Log[] >() } }) test('parameters: config', async () => { const result = useWaitForTransactionReceipt({ config }) if (result.data && 'l1BatchNumber' in result.data) expectTypeOf(result.data.l1BatchNumber).toEqualTypeOf() }) ================================================ FILE: packages/register-tests/vue/src/useWriteContract.test-d.ts ================================================ import { abi, config } from '@wagmi/test' import { useWriteContract } from '@wagmi/vue' import { celo, mainnet, optimism } from '@wagmi/vue/chains' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' test('chain formatters', () => { const { mutate } = useWriteContract() const shared = { address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], } as const mutate({ ...shared, feeCurrency: '0x', }) type Result = Parameters< typeof mutate< typeof abi.erc20, 'transferFrom', [Address, Address, bigint], typeof celo.id > >[0] expectTypeOf().toEqualTypeOf< `0x${string}` | undefined >() mutate({ ...shared, chainId: celo.id, feeCurrency: '0x', }) mutate({ ...shared, chainId: mainnet.id, // @ts-expect-error feeCurrency: '0x', }) mutate({ ...shared, chainId: optimism.id, // @ts-expect-error feeCurrency: '0x', }) }) test('parameters: config', async () => { const { mutate } = useWriteContract({ config }) mutate({ address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], // @ts-expect-error feeCurrency: '0x', }) }) ================================================ FILE: packages/register-tests/vue/tsconfig.json ================================================ { "extends": "../../../tsconfig.base.json", "include": ["src/**/*.ts"], "exclude": [] } ================================================ FILE: packages/solid/CHANGELOG.md ================================================ # @wagmi/solid ## 0.0.4 ### Patch Changes - Updated query entrypoint exports ([#4995](https://github.com/wevm/wagmi/pull/4995)) - Updated dependencies [[`8b96e2f`](https://github.com/wevm/wagmi/commit/8b96e2f46d9b3441d3b499b03924700ac0629be6)]: - @wagmi/core@3.4.0 - @wagmi/connectors@7.2.1 ## 0.0.3 ### Patch Changes - Updated dependencies [[`c1dedd9`](https://github.com/wevm/wagmi/commit/c1dedd99c0a1878d7cd48476946868636ac81dd8), [`9dbdd82`](https://github.com/wevm/wagmi/commit/9dbdd8277808eb361fe7fe01ea34e4c6bb85c7a5)]: - @wagmi/core@3.3.4 - @wagmi/connectors@7.2.0 ## 0.0.2 ### Patch Changes - Updated dependencies [[`4b3f5a3`](https://github.com/wevm/wagmi/commit/4b3f5a3f7b3f242e8fbc1f08ae2f81ae13c5e09f)]: - @wagmi/core@3.3.3 - @wagmi/connectors@7.1.7 ## 0.0.1 ### Patch Changes - Initial release ([`68e17db`](https://github.com/wevm/wagmi/commit/68e17db7ff84982db8f52f54e6f047c5efab62ab)) - Updated dependencies [[`68e17db`](https://github.com/wevm/wagmi/commit/68e17db7ff84982db8f52f54e6f047c5efab62ab)]: - @wagmi/core@3.3.2 - @wagmi/connectors@7.1.6 ================================================ FILE: packages/solid/README.md ================================================ # @wagmi/solid Solid Primitives for Ethereum ## Installation ```bash pnpm add @wagmi/solid viem @tanstack/solid-query ``` ## Documentation For documentation and guides, visit [wagmi.sh](https://wagmi.sh). ================================================ FILE: packages/solid/package.json ================================================ { "name": "@wagmi/solid", "description": "Solid Primitives for Ethereum", "version": "0.0.4", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/wevm/wagmi.git", "directory": "packages/solid" }, "scripts": { "build": "pnpm run clean && pnpm run build:esm+types", "build:esm+types": "tsc --project tsconfig.build.json --outDir ./dist/esm --declaration --declarationMap --declarationDir ./dist/types", "check:types": "tsc --noEmit", "clean": "rm -rf dist tsconfig.tsbuildinfo actions chains connectors query", "test:build": "publint --strict && attw --pack --ignore-rules cjs-resolves-to-esm" }, "files": [ "dist/**", "!dist/**/*.tsbuildinfo", "src/**/*.ts", "!src/**/*.test.ts", "!src/**/*.test-d.ts", "/actions", "/chains", "/connectors", "/query" ], "sideEffects": false, "type": "module", "main": "./dist/esm/exports/index.js", "types": "./dist/types/exports/index.d.ts", "typings": "./dist/types/exports/index.d.ts", "exports": { ".": { "types": "./dist/types/exports/index.d.ts", "default": "./dist/esm/exports/index.js" }, "./actions": { "types": "./dist/types/exports/actions.d.ts", "default": "./dist/esm/exports/actions.js" }, "./chains": { "types": "./dist/types/exports/chains.d.ts", "default": "./dist/esm/exports/chains.js" }, "./connectors": { "types": "./dist/types/exports/connectors.d.ts", "default": "./dist/esm/exports/connectors.js" }, "./query": { "types": "./dist/types/exports/query.d.ts", "default": "./dist/esm/exports/query.js" }, "./package.json": "./package.json" }, "typesVersions": { "*": { "actions": [ "./dist/types/exports/actions.d.ts" ], "chains": [ "./dist/types/exports/chains.d.ts" ], "connectors": [ "./dist/types/exports/connectors.d.ts" ], "query": [ "./dist/types/exports/query.d.ts" ] } }, "peerDependencies": { "@tanstack/solid-query": ">=5.0.0", "solid-js": "1.x", "typescript": ">=5.7.3", "viem": "2.x" }, "peerDependenciesMeta": { "typescript": { "optional": true } }, "dependencies": { "@wagmi/connectors": "workspace:*", "@wagmi/core": "workspace:*" }, "devDependencies": { "@tanstack/solid-query": "catalog:", "solid-js": "catalog:" }, "contributors": [ "awkweb.eth ", "jxom.eth " ], "funding": "https://github.com/sponsors/wevm", "keywords": [ "wagmi", "solid", "primitives", "eth", "ethereum", "dapps", "wallet", "web3" ] } ================================================ FILE: packages/solid/src/context.ts ================================================ import type { ResolvedRegister, State } from '@wagmi/core' import { createComponent, createContext, mergeProps, type ParentProps, } from 'solid-js' import { Hydrate } from './hydrate.js' export const WagmiContext = createContext< ResolvedRegister['config'] | undefined >(undefined) export type WagmiProviderProps = { config: ResolvedRegister['config'] initialState?: State | undefined reconnectOnMount?: boolean | undefined } export function WagmiProvider(parameters: ParentProps) { const props = mergeProps({ reconnectOnMount: true }, parameters) return createComponent(Hydrate, { get config() { return props.config }, get initialState() { return props.initialState }, get reconnectOnMount() { return props.reconnectOnMount }, get children() { return createComponent(WagmiContext.Provider, { get value() { return props.config }, get children() { return props.children }, }) }, }) } ================================================ FILE: packages/solid/src/errors/base.test.ts ================================================ import { expect, test } from 'vitest' import { BaseError } from './base.js' test('BaseError', () => { expect(new BaseError('An error occurred.')).toMatchInlineSnapshot(` [WagmiError: An error occurred. Version: @wagmi/solid@x.y.z] `) expect( new BaseError('An error occurred.', { details: 'details' }), ).toMatchInlineSnapshot(` [WagmiError: An error occurred. Details: details Version: @wagmi/solid@x.y.z] `) expect(new BaseError('', { details: 'details' })).toMatchInlineSnapshot(` [WagmiError: An error occurred. Details: details Version: @wagmi/solid@x.y.z] `) }) test('BaseError (w/ docsPath)', () => { expect( new BaseError('An error occurred.', { details: 'details', docsPath: '/lol', }), ).toMatchInlineSnapshot(` [WagmiError: An error occurred. Docs: https://wagmi.sh/solid/lol.html Details: details Version: @wagmi/solid@x.y.z] `) expect( new BaseError('An error occurred.', { cause: new BaseError('error', { docsPath: '/docs' }), }), ).toMatchInlineSnapshot(` [WagmiError: An error occurred. Docs: https://wagmi.sh/solid/docs.html Version: @wagmi/solid@x.y.z] `) expect( new BaseError('An error occurred.', { cause: new BaseError('error'), docsPath: '/lol', }), ).toMatchInlineSnapshot(` [WagmiError: An error occurred. Docs: https://wagmi.sh/solid/lol.html Version: @wagmi/solid@x.y.z] `) expect( new BaseError('An error occurred.', { details: 'details', docsPath: '/lol', docsSlug: 'test', }), ).toMatchInlineSnapshot(` [WagmiError: An error occurred. Docs: https://wagmi.sh/solid/lol.html#test Details: details Version: @wagmi/solid@x.y.z] `) }) test('BaseError (w/ metaMessages)', () => { expect( new BaseError('An error occurred.', { details: 'details', metaMessages: ['Reason: idk', 'Cause: lol'], }), ).toMatchInlineSnapshot(` [WagmiError: An error occurred. Reason: idk Cause: lol Details: details Version: @wagmi/solid@x.y.z] `) }) test('inherited BaseError', () => { const err = new BaseError('An error occurred.', { details: 'details', docsPath: '/lol', }) expect( new BaseError('An internal error occurred.', { cause: err, }), ).toMatchInlineSnapshot(` [WagmiError: An internal error occurred. Docs: https://wagmi.sh/solid/lol.html Details: details Version: @wagmi/solid@x.y.z] `) }) test('inherited Error', () => { const err = new Error('details') expect( new BaseError('An internal error occurred.', { cause: err, docsPath: '/lol', }), ).toMatchInlineSnapshot(` [WagmiError: An internal error occurred. Docs: https://wagmi.sh/solid/lol.html Details: details Version: @wagmi/solid@x.y.z] `) }) test('walk: no predicate fn (walks to leaf)', () => { class FooError extends BaseError {} class BarError extends BaseError {} const err = new BaseError('test1', { cause: new FooError('test2', { cause: new BarError('test3') }), }) expect(err.walk()).toMatchInlineSnapshot(` [WagmiError: test3 Version: @wagmi/solid@x.y.z] `) }) test('walk: predicate fn', () => { class FooError extends BaseError {} class BarError extends BaseError {} const err = new BaseError('test1', { cause: new FooError('test2', { cause: new BarError('test3') }), }) expect(err.walk((err) => err instanceof FooError)).toMatchInlineSnapshot(` [WagmiError: test2 Version: @wagmi/solid@x.y.z] `) }) ================================================ FILE: packages/solid/src/errors/base.ts ================================================ import { BaseError as CoreError } from '@wagmi/core' import { getVersion } from '../utils/getVersion.js' export type BaseErrorType = BaseError & { name: 'WagmiError' } export class BaseError extends CoreError { override name = 'WagmiError' override get docsBaseUrl() { return 'https://wagmi.sh/solid' // TODO: add solid docs } override get version() { return getVersion() } } ================================================ FILE: packages/solid/src/errors/context.test.ts ================================================ import { expect, test } from 'vitest' import { WagmiProviderNotFoundError } from './context.js' test('WagmiProviderNotFoundError', () => { expect(new WagmiProviderNotFoundError()).toMatchInlineSnapshot(` [WagmiProviderNotFoundError: \`useConfig\` must be used within \`WagmiProvider\`. Docs: https://wagmi.sh/solid/api/WagmiProvider.html Version: @wagmi/solid@x.y.z] `) }) ================================================ FILE: packages/solid/src/errors/context.ts ================================================ import { BaseError } from './base.js' export type WagmiProviderNotFoundErrorType = WagmiProviderNotFoundError & { name: 'WagmiProviderNotFoundError' } export class WagmiProviderNotFoundError extends BaseError { override name = 'WagmiProviderNotFoundError' constructor() { super('`useConfig` must be used within `WagmiProvider`.', { docsPath: '/api/WagmiProvider', }) } } ================================================ FILE: packages/solid/src/exports/actions.test.ts ================================================ import { expect, test } from 'vitest' import * as actions from './actions.js' test('exports', () => { expect(Object.keys(actions)).toMatchInlineSnapshot(` [ "call", "connect", "deployContract", "disconnect", "estimateFeesPerGas", "estimateGas", "estimateMaxPriorityFeePerGas", "getAccount", "getBalance", "getBlobBaseFee", "getBlock", "getBlockNumber", "getBlockTransactionCount", "getBytecode", "getCallsStatus", "getCapabilities", "getChainId", "getChains", "getClient", "getConnection", "getConnections", "getConnectorClient", "getConnectors", "getContractEvents", "getEnsAddress", "getEnsAvatar", "getEnsName", "getEnsResolver", "getEnsText", "getFeeHistory", "getGasPrice", "getProof", "getPublicClient", "getStorageAt", "getTransaction", "getTransactionConfirmations", "getTransactionCount", "getTransactionReceipt", "getWalletClient", "multicall", "prepareTransactionRequest", "readContract", "readContracts", "reconnect", "sendCalls", "sendTransaction", "showCallsStatus", "signMessage", "signTransaction", "signTypedData", "simulateContract", "switchAccount", "switchChain", "switchConnection", "verifyMessage", "verifyTypedData", "waitForCallsStatus", "waitForTransactionReceipt", "watchAccount", "watchAsset", "watchBlockNumber", "watchBlocks", "watchChainId", "watchClient", "watchConnection", "watchConnections", "watchConnectors", "watchContractEvent", "watchPendingTransactions", "watchPublicClient", "writeContract", ] `) }) ================================================ FILE: packages/solid/src/exports/actions.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // @wagmi/core/actions //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module // biome-ignore lint/performance/noReExportAll: entrypoint module export * from '@wagmi/core/actions' ================================================ FILE: packages/solid/src/exports/chains.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // viem/chains //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module // biome-ignore lint/performance/noReExportAll: entrypoint module export * from 'viem/chains' ================================================ FILE: packages/solid/src/exports/connectors.test.ts ================================================ import { expect, test } from 'vitest' import * as connectors from './connectors.js' test('exports', () => { expect(Object.keys(connectors)).toMatchInlineSnapshot(` [ "baseAccount", "coinbaseWallet", "injected", "metaMask", "mock", "porto", "safe", "version", "walletConnect", ] `) }) ================================================ FILE: packages/solid/src/exports/connectors.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // @wagmi/connectors //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module // biome-ignore lint/performance/noReExportAll: entrypoint module export * from '@wagmi/connectors' ================================================ FILE: packages/solid/src/exports/index.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // Context //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module export { WagmiContext, WagmiProvider, type WagmiProviderProps, } from '../context.js' //////////////////////////////////////////////////////////////////////////////// // Errors //////////////////////////////////////////////////////////////////////////////// export { BaseError, type BaseErrorType } from '../errors/base.js' export { WagmiProviderNotFoundError, type WagmiProviderNotFoundErrorType, } from '../errors/context.js' //////////////////////////////////////////////////////////////////////////////// // Primitives //////////////////////////////////////////////////////////////////////////////// export { useBalance } from '../primitives/useBalance.js' export { useBlockNumber } from '../primitives/useBlockNumber.js' export { useChainId } from '../primitives/useChainId.js' export { useChains } from '../primitives/useChains.js' export { useClient } from '../primitives/useClient.js' export { useConfig } from '../primitives/useConfig.js' export { useConnect } from '../primitives/useConnect.js' export { useConnection } from '../primitives/useConnection.js' export { useConnectionEffect } from '../primitives/useConnectionEffect.js' export { useConnections } from '../primitives/useConnections.js' export { useConnectorClient } from '../primitives/useConnectorClient.js' export { useConnectors } from '../primitives/useConnectors.js' export { useDisconnect } from '../primitives/useDisconnect.js' export { useReconnect } from '../primitives/useReconnect.js' export { useSwitchChain } from '../primitives/useSwitchChain.js' export { useSwitchConnection } from '../primitives/useSwitchConnection.js' export { useWatchBlockNumber } from '../primitives/useWatchBlockNumber.js' //////////////////////////////////////////////////////////////////////////////// // Hydrate //////////////////////////////////////////////////////////////////////////////// export { Hydrate, type HydrateProps, } from '../hydrate.js' //////////////////////////////////////////////////////////////////////////////// // @wagmi/core //////////////////////////////////////////////////////////////////////////////// export { ChainNotConfiguredError, // Errors type ChainNotConfiguredErrorType, type Config, // Config type Connection, type Connector, ConnectorAccountNotFoundError, type ConnectorAccountNotFoundErrorType, ConnectorAlreadyConnectedError, type ConnectorAlreadyConnectedErrorType, ConnectorChainMismatchError, type ConnectorChainMismatchErrorType, // Connector type ConnectorEventMap, ConnectorNotFoundError, type ConnectorNotFoundErrorType, ConnectorUnavailableReconnectingError, type ConnectorUnavailableReconnectingErrorType, type CreateConfigParameters, type CreateConnectorFn, // Storage type CreateStorageParameters, // Utilities cookieStorage, cookieToInitialState, createConfig, createConnector, createStorage, // Transports custom, deepEqual, deserialize, fallback, http, injected, mock, noopStorage, type PartializedState, ProviderNotFoundError, type ProviderNotFoundErrorType, parseCookie, // Types type Register, type ResolvedRegister, type State, type Storage, SwitchChainNotSupportedError, type SwitchChainNotSupportedErrorType, serialize, type Transport, unstable_connector, webSocket, } from '@wagmi/core' //////////////////////////////////////////////////////////////////////////////// // Version //////////////////////////////////////////////////////////////////////////////// export { version } from '../version.js' ================================================ FILE: packages/solid/src/exports/query.test.ts ================================================ import { expect, test } from 'vitest' import * as query from './query.js' test('exports', () => { expect(Object.keys(query)).toMatchInlineSnapshot(` [ "callQueryKey", "callQueryOptions", "connectMutationOptions", "deployContractMutationOptions", "disconnectMutationOptions", "estimateFeesPerGasQueryKey", "estimateFeesPerGasQueryOptions", "estimateGasQueryKey", "estimateGasQueryOptions", "estimateMaxPriorityFeePerGasQueryKey", "estimateMaxPriorityFeePerGasQueryOptions", "getBalanceQueryKey", "getBalanceQueryOptions", "getBlobBaseFeeQueryKey", "getBlobBaseFeeQueryOptions", "getBlockNumberQueryKey", "getBlockNumberQueryOptions", "getBlockQueryKey", "getBlockQueryOptions", "getBlockTransactionCountQueryKey", "getBlockTransactionCountQueryOptions", "getBytecodeQueryKey", "getBytecodeQueryOptions", "getCallsStatusQueryKey", "getCallsStatusQueryOptions", "getCapabilitiesQueryKey", "getCapabilitiesQueryOptions", "getConnectorClientQueryKey", "getConnectorClientQueryOptions", "getContractEventsQueryKey", "getContractEventsQueryOptions", "getEnsAddressQueryKey", "getEnsAddressQueryOptions", "getEnsAvatarQueryKey", "getEnsAvatarQueryOptions", "getEnsNameQueryKey", "getEnsNameQueryOptions", "getEnsResolverQueryKey", "getEnsResolverQueryOptions", "getEnsTextQueryKey", "getEnsTextQueryOptions", "getFeeHistoryQueryKey", "getFeeHistoryQueryOptions", "getGasPriceQueryKey", "getGasPriceQueryOptions", "getProofQueryKey", "getProofQueryOptions", "getStorageAtQueryKey", "getStorageAtQueryOptions", "getTransactionConfirmationsQueryKey", "getTransactionConfirmationsQueryOptions", "getTransactionCountQueryKey", "getTransactionCountQueryOptions", "getTransactionQueryKey", "getTransactionQueryOptions", "getTransactionReceiptQueryKey", "getTransactionReceiptQueryOptions", "getWalletClientQueryKey", "getWalletClientQueryOptions", "hashFn", "infiniteReadContractsQueryKey", "infiniteReadContractsQueryOptions", "prepareTransactionRequestQueryKey", "prepareTransactionRequestQueryOptions", "readContractQueryKey", "readContractQueryOptions", "readContractsQueryKey", "readContractsQueryOptions", "reconnectMutationOptions", "sendCallsMutationOptions", "sendCallsSyncMutationOptions", "sendTransactionMutationOptions", "sendTransactionSyncMutationOptions", "showCallsStatusMutationOptions", "signMessageMutationOptions", "signTransactionMutationOptions", "signTypedDataMutationOptions", "simulateContractQueryKey", "simulateContractQueryOptions", "structuralSharing", "switchAccountMutationOptions", "switchChainMutationOptions", "switchConnectionMutationOptions", "useInfiniteQuery", "useMutation", "useQuery", "verifyMessageQueryKey", "verifyMessageQueryOptions", "verifyTypedDataQueryKey", "verifyTypedDataQueryOptions", "waitForCallsStatusQueryKey", "waitForCallsStatusQueryOptions", "waitForTransactionReceiptQueryKey", "waitForTransactionReceiptQueryOptions", "watchAssetMutationOptions", "writeContractMutationOptions", "writeContractSyncMutationOptions", ] `) }) ================================================ FILE: packages/solid/src/exports/query.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // @wagmi/core/query //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module // biome-ignore lint/performance/noReExportAll: entrypoint module export * from '@wagmi/core/query' export { type SolidInfiniteQueryParameters, type SolidMutationParameters, type SolidQueryParameters, type UseInfiniteQueryReturnType, type UseMutationReturnType, type UseQueryReturnType, useInfiniteQuery, useMutation, useQuery, } from '../utils/query.js' ================================================ FILE: packages/solid/src/hydrate.ts ================================================ import { hydrate, type ResolvedRegister, type State } from '@wagmi/core' import { mergeProps, onMount, type ParentProps } from 'solid-js' export type HydrateProps = { config: ResolvedRegister['config'] initialState?: State | undefined reconnectOnMount?: boolean | undefined } export function Hydrate(parameters: ParentProps) { const props = mergeProps({ reconnectOnMount: true }, parameters) const { onMount: hydrateOnMount } = hydrate(props.config, { initialState: props.initialState, reconnectOnMount: props.reconnectOnMount, }) // Hydrate for non-SSR if (!props.config._internal.ssr) hydrateOnMount() onMount(() => { if (!props.config._internal.ssr) return hydrateOnMount() }) return props.children } ================================================ FILE: packages/solid/src/primitives/useBalance.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useBalance } from './useBalance.js' test('select data', () => { const result = useBalance(() => ({ query: { select(data) { return data?.value }, }, })) expectTypeOf(result.data).toEqualTypeOf() }) ================================================ FILE: packages/solid/src/primitives/useBalance.test.ts ================================================ import { accounts, chain, testClient, wait } from '@wagmi/test' import { renderPrimitive } from '@wagmi/test/solid' import { createSignal } from 'solid-js' import { type Address, parseEther } from 'viem' import { beforeEach, expect, test, vi } from 'vitest' import { useBalance } from './useBalance.js' const address = accounts[0] beforeEach(async () => { await testClient.mainnet.setBalance({ address, value: parseEther('10000') }) await testClient.mainnet.mine({ blocks: 1 }) await testClient.mainnet2.setBalance({ address, value: parseEther('69') }) await testClient.mainnet2.mine({ blocks: 1 }) }) test('default', async () => { const { result } = renderPrimitive(() => useBalance(() => ({ address }))) await vi.waitUntil(() => result.isSuccess, { timeout: 10_000 }) const { data, ...rest } = result expect(data).toMatchObject( expect.objectContaining({ decimals: expect.any(Number), symbol: expect.any(String), value: expect.any(BigInt), }), ) expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "balance", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) test('parameters: chainId', async () => { const { result } = renderPrimitive(() => useBalance(() => ({ address, chainId: chain.mainnet2.id })), ) await vi.waitUntil(() => result.isSuccess, { timeout: 10_000 }) expect(result).toMatchInlineSnapshot(` { "data": { "decimals": 18, "symbol": "WAG", "value": 69000000000000000000n, }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "balance", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 456, }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: address: undefined -> defined', async () => { const [address, setAddress] = createSignal
() const { result } = renderPrimitive(() => useBalance(() => ({ address: address() })), ) expect(result).toMatchInlineSnapshot(` { "data": undefined, "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "balance", { "address": undefined, "chainId": 1, }, ], "refetch": [Function], "status": "pending", } `) setAddress(accounts[0]) await vi.waitUntil(() => result.isSuccess, { timeout: 10_000 }) expect(result).toMatchInlineSnapshot(` { "data": { "decimals": 18, "symbol": "ETH", "value": 10000000000000000000000n, }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "balance", { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) }) test('behavior: disabled when properties missing', async () => { const { result } = renderPrimitive(() => useBalance()) await wait(100) await vi.waitFor(() => expect(result.isPending).toBeTruthy()) }) ================================================ FILE: packages/solid/src/primitives/useBalance.ts ================================================ import type { Config, GetBalanceErrorType, ResolvedRegister } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetBalanceData, type GetBalanceOptions, getBalanceQueryOptions, } from '@wagmi/core/query' import { type Accessor, createMemo } from 'solid-js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' /** https://wagmi.sh/solid/api/primitives/useBalance */ export function useBalance< config extends Config = ResolvedRegister['config'], selectData = GetBalanceData, >( parameters: useBalance.Parameters = () => ({}), ): useBalance.ReturnType { const config = useConfig(parameters) const chainId = useChainId(() => ({ config: config() })) const options = createMemo(() => getBalanceQueryOptions(config(), { ...parameters(), chainId: parameters().chainId ?? chainId(), }), ) return useQuery(options) } export namespace useBalance { export type Parameters< config extends Config = Config, selectData = GetBalanceData, > = Accessor> export type ReturnType = UseQueryReturnType< selectData, GetBalanceErrorType > export type SolidParameters< config extends Config = Config, selectData = GetBalanceData, > = Compute & ConfigParameter> } ================================================ FILE: packages/solid/src/primitives/useBlockNumber.test-d.ts ================================================ import { createConfig, http, webSocket } from '@wagmi/core' import { mainnet, optimism } from '@wagmi/core/chains' import { expectTypeOf, test } from 'vitest' import { useBlockNumber } from './useBlockNumber.js' test('select data', () => { const result = useBlockNumber(() => ({ query: { select(data) { expectTypeOf(data).toEqualTypeOf() return data?.toString() }, }, })) expectTypeOf(result.data).toEqualTypeOf() }) test('differing transports', () => { const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: webSocket(), }, }) useBlockNumber(() => ({ config, watch: { poll: false, }, })) useBlockNumber(() => ({ config, chainId: mainnet.id, watch: { poll: true, }, })) // @ts-expect-error useBlockNumber(() => ({ config, chainId: mainnet.id, watch: { poll: false, }, })) useBlockNumber(() => ({ config, chainId: optimism.id, watch: { poll: true, }, })) useBlockNumber(() => ({ config, chainId: optimism.id, watch: { poll: false, }, })) }) ================================================ FILE: packages/solid/src/primitives/useBlockNumber.test.ts ================================================ import { testClient } from '@wagmi/test' import { renderPrimitive } from '@wagmi/test/solid' import { describe, expect, test, vi } from 'vitest' import { useBlockNumber } from './useBlockNumber.js' describe.sequential('useBlockNumber', () => { test('mounts', async () => { await testClient.mainnet.restart() const { result, cleanup } = renderPrimitive(() => useBlockNumber()) await vi.waitUntil(() => result.isSuccess, { timeout: 10_000 }) // result is a proxy object (store in Solid) // so we spread it into a new object for snapshot testing expect({ ...result }).toMatchInlineSnapshot(` { "data": 23535880n, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "blockNumber", { "chainId": 1, }, ], "refetch": [Function], "status": "success", } `) cleanup() }) test('parameters: watch', async () => { await testClient.mainnet.restart() const { result, cleanup } = renderPrimitive(() => useBlockNumber(() => ({ watch: { pollingInterval: 100 } })), ) await vi.waitUntil(() => result.isSuccess, { timeout: 10_000 }) const blockNumber = result.data! expect(result.data).toBeTypeOf('bigint') await testClient.mainnet.mine({ blocks: 1 }) await vi.waitFor( () => { expect(result.data).toEqual(blockNumber + 1n) }, { timeout: 10_000 }, ) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitFor( () => { expect(result.data).toEqual(blockNumber + 2n) }, { timeout: 10_000 }, ) cleanup() }) }) ================================================ FILE: packages/solid/src/primitives/useBlockNumber.ts ================================================ import { useQueryClient } from '@tanstack/solid-query' import type { Config, GetBlockNumberErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter, UnionCompute, UnionStrictOmit, } from '@wagmi/core/internal' import { type GetBlockNumberData, type GetBlockNumberOptions, getBlockNumberQueryOptions, } from '@wagmi/core/query' import { type Accessor, createMemo } from 'solid-js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' import { useWatchBlockNumber } from './useWatchBlockNumber.js' /** https://wagmi.sh/solid/api/hooks/useBlockNumber */ export function useBlockNumber< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetBlockNumberData, >( parameters: useBlockNumber.Parameters< config, chainId, selectData > = () => ({}), ): useBlockNumber.ReturnType { const config = useConfig(parameters) const chainId = useChainId(() => ({ config: config() })) const options = createMemo(() => getBlockNumberQueryOptions(config(), { ...parameters(), chainId: parameters().chainId ?? chainId(), }), ) const queryClient = useQueryClient() const watchBlockNumberArgs = createMemo(() => { // Assign to variable to help type narrowing const { watch } = parameters() return { ...({ config: config(), chainId: parameters().chainId ?? chainId(), ...(typeof watch === 'object' ? watch : {}), } as useWatchBlockNumber.SolidParameters), enabled: (parameters().query?.enabled ?? true) && (typeof watch === 'object' ? watch.enabled : watch), onBlockNumber(blockNumber) { queryClient.setQueryData(options().queryKey, blockNumber) }, } satisfies useWatchBlockNumber.SolidParameters }) useWatchBlockNumber(watchBlockNumberArgs) return useQuery(options) } export namespace useBlockNumber { export type Parameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetBlockNumberData, > = Accessor> export type ReturnType = UseQueryReturnType< selectData, GetBlockNumberErrorType > export type SolidParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetBlockNumberData, > = Compute< GetBlockNumberOptions & ConfigParameter & { watch?: | boolean | UnionCompute< UnionStrictOmit< useWatchBlockNumber.SolidParameters, 'chainId' | 'config' | 'onBlockNumber' | 'onError' > > | undefined } > } ================================================ FILE: packages/solid/src/primitives/useChainId.test-d.ts ================================================ import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useChainId } from './useChainId.js' test('default', () => { const chainId = useChainId() expectTypeOf(chainId()).toEqualTypeOf() }) test('parameters: config', () => { const chainId = useChainId(() => ({ config })) expectTypeOf(chainId()).toEqualTypeOf<1 | 456 | 10>() }) ================================================ FILE: packages/solid/src/primitives/useChainId.test.ts ================================================ import { config } from '@wagmi/test' import { renderPrimitive } from '@wagmi/test/solid' import { expect, test } from 'vitest' import { useChainId } from './useChainId.js' test('default', async () => { const { result } = renderPrimitive(() => useChainId()) expect(result()).toMatchInlineSnapshot('1') config.setState((x) => ({ ...x, chainId: 456 })) expect(result()).toMatchInlineSnapshot('456') }) test('parameters: config', async () => { const { result } = renderPrimitive(() => useChainId(() => ({ config }))) expect(result()).toBeDefined() }) ================================================ FILE: packages/solid/src/primitives/useChainId.ts ================================================ import { type Config, type GetChainIdReturnType, getChainId, type ResolvedRegister, watchChainId, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js' import { useConfig } from './useConfig.js' /** https://wagmi.sh/solid/api/hooks/useChainId */ export function useChainId( parameters: useChainId.Parameters = () => ({}), ): useChainId.ReturnType { const config = useConfig(parameters) const [chainId, setChainId] = createSignal(getChainId(config())) createEffect(() => { const _config = config() setChainId(() => getChainId(_config)) const unsubscribe = watchChainId(_config, { onChange(data) { setChainId(() => data) }, }) onCleanup(() => unsubscribe()) }) return chainId } export namespace useChainId { export type Parameters = Accessor< SolidParameters > export type ReturnType = Accessor< SolidReturnType > export type SolidParameters = ConfigParameter export type SolidReturnType = GetChainIdReturnType } ================================================ FILE: packages/solid/src/primitives/useChains.test.ts ================================================ import { chain, config } from '@wagmi/test' import { renderPrimitive } from '@wagmi/test/solid' import { expect, test } from 'vitest' import { useChains } from './useChains.js' test('default', async () => { const { result } = renderPrimitive(() => useChains()) expect(result().map((x) => x.id)).toMatchInlineSnapshot(` [ 1, 456, 10, ] `) }) test('parameters: config', async () => { const { result } = renderPrimitive(() => useChains(() => ({ config })), { wrapper: (props) => props.children, }) expect(result().map((x) => x.id)).toMatchInlineSnapshot(` [ 1, 456, 10, ] `) }) test('behavior: chains updates', async () => { const { result } = renderPrimitive(() => useChains()) const chains = result() expect( result().map(({ id, name }) => ({ id, name, })), ).toMatchInlineSnapshot(` [ { "id": 1, "name": "Ethereum", }, { "id": 456, "name": "Ethereum", }, { "id": 10, "name": "OP Mainnet", }, ] `) config._internal.chains.setState([chain.mainnet, chain.mainnet2]) expect( result().map(({ id, name }) => ({ id, name, })), ).toMatchInlineSnapshot(` [ { "id": 1, "name": "Ethereum", }, { "id": 456, "name": "Ethereum", }, ] `) config._internal.chains.setState(chains) expect( result().map(({ id, name }) => ({ id, name, })), ).toMatchInlineSnapshot(` [ { "id": 1, "name": "Ethereum", }, { "id": 456, "name": "Ethereum", }, { "id": 10, "name": "OP Mainnet", }, ] `) }) ================================================ FILE: packages/solid/src/primitives/useChains.ts ================================================ import { type Config, type GetChainsReturnType, getChains, type ResolvedRegister, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { watchChains } from '@wagmi/core/internal' import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js' import { useConfig } from './useConfig.js' /** https://wagmi.sh/solid/api/primitives/useChains */ export function useChains( parameters: useChains.Parameters = () => ({}), ): useChains.ReturnType { const config = useConfig(parameters) const [chains, setChains] = createSignal>( getChains(config()), ) createEffect(() => { const unsubscribe = watchChains(config(), { onChange(data) { setChains(() => data) }, }) onCleanup(() => unsubscribe()) }) return chains } export namespace useChains { export type Parameters = Accessor< ConfigParameter > export type ReturnType = Accessor< GetChainsReturnType > export type SolidParameters = ConfigParameter export type SolidReturnType = GetChainsReturnType } ================================================ FILE: packages/solid/src/primitives/useClient.test-d.ts ================================================ import { chain, config } from '@wagmi/test' import type { Chain } from 'viem' import { expectTypeOf, test } from 'vitest' import { useClient } from './useClient.js' test('default', () => { const client = useClient(() => ({ config })) expectTypeOf(client().chain).toEqualTypeOf< (typeof config)['chains'][number] >() expectTypeOf(client().transport.type).toEqualTypeOf<'http'>() }) test('parameters: chainId', () => { const client = useClient(() => ({ config, chainId: chain.mainnet.id, })) expectTypeOf(client().chain).toEqualTypeOf() expectTypeOf(client().chain).not.toEqualTypeOf() expectTypeOf(client().transport.type).toEqualTypeOf<'http'>() }) test('behavior: unconfigured chain', () => { { const client = useClient(() => ({ chainId: 123456 })) const _client = client() if (_client) { expectTypeOf(_client.chain).toEqualTypeOf() expectTypeOf(_client.transport.type).toEqualTypeOf() } else { expectTypeOf(_client).toEqualTypeOf() } } // @ts-expect-error const client = useClient(() => ({ config, chainId: 123456, })) expectTypeOf(client()).toEqualTypeOf() }) ================================================ FILE: packages/solid/src/primitives/useClient.test.ts ================================================ import { switchChain } from '@wagmi/core' import { config } from '@wagmi/test' import { renderPrimitive } from '@wagmi/test/solid' import { createSignal } from 'solid-js' import { expect, test, vi } from 'vitest' import { useClient } from './useClient.js' test('default', async () => { const { result } = renderPrimitive(() => useClient()) expect(result?.()?.chain.id).toEqual(1) await switchChain(config, { chainId: 456 }) expect(result?.()?.chain?.id).toEqual(456) }) test('parameters: config', () => { const { result } = renderPrimitive(() => useClient(() => ({ config })), { wrapper: (props) => props.children, }) expect(result()).toBeDefined() }) test('behavior: controlled chainId', async () => { const [chainId, setChainId] = createSignal(456) const { result } = renderPrimitive(() => useClient(() => ({ chainId: chainId() })), ) expect(result()?.chain.id).toEqual(456) setChainId(1) await vi.waitFor(() => { expect(result()?.chain.id).toEqual(1) }) }) test('behavior: unconfigured chain', () => { const { result } = renderPrimitive(() => useClient(() => ({ chainId: 123456 })), ) expect(result()).toBeUndefined() }) ================================================ FILE: packages/solid/src/primitives/useClient.ts ================================================ import { type Config, type GetClientParameters, type GetClientReturnType, getClient, type ResolvedRegister, watchClient, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import type { Accessor } from 'solid-js' import { createEffect, createSignal, onCleanup } from 'solid-js' import { useConfig } from './useConfig.js' /** https://wagmi.sh/solid/api/primitives/useClient */ export function useClient< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] | number | undefined = | config['chains'][number]['id'] | undefined, >( parameters: useClient.Parameters = () => ({}), ): useClient.ReturnType { const config = useConfig(parameters) const [client, setClient] = createSignal(getClient(config(), parameters())) createEffect(() => { const _config = config() setClient(() => getClient(_config, parameters())) const unsubscribe = watchClient(_config, { onChange(data) { if (client()?.uid === data?.uid) return setClient(() => data) }, }) onCleanup(() => unsubscribe()) }) return client as unknown as useClient.ReturnType } export namespace useClient { export type Parameters< config extends Config = Config, chainId extends config['chains'][number]['id'] | number | undefined = | config['chains'][number]['id'] | undefined, > = Accessor> export type ReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] | number | undefined = | config['chains'][number]['id'] | undefined, > = Accessor> export type SolidParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] | number | undefined = | config['chains'][number]['id'] | undefined, > = Compute & ConfigParameter> export type SolidReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] | number | undefined = | config['chains'][number]['id'] | undefined, > = GetClientReturnType } ================================================ FILE: packages/solid/src/primitives/useConfig.test-d.ts ================================================ import type { Config } from '@wagmi/core' import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useConfig } from './useConfig.js' test('default', async () => { const result = useConfig() expectTypeOf(result()).toEqualTypeOf() }) test('parameters: config', async () => { const result = useConfig(() => ({ config })) expectTypeOf(result()).not.toEqualTypeOf() expectTypeOf(result()).toEqualTypeOf() }) ================================================ FILE: packages/solid/src/primitives/useConfig.test.ts ================================================ import { config } from '@wagmi/test' import { renderPrimitive } from '@wagmi/test/solid' import { expect, test, vi } from 'vitest' import { useConfig } from './useConfig.js' test('default', () => { const { result } = renderPrimitive(useConfig(() => ({ config }))) expect(result).toBeDefined() }) test('behavior: throws when not inside Provider', async () => { vi.spyOn(console, 'error').mockImplementation(() => {}) try { renderPrimitive(useConfig(), { wrapper: (props) => props.children, }) } catch (error) { expect(error).toMatchInlineSnapshot(` [WagmiProviderNotFoundError: \`useConfig\` must be used within \`WagmiProvider\`. Docs: https://wagmi.sh/solid/api/WagmiProvider.html Version: @wagmi/solid@x.y.z] `) } }) ================================================ FILE: packages/solid/src/primitives/useConfig.ts ================================================ import type { Config, ResolvedRegister } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { type Accessor, createMemo, useContext } from 'solid-js' import { WagmiContext } from '../context.js' import { WagmiProviderNotFoundError } from '../errors/context.js' export function useConfig( parameters: useConfig.Parameters = () => ({}), ): useConfig.ReturnType { return createMemo(() => { const config = parameters().config ?? useContext(WagmiContext) if (!config) throw new WagmiProviderNotFoundError() return config as config }) } export namespace useConfig { export type Parameters = Accessor< SolidParameters > export type ReturnType = Accessor< SolidReturnType > export type SolidParameters = ConfigParameter export type SolidReturnType = config } ================================================ FILE: packages/solid/src/primitives/useConnect.test-d.ts ================================================ import type { ConnectErrorType, Connector, CreateConnectorFn, } from '@wagmi/core' import { config } from '@wagmi/test' import type { Address, Hex } from 'viem' import { expectTypeOf, test } from 'vitest' import { useConnect } from './useConnect.js' const connector = config.connectors[0]! const contextValue = { foo: 'bar' } as const test('context', () => { const connect = useConnect(() => ({ mutation: { onMutate(variables) { expectTypeOf(variables).toEqualTypeOf<{ chainId?: number | undefined connector: Connector | CreateConnectorFn withCapabilities?: boolean | undefined }>() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ chainId?: number | undefined connector: Connector | CreateConnectorFn withCapabilities?: boolean | undefined }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ chainId?: number | undefined connector: Connector | CreateConnectorFn withCapabilities?: boolean | undefined }>() expectTypeOf(data).toEqualTypeOf<{ accounts: | readonly [Address, ...Address[]] | readonly [ { address: Address; capabilities: Record }, ...{ address: Address capabilities: Record }[], ] chainId: number }>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf< | { accounts: | readonly [Address, ...Address[]] | readonly [ { address: Address capabilities: Record }, ...{ address: Address capabilities: Record }[], ] chainId: number } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf<{ chainId?: number | undefined connector: Connector | CreateConnectorFn withCapabilities?: boolean | undefined }>() expectTypeOf(context).toEqualTypeOf() }, }, })) expectTypeOf(connect.data).toEqualTypeOf< | { accounts: | readonly [Address, ...Address[]] | readonly [ { address: Address; capabilities: Record }, ...{ address: Address capabilities: Record }[], ] chainId: number } | undefined >() expectTypeOf(connect.error).toEqualTypeOf() expectTypeOf(connect.variables).toMatchTypeOf< | { chainId?: number | undefined connector: Connector | CreateConnectorFn } | undefined >() expectTypeOf(connect.context).toEqualTypeOf() connect.mutate( { connector }, { onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ chainId?: number | undefined connector: typeof connector | CreateConnectorFn foo?: string | undefined withCapabilities?: boolean | undefined }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ chainId?: number | undefined connector: typeof connector | CreateConnectorFn foo?: string | undefined withCapabilities?: boolean | undefined }>() expectTypeOf(data).toEqualTypeOf<{ accounts: readonly [Address, ...Address[]] chainId: number }>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf<{ chainId?: number | undefined connector: typeof connector | CreateConnectorFn foo?: string | undefined withCapabilities?: boolean | undefined }>() expectTypeOf(context).toEqualTypeOf() }, }, ) connect.mutate( { connector, foo: 'bar', withCapabilities: true, }, { onSuccess(data, _variables, _context) { expectTypeOf(data).toEqualTypeOf<{ accounts: readonly [ { address: Address capabilities: { foo: { bar: Hex } } }, ...{ address: Address capabilities: { foo: { bar: Hex } } }[], ] chainId: number }>() }, onSettled(data, _error, _variables, _context) { expectTypeOf(data).toEqualTypeOf< | { accounts: readonly [ { address: Address capabilities: { foo: { bar: Hex } } }, ...{ address: Address capabilities: { foo: { bar: Hex } } }[], ] chainId: number } | undefined >() }, }, ) ;(async () => { const res = await connect.mutateAsync({ connector, foo: 'bar', withCapabilities: true, }) expectTypeOf(res).toEqualTypeOf<{ accounts: readonly [ { address: Address capabilities: { foo: { bar: Hex } } }, ...{ address: Address capabilities: { foo: { bar: Hex } } }[], ] chainId: number }>() })() }) ================================================ FILE: packages/solid/src/primitives/useConnect.test.ts ================================================ import { disconnect } from '@wagmi/core' import { config } from '@wagmi/test' import { renderPrimitive } from '@wagmi/test/solid' import { afterEach, expect, test, vi } from 'vitest' import { useConnect } from './useConnect.js' import { useConnection } from './useConnection.js' import { useConnectors } from './useConnectors.js' const connector = config.connectors[0]! afterEach(async () => { if (config.state.current === connector.uid) await disconnect(config, { connector }) }) test('default', async () => { const { result } = renderPrimitive(() => ({ useConnection: useConnection(), useConnect: useConnect(), useConnectors: useConnectors(), })) expect(result.useConnection().address).not.toBeDefined() expect(result.useConnection().status).toEqual('disconnected') result.useConnect.mutate({ connector: result.useConnectors()[0]!, }) await vi.waitFor(() => expect(result.useConnection().isConnected).toBeTruthy(), ) expect(result.useConnection().address).toBeDefined() expect(result.useConnection().status).toEqual('connected') }) ================================================ FILE: packages/solid/src/primitives/useConnect.ts ================================================ import type { Config, ConnectErrorType } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type ConnectData, type ConnectMutate, type ConnectMutateAsync, type ConnectOptions, type ConnectVariables, connectMutationOptions, } from '@wagmi/core/query' import { type Accessor, createEffect, onCleanup } from 'solid-js' import type { UseMutationReturnType } from '../utils/query.js' import { useMutation } from '../utils/query.js' import { useConfig } from './useConfig.js' /** https://wagmi.sh/solid/api/hooks/useConnect */ export function useConnect( parameters: useConnect.Parameters = () => ({}), ): useConnect.ReturnType { const config = useConfig(parameters) const mutation = useMutation(() => connectMutationOptions(config(), parameters()), ) // Reset mutation back to an idle state when the connector disconnects. createEffect(() => { const unsubscribe = config().subscribe( ({ status }) => status, (status, previousStatus) => { if (previousStatus === 'connected' && status === 'disconnected') { mutation.reset() } }, ) onCleanup(() => unsubscribe()) }) return mutation as unknown as useConnect.ReturnType } export namespace useConnect { export type Parameters< config extends Config = Config, context = unknown, > = Accessor> export type ReturnType< config extends Config = Config, context = unknown, > = Compute< UseMutationReturnType< ConnectData, ConnectErrorType, ConnectVariables, context, ConnectMutate, ConnectMutateAsync > > export type SolidParameters< config extends Config = Config, context = unknown, > = Compute & ConnectOptions> } ================================================ FILE: packages/solid/src/primitives/useConnection.test-d.ts ================================================ import type { Connector } from '@wagmi/core' import type { Address, Chain } from 'viem' import { expectTypeOf, test } from 'vitest' import { useConnection } from './useConnection.js' test('states', () => { const result = useConnection() const connection = result() switch (connection.status) { case 'reconnecting': { expectTypeOf(connection).toMatchTypeOf<{ address: Address | undefined chain: Chain | undefined chainId: number | undefined connector: Connector | undefined isConnected: boolean isConnecting: false isDisconnected: false isReconnecting: true status: 'reconnecting' }>() break } case 'connecting': { expectTypeOf(connection).toMatchTypeOf<{ address: Address | undefined chain: Chain | undefined chainId: number | undefined connector: Connector | undefined isConnected: false isReconnecting: false isConnecting: true isDisconnected: false status: 'connecting' }>() break } case 'connected': { expectTypeOf(connection).toMatchTypeOf<{ address: Address chain: Chain | undefined chainId: number connector: Connector isConnected: true isConnecting: false isDisconnected: false isReconnecting: false status: 'connected' }>() break } case 'disconnected': { expectTypeOf(connection).toMatchTypeOf<{ address: undefined chain: undefined chainId: undefined connector: undefined isConnected: false isReconnecting: false isConnecting: false isDisconnected: true status: 'disconnected' }>() break } } }) ================================================ FILE: packages/solid/src/primitives/useConnection.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { config } from '@wagmi/test' import { renderPrimitive } from '@wagmi/test/solid' import { expect, test } from 'vitest' import { useConnection } from './useConnection.js' test('default', async () => { const { result } = renderPrimitive(() => useConnection()) expect(result().address).not.toBeDefined() expect(result().status).toEqual('disconnected') await connect(config, { connector: config.connectors[0]! }) expect(result().address).toBeDefined() expect(result().status).toEqual('connected') await disconnect(config) }) test('parameters: config', async () => { const { result } = renderPrimitive(() => useConnection(() => ({ config })), { wrapper: ({ children }) => children, }) expect(result()).toBeDefined() }) ================================================ FILE: packages/solid/src/primitives/useConnection.ts ================================================ import { type Config, type GetConnectionReturnType, getConnection, type ResolvedRegister, watchConnection, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js' import { useConfig } from './useConfig.js' /** https://wagmi.sh/solid/api/primitives/useConnection */ export function useConnection< config extends Config = ResolvedRegister['config'], >( parameters: useConnection.Parameters = () => ({}), ): useConnection.ReturnType { const config = useConfig(parameters) const [connection, setConnection] = createSignal(getConnection(config())) createEffect(() => { const _config = config() setConnection(() => getConnection(_config)) const unsubscribe = watchConnection(_config, { onChange(data) { setConnection(() => data) }, }) onCleanup(() => unsubscribe()) }) return connection } export namespace useConnection { export type Parameters = Accessor< SolidParameters > export type ReturnType = Accessor< SolidReturnType > export type SolidParameters = ConfigParameter export type SolidReturnType = GetConnectionReturnType } ================================================ FILE: packages/solid/src/primitives/useConnectionEffect.test.ts ================================================ import { mock } from '@wagmi/connectors' import { connect, createConfig, disconnect, http } from '@wagmi/core' import { accounts, chain, config } from '@wagmi/test' import { createWrapper, renderPrimitive } from '@wagmi/test/solid' import { expect, test, vi } from 'vitest' import { WagmiProvider } from '../context.js' import { useConnect } from './useConnect.js' import { useConnectionEffect } from './useConnectionEffect.js' import { useConnectors } from './useConnectors.js' import { useDisconnect } from './useDisconnect.js' test('parameters: config', async () => { const { result } = renderPrimitive( () => useConnectionEffect(() => ({ config })), { wrapper: (props) => props.children, }, ) expect(result).toBeUndefined() }) test('behavior: connect and disconnect called once', async () => { const onConnect = vi.fn() const onDisconnect = vi.fn() const { result } = renderPrimitive(() => ({ useConnectionEffect: useConnectionEffect(() => ({ onConnect, onDisconnect, })), useConnect: useConnect(), useConnectors: useConnectors(), useDisconnect: useDisconnect(), })) result.useConnect.mutate({ connector: result.useConnectors()[0]!, }) await vi.waitFor(() => expect(result.useConnect.isSuccess).toBeTruthy()) result.useConnect.mutate({ connector: result.useConnectors()[0]!, }) result.useDisconnect.mutate() await vi.waitFor(() => expect(result.useDisconnect.isSuccess).toBeTruthy()) result.useDisconnect.mutate() expect(onConnect).toBeCalledTimes(1) expect(onDisconnect).toBeCalledTimes(1) }) test('behavior: connect called on reconnect', async () => { const config = createConfig({ chains: [chain.mainnet], connectors: [ mock({ accounts, features: { reconnect: true }, }), ], transports: { [chain.mainnet.id]: http() }, }) await connect(config, { connector: config.connectors[0]! }) const onConnect = vi.fn((data) => { expect(data.isReconnected).toBeTruthy() }) renderPrimitive(() => useConnectionEffect(() => ({ onConnect })), { wrapper: createWrapper(WagmiProvider, { config, reconnectOnMount: true }), }) await vi.waitFor(() => expect(onConnect).toBeCalledTimes(1), { timeout: 10_000, }) await disconnect(config) }) ================================================ FILE: packages/solid/src/primitives/useConnectionEffect.ts ================================================ import { type GetConnectionReturnType, watchConnection } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import type { Accessor } from 'solid-js' import { createEffect, onCleanup } from 'solid-js' import { useConfig } from './useConfig.js' /** https://wagmi.sh/solid/api/primitives/useConnectionEffect */ export function useConnectionEffect( parameters: useConnectionEffect.Parameters = () => ({}), ) { const config = useConfig(parameters) createEffect(() => { const { onConnect, onDisconnect } = parameters() const unsubscribe = watchConnection(config(), { onChange(data, prevData) { if ( (prevData.status === 'reconnecting' || (prevData.status === 'connecting' && prevData.address === undefined)) && data.status === 'connected' ) { const { address, addresses, chain, chainId, connector } = data const isReconnected = prevData.status === 'reconnecting' || // if `previousAccount.status` is `undefined`, the connector connected immediately. prevData.status === undefined onConnect?.({ address, addresses, chain, chainId, connector, isReconnected, }) } else if ( prevData.status === 'connected' && data.status === 'disconnected' ) onDisconnect?.() }, }) onCleanup(() => unsubscribe()) }) } export namespace useConnectionEffect { export type Parameters = Accessor export type SolidParameters = Compute< { onConnect?( data: Compute< Pick< Extract, 'address' | 'addresses' | 'chain' | 'chainId' | 'connector' > & { isReconnected: boolean } >, ): void onDisconnect?(): void } & ConfigParameter > } ================================================ FILE: packages/solid/src/primitives/useConnections.test.ts ================================================ import { connect } from '@wagmi/core' import { config } from '@wagmi/test' import { renderPrimitive } from '@wagmi/test/solid' import { expect, test } from 'vitest' import { useConnections } from './useConnections.js' test('default', async () => { const { result } = renderPrimitive(() => useConnections()) expect(result()).toEqual([]) await connect(config, { connector: config.connectors[0]! }) expect(result().length).toBe(1) }) test('parameters: config', () => { const { result } = renderPrimitive(() => useConnections(() => ({ config })), { wrapper: (props) => props.children, }) expect(result()).toBeDefined() }) ================================================ FILE: packages/solid/src/primitives/useConnections.ts ================================================ import { type GetConnectionsReturnType, getConnections, watchConnections, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js' import { useConfig } from './useConfig.js' /** https://wagmi.sh/solid/api/primitives/useConnections */ export function useConnections( parameters: useConnections.Parameters = () => ({}), ): useConnections.ReturnType { const config = useConfig(parameters) const [connections, setConnections] = createSignal(getConnections(config())) createEffect(() => { const _config = config() setConnections(() => getConnections(_config)) const unsubscribe = watchConnections(_config, { onChange(data) { setConnections(() => data) }, }) onCleanup(() => unsubscribe()) }) return connections } export namespace useConnections { export type Parameters = Accessor export type ReturnType = Accessor export type SolidParameters = ConfigParameter export type SolidReturnType = GetConnectionsReturnType } ================================================ FILE: packages/solid/src/primitives/useConnectorClient.test-d.ts ================================================ import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useConnectorClient } from './useConnectorClient.js' test('parameters: config', async () => { const client = useConnectorClient(() => ({ config })) expectTypeOf(client.data?.chain?.id!).toEqualTypeOf<1 | 456 | 10>() const client2 = useConnectorClient(() => ({ config, chainId: 1 })) expectTypeOf(client2.data?.chain?.id!).toEqualTypeOf<1>() }) ================================================ FILE: packages/solid/src/primitives/useConnectorClient.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { config, wait } from '@wagmi/test' import { renderPrimitive } from '@wagmi/test/solid' import { expect, test, vi } from 'vitest' import { useConnect } from './useConnect.js' import { useConnectorClient } from './useConnectorClient.js' import { useConnectors } from './useConnectors.js' import { useDisconnect } from './useDisconnect.js' import { useSwitchChain } from './useSwitchChain.js' const connector = config.connectors[0]! test('default', async () => { const { result } = renderPrimitive(() => useConnectorClient()) await vi.waitFor(() => expect(result.isPending).toBeTruthy()) expect(result).toMatchInlineSnapshot(` { "data": undefined, "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "connectorClient", { "chainId": 1, }, ], "refetch": [Function], "status": "pending", } `) }) test('behavior: connected on mount', async () => { await connect(config, { connector }) const { result } = renderPrimitive(() => useConnectorClient()) await vi.waitUntil(() => result.isSuccess, { timeout: 10_000 }) const { data, queryKey: _, ...rest } = result expect(data).toMatchObject( expect.objectContaining({ account: expect.any(Object), chain: expect.any(Object), }), ) expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": true, "refetch": [Function], "status": "success", } `) await disconnect(config, { connector }) }) test('behavior: connect and disconnect', async () => { const { result } = renderPrimitive(() => ({ useConnect: useConnect(), useConnectors: useConnectors(), useConnectorClient: useConnectorClient(), useDisconnect: useDisconnect(), })) expect(result.useConnectorClient.data).not.toBeDefined() result.useConnect.mutate({ connector: result.useConnectors()[0]!, }) await vi.waitFor(() => expect(result.useConnectorClient.data).toBeDefined()) result.useDisconnect.mutate() await vi.waitFor(() => expect(result.useConnectorClient.data).not.toBeDefined(), ) }) test('behavior: switch chains', async () => { await connect(config, { connector }) const { result } = renderPrimitive(() => ({ useConnectorClient: useConnectorClient(), useSwitchChain: useSwitchChain(), })) expect(result.useConnectorClient.data).not.toBeDefined() await vi.waitFor(() => expect(result.useConnectorClient.data).toBeDefined()) result.useSwitchChain.mutate({ chainId: 456 }) await vi.waitUntil(() => result.useSwitchChain.isSuccess, { timeout: 10_000, }) result.useSwitchChain.reset() await vi.waitUntil(() => result.useConnectorClient.isSuccess, { timeout: 10_000, }) expect(result.useConnectorClient.data?.chain.id).toEqual(456) result.useSwitchChain.mutate({ chainId: 1 }) await vi.waitUntil(() => result.useSwitchChain.isSuccess, { timeout: 10_000, }) await vi.waitUntil(() => result.useConnectorClient.isSuccess, { timeout: 10_000, }) expect(result.useConnectorClient.data?.chain.id).toEqual(1) await disconnect(config, { connector }) }) test('behavior: disabled when properties missing', async () => { await disconnect(config, { connector }) const { result } = renderPrimitive(() => useConnectorClient()) await wait(0) await vi.waitFor(() => expect(result.isPending).toBeTruthy()) }) test('behavior: disabled when connecting', async () => { const { result } = renderPrimitive(() => useConnectorClient()) config.setState((x) => ({ ...x, status: 'connecting' })) await wait(0) expect(result.isLoading).not.toBeTruthy() }) ================================================ FILE: packages/solid/src/primitives/useConnectorClient.ts ================================================ import { useQueryClient } from '@tanstack/solid-query' import type { Config, GetConnectorClientErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetConnectorClientData, type GetConnectorClientOptions, getConnectorClientQueryOptions, } from '@wagmi/core/query' import type { Accessor } from 'solid-js' import { createEffect, createMemo, on } from 'solid-js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' import { useConnection } from './useConnection.js' /** https://wagmi.sh/solid/api/primitives/useConnectorClient */ export function useConnectorClient< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetConnectorClientData, >( parameters: useConnectorClient.Parameters< config, chainId, selectData > = () => ({}), ): useConnectorClient.ReturnType { const config = useConfig(parameters) const chainId = useChainId(() => ({ config: config() })) const connection = useConnection(() => ({ config: config() })) const options = createMemo(() => getConnectorClientQueryOptions(config(), { ...(parameters() as any), chainId: parameters().chainId ?? chainId(), connector: parameters().connector ?? connection().connector, }), ) const queryClient = useQueryClient() createEffect( on( () => connection().address, (currentAddress, previousAddress) => { if (!currentAddress && previousAddress) { // remove when account is disconnected queryClient.removeQueries({ queryKey: options().queryKey }) } else if (currentAddress !== previousAddress) { // invalidate when address changes queryClient.invalidateQueries({ queryKey: options().queryKey }) } }, { defer: true }, ), ) return useQuery(options) as any } export namespace useConnectorClient { export type Parameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetConnectorClientData, > = Accessor> export type ReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetConnectorClientData, > = UseQueryReturnType export type SolidParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetConnectorClientData, > = Compute< GetConnectorClientOptions & ConfigParameter > } ================================================ FILE: packages/solid/src/primitives/useConnectors.test.ts ================================================ import { mock } from '@wagmi/connectors' import { accounts, config } from '@wagmi/test' import { renderPrimitive } from '@wagmi/test/solid' import { expect, test } from 'vitest' import { useConnectors } from './useConnectors.js' test('default', async () => { const { result } = renderPrimitive(() => useConnectors()) const count = config.connectors.length expect(result().length).toBe(count) expect(result()).toEqual(config.connectors) config._internal.connectors.setState(() => [ ...config.connectors, config._internal.connectors.setup(mock({ accounts })), ]) expect(result().length).toBe(count + 1) }) ================================================ FILE: packages/solid/src/primitives/useConnectors.ts ================================================ import { type Config, type GetConnectorsReturnType, getConnectors, type ResolvedRegister, watchConnectors, } from '@wagmi/core' import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js' import { useConfig } from './useConfig.js' /** https://wagmi.sh/solid/api/primitives/useConnectors */ export function useConnectors< config extends Config = ResolvedRegister['config'], >( parameters: useConnectors.Parameters = () => ({}), ): useConnectors.ReturnType { const config = useConfig(parameters) const [connectors, setConnectors] = createSignal(getConnectors(config())) createEffect(() => { const _config = config() setConnectors(() => getConnectors(_config)) const unsubscribe = watchConnectors(_config, { onChange(data) { setConnectors(() => data) }, }) onCleanup(() => unsubscribe()) }) return connectors } export namespace useConnectors { export type Parameters = Accessor< SolidParameters > export type ReturnType = Accessor< SolidReturnType > export type SolidParameters = useConfig.SolidParameters export type SolidReturnType = GetConnectorsReturnType } ================================================ FILE: packages/solid/src/primitives/useDisconnect.test-d.ts ================================================ import type { Connector, DisconnectErrorType } from '@wagmi/core' import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useDisconnect } from './useDisconnect.js' const connector = config.connectors[0]! const contextValue = { foo: 'bar' } as const test('parameter', () => { expectTypeOf(useDisconnect().mutate) .parameter(0) .toEqualTypeOf<{ connector?: Connector | undefined } | undefined>() expectTypeOf(useDisconnect().mutate) .parameter(0) .toEqualTypeOf<{ connector?: Connector | undefined } | undefined>() }) test('context', () => { const disconnect = useDisconnect(() => ({ mutation: { onMutate(variables) { expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(context).toEqualTypeOf() }, }, })) expectTypeOf(disconnect.data).toEqualTypeOf() expectTypeOf(disconnect.error).toEqualTypeOf() expectTypeOf(disconnect.variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(disconnect.context).toEqualTypeOf< typeof contextValue | undefined >() disconnect.mutate( { connector }, { onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/solid/src/primitives/useDisconnect.test.ts ================================================ import { connect } from '@wagmi/core' import { config } from '@wagmi/test' import { renderPrimitive } from '@wagmi/test/solid' import { beforeEach, expect, test, vi } from 'vitest' import { useConnection } from './useConnection.js' import { useDisconnect } from './useDisconnect.js' const connector = config.connectors[0]! beforeEach(async () => { await connect(config, { connector }) }) test('default', async () => { const { result } = renderPrimitive(() => ({ useConnection: useConnection(), useDisconnect: useDisconnect(), })) expect(result.useConnection().address).toBeDefined() expect(result.useConnection().status).toEqual('connected') result.useDisconnect.mutate() await vi.waitFor(() => expect(result.useConnection().isDisconnected).toBeTruthy(), ) expect(result.useConnection().address).not.toBeDefined() expect(result.useConnection().status).toEqual('disconnected') }) ================================================ FILE: packages/solid/src/primitives/useDisconnect.ts ================================================ import { createMutation as useMutation } from '@tanstack/solid-query' import type { DisconnectErrorType } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type DisconnectData, type DisconnectMutate, type DisconnectMutateAsync, type DisconnectOptions, type DisconnectVariables, disconnectMutationOptions, } from '@wagmi/core/query' import type { Accessor } from 'solid-js' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' /** https://wagmi.sh/solid/api/primitives/useDisconnect */ export function useDisconnect( parameters: useDisconnect.Parameters = () => ({}), ): useDisconnect.ReturnType { const config = useConfig(parameters) const mutation = useMutation(() => disconnectMutationOptions(config(), parameters()), ) return mutation as useDisconnect.ReturnType } export namespace useDisconnect { export type Parameters = Accessor> export type ReturnType = Compute< UseMutationReturnType< DisconnectData, DisconnectErrorType, DisconnectVariables, context, DisconnectMutate, DisconnectMutateAsync > > export type SolidParameters = Compute< ConfigParameter & DisconnectOptions > } ================================================ FILE: packages/solid/src/primitives/useReconnect.test-d.ts ================================================ import type { Connector, CreateConnectorFn, ReconnectErrorType, } from '@wagmi/core' import { config } from '@wagmi/test' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' import { useReconnect } from './useReconnect.js' const connectors = [config.connectors[0]!] const contextValue = { foo: 'bar' } as const test('context', () => { const reconnect = useReconnect(() => ({ mutation: { onMutate(variables) { expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(data).toEqualTypeOf< { accounts: readonly [Address, ...Address[]] chainId: number connector: Connector }[] >() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number connector: Connector }[] | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(context).toEqualTypeOf() }, }, })) expectTypeOf(reconnect.data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number connector: Connector }[] | undefined >() expectTypeOf(reconnect.error).toEqualTypeOf() expectTypeOf(reconnect.variables).toEqualTypeOf< | { connectors?: readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(reconnect.context).toEqualTypeOf< typeof contextValue | undefined >() reconnect.mutate( { connectors }, { onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(data).toEqualTypeOf< { accounts: readonly [Address, ...Address[]] chainId: number connector: Connector }[] >() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number connector: Connector }[] | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/solid/src/primitives/useReconnect.test.ts ================================================ import { mock } from '@wagmi/connectors' import { connect, disconnect } from '@wagmi/core' import { accounts, config } from '@wagmi/test' import { renderPrimitive } from '@wagmi/test/solid' import { afterEach, expect, test, vi } from 'vitest' import { useReconnect } from './useReconnect.js' const connector = config._internal.connectors.setup( mock({ accounts, features: { reconnect: true }, }), ) afterEach(async () => { if (config.state.current) await disconnect(config) }) test('default', async () => { const { result } = renderPrimitive(() => useReconnect()) result.mutate() await vi.waitUntil(() => result.isSuccess, { timeout: 10_000 }) expect(result.data).toStrictEqual([]) }) test('parameters: connectors (Connector)', async () => { await connect(config, { connector }) const { result } = renderPrimitive(() => useReconnect()) result.mutate({ connectors: [connector] }) await vi.waitUntil(() => result.isSuccess, { timeout: 10_000 }) expect(result.data).toMatchObject( expect.arrayContaining([ expect.objectContaining({ accounts: expect.any(Array), chainId: expect.any(Number), }), ]), ) }) test('parameters: connectors (CreateConnectorFn)', async () => { const connector = mock({ accounts, features: { reconnect: true }, }) await connect(config, { connector }) const { result } = renderPrimitive(() => useReconnect()) result.mutate({ connectors: [connector] }) await vi.waitUntil(() => result.isSuccess, { timeout: 10_000 }) expect(result.data).toMatchObject( expect.arrayContaining([ expect.objectContaining({ accounts: expect.any(Array), chainId: expect.any(Number), }), ]), ) }) test("behavior: doesn't reconnect if already reconnecting", async () => { const previousStatus = config.state.status config.setState((x) => ({ ...x, status: 'reconnecting' })) const { result } = renderPrimitive(() => useReconnect()) await expect( result.mutateAsync({ connectors: [connector] }), ).resolves.toStrictEqual([]) config.setState((x) => ({ ...x, status: previousStatus })) }) ================================================ FILE: packages/solid/src/primitives/useReconnect.ts ================================================ import { createMutation as useMutation } from '@tanstack/solid-query' import type { ReconnectErrorType } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type ReconnectData, type ReconnectMutate, type ReconnectMutateAsync, type ReconnectOptions, type ReconnectVariables, reconnectMutationOptions, } from '@wagmi/core/query' import type { Accessor } from 'solid-js' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' /** https://wagmi.sh/solid/api/primitives/useReconnect */ export function useReconnect( parameters: useReconnect.Parameters = () => ({}), ): useReconnect.ReturnType { const config = useConfig(parameters) const mutation = useMutation(() => reconnectMutationOptions(config(), parameters()), ) return mutation as useReconnect.ReturnType } export namespace useReconnect { export type Parameters = Accessor> export type ReturnType = Compute< UseMutationReturnType< ReconnectData, ReconnectErrorType, ReconnectVariables, context, ReconnectMutate, ReconnectMutateAsync > > export type SolidParameters = Compute< ConfigParameter & ReconnectOptions > } ================================================ FILE: packages/solid/src/primitives/useSwitchChain.test-d.ts ================================================ import type { Connector, SwitchChainErrorType } from '@wagmi/core' import type { Chain } from '@wagmi/core/chains' import type { Compute, ExactPartial } from '@wagmi/core/internal' import { chain } from '@wagmi/test' import type { AddEthereumChainParameter } from 'viem' import { expectTypeOf, test } from 'vitest' import { useSwitchChain } from './useSwitchChain.js' const chainId = chain.mainnet.id const contextValue = { foo: 'bar' } as const test('context', () => { const switchChain = useSwitchChain(() => ({ mutation: { onMutate(variables) { expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() expectTypeOf(data).toEqualTypeOf>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf | undefined>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() expectTypeOf(context).toEqualTypeOf() }, }, })) expectTypeOf(switchChain.data).toEqualTypeOf | undefined>() expectTypeOf(switchChain.error).toEqualTypeOf() expectTypeOf(switchChain.variables).toEqualTypeOf< | { addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined } | undefined >() expectTypeOf(switchChain.context).toEqualTypeOf< typeof contextValue | undefined >() switchChain.mutate( { chainId }, { onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() expectTypeOf(data).toEqualTypeOf>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf | undefined>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/solid/src/primitives/useSwitchChain.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { chain, config } from '@wagmi/test' import { renderPrimitive } from '@wagmi/test/solid' import { expect, test, vi } from 'vitest' import { useConnection } from './useConnection.js' import { useSwitchChain } from './useSwitchChain.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const { result } = renderPrimitive(() => ({ useConnection: useConnection(), useSwitchChain: useSwitchChain(), })) const chainId1 = result.useConnection().chainId expect(chainId1).toBeDefined() result.useSwitchChain.mutate({ chainId: chain.mainnet2.id }) await vi.waitFor(() => expect(result.useSwitchChain.isSuccess).toBeTruthy()) const chainId2 = result.useConnection().chainId expect(chainId2).toBeDefined() expect(chainId1).not.toBe(chainId2) result.useSwitchChain.mutate({ chainId: chain.mainnet.id }) await vi.waitFor(() => expect(result.useSwitchChain.isSuccess).toBeTruthy()) const chainId3 = result.useConnection().chainId expect(chainId3).toBeDefined() expect(chainId1).toBe(chainId3) await disconnect(config, { connector }) }) ================================================ FILE: packages/solid/src/primitives/useSwitchChain.ts ================================================ import { createMutation as useMutation } from '@tanstack/solid-query' import type { Config, ResolvedRegister, SwitchChainErrorType, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type SwitchChainData, type SwitchChainMutate, type SwitchChainMutateAsync, type SwitchChainOptions, type SwitchChainVariables, switchChainMutationOptions, } from '@wagmi/core/query' import type { Accessor } from 'solid-js' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' /** https://wagmi.sh/solid/api/primitives/useSwitchChain */ export function useSwitchChain< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useSwitchChain.Parameters = () => ({}), ): useSwitchChain.ReturnType { const config = useConfig(parameters) const mutation = useMutation(() => switchChainMutationOptions(config(), parameters()), ) return mutation as useSwitchChain.ReturnType } export namespace useSwitchChain { export type Parameters< config extends Config = Config, context = unknown, > = Accessor> export type ReturnType< config extends Config = Config, context = unknown, > = Compute< UseMutationReturnType< SwitchChainData, SwitchChainErrorType, SwitchChainVariables, context, SwitchChainMutate, SwitchChainMutateAsync > > export type SolidParameters< config extends Config = Config, context = unknown, > = Compute & SwitchChainOptions> } ================================================ FILE: packages/solid/src/primitives/useSwitchConnection.test-d.ts ================================================ import type { Connector, SwitchConnectionErrorType } from '@wagmi/core' import { config } from '@wagmi/test' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' import { useSwitchConnection } from './useSwitchConnection.js' const connector = config.connectors[0]! const contextValue = { foo: 'bar' } as const test('context', () => { const switchConnection = useSwitchConnection(() => ({ mutation: { onMutate(variables) { expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() expectTypeOf(data).toEqualTypeOf<{ accounts: readonly [Address, ...Address[]] chainId: number }>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() expectTypeOf(context).toEqualTypeOf() }, }, })) expectTypeOf(switchConnection.data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number } | undefined >() expectTypeOf( switchConnection.error, ).toEqualTypeOf() expectTypeOf(switchConnection.variables).toEqualTypeOf< { connector: Connector } | undefined >() expectTypeOf(switchConnection.context).toEqualTypeOf< typeof contextValue | undefined >() switchConnection.mutate( { connector }, { onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() expectTypeOf(data).toEqualTypeOf<{ accounts: readonly [Address, ...Address[]] chainId: number }>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/solid/src/primitives/useSwitchConnection.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { config, wait } from '@wagmi/test' import { renderPrimitive } from '@wagmi/test/solid' import { expect, test, vi } from 'vitest' import { useConnection } from './useConnection.js' import { useSwitchConnection } from './useSwitchConnection.js' const connector1 = config.connectors[0]! const connector2 = config.connectors[1]! test('default', async () => { await connect(config, { connector: connector2 }) await connect(config, { connector: connector1 }) const { result } = renderPrimitive(() => ({ useConnection: useConnection(), useSwitchConnection: useSwitchConnection(), })) const address1 = result.useConnection().address expect(address1).toBeDefined() result.useSwitchConnection.mutate({ connector: connector2 }) await vi.waitFor(() => expect(result.useSwitchConnection.isSuccess).toBeTruthy(), ) await wait(0) const address2 = result.useConnection().address expect(address2).toBeDefined() expect(address1).not.toBe(address2) result.useSwitchConnection.mutate({ connector: connector1 }) await vi.waitFor(() => expect(result.useSwitchConnection.isSuccess).toBeTruthy(), ) await wait(0) const address3 = result.useConnection().address expect(address3).toBeDefined() expect(address1).toBe(address3) await disconnect(config, { connector: connector1 }) await disconnect(config, { connector: connector2 }) }) ================================================ FILE: packages/solid/src/primitives/useSwitchConnection.ts ================================================ import { createMutation as useMutation } from '@tanstack/solid-query' import type { Config, ResolvedRegister, SwitchConnectionErrorType, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type SwitchConnectionData, type SwitchConnectionMutate, type SwitchConnectionMutateAsync, type SwitchConnectionOptions, type SwitchConnectionVariables, switchConnectionMutationOptions, } from '@wagmi/core/query' import type { Accessor } from 'solid-js' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' /** https://wagmi.sh/solid/api/primitives/useSwitchConnection */ export function useSwitchConnection< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: useSwitchConnection.Parameters = () => ({}), ): useSwitchConnection.ReturnType { const config = useConfig(parameters) const mutation = useMutation(() => switchConnectionMutationOptions(config(), parameters()), ) return mutation as useSwitchConnection.ReturnType } export namespace useSwitchConnection { export type Parameters< config extends Config = Config, context = unknown, > = Accessor> export type ReturnType< config extends Config = Config, context = unknown, > = Compute< UseMutationReturnType< SwitchConnectionData, SwitchConnectionErrorType, SwitchConnectionVariables, context, SwitchConnectionMutate, SwitchConnectionMutateAsync > > export type SolidParameters< config extends Config = Config, context = unknown, > = Compute< ConfigParameter & SwitchConnectionOptions > } ================================================ FILE: packages/solid/src/primitives/useWatchBlockNumber.test-d.ts ================================================ import { createConfig } from '@wagmi/core' import { http, webSocket } from 'viem' import { mainnet, optimism } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import { useWatchBlockNumber } from './useWatchBlockNumber.js' test('default', () => { useWatchBlockNumber(() => ({ poll: false, onBlockNumber() {}, })) }) test('differing transports', () => { const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: webSocket(), }, }) type Result = useWatchBlockNumber.SolidParameters< typeof config, typeof mainnet.id | typeof optimism.id > expectTypeOf().toEqualTypeOf() useWatchBlockNumber(() => ({ config, poll: false, onBlockNumber() {}, })) type Result2 = useWatchBlockNumber.SolidParameters< typeof config, typeof mainnet.id > expectTypeOf().toEqualTypeOf() useWatchBlockNumber(() => ({ config, chainId: mainnet.id, poll: true, onBlockNumber() {}, })) // @ts-expect-error useWatchBlockNumber(() => ({ config, chainId: mainnet.id, poll: false, onBlockNumber() {}, })) type Result3 = useWatchBlockNumber.SolidParameters< typeof config, typeof optimism.id > expectTypeOf().toEqualTypeOf() useWatchBlockNumber(() => ({ config, chainId: optimism.id, poll: true, onBlockNumber() {}, })) useWatchBlockNumber(() => ({ config, chainId: optimism.id, poll: false, onBlockNumber() {}, })) }) ================================================ FILE: packages/solid/src/primitives/useWatchBlockNumber.test.ts ================================================ import { config, testClient, wait } from '@wagmi/test' import { renderPrimitive } from '@wagmi/test/solid' import { expect, test, vi } from 'vitest' import { useWatchBlockNumber } from './useWatchBlockNumber.js' test('default', async () => { await testClient.mainnet.restart() const blockNumbers: bigint[] = [] renderPrimitive(() => useWatchBlockNumber(() => ({ onBlockNumber(blockNumber) { blockNumbers.push(blockNumber) }, })), ) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitUntil(() => blockNumbers.length === 3, { timeout: 10_000 }) expect(blockNumbers.length).toBe(3) }) test('parameters: config', async () => { const blockNumbers: bigint[] = [] renderPrimitive(() => useWatchBlockNumber(() => ({ config, onBlockNumber(blockNumber) { blockNumbers.push(blockNumber) }, })), ) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) await testClient.mainnet.mine({ blocks: 1 }) await vi.waitUntil(() => blockNumbers.length === 3, { timeout: 10_000 }) expect(blockNumbers.length).toBe(3) }) test('parameters: enabled', async () => { const onBlockNumber = vi.fn() renderPrimitive(() => useWatchBlockNumber(() => ({ enabled: false, onBlockNumber, emitOnBegin: true, })), ) await wait(200) expect(onBlockNumber).not.toHaveBeenCalled() }) ================================================ FILE: packages/solid/src/primitives/useWatchBlockNumber.ts ================================================ import { type Config, type ResolvedRegister, type WatchBlockNumberParameters, watchBlockNumber, } from '@wagmi/core' import type { ConfigParameter, EnabledParameter, UnionCompute, UnionExactPartial, } from '@wagmi/core/internal' import { type Accessor, createEffect, onCleanup } from 'solid-js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' /** https://wagmi.sh/solid/api/hooks/useWatchBlockNumber */ export function useWatchBlockNumber< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], >( parameters: useWatchBlockNumber.Parameters = () => ({}) as any, ): useWatchBlockNumber.ReturnType { const config = useConfig(parameters) const configChainId = useChainId(() => ({ config: config() })) createEffect(() => { const { config: _, chainId = configChainId(), enabled = true, onBlockNumber, ...rest } = parameters() if (!enabled) return if (!onBlockNumber) return const unwatch = watchBlockNumber(config(), { ...(rest as any), chainId, onBlockNumber, }) onCleanup(() => unwatch()) }) } export namespace useWatchBlockNumber { export type Parameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = Accessor> export type ReturnType = void export type SolidParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = UnionCompute< UnionExactPartial> & ConfigParameter & EnabledParameter > } ================================================ FILE: packages/solid/src/utils/getVersion.test.ts ================================================ import { expect, test } from 'vitest' import { getVersion } from './getVersion.js' test('default', () => { expect(getVersion()).toMatchInlineSnapshot(`"@wagmi/solid@x.y.z"`) }) ================================================ FILE: packages/solid/src/utils/getVersion.ts ================================================ import { version } from '../version.js' export const getVersion = () => `@wagmi/solid@${version}` ================================================ FILE: packages/solid/src/utils/query.ts ================================================ import { type DefaultError, type MutateFunction, type QueryKey, type SolidInfiniteQueryOptions, type SolidMutationOptions, type SolidQueryOptions, // TODO: import use___ once solid-query version is updated createInfiniteQuery as tanstack_useInfiniteQuery, createQuery as tanstack_useQuery, type CreateInfiniteQueryResult as UseInfiniteQueryResult, type CreateMutationResult as UseMutationResult, type CreateQueryResult as UseQueryResult, createMutation as useMutation, } from '@tanstack/solid-query' import type { Compute, ExactPartial, Omit, UnionStrictOmit, } from '@wagmi/core/internal' import { hashFn } from '@wagmi/core/query' import { type Accessor, mergeProps } from 'solid-js' export type SolidMutationParameters< data = unknown, error = Error, variables = void, context = unknown, > = Compute< Omit< SolidMutationOptions, context>, 'mutationFn' | 'mutationKey' | 'throwOnError' > > export type UseMutationReturnType< data = unknown, error = Error, variables = void, context = unknown, mutate = MutateFunction, mutateAsync = MutateFunction, > = Compute< UnionStrictOmit< UseMutationResult, 'mutate' | 'mutateAsync' > & { mutate: mutate mutateAsync: mutateAsync } > export { useMutation } //////////////////////////////////////////////////////////////////////////////// export type SolidQueryParameters< queryFnData = unknown, error = DefaultError, data = queryFnData, queryKey extends QueryKey = QueryKey, > = Compute< ExactPartial< Omit, 'initialData'> > & { // Fix `initialData` type initialData?: | SolidQueryOptions['initialData'] | undefined } > export type UseQueryReturnType = Compute< UseQueryResult & { queryKey: QueryKey } > // Adding some basic customization. // Ideally we don't have this function, but `import('@tanstack/react-query').useQuery` currently has some quirks where it is super hard to // pass down the inferred `initialData` type because of it's discriminated overload in the on `useQuery`. export function useQuery( parameters: Accessor< SolidQueryParameters & { queryKey: QueryKey } >, ): UseQueryReturnType { const result = tanstack_useQuery(() => ({ ...(parameters() as any), queryKeyHashFn: hashFn, // for bigint support })) return mergeProps(result, { get queryKey() { return parameters().queryKey }, }) as UseQueryReturnType } //////////////////////////////////////////////////////////////////////////////// export type SolidInfiniteQueryParameters< queryFnData = unknown, error = DefaultError, data = queryFnData, queryData = queryFnData, queryKey extends QueryKey = QueryKey, pageParam = unknown, > = Compute< Omit< SolidInfiniteQueryOptions< queryFnData, error, data, queryData, queryKey, pageParam >, 'initialData' > & { // Fix `initialData` type initialData?: | SolidInfiniteQueryOptions< queryFnData, error, data, queryKey >['initialData'] | undefined } > export type UseInfiniteQueryReturnType< data = unknown, error = DefaultError, > = UseInfiniteQueryResult & { queryKey: QueryKey } // Adding some basic customization. export function useInfiniteQuery< queryFnData, error, data, queryData, queryKey extends QueryKey, pageParam = unknown, >( parameters: Accessor< SolidInfiniteQueryParameters< queryFnData, error, data, queryData, queryKey, pageParam > & { queryKey: QueryKey } >, ): UseInfiniteQueryReturnType { const result = tanstack_useInfiniteQuery(() => ({ ...(parameters() as any), queryKeyHashFn: hashFn, // for bigint support })) return mergeProps( result, parameters().queryKey, ) as unknown as UseInfiniteQueryReturnType } ================================================ FILE: packages/solid/src/version.ts ================================================ export const version = '0.0.4' ================================================ FILE: packages/solid/test/setup.ts ================================================ import { vi } from 'vitest' // Make dates stable across runs Date.now = vi.fn(() => new Date(Date.UTC(2023, 1, 1)).valueOf()) vi.mock('../src/version.ts', () => { return { version: 'x.y.z' } }) ================================================ FILE: packages/solid/tsconfig.build.json ================================================ { "extends": "../../tsconfig.base.json", "include": ["src/**/*.ts"], "exclude": ["src/**/*.test.ts", "src/**/*.test-d.ts"], "compilerOptions": { "sourceMap": true } } ================================================ FILE: packages/solid/tsconfig.json ================================================ { "extends": "./tsconfig.build.json", "compilerOptions": { "jsx": "preserve" }, "include": ["src/**/*.ts", "src/**/*.tsx", "test/**/*.ts", "test/**/*.tsx"], "exclude": [] } ================================================ FILE: packages/test/package.json ================================================ { "name": "@wagmi/test", "private": true, "scripts": { "check:types": "tsc --noEmit", "clean": "rm -rf dist tsconfig.tsbuildinfo" }, "files": [ "dist/**", "!dist/**/*.tsbuildinfo", "src/**/*.ts", "!src/**/*.test.ts", "!src/**/*.test-d.ts", "react/**", "solid/**", "vue/**", "tempo/**" ], "sideEffects": false, "type": "module", "main": "./dist/esm/exports/index.js", "types": "./dist/types/exports/index.d.ts", "typings": "./dist/types/exports/index.d.ts", "exports": { ".": { "types": "./dist/types/exports/index.d.ts", "default": "./dist/esm/exports/index.js" }, "./react": { "types": "./dist/types/exports/react.d.ts", "default": "./dist/esm/exports/react.js" }, "./solid": { "types": "./dist/types/exports/solid.d.ts", "default": "./dist/esm/exports/solid.js" }, "./tempo": { "types": "./dist/types/exports/tempo.d.ts", "default": "./dist/esm/exports/tempo.js" }, "./vue": { "types": "./dist/types/exports/vue.d.ts", "default": "./dist/esm/exports/vue.js" }, "./package.json": "./package.json" }, "typesVersions": { "*": { "react": [ "./dist/types/exports/react.d.ts" ], "solid": [ "./dist/types/exports/solid.d.ts" ], "tempo": [ "./dist/types/exports/tempo.d.ts" ], "vue": [ "./dist/types/exports/vue.d.ts" ] } }, "peerDependencies": { "@tanstack/react-query": ">=5.0.0", "@tanstack/solid-query": ">=5.0.0", "@tanstack/vue-query": ">=5.0.0", "@types/react": ">=18", "@types/react-dom": ">=18", "@wagmi/core": "workspace:*", "@wagmi/solid": "workspace:*", "@wagmi/vue": "workspace:*", "ox": "catalog:", "prool": "^0.0.24", "react": ">=18", "react-dom": ">=18", "solid-js": "1.x", "typescript": ">=5.7.3", "viem": "2.x", "vue": ">=3", "wagmi": "workspace:*" }, "peerDependenciesMeta": { "@tanstack/react-query": { "optional": true }, "@tanstack/solid-query": { "optional": true }, "@tanstack/vue-query": { "optional": true }, "@types/react": { "optional": true }, "@types/react-dom": { "optional": true }, "@wagmi/vue": { "optional": true }, "react": { "optional": true }, "react-dom": { "optional": true }, "solid-js": { "optional": true }, "typescript": { "optional": true }, "vue": { "optional": true }, "wagmi": { "optional": true } }, "devDependencies": { "@solidjs/testing-library": "^0.8.10", "@tanstack/react-query": "catalog:", "@tanstack/solid-query": "catalog:", "@tanstack/vue-query": "catalog:", "@types/react": "catalog:", "@types/react-dom": "catalog:", "@wagmi/core": "workspace:*", "@wagmi/solid": "workspace:*", "@wagmi/vue": "workspace:*", "ox": "catalog:", "react": "catalog:", "react-dom": "catalog:", "solid-js": "catalog:", "vue": "catalog:", "wagmi": "workspace:*" }, "contributors": [ "awkweb.eth ", "jxom.eth " ], "funding": "https://github.com/sponsors/wevm", "keywords": [ "eth", "ethereum", "dapps", "wallet", "web3" ] } ================================================ FILE: packages/test/src/chains.ts ================================================ /// import type { Compute } from '@wagmi/core/internal' import * as chains from 'viem/chains' import { getRpcUrls } from './utils.js' export type Chain = Compute< chains.Chain & { fork: { blockNumber: bigint; url: string } port: number } > const mainnetFork = { blockNumber: 23_535_880n, url: unwrapEnv('VITE_MAINNET_FORK_URL', 'https://eth.merkle.io'), } as const satisfies Chain['fork'] export const mainnet = { ...chains.mainnet, ...getRpcUrls({ port: 8545 }), fork: mainnetFork, } as const satisfies Chain export const mainnet2 = { ...chains.mainnet, ...getRpcUrls({ port: 8546 }), id: 456, nativeCurrency: { decimals: 18, name: 'wagmi', symbol: 'WAG' }, fork: mainnetFork, } as const satisfies Chain export const optimism = { ...chains.optimism, ...getRpcUrls({ port: 8547 }), fork: { blockNumber: 107_317_577n, url: unwrapEnv('VITE_OPTIMISM_FORK_URL', 'https://mainnet.optimism.io'), }, } as const satisfies Chain export const chain = { mainnet, mainnet2, optimism, } function unwrapEnv< name extends keyof ImportMetaEnv, defaultValue extends NonNullable & {}, >(name: name, defaultValue?: defaultValue) { const value = (() => { // biome-ignore lint/complexity/useOptionalChain: stable if (typeof process !== 'undefined' && process.env[name]) return process.env[name] if (typeof import.meta !== 'undefined' && import.meta.env[name]) return import.meta.env[name] return defaultValue })() if (!value) throw new Error(`missing env var for "${name}"`) return value } ================================================ FILE: packages/test/src/clients.ts ================================================ import { type Account, type Client, createTestClient, http, type TestActions, type TestRpcSchema, type Transport, } from 'viem' import { type Chain, mainnet, mainnet2, optimism } from './chains.js' export const mainnetTestClient = createTestClient({ mode: 'anvil', cacheTime: 0, chain: mainnet, transport: http(), }).extend(wagmiTestMethods) export const mainnet2TestClient = createTestClient({ mode: 'anvil', cacheTime: 0, chain: mainnet2, transport: http(), }).extend(wagmiTestMethods) export const optimismTestClient = createTestClient({ mode: 'anvil', cacheTime: 0, chain: optimism, transport: http(), }).extend(wagmiTestMethods) export const testClient = { mainnet: mainnetTestClient, mainnet2: mainnet2TestClient, optimism: optimismTestClient, } function wagmiTestMethods( client: Client< Transport, Chain, Account | undefined, TestRpcSchema<'anvil'>, TestActions >, ) { return { /** Resets instance attached to chain. */ async restart() { return await fetch(`${client.chain.rpcUrls.default.http[0]}/restart`) }, /** Resets fork attached to chain at starting block number. */ resetFork() { return client.reset({ jsonRpcUrl: client.chain.fork.url, blockNumber: client.chain.fork.blockNumber, }) }, } } ================================================ FILE: packages/test/src/config.ts ================================================ import { createConfig, mock } from '@wagmi/core' import { http } from 'viem' import { mainnet, mainnet2, optimism } from './chains.js' import { accounts } from './constants.js' export const config = createConfig({ chains: [mainnet, mainnet2, optimism], connectors: [mock({ accounts }), mock({ accounts: reverse(accounts) })], pollingInterval: 100, storage: null, transports: { [mainnet.id]: http(), [mainnet2.id]: http(), [optimism.id]: http(), }, }) type Reverse< list extends readonly unknown[], /// result extends readonly unknown[] = [], > = list extends readonly [infer head, ...infer tail] ? Reverse : result function reverse(list: list): Reverse { return [...list].reverse() as Reverse } ================================================ FILE: packages/test/src/constants.ts ================================================ /// import type { FixedArray } from '@wagmi/core/internal' import { type Address, parseAbi } from 'viem' import { mnemonicToAccount } from 'viem/accounts' import type { chain } from './chains.js' // Test accounts export const accounts = new Array(10).fill(0).map( (_, addressIndex) => mnemonicToAccount( 'gesture car maximum regret pudding merry fatal electric sea grab crack social', { addressIndex, }, ).address, ) as unknown as FixedArray // for `'0x95132632579b073D12a6673e18Ab05777a6B86f8'` export const privateKey = '0x2300b80db97008804dc601f4b2ac9ed24311f79ccb506d0907ee6839314a78d4' export let walletConnectProjectId: string // biome-ignore lint/complexity/useOptionalChain: _ if (typeof process !== 'undefined' && process.env.VITE_WC_PROJECT_ID) walletConnectProjectId = process.env.VITE_WC_PROJECT_ID if (typeof import.meta !== 'undefined' && import.meta.env.VITE_WC_PROJECT_ID) walletConnectProjectId = import.meta.env.VITE_WC_PROJECT_ID else walletConnectProjectId = 'foobarbaz' export const typedData = { basic: { domain: { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0x0000000000000000000000000000000000000000', }, types: { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }, complex: { domain: { name: 'Ether Mail 🥵', version: '1.1.1', chainId: 1, verifyingContract: '0x0000000000000000000000000000000000000000', }, types: { Name: [ { name: 'first', type: 'string' }, { name: 'last', type: 'string' }, ], Person: [ { name: 'name', type: 'Name' }, { name: 'wallet', type: 'address' }, { name: 'favoriteColors', type: 'string[3]' }, { name: 'foo', type: 'uint256' }, { name: 'age', type: 'uint8' }, { name: 'isCool', type: 'bool' }, ], Mail: [ { name: 'timestamp', type: 'uint256' }, { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, { name: 'hash', type: 'bytes' }, ], }, message: { timestamp: 1234567890n, contents: 'Hello, Bob! 🖤', hash: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef', from: { name: { first: 'Cow', last: 'Burns', }, wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', age: 69, foo: 123123123123123123n, favoriteColors: ['red', 'green', 'blue'], isCool: false, }, to: { name: { first: 'Bob', last: 'Builder' }, wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', age: 70, foo: 123123123123123123n, favoriteColors: ['orange', 'yellow', 'green'], isCool: true, }, }, }, } as const export const abi = { erc20: parseAbi([ 'event Approval(address indexed owner, address indexed spender, uint256 value)', 'event Transfer(address indexed from, address indexed to, uint256 value)', 'function allowance(address owner, address spender) view returns (uint256)', 'function approve(address spender, uint256 amount) returns (bool)', 'function balanceOf(address account) view returns (uint256)', 'function decimals() view returns (uint8)', 'function name() view returns (string)', 'function symbol() view returns (string)', 'function totalSupply() view returns (uint256)', 'function transfer(address recipient, uint256 amount) returns (bool)', 'function transferFrom(address sender, address recipient, uint256 amount) returns (bool)', ]), mloot: parseAbi([ 'constructor()', 'event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId)', 'event ApprovalForAll(address indexed owner, address indexed operator, bool approved)', 'event OwnershipTransferred(address indexed previousOwner, address indexed newOwner)', 'event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)', 'function approve(address to, uint256 tokenId)', 'function balanceOf(address owner) view returns (uint256)', 'function claim(uint256 tokenId)', 'function getApproved(uint256 tokenId) view returns (address)', 'function getChest(uint256 tokenId) view returns (string)', 'function getFoot(uint256 tokenId) view returns (string)', 'function getHand(uint256 tokenId) view returns (string)', 'function getHead(uint256 tokenId) view returns (string)', 'function getNeck(uint256 tokenId) view returns (string)', 'function getRing(uint256 tokenId) view returns (string)', 'function getWaist(uint256 tokenId) view returns (string)', 'function getWeapon(uint256 tokenId) view returns (string)', 'function isApprovedForAll(address owner, address operator) view returns (bool)', 'function name() view returns (string)', 'function owner() view returns (address)', 'function ownerOf(uint256 tokenId) view returns (address)', 'function renounceOwnership()', 'function safeTransferFrom(address from, address to, uint256 tokenId)', 'function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data)', 'function setApprovalForAll(address operator, bool approved)', 'function supportsInterface(bytes4 interfaceId) view returns (bool)', 'function symbol() view returns (string)', 'function tokenByIndex(uint256 index) view returns (uint256)', 'function tokenOfOwnerByIndex(address owner, uint256 index) view returns (uint256)', 'function tokenURI(uint256 tokenId) view returns (string)', 'function totalSupply() view returns (uint256)', 'function transferFrom(address from, address to, uint256 tokenId)', 'function transferOwnership(address newOwner)', ]), shields: parseAbi([ 'constructor(string name_, string symbol_, address _emblemWeaver, address makerBadgeRecipient, address granteeBadgeRecipient)', 'event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId)', 'event ApprovalForAll(address indexed owner, address indexed operator, bool approved)', 'event OwnershipTransferred(address indexed previousOwner, address indexed newOwner)', 'event ShieldBuilt(uint256 tokenId, uint16 field, uint16 hardware, uint16 frame, uint24[4] colors, uint8 shieldBadge)', 'event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)', 'function approve(address to, uint256 tokenId)', 'function balanceOf(address owner) view returns (uint256)', 'function build(uint16 field, uint16 hardware, uint16 frame, uint24[4] colors, uint256 tokenId) payable', 'function collectFees()', 'function emblemWeaver() view returns (address)', 'function getApproved(uint256 tokenId) view returns (address)', 'function isApprovedForAll(address owner, address operator) view returns (bool)', 'function mint(address to, uint8 count) payable', 'function mythicFee() view returns (uint256)', 'function name() view returns (string)', 'function owner() view returns (address)', 'function ownerOf(uint256 tokenId) view returns (address)', 'function publicMintActive() view returns (bool)', 'function publicMintPrice() view returns (uint256)', 'function renounceOwnership()', 'function safeTransferFrom(address from, address to, uint256 tokenId)', 'function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data)', 'function setApprovalForAll(address operator, bool approved)', 'function setPublicMintActive()', 'function setPublicMintPrice(uint256 _publicMintPrice)', 'function shieldHashes(bytes32) view returns (bool)', 'function shields(uint256 tokenId) view returns (uint16 field, uint16 hardware, uint16 frame, uint24 color1, uint24 color2, uint24 color3, uint24 color4, uint8 shieldBadge)', 'function specialFee() view returns (uint256)', 'function supportsInterface(bytes4 interfaceId) view returns (bool)', 'function symbol() view returns (string)', 'function tokenURI(uint256 tokenId) view returns (string)', 'function totalSupply() view returns (uint256)', 'function transferFrom(address from, address to, uint256 tokenId)', 'function transferOwnership(address newOwner)', ]), wagmigotchi: parseAbi([ 'constructor()', 'event CaretakerLoved(address indexed caretaker, uint256 indexed amount)', 'function clean()', 'function feed()', 'function getAlive() view returns (bool)', 'function getBoredom() view returns (uint256)', 'function getHunger() view returns (uint256)', 'function getSleepiness() view returns (uint256)', 'function getStatus() view returns (string)', 'function getUncleanliness() view returns (uint256)', 'function love(address) view returns (uint256)', 'function play()', 'function sleep()', ]), wagmiMintExample: parseAbi([ 'constructor()', 'event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId)', 'event ApprovalForAll(address indexed owner, address indexed operator, bool approved)', 'event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)', 'function approve(address to, uint256 tokenId)', 'function balanceOf(address owner) view returns (uint256)', 'function getApproved(uint256 tokenId) view returns (address)', 'function isApprovedForAll(address owner, address operator) view returns (bool)', 'function mint()', 'function name() view returns (string)', 'function ownerOf(uint256 tokenId) view returns (address)', 'function safeTransferFrom(address from, address to, uint256 tokenId)', 'function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data)', 'function setApprovalForAll(address operator, bool approved)', 'function supportsInterface(bytes4 interfaceId) view returns (bool)', 'function symbol() view returns (string)', 'function tokenURI(uint256 tokenId) pure returns (string)', 'function totalSupply() view returns (uint256)', 'function transferFrom(address from, address to, uint256 tokenId)', ]), viewOverloads: parseAbi([ 'function foo() view returns (int8)', 'function foo(address account) view returns (string)', 'function foo(address a, address b) view returns ((address foo, address bar))', 'function bar() view returns (int8)', ]), writeOverloads: parseAbi([ 'function foo() payable returns (int8)', 'function foo(address) returns (string)', 'function foo(address, address) returns ((address foo, address bar))', 'function bar() payable returns (int8)', ]), bayc: parseAbi([ 'constructor(string name, string symbol, uint256 maxNftSupply, uint256 saleStart)', 'function mintApe(uint256 numberOfTokens) payable', 'function reserveApes()', 'function flipSaleState()', 'function emergencySetStartingIndexBlock()', 'function setStartingIndex()', 'function setRevealTimestamp(uint256 revealTimeStamp)', 'function setProvenanceHash(string provenanceHash)', 'function setBaseURI(string baseURI)', 'function startingIndex() view returns (uint256)', 'function startingIndexBlock() view returns (uint256)', 'function saleIsActive() view returns (bool)', 'function maxApePurchase() view returns (uint256)', 'function apePrice() view returns (uint256)', 'function REVEAL_TIMESTAMP() view returns (uint256)', 'function MAX_APES() view returns (uint256)', 'function BAYC_PROVENANCE() view returns (string)', 'function name() view returns (string)', 'function symbol() view returns (string)', 'function totalSupply() view returns (uint256)', 'function balanceOf(address owner) view returns (uint256)', 'function ownerOf(uint256 tokenId) view returns (address)', 'function getApproved(uint256 tokenId) view returns (address)', 'function isApprovedForAll(address owner, address operator) view returns (bool)', 'function approve(address to, uint256 tokenId)', 'function setApprovalForAll(address operator, bool approved)', 'function safeTransferFrom(address from, address to, uint256 tokenId)', 'function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data)', 'function tokenOfOwnerByIndex(address owner, uint256 index) view returns (uint256)', 'function tokenByIndex(uint256 index) view returns (uint256)', 'function tokenURI(uint256 tokenId) view returns (string)', 'function supportsInterface(bytes4 interfaceId) view returns (bool)', 'function transferFrom(address from, address to, uint256 tokenId)', 'function renounceOwnership()', 'function transferOwnership(address newOwner)', 'function withdraw()', ]), } as const const mainnetAddress = { mloot: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', shields: '0x0747118c9f44c7a23365b2476dcd05e03114c747', usdc: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', usdcHolder: '0x5414d89a8bf7e99d732bc52f3e6a3ef461c0c078', wagmigotchi: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', wagmiMintExample: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', } as const export const address = { ...mainnetAddress, mainnet: mainnetAddress, mainnet2: mainnetAddress, optimism: { usdc: '0x7f5c764cbc14f9669b88837ca1490cca17c31607', }, } as const satisfies Record & Record> export const bytecode = { bayc: '0x608060405260405180602001604052806000815250600b90805190602001906200002b92919062000484565b506000600f60006101000a81548160ff0219169083151502179055503480156200005457600080fd5b50604051620046d0380380620046d0833981810160405260808110156200007a57600080fd5b81019080805160405193929190846401000000008211156200009b57600080fd5b83820191506020820185811115620000b257600080fd5b8251866001820283011164010000000082111715620000d057600080fd5b8083526020830192505050908051906020019080838360005b8381101562000106578082015181840152602081019050620000e9565b50505050905090810190601f168015620001345780820380516001836020036101000a031916815260200191505b50604052602001805160405193929190846401000000008211156200015857600080fd5b838201915060208201858111156200016f57600080fd5b82518660018202830111640100000000821117156200018d57600080fd5b8083526020830192505050908051906020019080838360005b83811015620001c3578082015181840152602081019050620001a6565b50505050905090810190601f168015620001f15780820380516001836020036101000a031916815260200191505b5060405260200180519060200190929190805190602001909291905050508383620002296301ffc9a760e01b6200037360201b60201c565b81600690805190602001906200024192919062000484565b5080600790805190602001906200025a92919062000484565b50620002736380ac58cd60e01b6200037360201b60201c565b6200028b635b5e139f60e01b6200037360201b60201c565b620002a363780e9d6360e01b6200037360201b60201c565b50506000620002b76200047c60201b60201c565b905080600a60006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508073ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a35081600e81905550620bdd808101601081905550505050506200052a565b63ffffffff60e01b817bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916141562000410576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601c8152602001807f4552433136353a20696e76616c696420696e746572666163652069640000000081525060200191505060405180910390fd5b6001600080837bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916815260200190815260200160002060006101000a81548160ff02191690831515021790555050565b600033905090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10620004c757805160ff1916838001178555620004f8565b82800160010185558215620004f8579182015b82811115620004f7578251825591602001919060010190620004da565b5b5090506200050791906200050b565b5090565b5b80821115620005265760008160009055506001016200050c565b5090565b614196806200053a6000396000f3fe60806040526004361061021a5760003560e01c80636c0360eb11610123578063b0f67427116100ab578063e36d64981161006f578063e36d649814610ddf578063e985e9c514610e0a578063e986655014610e91578063eb8d244414610ea8578063f2fde38b14610ed55761021a565b8063b0f6742714610bac578063b88d4fde14610bc3578063bb8a16bd14610cd5578063c87b56dd14610d00578063cb774d4714610db45761021a565b80637d17fcbe116100f25780637d17fcbe14610a395780638da5cb5b14610a5057806395d89b4114610a91578063a22cb46514610b21578063a723533e14610b7e5761021a565b80636c0360eb1461090257806370a0823114610992578063715018a6146109f75780637a3f451e14610a0e5761021a565b80632f745c59116101a65780634f6ccce7116101755780634f6ccce7146106cb57806355f804b31461071a578063571dff3b146107e2578063607e20e31461080d5780636352211e1461089d5761021a565b80632f745c59146105b357806334918dfd146106225780633ccfd60b1461063957806342842e0e146106505761021a565b8063095ea7b3116101ed578063095ea7b3146103bf578063109695231461041a57806318160ddd146104e257806318e20a381461050d57806323b872dd146105385761021a565b8063018a2c371461021f57806301ffc9a71461025a57806306fdde03146102ca578063081812fc1461035a575b600080fd5b34801561022b57600080fd5b506102586004803603602081101561024257600080fd5b8101908080359060200190929190505050610f26565b005b34801561026657600080fd5b506102b26004803603602081101561027d57600080fd5b8101908080357bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19169060200190929190505050610fdf565b60405180821515815260200191505060405180910390f35b3480156102d657600080fd5b506102df611046565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561031f578082015181840152602081019050610304565b50505050905090810190601f16801561034c5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561036657600080fd5b506103936004803603602081101561037d57600080fd5b81019080803590602001909291905050506110e8565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b3480156103cb57600080fd5b50610418600480360360408110156103e257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050611183565b005b34801561042657600080fd5b506104e06004803603602081101561043d57600080fd5b810190808035906020019064010000000081111561045a57600080fd5b82018360208201111561046c57600080fd5b8035906020019184600183028401116401000000008311171561048e57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192905050506112c7565b005b3480156104ee57600080fd5b506104f7611390565b6040518082815260200191505060405180910390f35b34801561051957600080fd5b506105226113a1565b6040518082815260200191505060405180910390f35b34801561054457600080fd5b506105b16004803603606081101561055b57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506113a7565b005b3480156105bf57600080fd5b5061060c600480360360408110156105d657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061141d565b6040518082815260200191505060405180910390f35b34801561062e57600080fd5b50610637611478565b005b34801561064557600080fd5b5061064e611553565b005b34801561065c57600080fd5b506106c96004803603606081101561067357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050611651565b005b3480156106d757600080fd5b50610704600480360360208110156106ee57600080fd5b8101908080359060200190929190505050611671565b6040518082815260200191505060405180910390f35b34801561072657600080fd5b506107e06004803603602081101561073d57600080fd5b810190808035906020019064010000000081111561075a57600080fd5b82018360208201111561076c57600080fd5b8035906020019184600183028401116401000000008311171561078e57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f820116905080830192505050505050509192919290505050611694565b005b3480156107ee57600080fd5b506107f761174f565b6040518082815260200191505060405180910390f35b34801561081957600080fd5b50610822611754565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610862578082015181840152602081019050610847565b50505050905090810190601f16801561088f5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156108a957600080fd5b506108d6600480360360208110156108c057600080fd5b81019080803590602001909291905050506117f2565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34801561090e57600080fd5b50610917611829565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561095757808201518184015260208101905061093c565b50505050905090810190601f1680156109845780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561099e57600080fd5b506109e1600480360360208110156109b557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506118cb565b6040518082815260200191505060405180910390f35b348015610a0357600080fd5b50610a0c6119a0565b005b348015610a1a57600080fd5b50610a23611b10565b6040518082815260200191505060405180910390f35b348015610a4557600080fd5b50610a4e611b1c565b005b348015610a5c57600080fd5b50610a65611c4c565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b348015610a9d57600080fd5b50610aa6611c76565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610ae6578082015181840152602081019050610acb565b50505050905090810190601f168015610b135780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b348015610b2d57600080fd5b50610b7c60048036036040811015610b4457600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803515159060200190929190505050611d18565b005b610baa60048036036020811015610b9457600080fd5b8101908080359060200190929190505050611ece565b005b348015610bb857600080fd5b50610bc1612127565b005b348015610bcf57600080fd5b50610cd360048036036080811015610be657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919080359060200190640100000000811115610c4d57600080fd5b820183602082011115610c5f57600080fd5b80359060200191846001830284011164010000000083111715610c8157600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f82011690508083019250505050505050919291929050505061220b565b005b348015610ce157600080fd5b50610cea612283565b6040518082815260200191505060405180910390f35b348015610d0c57600080fd5b50610d3960048036036020811015610d2357600080fd5b8101908080359060200190929190505050612289565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610d79578082015181840152602081019050610d5e565b50505050905090810190601f168015610da65780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b348015610dc057600080fd5b50610dc961255a565b6040518082815260200191505060405180910390f35b348015610deb57600080fd5b50610df4612560565b6040518082815260200191505060405180910390f35b348015610e1657600080fd5b50610e7960048036036040811015610e2d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612566565b60405180821515815260200191505060405180910390f35b348015610e9d57600080fd5b50610ea66125fa565b005b348015610eb457600080fd5b50610ebd612764565b60405180821515815260200191505060405180910390f35b348015610ee157600080fd5b50610f2460048036036020811015610ef857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612777565b005b610f2e61296c565b73ffffffffffffffffffffffffffffffffffffffff16610f4c611c4c565b73ffffffffffffffffffffffffffffffffffffffff1614610fd5576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b8060108190555050565b6000806000837bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916815260200190815260200160002060009054906101000a900460ff169050919050565b606060068054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156110de5780601f106110b3576101008083540402835291602001916110de565b820191906000526020600020905b8154815290600101906020018083116110c157829003601f168201915b5050505050905090565b60006110f382612974565b611148576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602c81526020018061408b602c913960400191505060405180910390fd5b6004600083815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff169050919050565b600061118e826117f2565b90508073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415611215576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602181526020018061410f6021913960400191505060405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff1661123461296c565b73ffffffffffffffffffffffffffffffffffffffff16148061126357506112628161125d61296c565b612566565b5b6112b8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526038815260200180613f956038913960400191505060405180910390fd5b6112c28383612991565b505050565b6112cf61296c565b73ffffffffffffffffffffffffffffffffffffffff166112ed611c4c565b73ffffffffffffffffffffffffffffffffffffffff1614611376576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b80600b908051906020019061138c929190613de6565b5050565b600061139c6002612a4a565b905090565b60105481565b6113b86113b261296c565b82612a5f565b61140d576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260318152602001806141306031913960400191505060405180910390fd5b611418838383612b53565b505050565b600061147082600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020612d9690919063ffffffff16565b905092915050565b61148061296c565b73ffffffffffffffffffffffffffffffffffffffff1661149e611c4c565b73ffffffffffffffffffffffffffffffffffffffff1614611527576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b600f60009054906101000a900460ff1615600f60006101000a81548160ff021916908315150217905550565b61155b61296c565b73ffffffffffffffffffffffffffffffffffffffff16611579611c4c565b73ffffffffffffffffffffffffffffffffffffffff1614611602576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b60004790503373ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051600060405180830381858888f1935050505015801561164d573d6000803e3d6000fd5b5050565b61166c8383836040518060200160405280600081525061220b565b505050565b600080611688836002612db090919063ffffffff16565b50905080915050919050565b61169c61296c565b73ffffffffffffffffffffffffffffffffffffffff166116ba611c4c565b73ffffffffffffffffffffffffffffffffffffffff1614611743576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b61174c81612ddc565b50565b601481565b600b8054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156117ea5780601f106117bf576101008083540402835291602001916117ea565b820191906000526020600020905b8154815290600101906020018083116117cd57829003601f168201915b505050505081565b600061182282604051806060016040528060298152602001613ff7602991396002612df69092919063ffffffff16565b9050919050565b606060098054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156118c15780601f10611896576101008083540402835291602001916118c1565b820191906000526020600020905b8154815290600101906020018083116118a457829003601f168201915b5050505050905090565b60008073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415611952576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602a815260200180613fcd602a913960400191505060405180910390fd5b611999600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020612e15565b9050919050565b6119a861296c565b73ffffffffffffffffffffffffffffffffffffffff166119c6611c4c565b73ffffffffffffffffffffffffffffffffffffffff1614611a4f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff16600a60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a36000600a60006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550565b67011c37937e08000081565b611b2461296c565b73ffffffffffffffffffffffffffffffffffffffff16611b42611c4c565b73ffffffffffffffffffffffffffffffffffffffff1614611bcb576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b6000600d5414611c43576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f5374617274696e6720696e64657820697320616c72656164792073657400000081525060200191505060405180910390fd5b43600c81905550565b6000600a60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b606060078054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015611d0e5780601f10611ce357610100808354040283529160200191611d0e565b820191906000526020600020905b815481529060010190602001808311611cf157829003601f168201915b5050505050905090565b611d2061296c565b73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415611dc1576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260198152602001807f4552433732313a20617070726f766520746f2063616c6c65720000000000000081525060200191505060405180910390fd5b8060056000611dce61296c565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055508173ffffffffffffffffffffffffffffffffffffffff16611e7b61296c565b73ffffffffffffffffffffffffffffffffffffffff167f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c318360405180821515815260200191505060405180910390a35050565b600f60009054906101000a900460ff16611f50576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601f8152602001807f53616c65206d7573742062652061637469766520746f206d696e74204170650081525060200191505060405180910390fd5b6014811115611faa576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526021815260200180613f746021913960400191505060405180910390fd5b600e54611fc782611fb9611390565b612e2a90919063ffffffff16565b111561201e576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260288152602001806140426028913960400191505060405180910390fd5b3461203a8267011c37937e080000612eb290919063ffffffff16565b11156120ae576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601f8152602001807f45746865722076616c75652073656e74206973206e6f7420636f72726563740081525060200191505060405180910390fd5b60005b818110156120ef5760006120c3611390565b9050600e546120d0611390565b10156120e1576120e03382612f38565b5b5080806001019150506120b1565b506000600c541480156121175750600e54612108611390565b148061211657506010544210155b5b156121245743600c819055505b50565b61212f61296c565b73ffffffffffffffffffffffffffffffffffffffff1661214d611c4c565b73ffffffffffffffffffffffffffffffffffffffff16146121d6576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b60006121e0611390565b905060005b601e811015612207576121fa33828401612f38565b80806001019150506121e5565b5050565b61221c61221661296c565b83612a5f565b612271576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260318152602001806141306031913960400191505060405180910390fd5b61227d84848484612f56565b50505050565b600e5481565b606061229482612974565b6122e9576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602f8152602001806140e0602f913960400191505060405180910390fd5b6060600860008481526020019081526020016000208054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156123925780601f1061236757610100808354040283529160200191612392565b820191906000526020600020905b81548152906001019060200180831161237557829003601f168201915b5050505050905060606123a3611829565b90506000815114156123b9578192505050612555565b60008251111561248a5780826040516020018083805190602001908083835b602083106123fb57805182526020820191506020810190506020830392506123d8565b6001836020036101000a03801982511681845116808217855250505050505090500182805190602001908083835b6020831061244c5780518252602082019150602081019050602083039250612429565b6001836020036101000a0380198251168184511680821785525050505050509050019250505060405160208183030381529060405292505050612555565b8061249485612fc8565b6040516020018083805190602001908083835b602083106124ca57805182526020820191506020810190506020830392506124a7565b6001836020036101000a03801982511681845116808217855250505050505090500182805190602001908083835b6020831061251b57805182526020820191506020810190506020830392506124f8565b6001836020036101000a03801982511681845116808217855250505050505090500192505050604051602081830303815290604052925050505b919050565b600d5481565b600c5481565b6000600560008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16905092915050565b6000600d5414612672576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f5374617274696e6720696e64657820697320616c72656164792073657400000081525060200191505060405180910390fd5b6000600c5414156126eb576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f5374617274696e6720696e64657820626c6f636b206d7573742062652073657481525060200191505060405180910390fd5b600e54600c544060001c816126fc57fe5b06600d8190555060ff61271a600c544361310f90919063ffffffff16565b111561273a57600e54600143034060001c8161273257fe5b06600d819055505b6000600d5414156127625761275b6001600d54612e2a90919063ffffffff16565b600d819055505b565b600f60009054906101000a900460ff1681565b61277f61296c565b73ffffffffffffffffffffffffffffffffffffffff1661279d611c4c565b73ffffffffffffffffffffffffffffffffffffffff1614612826576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156128ac576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526026815260200180613ed86026913960400191505060405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff16600a60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a380600a60006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b600033905090565b600061298a82600261319290919063ffffffff16565b9050919050565b816004600083815260200190815260200160002060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550808273ffffffffffffffffffffffffffffffffffffffff16612a04836117f2565b73ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560405160405180910390a45050565b6000612a58826000016131ac565b9050919050565b6000612a6a82612974565b612abf576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602c815260200180613f48602c913960400191505060405180910390fd5b6000612aca836117f2565b90508073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff161480612b3957508373ffffffffffffffffffffffffffffffffffffffff16612b21846110e8565b73ffffffffffffffffffffffffffffffffffffffff16145b80612b4a5750612b498185612566565b5b91505092915050565b8273ffffffffffffffffffffffffffffffffffffffff16612b73826117f2565b73ffffffffffffffffffffffffffffffffffffffff1614612bdf576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260298152602001806140b76029913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415612c65576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526024815260200180613efe6024913960400191505060405180910390fd5b612c708383836131bd565b612c7b600082612991565b612ccc81600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206131c290919063ffffffff16565b50612d1e81600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206131dc90919063ffffffff16565b50612d35818360026131f69092919063ffffffff16565b50808273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60405160405180910390a4505050565b6000612da5836000018361322b565b60001c905092915050565b600080600080612dc386600001866132ae565b915091508160001c8160001c9350935050509250929050565b8060099080519060200190612df2929190613de6565b5050565b6000612e09846000018460001b84613347565b60001c90509392505050565b6000612e238260000161343d565b9050919050565b600080828401905083811015612ea8576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b600080831415612ec55760009050612f32565b6000828402905082848281612ed657fe5b0414612f2d576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602181526020018061406a6021913960400191505060405180910390fd5b809150505b92915050565b612f5282826040518060200160405280600081525061344e565b5050565b612f61848484612b53565b612f6d848484846134bf565b612fc2576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526032815260200180613ea66032913960400191505060405180910390fd5b50505050565b60606000821415613010576040518060400160405280600181526020017f3000000000000000000000000000000000000000000000000000000000000000815250905061310a565b600082905060005b6000821461303a578080600101915050600a828161303257fe5b049150613018565b60608167ffffffffffffffff8111801561305357600080fd5b506040519080825280601f01601f1916602001820160405280156130865781602001600182028036833780820191505090505b50905060006001830390508593505b6000841461310257600a84816130a757fe5b0660300160f81b828280600190039350815181106130c157fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350600a84816130fa57fe5b049350613095565b819450505050505b919050565b600082821115613187576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601e8152602001807f536166654d6174683a207375627472616374696f6e206f766572666c6f77000081525060200191505060405180910390fd5b818303905092915050565b60006131a4836000018360001b6136d8565b905092915050565b600081600001805490509050919050565b505050565b60006131d4836000018360001b6136fb565b905092915050565b60006131ee836000018360001b6137e3565b905092915050565b6000613222846000018460001b8473ffffffffffffffffffffffffffffffffffffffff1660001b613853565b90509392505050565b60008183600001805490501161328c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180613e846022913960400191505060405180910390fd5b82600001828154811061329b57fe5b9060005260206000200154905092915050565b60008082846000018054905011613310576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806140206022913960400191505060405180910390fd5b600084600001848154811061332157fe5b906000526020600020906002020190508060000154816001015492509250509250929050565b6000808460010160008581526020019081526020016000205490506000811415839061340e576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b838110156133d35780820151818401526020810190506133b8565b50505050905090810190601f1680156134005780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5084600001600182038154811061342157fe5b9060005260206000209060020201600101549150509392505050565b600081600001805490509050919050565b613458838361392f565b61346560008484846134bf565b6134ba576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526032815260200180613ea66032913960400191505060405180910390fd5b505050565b60006134e08473ffffffffffffffffffffffffffffffffffffffff16613b23565b6134ed57600190506136d0565b606061365763150b7a0260e01b61350261296c565b888787604051602401808573ffffffffffffffffffffffffffffffffffffffff1681526020018473ffffffffffffffffffffffffffffffffffffffff16815260200183815260200180602001828103825283818151815260200191508051906020019080838360005b8381101561358657808201518184015260208101905061356b565b50505050905090810190601f1680156135b35780820380516001836020036101000a031916815260200191505b5095505050505050604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050604051806060016040528060328152602001613ea6603291398773ffffffffffffffffffffffffffffffffffffffff16613b369092919063ffffffff16565b9050600081806020019051602081101561367057600080fd5b8101908080519060200190929190505050905063150b7a0260e01b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916817bffffffffffffffffffffffffffffffffffffffffffffffffffffffff191614925050505b949350505050565b600080836001016000848152602001908152602001600020541415905092915050565b600080836001016000848152602001908152602001600020549050600081146137d7576000600182039050600060018660000180549050039050600086600001828154811061374657fe5b906000526020600020015490508087600001848154811061376357fe5b906000526020600020018190555060018301876001016000838152602001908152602001600020819055508660000180548061379b57fe5b600190038181906000526020600020016000905590558660010160008781526020019081526020016000206000905560019450505050506137dd565b60009150505b92915050565b60006137ef8383613b4e565b61384857826000018290806001815401808255809150506001900390600052602060002001600090919091909150558260000180549050836001016000848152602001908152602001600020819055506001905061384d565b600090505b92915050565b60008084600101600085815260200190815260200160002054905060008114156138fa57846000016040518060400160405280868152602001858152509080600181540180825580915050600190039060005260206000209060020201600090919091909150600082015181600001556020820151816001015550508460000180549050856001016000868152602001908152602001600020819055506001915050613928565b8285600001600183038154811061390d57fe5b90600052602060002090600202016001018190555060009150505b9392505050565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614156139d2576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4552433732313a206d696e7420746f20746865207a65726f206164647265737381525060200191505060405180910390fd5b6139db81612974565b15613a4e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601c8152602001807f4552433732313a20746f6b656e20616c7265616479206d696e7465640000000081525060200191505060405180910390fd5b613a5a600083836131bd565b613aab81600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206131dc90919063ffffffff16565b50613ac2818360026131f69092919063ffffffff16565b50808273ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60405160405180910390a45050565b600080823b905060008111915050919050565b6060613b458484600085613b71565b90509392505050565b600080836001016000848152602001908152602001600020541415905092915050565b606082471015613bcc576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526026815260200180613f226026913960400191505060405180910390fd5b613bd585613b23565b613c47576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000081525060200191505060405180910390fd5b600060608673ffffffffffffffffffffffffffffffffffffffff1685876040518082805190602001908083835b60208310613c975780518252602082019150602081019050602083039250613c74565b6001836020036101000a03801982511681845116808217855250505050505090500191505060006040518083038185875af1925050503d8060008114613cf9576040519150601f19603f3d011682016040523d82523d6000602084013e613cfe565b606091505b5091509150613d0e828286613d1a565b92505050949350505050565b60608315613d2a57829050613ddf565b600083511115613d3d5782518084602001fd5b816040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015613da4578082015181840152602081019050613d89565b50505050905090810190601f168015613dd15780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b9392505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10613e2757805160ff1916838001178555613e55565b82800160010185558215613e55579182015b82811115613e54578251825591602001919060010190613e39565b5b509050613e629190613e66565b5090565b5b80821115613e7f576000816000905550600101613e67565b509056fe456e756d657261626c655365743a20696e646578206f7574206f6620626f756e64734552433732313a207472616e7366657220746f206e6f6e20455243373231526563656976657220696d706c656d656e7465724f776e61626c653a206e6577206f776e657220697320746865207a65726f20616464726573734552433732313a207472616e7366657220746f20746865207a65726f2061646472657373416464726573733a20696e73756666696369656e742062616c616e636520666f722063616c6c4552433732313a206f70657261746f7220717565727920666f72206e6f6e6578697374656e7420746f6b656e43616e206f6e6c79206d696e7420323020746f6b656e7320617420612074696d654552433732313a20617070726f76652063616c6c6572206973206e6f74206f776e6572206e6f7220617070726f76656420666f7220616c6c4552433732313a2062616c616e636520717565727920666f7220746865207a65726f20616464726573734552433732313a206f776e657220717565727920666f72206e6f6e6578697374656e7420746f6b656e456e756d657261626c654d61703a20696e646578206f7574206f6620626f756e6473507572636861736520776f756c6420657863656564206d617820737570706c79206f662041706573536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f774552433732313a20617070726f76656420717565727920666f72206e6f6e6578697374656e7420746f6b656e4552433732313a207472616e73666572206f6620746f6b656e2074686174206973206e6f74206f776e4552433732314d657461646174613a2055524920717565727920666f72206e6f6e6578697374656e7420746f6b656e4552433732313a20617070726f76616c20746f2063757272656e74206f776e65724552433732313a207472616e736665722063616c6c6572206973206e6f74206f776e6572206e6f7220617070726f766564a2646970667358221220b0e64d1fa6c4dbeb9c6f54607d7e1996943fe27624a80652f57b53fda084621b64736f6c63430007000033000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000002710000000000000000000000000000000000000000000000000000000006080e6d70000000000000000000000000000000000000000000000000000000000000011426f7265644170655961636874436c756200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044241594300000000000000000000000000000000000000000000000000000000', wagmiMintExample: '0x608060405260006007553480156200001657600080fd5b50604051806040016040528060058152602001647761676d6960d81b815250604051806040016040528060058152602001645741474d4960d81b81525081600090805190602001906200006b9291906200008a565b508051620000819060019060208401906200008a565b5050506200016c565b828054620000989062000130565b90600052602060002090601f016020900481019282620000bc576000855562000107565b82601f10620000d757805160ff191683800117855562000107565b8280016001018555821562000107579182015b8281111562000107578251825591602001919060010190620000ea565b506200011592915062000119565b5090565b5b808211156200011557600081556001016200011a565b600181811c908216806200014557607f821691505b6020821081036200016657634e487b7160e01b600052602260045260246000fd5b50919050565b6128c2806200017c6000396000f3fe608060405234801561001057600080fd5b50600436106101005760003560e01c80636352211e11610097578063a22cb46511610066578063a22cb46514610215578063b88d4fde14610228578063c87b56dd1461023b578063e985e9c51461024e57600080fd5b80636352211e146101d457806370a08231146101e757806395d89b41146101fa578063a0712d681461020257600080fd5b80631249c58b116100d35780631249c58b1461018f57806318160ddd1461019757806323b872dd146101ae57806342842e0e146101c157600080fd5b806301ffc9a71461010557806306fdde031461012d578063081812fc14610142578063095ea7b31461017a575b600080fd5b61011861011336600461178f565b610297565b60405190151581526020015b60405180910390f35b61013561037c565b6040516101249190611829565b61015561015036600461183c565b61040e565b60405173ffffffffffffffffffffffffffffffffffffffff9091168152602001610124565b61018d61018836600461187e565b6104d3565b005b61018d61062b565b6101a060065481565b604051908152602001610124565b61018d6101bc3660046118a8565b61067d565b61018d6101cf3660046118a8565b610704565b6101556101e236600461183c565b61071f565b6101a06101f53660046118e4565b6107b7565b61013561086b565b61018d61021036600461183c565b61087a565b61018d6102233660046118ff565b610902565b61018d61023636600461196a565b610911565b61013561024936600461183c565b61099f565b61011861025c366004611a64565b73ffffffffffffffffffffffffffffffffffffffff918216600090815260056020908152604080832093909416825291909152205460ff1690565b60007fffffffff0000000000000000000000000000000000000000000000000000000082167f80ac58cd00000000000000000000000000000000000000000000000000000000148061032a57507fffffffff0000000000000000000000000000000000000000000000000000000082167f5b5e139f00000000000000000000000000000000000000000000000000000000145b8061037657507f01ffc9a7000000000000000000000000000000000000000000000000000000007fffffffff000000000000000000000000000000000000000000000000000000008316145b92915050565b60606000805461038b90611a97565b80601f01602080910402602001604051908101604052809291908181526020018280546103b790611a97565b80156104045780601f106103d957610100808354040283529160200191610404565b820191906000526020600020905b8154815290600101906020018083116103e757829003601f168201915b5050505050905090565b60008181526002602052604081205473ffffffffffffffffffffffffffffffffffffffff166104aa5760405162461bcd60e51b815260206004820152602c60248201527f4552433732313a20617070726f76656420717565727920666f72206e6f6e657860448201527f697374656e7420746f6b656e000000000000000000000000000000000000000060648201526084015b60405180910390fd5b5060009081526004602052604090205473ffffffffffffffffffffffffffffffffffffffff1690565b60006104de8261071f565b90508073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16036105815760405162461bcd60e51b815260206004820152602160248201527f4552433732313a20617070726f76616c20746f2063757272656e74206f776e6560448201527f720000000000000000000000000000000000000000000000000000000000000060648201526084016104a1565b3373ffffffffffffffffffffffffffffffffffffffff821614806105aa57506105aa813361025c565b61061c5760405162461bcd60e51b815260206004820152603860248201527f4552433732313a20617070726f76652063616c6c6572206973206e6f74206f7760448201527f6e6572206e6f7220617070726f76656420666f7220616c6c000000000000000060648201526084016104a1565b6106268383610b07565b505050565b6007545b60008181526002602052604090205473ffffffffffffffffffffffffffffffffffffffff16156106615760010161062f565b61066b3382610ba7565b60068054600190810190915501600755565b6106873382610bc1565b6106f95760405162461bcd60e51b815260206004820152603160248201527f4552433732313a207472616e736665722063616c6c6572206973206e6f74206f60448201527f776e6572206e6f7220617070726f76656400000000000000000000000000000060648201526084016104a1565b610626838383610d17565b61062683838360405180602001604052806000815250610911565b60008181526002602052604081205473ffffffffffffffffffffffffffffffffffffffff16806103765760405162461bcd60e51b815260206004820152602960248201527f4552433732313a206f776e657220717565727920666f72206e6f6e657869737460448201527f656e7420746f6b656e000000000000000000000000000000000000000000000060648201526084016104a1565b600073ffffffffffffffffffffffffffffffffffffffff82166108425760405162461bcd60e51b815260206004820152602a60248201527f4552433732313a2062616c616e636520717565727920666f7220746865207a6560448201527f726f20616464726573730000000000000000000000000000000000000000000060648201526084016104a1565b5073ffffffffffffffffffffffffffffffffffffffff1660009081526003602052604090205490565b60606001805461038b90611a97565b60008181526002602052604090205473ffffffffffffffffffffffffffffffffffffffff16156108ec5760405162461bcd60e51b815260206004820152601160248201527f546f6b656e2049442069732074616b656e00000000000000000000000000000060448201526064016104a1565b6108f63382610ba7565b50600680546001019055565b61090d338383610f4a565b5050565b61091b3383610bc1565b61098d5760405162461bcd60e51b815260206004820152603160248201527f4552433732313a207472616e736665722063616c6c6572206973206e6f74206f60448201527f776e6572206e6f7220617070726f76656400000000000000000000000000000060648201526084016104a1565b6109998484848461105d565b50505050565b6040517f666f726567726f756e64000000000000000000000000000000000000000000006020820152602a810182905260609060009061016890604a016040516020818303038152906040528051906020012060001c6109ff9190611b19565b6040517f6261636b67726f756e64000000000000000000000000000000000000000000006020820152602a810185905290915060009061016890604a016040516020818303038152906040528051906020012060001c610a5f9190611b19565b90506000610aba610a6f866110e6565b610aa9610a7b866110e6565b610a84866110e6565b604051602001610a95929190611b2d565b60405160208183030381529060405261121b565b604051602001610a959291906125ba565b9050600081604051602001610acf919061268b565b604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08184030181529190529695505050505050565b600081815260046020526040902080547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff84169081179091558190610b618261071f565b73ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560405160405180910390a45050565b61090d82826040518060200160405280600081525061136e565b60008181526002602052604081205473ffffffffffffffffffffffffffffffffffffffff16610c585760405162461bcd60e51b815260206004820152602c60248201527f4552433732313a206f70657261746f7220717565727920666f72206e6f6e657860448201527f697374656e7420746f6b656e000000000000000000000000000000000000000060648201526084016104a1565b6000610c638361071f565b90508073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff161480610cd1575073ffffffffffffffffffffffffffffffffffffffff80821660009081526005602090815260408083209388168352929052205460ff165b80610d0f57508373ffffffffffffffffffffffffffffffffffffffff16610cf78461040e565b73ffffffffffffffffffffffffffffffffffffffff16145b949350505050565b8273ffffffffffffffffffffffffffffffffffffffff16610d378261071f565b73ffffffffffffffffffffffffffffffffffffffff1614610dc05760405162461bcd60e51b815260206004820152602560248201527f4552433732313a207472616e736665722066726f6d20696e636f72726563742060448201527f6f776e657200000000000000000000000000000000000000000000000000000060648201526084016104a1565b73ffffffffffffffffffffffffffffffffffffffff8216610e485760405162461bcd60e51b8152602060048201526024808201527f4552433732313a207472616e7366657220746f20746865207a65726f2061646460448201527f726573730000000000000000000000000000000000000000000000000000000060648201526084016104a1565b610e53600082610b07565b73ffffffffffffffffffffffffffffffffffffffff83166000908152600360205260408120805460019290610e899084906126ff565b909155505073ffffffffffffffffffffffffffffffffffffffff82166000908152600360205260408120805460019290610ec4908490612716565b909155505060008181526002602052604080822080547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff86811691821790925591518493918716917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a4505050565b8173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1603610fc55760405162461bcd60e51b815260206004820152601960248201527f4552433732313a20617070726f766520746f2063616c6c65720000000000000060448201526064016104a1565b73ffffffffffffffffffffffffffffffffffffffff83811660008181526005602090815260408083209487168084529482529182902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001686151590811790915591519182527f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31910160405180910390a3505050565b611068848484610d17565b611074848484846113f7565b6109995760405162461bcd60e51b815260206004820152603260248201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560448201527f63656976657220696d706c656d656e746572000000000000000000000000000060648201526084016104a1565b60608160000361112957505060408051808201909152600181527f3000000000000000000000000000000000000000000000000000000000000000602082015290565b8160005b8115611153578061113d8161272e565b915061114c9050600a83612766565b915061112d565b60008167ffffffffffffffff81111561116e5761116e61193b565b6040519080825280601f01601f191660200182016040528015611198576020820181803683370190505b5090505b8415610d0f576111ad6001836126ff565b91506111ba600a86611b19565b6111c5906030612716565b60f81b8183815181106111da576111da61277a565b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350611214600a86612766565b945061119c565b6060815160000361123a57505060408051602081019091526000815290565b600060405180606001604052806040815260200161284d60409139905060006003845160026112699190612716565b6112739190612766565b61127e9060046127a9565b67ffffffffffffffff8111156112965761129661193b565b6040519080825280601f01601f1916602001820160405280156112c0576020820181803683370190505b509050600182016020820185865187015b8082101561132c576003820191508151603f8160121c168501518453600184019350603f81600c1c168501518453600184019350603f8160061c168501518453600184019350603f81168501518453506001830192506112d1565b5050600386510660018114611348576002811461135b57611363565b603d6001830353603d6002830353611363565b603d60018303535b509195945050505050565b61137883836115d0565b61138560008484846113f7565b6106265760405162461bcd60e51b815260206004820152603260248201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560448201527f63656976657220696d706c656d656e746572000000000000000000000000000060648201526084016104a1565b600073ffffffffffffffffffffffffffffffffffffffff84163b156115c5576040517f150b7a0200000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff85169063150b7a029061146e9033908990889088906004016127e6565b6020604051808303816000875af19250505080156114c7575060408051601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01682019092526114c49181019061282f565b60015b61157a573d8080156114f5576040519150601f19603f3d011682016040523d82523d6000602084013e6114fa565b606091505b5080516000036115725760405162461bcd60e51b815260206004820152603260248201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560448201527f63656976657220696d706c656d656e746572000000000000000000000000000060648201526084016104a1565b805181602001fd5b7fffffffff00000000000000000000000000000000000000000000000000000000167f150b7a0200000000000000000000000000000000000000000000000000000000149050610d0f565b506001949350505050565b73ffffffffffffffffffffffffffffffffffffffff82166116335760405162461bcd60e51b815260206004820181905260248201527f4552433732313a206d696e7420746f20746865207a65726f206164647265737360448201526064016104a1565b60008181526002602052604090205473ffffffffffffffffffffffffffffffffffffffff16156116a55760405162461bcd60e51b815260206004820152601c60248201527f4552433732313a20746f6b656e20616c7265616479206d696e7465640000000060448201526064016104a1565b73ffffffffffffffffffffffffffffffffffffffff821660009081526003602052604081208054600192906116db908490612716565b909155505060008181526002602052604080822080547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff861690811790915590518392907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef908290a45050565b7fffffffff000000000000000000000000000000000000000000000000000000008116811461178c57600080fd5b50565b6000602082840312156117a157600080fd5b81356117ac8161175e565b9392505050565b60005b838110156117ce5781810151838201526020016117b6565b838111156109995750506000910152565b600081518084526117f78160208601602086016117b3565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b6020815260006117ac60208301846117df565b60006020828403121561184e57600080fd5b5035919050565b803573ffffffffffffffffffffffffffffffffffffffff8116811461187957600080fd5b919050565b6000806040838503121561189157600080fd5b61189a83611855565b946020939093013593505050565b6000806000606084860312156118bd57600080fd5b6118c684611855565b92506118d460208501611855565b9150604084013590509250925092565b6000602082840312156118f657600080fd5b6117ac82611855565b6000806040838503121561191257600080fd5b61191b83611855565b91506020830135801515811461193057600080fd5b809150509250929050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b6000806000806080858703121561198057600080fd5b61198985611855565b935061199760208601611855565b925060408501359150606085013567ffffffffffffffff808211156119bb57600080fd5b818701915087601f8301126119cf57600080fd5b8135818111156119e1576119e161193b565b604051601f82017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0908116603f01168101908382118183101715611a2757611a2761193b565b816040528281528a6020848701011115611a4057600080fd5b82602086016020830137600060208483010152809550505050505092959194509250565b60008060408385031215611a7757600080fd5b611a8083611855565b9150611a8e60208401611855565b90509250929050565b600181811c90821680611aab57607f821691505b602082108103611ae4577f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b50919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b600082611b2857611b28611aea565b500690565b7f3c73766720786d6c6e733d22687474703a2f2f7777772e77332e6f72672f323081527f30302f737667222077696474683d223130323422206865696768743d2231303260208201527f34222066696c6c3d226e6f6e65223e3c706174682066696c6c3d2268736c2800604082015260008351611bb181605f8501602088016117b3565b7f2c20313030252c20313025292220643d224d3020306831303234763130323448605f918401918201527f307a22202f3e3c672066696c6c3d2268736c2800000000000000000000000000607f8201528351611c148160928401602088016117b3565b7f2c20313030252c2039302529223e3c7061746820643d224d393033203433372e609292909101918201527f35633020392e3131332d372e3338382031362e352d31362e352031362e35732d60b28201527f31362e352d372e3338372d31362e352d31362e3520372e3338382d31362e352060d28201527f31362e352d31362e352031362e3520372e3338372031362e352031362e357a4d60f28201527f3639382e3532392035363663362e39323120302031322e35332d352e353936206101128201527f31322e35332d31322e35762d353063302d362e39303420352e3630392d31322e6101328201527f352031322e3532392d31322e356832352e30353963362e393220302031322e356101528201527f323920352e3539362031322e3532392031322e35763530633020362e393034206101728201527f352e3630392031322e352031322e35332031322e357331322e3532392d352e356101928201527f39362031322e3532392d31322e35762d353063302d362e39303420352e3630396101b28201527f2d31322e352031322e35332d31322e356832352e30353963362e3932203020316101d28201527f322e35323920352e3539362031322e3532392031322e35763530633020362e396101f28201527f303420352e3630392031322e352031322e3532392031322e356833372e3538396102128201527f63362e393220302031322e3532392d352e3539362031322e3532392d31322e356102328201527f762d373563302d362e3930342d352e3630392d31322e352d31322e3532392d316102528201527f322e35732d31322e353320352e3539362d31322e35332031322e357635362e326102728201527f3561362e32363420362e3236342030203120312d31322e3532392030563437386102928201527f2e3563302d362e3930342d352e3630392d31322e352d31322e35332d31322e356102b28201527f483639382e353239632d362e393220302d31322e35323920352e3539362d31326102d28201527f2e3532392031322e35763735633020362e39303420352e3630392031322e35206102f28201527f31322e3532392031322e357a22202f3e3c7061746820643d224d3135372e36356103128201527f3520353431632d362e39333220302d31322e3535322d352e3539362d31322e356103328201527f35322d31322e35762d353063302d362e3930342d352e3631392d31322e352d316103528201527f322e3535312d31322e3553313230203437312e35393620313230203437382e356103728201527f763735633020362e39303420352e36322031322e352031322e3535322031322e6103928201527f35683135302e363263362e39333320302031322e3535322d352e3539362031326103b28201527f2e3535322d31322e35762d353063302d362e39303420352e3631392d31322e356103d28201527f2031322e3535322d31322e35683134342e33343563332e343635203020362e326103f28201527f373620322e37393820362e32373620362e3235732d322e38313120362e32352d6104128201527f362e32373620362e3235483332302e383238632d362e39333320302d31322e356104328201527f353220352e3539362d31322e3535322031322e357633372e35633020362e39306104528201527f3420352e3631392031322e352031322e3535322031322e35683135302e3632636104728201527f362e39333320302031322e3535322d352e3539362031322e3535322d31322e356104928201527f762d373563302d362e3930342d352e3631392d31322e352d31322e3535322d316104b28201527f322e35483238332e313732632d362e39333220302d31322e35353120352e35396104d28201527f362d31322e3535312031322e35763530633020362e3930342d352e36313920316104f28201527f322e352d31322e3535322031322e35682d32352e313033632d362e39333320306105128201527f2d31322e3535322d352e3539362d31322e3535322d31322e35762d353063302d6105328201527f362e3930342d352e36322d31322e352d31322e3535322d31322e35732d31322e6105528201527f35353220352e3539362d31322e3535322031322e35763530633020362e3930346105728201527f2d352e3631392031322e352d31322e3535312031322e35682d32352e3130347a6105928201527f6d3330312e3234322d362e3235633020332e3435322d322e38313120362e32356105b28201527f2d362e32373620362e3235483333392e363535632d332e34363520302d362e326105d28201527f37362d322e3739382d362e3237362d362e323573322e3831312d362e323520366105f28201527f2e3237362d362e3235683131322e39363663332e343635203020362e323736206106128201527f322e37393820362e32373620362e32357a4d343937203535332e3831386330206106328201527f362e39323920352e3632382031322e3534362031322e3537312031322e3534366106528201527f6831333261362e323820362e323820302030203120362e32383620362e3237326106728201527f20362e323820362e32382030203020312d362e32383620362e323733682d31336106928201527f32632d362e39343320302d31322e35373120352e3631362d31322e35373120316106b28201527f322e3534364131322e35362031322e3536203020302030203530392e353731206106d28201527f363034683135302e38353863362e39343320302031322e3537312d352e3631366106f28201527f2031322e3537312d31322e353435762d3131322e393163302d362e3932382d356107128201527f2e3632382d31322e3534352d31322e3537312d31322e353435483530392e35376107328201527f31632d362e39343320302d31322e35373120352e3631372d31322e35373120316107528201527f322e3534357637352e3237337a6d33372e3731342d36322e373237632d362e396107728201527f343320302d31322e35373120352e3631372d31322e3537312031322e353435766107928201527f32352e303931633020362e39323920352e3632382031322e3534362031322e356107b28201527f37312031322e353436683130302e35373263362e39343320302031322e3537316107d28201527f2d352e3631372031322e3537312d31322e353436762d32352e30393163302d366107f28201527f2e3932382d352e3632382d31322e3534352d31322e3537312d31322e353435486108128201527f3533342e3731347a222066696c6c2d72756c653d226576656e6f646422202f3e6108328201527f3c2f673e3c2f7376673e0000000000000000000000000000000000000000000061085282015261085c01949350505050565b7f7b226e616d65223a20227761676d6920230000000000000000000000000000008152600083516125f28160118501602088016117b3565b7f222c2022696d616765223a2022646174613a696d6167652f7376672b786d6c3b6011918401918201527f6261736536342c00000000000000000000000000000000000000000000000000603182015283516126558160388401602088016117b3565b7f227d00000000000000000000000000000000000000000000000000000000000060389290910191820152603a01949350505050565b7f646174613a6170706c69636174696f6e2f6a736f6e3b6261736536342c0000008152600082516126c381601d8501602087016117b3565b91909101601d0192915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b600082821015612711576127116126d0565b500390565b60008219821115612729576127296126d0565b500190565b60007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff820361275f5761275f6126d0565b5060010190565b60008261277557612775611aea565b500490565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b6000817fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff04831182151516156127e1576127e16126d0565b500290565b600073ffffffffffffffffffffffffffffffffffffffff80871683528086166020840152508360408301526080606083015261282560808301846117df565b9695505050505050565b60006020828403121561284157600080fd5b81516117ac8161175e56fe4142434445464748494a4b4c4d4e4f505152535455565758595a6162636465666768696a6b6c6d6e6f707172737475767778797a303132333435363738392b2fa26469706673582212201665a4f9111990d7529375848d3fd02c0121091a940da59e763eba826e7b077064736f6c634300080d0033', } as const ================================================ FILE: packages/test/src/exports/index.test-d.ts ================================================ import { expectTypeOf } from 'vitest' // noop test because vitest typecheck fails unless each workspace project has type test expectTypeOf(1).toEqualTypeOf() ================================================ FILE: packages/test/src/exports/index.test.ts ================================================ import { expect, test } from 'vitest' import * as react from './index.js' test('exports', () => { expect(Object.keys(react)).toMatchInlineSnapshot(` [ "chain", "mainnet", "mainnet2", "optimism", "mainnet2TestClient", "mainnetTestClient", "optimismTestClient", "testClient", "config", "abi", "accounts", "address", "bytecode", "privateKey", "typedData", "walletConnectProjectId", "addressRegex", "signedTransactionRegex", "transactionHashRegex", "wait", ] `) }) ================================================ FILE: packages/test/src/exports/index.ts ================================================ // biome-ignore lint/performance/noBarrelFile: entrypoint module export { chain, mainnet, mainnet2, optimism } from '../chains.js' export { mainnet2TestClient, mainnetTestClient, optimismTestClient, testClient, } from '../clients.js' export { config } from '../config.js' export { abi, accounts, address, bytecode, privateKey, typedData, walletConnectProjectId, } from '../constants.js' export { addressRegex, signedTransactionRegex, transactionHashRegex, } from '../regex.js' export { wait } from '../utils.js' ================================================ FILE: packages/test/src/exports/react.ts ================================================ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import * as React from 'react' import { type RenderHookOptions, type RenderHookResult, type RenderResult, render as vbr_render, renderHook as vbr_renderHook, } from 'vitest-browser-react' import { WagmiProvider } from 'wagmi' import { config } from '../config.js' export const queryClient = new QueryClient() export function createWrapper>( Wrapper: component, props: Parameters[0], ) { type Props = { children?: React.ReactNode | undefined } return function CreatedWrapper({ children }: Props) { return React.createElement( Wrapper, props, React.createElement( QueryClientProvider, { client: queryClient }, children, ), ) } } export function renderHook( renderCallback: (initialProps?: props) => result, options?: RenderHookOptions, ): Promise> { queryClient.clear() return vbr_renderHook(renderCallback, { wrapper: createWrapper(WagmiProvider, { config, reconnectOnMount: false }), ...options, }) } export function render( ...args: Parameters ): Promise { queryClient.clear() return vbr_render(args[0], { ...args[1], wrapper: createWrapper(WagmiProvider, { config, reconnectOnMount: false }), }) } ================================================ FILE: packages/test/src/exports/solid.ts ================================================ import { renderHook } from '@solidjs/testing-library' import { QueryClient, QueryClientProvider } from '@tanstack/solid-query' import { WagmiProvider } from '@wagmi/solid' import { type Component, createComponent, type ParentProps } from 'solid-js' import { config } from '../config.js' export const queryClient = new QueryClient() export function createWrapper>( Wrapper: component, props: Parameters[0], ) { return function CreatedWrapper(wrapperProps: ParentProps) { return createComponent(Wrapper, { ...props, get children() { return createComponent(QueryClientProvider, { client: queryClient, get children() { return wrapperProps.children }, }) }, }) } } export type RenderPrimitiveReturnType unknown> = { result: ReturnType cleanup: () => void } export function renderPrimitive unknown>( primitive: primitive, options?: { wrapper?: Component }, ): RenderPrimitiveReturnType { queryClient.clear() const wrapper = options?.wrapper ?? createWrapper(WagmiProvider, { config, reconnectOnMount: false, }) const { result, cleanup } = renderHook(primitive, { wrapper }) return { result: result as ReturnType, cleanup, } } ================================================ FILE: packages/test/src/exports/tempo.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // Tempo Test Utilities //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module export { accounts, addresses, config, createWrapper, queryClient, renderHook, restart, rpcUrl, setupOrders, setupPoolWithLiquidity, setupToken, setupTokenPair, tempoLocal, viem_setupOrders, viem_setupPoolWithLiquidity, viem_setupToken, viem_setupTokenPair, } from '../tempo/config.js' ================================================ FILE: packages/test/src/exports/vue.ts ================================================ import { VueQueryPlugin } from '@tanstack/vue-query' import { WagmiPlugin } from '@wagmi/vue' import { type App, createApp, type Ref, watch } from 'vue' import { config } from '../config.js' export type RenderComposableReturnType unknown> = [ ReturnType, App, ] export function renderComposable unknown>( composable: composable, options: { attach?: (app: App) => void } | undefined = { attach(app) { app .use(WagmiPlugin, { config, reconnectOnMount: false, }) .use(VueQueryPlugin, {}) }, }, ): RenderComposableReturnType { let result: unknown const app = createApp({ setup() { result = composable() return () => {} }, }) options.attach?.(app) app.mount(document.createElement('div')) return [result, app] as unknown as RenderComposableReturnType } export type WaitForOptions = { timeout?: number } export function waitFor( ref: ref, predicate: (value: ref['value']) => boolean = (value) => value, options: WaitForOptions = {}, ) { const { timeout = 10_000 } = options return new Promise((resolve, reject) => { const timer = timeout ? setTimeout(() => { _unwatch() if (predicate(ref.value)) resolve() else reject(new Error(`\`waitFor\` timed out in ${timeout}ms.`)) }, timeout) : undefined const _unwatch = watch(ref, (value) => { if (predicate(value)) { if (timer) clearTimeout(timer) _unwatch() resolve() } }) }) } ================================================ FILE: packages/test/src/regex.ts ================================================ export const addressRegex = /^0x([A-Fa-f0-9]{40})$/ export const transactionHashRegex = /^0x([A-Fa-f0-9]{64})$/ export const signedTransactionRegex = /^0x([A-Fa-f0-9]+)$/ ================================================ FILE: packages/test/src/setup.global.ts ================================================ import { Instance, Server } from 'prool' import { chain as chainLookup } from './chains.js' export default async function () { const promises = [] for (const chain of Object.values(chainLookup)) { const instance = Instance.anvil({ chainId: chain.id, forkBlockNumber: chain.fork.blockNumber, forkUrl: chain.fork.url, noMining: true, // @ts-expect-error mnemonicSeedUnsafe: 1, }) promises.push(Server.create({ instance, port: chain.port }).start()) } const results = await Promise.all(promises) return async () => { await Promise.all(results.map((stop) => stop())) } } ================================================ FILE: packages/test/src/setup.global.types.ts ================================================ import { dirname, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import * as attest from '@ark/attest' const __filename = fileURLToPath(import.meta.url) const __dirname = dirname(__filename) export default function () { return attest.setup({ benchErrorOnThresholdExceeded: true, formatCmd: 'pnpm check', tsconfig: resolve(__dirname, '../../core/tsconfig.json'), }) } ================================================ FILE: packages/test/src/setup.ts ================================================ import { disconnect } from '@wagmi/core' import { afterAll, beforeEach } from 'vitest' import { testClient } from './clients.js' import { config } from './config.js' beforeEach(async () => { await disconnect(config).catch(() => {}) }) afterAll(async () => { // If you are using a fork, you can reset your anvil instance to the initial fork block. await Promise.all(Object.values(testClient).map((client) => client.restart())) }) ================================================ FILE: packages/test/src/tempo/config.ts ================================================ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { connect, getConnection, getConnectorClient } from '@wagmi/core' import * as chains from '@wagmi/core/chains' import type { FixedArray } from '@wagmi/core/internal' import { dangerous_secp256k1 } from '@wagmi/core/tempo' import { Mnemonic } from 'ox' import * as React from 'react' import { type Account, type Chain, type Client, defineChain, http, parseUnits, type Transport, } from 'viem' import { sendTransactionSync } from 'viem/actions' import { Actions, Addresses, Tick, Account as tempo_Account } from 'viem/tempo' import { vi } from 'vitest' import { type RenderHookOptions, type RenderHookResult, renderHook as vbr_renderHook, } from 'vitest-browser-react' import { createConfig, WagmiProvider } from 'wagmi' export const port = Number(import.meta.env.RPC_PORT ?? 4000) export const rpcUrl = (() => { const id = (typeof process !== 'undefined' && Number(process.env.VITEST_POOL_ID ?? 1) + Math.floor(Math.random() * 10_000)) || 1 + Math.floor(Math.random() * 10_000) return `http://localhost:${port}/${id}` })() export const addresses = { alphaUsd: '0x20c0000000000000000000000000000000000001', } as const export const accounts = Array.from({ length: 20 }, (_, i) => { const privateKey = Mnemonic.toPrivateKey( 'test test test test test test test test test test test junk', { as: 'Hex', path: Mnemonic.path({ account: i }) }, ) return tempo_Account.fromSecp256k1(privateKey) }) as unknown as FixedArray export const tempoLocal = defineChain({ ...chains.tempoLocalnet, rpcUrls: { default: { http: [rpcUrl] } }, }).extend({ feeToken: 1n }) export const config = createConfig({ chains: [tempoLocal], connectors: [ dangerous_secp256k1({ account: accounts.at(0) }), dangerous_secp256k1({ account: accounts.at(1) }), ], pollingInterval: 100, storage: null, transports: { [tempoLocal.id]: http(), }, }) export const queryClient = new QueryClient() export function createWrapper>( Wrapper: component, props: Parameters[0], ) { type Props = { children?: React.ReactNode | undefined } return function CreatedWrapper({ children }: Props) { return React.createElement( Wrapper, props, React.createElement( QueryClientProvider, { client: queryClient }, children, ), ) } } export function renderHook( renderCallback: (initialProps?: props) => result, options?: RenderHookOptions, ): Promise> { queryClient.clear() return vbr_renderHook(renderCallback, { wrapper: createWrapper(WagmiProvider, { config, reconnectOnMount: false }), ...options, }) } export async function restart() { await fetch(`${rpcUrl}/restart`) // Re-setup liquidity for fee tokens after restart if (getConnection(config).status === 'disconnected') await connect(config, { connector: config.connectors[0]!, }) const client = config.getClient() // Temporarily restore real Date.now so viem calculates a valid validBefore timestamp. if ((Date.now as any).mockRestore) (Date.now as any).mockRestore() await Promise.all( [1n, 2n, 3n].map((id) => Actions.amm.mintSync(client, { account: accounts[0], feeToken: Addresses.pathUsd, nonceKey: 'expiring', userTokenAddress: id, validatorTokenAddress: Addresses.pathUsd, validatorTokenAmount: parseUnits('1000', 6), to: accounts[0].address, }), ), ) vi.spyOn(Date, 'now').mockReturnValue( new Date(Date.UTC(2023, 1, 1)).valueOf(), ) } export async function setupToken() { if (getConnection(config).status === 'disconnected') await connect(config, { connector: config.connectors[0]!, }) const client = await getConnectorClient(config) return viem_setupToken(client as never) } export async function setupPoolWithLiquidity() { if (getConnection(config).status === 'disconnected') await connect(config, { connector: config.connectors[0]!, }) const client = await getConnectorClient(config) return viem_setupPoolWithLiquidity(client as never) } export async function setupTokenPair() { if (getConnection(config).status === 'disconnected') await connect(config, { connector: config.connectors[0]!, }) const client = await getConnectorClient(config) return viem_setupTokenPair(client as never) } export async function setupOrders() { if (getConnection(config).status === 'disconnected') await connect(config, { connector: config.connectors[0]!, }) const client = await getConnectorClient(config) return viem_setupOrders(client as never) } export async function viem_setupToken( client: Client, parameters: Partial< Awaited> > = {}, ) { const token = await Actions.token.createSync(client, { currency: 'USD', name: 'Test Token', symbol: 'TST', ...parameters, }) await Actions.token.grantRolesSync(client, { roles: ['issuer'], to: client.account.address, token: token.token, }) await Actions.token.mintSync(client, { amount: parseUnits('10000', 6), to: client.account.address, token: token.token, }) return token } export async function viem_setupPoolWithLiquidity( client: Client, ) { // Create a new token for testing const { token } = await Actions.token.createSync(client, { name: 'Test Token', symbol: 'TEST', currency: 'USD', }) // Grant issuer role to mint tokens await Actions.token.grantRolesSync(client, { token, roles: ['issuer'], to: client.account.address, }) // Mint some tokens to account await Actions.token.mintSync(client, { to: client.account.address, amount: parseUnits('1000', 6), token, }) // Add liquidity to pool await Actions.amm.mintSync(client, { userTokenAddress: token, validatorTokenAddress: addresses.alphaUsd, validatorTokenAmount: parseUnits('100', 6), to: client.account.address, }) return { tokenAddress: token } } export async function viem_setupTokenPair( client: Client, ) { // Create quote token const { token: quoteToken } = await Actions.token.createSync(client, { name: 'Test Quote Token', symbol: 'QUOTE', currency: 'USD', }) // Create base token const { token: baseToken } = await Actions.token.createSync(client, { name: 'Test Base Token', symbol: 'BASE', currency: 'USD', quoteToken, }) await sendTransactionSync(client, { calls: [ Actions.token.grantRoles.call({ token: baseToken, role: 'issuer', to: client.account.address, }), Actions.token.grantRoles.call({ token: quoteToken, role: 'issuer', to: client.account.address, }), Actions.token.mint.call({ token: baseToken, to: client.account.address, amount: parseUnits('10000', 6), }), Actions.token.mint.call({ token: quoteToken, to: client.account.address, amount: parseUnits('10000', 6), }), Actions.token.approve.call({ token: baseToken, spender: Addresses.stablecoinDex, amount: parseUnits('10000', 6), }), Actions.token.approve.call({ token: quoteToken, spender: Addresses.stablecoinDex, amount: parseUnits('10000', 6), }), ], }) // Create the pair on the DEX return await Actions.dex.createPairSync(client, { base: baseToken, }) } export async function viem_setupOrders( client: Client, ) { const { base: base1 } = await viem_setupTokenPair(client) const { base: base2 } = await viem_setupTokenPair(client) const bases = [base1, base2] // Create 50 orders with varying amounts, ticks, and tokens const calls = [] for (let i = 0; i < 50; i++) { const token = bases[i % bases.length]! const amount = parseUnits(String(100 + i * 10), 6) const isBuy = i % 2 === 0 const tickPrice = 1.0 + ((i % 20) - 10) * 0.001 const tick = Tick.fromPrice(String(tickPrice)) calls.push( Actions.dex.place.call({ token, amount, type: isBuy ? 'buy' : 'sell', tick, }), ) } await sendTransactionSync(client, { calls } as never) return { bases } } ================================================ FILE: packages/test/src/tempo/setup.global.ts ================================================ import * as os from 'node:os' import * as path from 'node:path' import { Instance, Server } from 'prool' import { GenericContainer, PullPolicy, type StartedTestContainer, Wait, } from 'testcontainers' const isMacOS = os.platform() === 'darwin' function toFlagCase(str: string, separator = '-') { const keys = [] for (const part of str.split('.')) { if (!part) continue keys.push( part .replace(/\s+/g, separator) .replace(/([a-z])([A-Z])/g, `$1${separator}$2`) .toLowerCase(), ) } return `--${keys.join('.')}` } function toArgs( obj: Record, options: { arraySeparator?: string | null } = {}, ): string[] { const { arraySeparator = ',' } = options return Object.entries(obj).flatMap(([key, value]) => { if (value === undefined) return [] if (Array.isArray(value)) { if (value[0] === true) return [toFlagCase(key), ...toArgs({ [key]: value[1] }, options)] const arrayValue = arraySeparator === null ? value : value.join(arraySeparator) return [toFlagCase(key), arrayValue].flat() } if (typeof value === 'object' && value !== null) { return Object.entries(value).flatMap(([subKey, subValue]) => { if (subValue === undefined) return [] const flag = toFlagCase(`${key}.${subKey}`) return toArgs({ [flag.slice(2)]: subValue }, options) }) } const flag = toFlagCase(key) if (value === false) return [flag, 'false'] if (value === true) return [flag] const stringified = value?.toString() ?? '' if (stringified === '') return [flag] return [flag, stringified] }) } function buildCommand(port: number, blockTime: string): string[] { const datadir = path.join(os.tmpdir(), '.prool', `tempo.${port}`) const params: Record = { authrpc: { port: port + 30 }, datadir, dev: [true, { blockTime }], engine: { disablePrecompileCache: true, legacyStateRoot: true }, faucet: { address: [ '0x20c0000000000000000000000000000000000000', '0x20c0000000000000000000000000000000000001', '0x20c0000000000000000000000000000000000002', '0x20c0000000000000000000000000000000000003', ], amount: '1000000000000', enabled: true, privateKey: '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80', }, http: { addr: '0.0.0.0', api: 'all', corsdomain: '*', port }, port: port + 10, ws: { port: port + 20 }, } return ['node', ...toArgs(params, { arraySeparator: null })] } const tempoInstance = Instance.define( (parameters?: { image: string port: number blockTime: string log?: string | boolean }) => { const { image, port, blockTime, log: log_, } = parameters ?? { image: 'ghcr.io/tempoxyz/tempo:latest', port: 8545, blockTime: '50ms', } const log = (() => { try { return JSON.parse(log_ as string) } catch { return log_ } })() const RUST_LOG = log && typeof log !== 'boolean' ? log : '' let container: StartedTestContainer | undefined return { _internal: {}, host: 'localhost', name: 'tempo', port, async start({ port: startPort = port }, { emitter }) { let resolve: () => void let reject: (reason?: unknown) => void const promise = new Promise((res, rej) => { resolve = res reject = rej }) const c = new GenericContainer(image) .withPullPolicy(PullPolicy.defaultPolicy()) .withName(`tempo.${crypto.randomUUID()}`) .withEnvironment({ RUST_LOG }) .withCommand(buildCommand(startPort, blockTime)) .withWaitStrategy( Wait.forLogMessage( /Received (block|new payload) from consensus engine/, ), ) .withLogConsumer((stream) => { stream.on('data', (data) => { const message = data.toString() emitter.emit('message', message) emitter.emit('stdout', message) if (log) console.log(message) if (message.includes('shutting down')) reject!(new Error(`Failed to start: ${message}`)) }) stream.on('error', (error) => { // biome-ignore lint/suspicious/noConsole: test setup logging if (log) console.error(error.message) emitter.emit('message', error.message) emitter.emit('stderr', error.message) reject!(new Error(`Failed to start: ${error.message}`)) }) }) .withStartupTimeout(30_000) if (isMacOS) { c.withExposedPorts({ container: startPort, host: startPort }) } else { c.withNetworkMode('host') c.withExtraHosts([ { host: 'host.docker.internal', ipAddress: 'host-gateway' }, { host: 'localhost', ipAddress: 'host-gateway' }, ]) } c.start() .then((started) => { container = started resolve!() }) .catch(reject!) return promise }, async stop() { if (!container) return await container.stop() container = undefined }, } }, ) export default async function () { const port = 4000 const tag = import.meta.env.VITE_NODE_TAG ?? 'latest' const server = Server.create({ instance: tempoInstance({ image: `ghcr.io/tempoxyz/tempo:${tag}`, port, blockTime: '2ms', log: import.meta.env.VITE_NODE_LOG, }), port, }) await server.start() return async () => await server.stop() } ================================================ FILE: packages/test/src/tempo/setup.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { parseUnits } from 'viem' import { Actions, Addresses } from 'viem/tempo' import { beforeAll, beforeEach, vi } from 'vitest' import { accounts, config } from './config.js' // @ts-expect-error BigInt.prototype.toJSON = function () { return this.toString() } beforeAll(async () => { await connect(config, { connector: config.connectors[0]!, }) const client = config.getClient() // Mint liquidity for fee tokens. // Temporarily restore real Date.now so viem calculates a valid validBefore timestamp. if ((Date.now as any).mockRestore) (Date.now as any).mockRestore() await Promise.all( [1n, 2n, 3n].map((id) => Actions.amm.mintSync(client, { account: accounts[0], feeToken: Addresses.pathUsd, nonceKey: 'expiring', userTokenAddress: id, validatorTokenAddress: Addresses.pathUsd, validatorTokenAmount: parseUnits('1000', 6), to: accounts[0].address, }), ), ) vi.spyOn(Date, 'now').mockReturnValue( new Date(Date.UTC(2023, 1, 1)).valueOf(), ) await disconnect(config).catch(() => {}) }) beforeEach(async () => { await disconnect(config).catch(() => {}) // Make dates stable across runs (set here so it doesn't affect beforeAll setup) vi.spyOn(Date, 'now').mockReturnValue( new Date(Date.UTC(2023, 1, 1)).valueOf(), ) }) vi.mock('../src/version.ts', () => { return { version: 'x.y.z' } }) vi.mock('../../core/src/version.ts', () => { return { version: 'x.y.z' } }) ================================================ FILE: packages/test/src/utils.ts ================================================ const pool = (typeof process !== 'undefined' && Number(process.env.VITEST_POOL_ID ?? 1) + Math.floor(Math.random() * 10_000)) || 1 + Math.floor(Math.random() * 10_000) export function getRpcUrls({ port }: { port: number }) { return { port, rpcUrls: { // These rpc urls are automatically used in the transports. default: { // Note how we append the worker id to the local rpc urls. http: [`http://127.0.0.1:${port}/${pool}`], webSocket: [`ws://127.0.0.1:${port}/${pool}`], }, public: { // Note how we append the worker id to the local rpc urls. http: [`http://127.0.0.1:${port}/${pool}`], webSocket: [`ws://127.0.0.1:${port}/${pool}`], }, }, } as const } export async function wait(time: number) { return new Promise((res) => setTimeout(res, time)) } ================================================ FILE: packages/test/src/vite-env.d.ts ================================================ /// interface ImportMetaEnv { readonly VITE_MAINNET_FORK_URL?: string | undefined readonly VITE_OPTIMISM_FORK_URL?: string | undefined readonly VITE_WC_PROJECT_ID?: string | undefined readonly VITE_NODE_LOG?: string | undefined readonly VITE_NODE_TAG?: string | undefined readonly RPC_PORT?: string | undefined } interface ImportMeta { readonly env: ImportMetaEnv } ================================================ FILE: packages/test/tsconfig.build.json ================================================ { "extends": "../../tsconfig.base.json", "include": ["src/**/*.ts"], "exclude": ["src/**/*.test.ts", "src/**/*.test-d.ts"], "compilerOptions": { "sourceMap": true } } ================================================ FILE: packages/test/tsconfig.json ================================================ { "extends": "./tsconfig.build.json", "include": ["src/**/*.ts"], "exclude": [] } ================================================ FILE: packages/vue/CHANGELOG.md ================================================ # @wagmi/vue ## 0.5.0 ### Minor Changes - Added `useSignTransaction` ([#4995](https://github.com/wevm/wagmi/pull/4995)) ### Patch Changes - Updated dependencies [[`8b96e2f`](https://github.com/wevm/wagmi/commit/8b96e2f46d9b3441d3b499b03924700ac0629be6)]: - @wagmi/core@3.4.0 - @wagmi/connectors@7.2.1 ## 0.4.17 ### Patch Changes - Updated dependencies [[`c1dedd9`](https://github.com/wevm/wagmi/commit/c1dedd99c0a1878d7cd48476946868636ac81dd8), [`9dbdd82`](https://github.com/wevm/wagmi/commit/9dbdd8277808eb361fe7fe01ea34e4c6bb85c7a5)]: - @wagmi/core@3.3.4 - @wagmi/connectors@7.2.0 ## 0.4.16 ### Patch Changes - Updated dependencies [[`4b3f5a3`](https://github.com/wevm/wagmi/commit/4b3f5a3f7b3f242e8fbc1f08ae2f81ae13c5e09f)]: - @wagmi/core@3.3.3 - @wagmi/connectors@7.1.7 ## 0.4.15 ### Patch Changes - Updated dependencies [[`68e17db`](https://github.com/wevm/wagmi/commit/68e17db7ff84982db8f52f54e6f047c5efab62ab)]: - @wagmi/core@3.3.2 - @wagmi/connectors@7.1.6 ## 0.4.14 ### Patch Changes - Updated dependencies [[`7f756bd`](https://github.com/wevm/wagmi/commit/7f756bda12cd332016f0bb3a2f20307c37499309)]: - @wagmi/core@3.3.1 - @wagmi/connectors@7.1.5 ## 0.4.13 ### Patch Changes - Updated dependencies [[`dfe7904`](https://github.com/wevm/wagmi/commit/dfe790426d5ac24d55eacdf8d0193292de801911), [`d503a2c`](https://github.com/wevm/wagmi/commit/d503a2cb6ef96018669a66d03f72a2b2b06dc0fb), [`5399840`](https://github.com/wevm/wagmi/commit/53998407645edd95d85e50a931acaed87c05e256), [`5978cc5`](https://github.com/wevm/wagmi/commit/5978cc508ac837be88ed84c15ea5aa805f59005a), [`67612ed`](https://github.com/wevm/wagmi/commit/67612edfbcb971b71c86964aae72ff3ef80bbe10), [`dbe9484`](https://github.com/wevm/wagmi/commit/dbe9484c1a635c3fc9b658a7d8e34ccc0a82ed1d)]: - @wagmi/core@3.3.0 - @wagmi/connectors@7.1.4 ## 0.4.12 ### Patch Changes - Updated dependencies [[`979fe26`](https://github.com/wevm/wagmi/commit/979fe265e5273a8b49a4469ffab88b1a18b1aeaa), [`979fe26`](https://github.com/wevm/wagmi/commit/979fe265e5273a8b49a4469ffab88b1a18b1aeaa), [`e4541de`](https://github.com/wevm/wagmi/commit/e4541def76a1744dc36c188453265cc6e9d83722)]: - @wagmi/core@3.2.3 - @wagmi/connectors@7.1.3 ## 0.4.11 ### Patch Changes - Updated query internals. ([`4fefa57`](https://github.com/wevm/wagmi/commit/4fefa576014820b454344b579282ddecde5c7994)) - Updated dependencies [[`4fefa57`](https://github.com/wevm/wagmi/commit/4fefa576014820b454344b579282ddecde5c7994)]: - @wagmi/core@3.2.2 - @wagmi/connectors@7.1.2 ## 0.4.10 ### Patch Changes - Updated dependencies [[`a373b50`](https://github.com/wevm/wagmi/commit/a373b504f2ba199ca63ec0da6138ad1aa12a3a8f)]: - @wagmi/core@3.2.1 - @wagmi/connectors@7.1.1 ## 0.4.9 ### Patch Changes - Updated dependencies [[`2ee3f55`](https://github.com/wevm/wagmi/commit/2ee3f559a2637c7aab3fca6c7d196cf238ecd63d)]: - @wagmi/core@3.2.0 - @wagmi/connectors@7.1.3 ## 0.4.8 ### Patch Changes - Updated dependencies [[`14989e4`](https://github.com/wevm/wagmi/commit/14989e425a36b765a6a24e5abf1782c2a26c70db)]: - @wagmi/core@3.1.0 - @wagmi/connectors@7.1.2 ## 0.4.7 ### Patch Changes - Updated dependencies [[`a5c4381`](https://github.com/wevm/wagmi/commit/a5c4381563374018dca0074017b21181ac027e9a)]: - @wagmi/core@3.0.2 - @wagmi/connectors@7.0.6 ## 0.4.6 ### Patch Changes - Fixed published exports. ([`ed86500`](https://github.com/wevm/wagmi/commit/ed86500fbd56e5f543cb04e990b2dadc08d8b3b5)) - Updated dependencies [[`ed86500`](https://github.com/wevm/wagmi/commit/ed86500fbd56e5f543cb04e990b2dadc08d8b3b5)]: - @wagmi/connectors@7.0.5 ## 0.4.5 ### Patch Changes - Updated dependencies [[`9bbf13e`](https://github.com/wevm/wagmi/commit/9bbf13eac895669e70b233de767c8731d221f16e)]: - @wagmi/connectors@7.0.4 ## 0.4.4 ### Patch Changes - Updated dependencies [[`058c8c1`](https://github.com/wevm/wagmi/commit/058c8c18459a69a4aa2141e34640273a06a819f4)]: - @wagmi/core@3.0.1 - @wagmi/connectors@7.0.3 ## 0.4.3 ### Patch Changes - Deprecated custom mutate function names and renamed to `mutate`/`mutateAsync` to reduce destructure key renaming fatigue and align with TanStack Query terminology. ([#4878](https://github.com/wevm/wagmi/pull/4878)) **Before** Had to destructure hook result and often rename keys when using multiple of the same hook. Could decide not to destructure, but syntax becomes awkward for mutate functions (e.g. `connect.connect` or `connect.connectAsync`). ```ts const { connect, isPending: connectIsPending } = useConnect(); const { writeContract: transfer, error: transferError, isPending: transferIsPending, } = useWriteContract(); const { writeContract: approve, error: approveError } = useWriteContract(); ``` **After** Allows you to name the hook result whatever you want and not worry about also renaming properties. ```ts const connect = useConnect(); // connect.isPending const transfer = useWriteContract(); // transfer.mutate, transfer.error, transfer.isPending const approve = useWriteContract(); // approve.mutate, approve.error ``` ## 0.4.2 ### Patch Changes - Updated dependencies [[`0a46561`](https://github.com/wevm/wagmi/commit/0a4656137e1f9ed101dd1f79545d516aba32a92e)]: - @wagmi/connectors@7.0.2 ## 0.4.1 ### Patch Changes - Updated dependencies [[`856548a`](https://github.com/wevm/wagmi/commit/856548a5ae23c8771e3a51a919e1e978b83c4b00)]: - @wagmi/connectors@7.0.1 ## 0.4.0 ### Minor Changes - All connector dependencies are now optional peer dependencies. This means that if you want to use a specific connector, you need to install its required dependencies. ([#4857](https://github.com/wevm/wagmi/pull/4857)) #### baseAccount [`baseAccount`](https://wagmi.sh/vue/api/connectors/baseAccount) requires `@base-org/account` ``` pnpm add @base-org/account@~2.4.0 ``` #### coinbaseWallet [`coinbaseWallet`](https://wagmi.sh/vue/api/connectors/coinbaseWallet) requires `@coinbase/wallet-sdk` ``` pnpm add @coinbase/wallet-sdk@~4.3.6 ``` #### gemini [`gemini`](https://wagmi.sh/vue/api/connectors/gemini) requires `@gemini-wallet/core` ``` pnpm add @gemini-wallet/core@~0.3.1 ``` #### metaMask [`metaMask`](https://wagmi.sh/vue/api/connectors/metaMask) requires `@metamask/sdk` ``` pnpm add @metamask/sdk@~0.33.1 ``` #### porto [`porto`](https://wagmi.sh/vue/api/connectors/porto) requires `porto` ``` pnpm add porto@~0.2.35 ``` #### safe [`safe`](https://wagmi.sh/vue/api/connectors/safe) requires `@safe-global/safe-apps-provider` and `@safe-global/safe-apps-sdk` ``` pnpm add @safe-global/safe-apps-provider@~0.18.6 @safe-global/safe-apps-sdk@~9.1.0 ``` #### walletConnect [`walletConnect`](https://wagmi.sh/vue/api/connectors/walletConnect) requires `walletconnect/ethereum-provider` ``` pnpm add @walletconnect/ethereum-provider@~2.21.1 ``` ### Patch Changes - Updated dependencies [[`73e7326`](https://github.com/wevm/wagmi/commit/73e7326ac21303d7790765c78a7076b319b2ad26)]: - @wagmi/connectors@7.0.0 - @wagmi/core@3.0.0 ## 0.3.4 ### Patch Changes - Updated dependencies [[`5388de5`](https://github.com/wevm/wagmi/commit/5388de593847b23368c42646c27ee5438260062d)]: - @wagmi/connectors@6.2.0 ## 0.3.3 ### Patch Changes - Updated dependencies [[`2ddb506`](https://github.com/wevm/wagmi/commit/2ddb506b67fcb2abb464765d2af88df2eb58de60)]: - @wagmi/connectors@6.1.4 ## 0.3.2 ### Patch Changes - Updated dependencies [[`65cf154`](https://github.com/wevm/wagmi/commit/65cf1544d65bfb1fb830c405a371e8cd3c3fb73e)]: - @wagmi/connectors@6.1.3 ## 0.3.1 ### Patch Changes - Updated dependencies [[`faf3eed`](https://github.com/wevm/wagmi/commit/faf3eeddb97c300f971083f8ee9b02a29ad23cbb)]: - @wagmi/connectors@6.1.2 ## 0.3.0 ### Minor Changes - Exported internal types ([`3e634b7`](https://github.com/wevm/wagmi/commit/3e634b7bcf0bd0e67e59fcb74ad89dfb56e4eae9)) ### Patch Changes - Updated dependencies [[`990dd23`](https://github.com/wevm/wagmi/commit/990dd2339e96b302931056e0fb898bd2dd42a04d)]: - @wagmi/connectors@6.1.1 ## 0.2.14 ### Patch Changes - Updated dependencies [[`ae31a8d`](https://github.com/wevm/wagmi/commit/ae31a8d3d0b436841d6546ab2565dee624204aca)]: - @wagmi/connectors@6.1.0 ## 0.2.13 ### Patch Changes - Updated dependencies [[`74100b0`](https://github.com/wevm/wagmi/commit/74100b0dea2dfe7b057fdbe1660596554c70642e)]: - @wagmi/core@2.22.1 - @wagmi/connectors@6.0.1 ## 0.2.12 ### Patch Changes - Updated dependencies [[`ebb2352`](https://github.com/wevm/wagmi/commit/ebb2352375e05e52d0bcf6ae1a60ac4e798bf29f)]: - @wagmi/core@2.22.0 - @wagmi/connectors@6.0.0 ## 0.2.11 ### Patch Changes - Updated dependencies [[`2f0db95`](https://github.com/wevm/wagmi/commit/2f0db9553d30dd95b3245c44dafec4fa1a758397), [`866aeb0`](https://github.com/wevm/wagmi/commit/866aeb0e6361ef9114246e50149c1077bc05bf10)]: - @wagmi/connectors@5.11.2 - @wagmi/core@2.21.2 ## 0.2.10 ### Patch Changes - Updated dependencies [[`41eb70e`](https://github.com/wevm/wagmi/commit/41eb70e072774b282053a5e98669a7d01c0e2438), [`9a00e42`](https://github.com/wevm/wagmi/commit/9a00e423d52df9478681df743f00429717ffc584)]: - @wagmi/connectors@5.11.1 ## 0.2.9 ### Patch Changes - Updated dependencies [[`f05c075`](https://github.com/wevm/wagmi/commit/f05c075365a737d870a657f2db9220eb93ad0ac1)]: - @wagmi/connectors@5.11.0 ## 0.2.8 ### Patch Changes - Updated dependencies [[`72b703a`](https://github.com/wevm/wagmi/commit/72b703ab379c74ecf88f637cf47f31786c823a48)]: - @wagmi/core@2.21.1 - @wagmi/connectors@5.10.2 ## 0.2.7 ### Patch Changes - Updated dependencies [[`5937456`](https://github.com/wevm/wagmi/commit/59374562f2c3a41245687eb1c29ee8023737c7cc)]: - @wagmi/connectors@5.10.1 ## 0.2.6 ### Patch Changes - [#4784](https://github.com/wevm/wagmi/pull/4784) [`8736133a13eb82099e20468b735525a266fdfd6c`](https://github.com/wevm/wagmi/commit/8736133a13eb82099e20468b735525a266fdfd6c) Thanks [@tmm](https://github.com/tmm)! - Added `withCapabilities` option to `connect` for exposing response capabilities. - Updated dependencies [[`8736133a13eb82099e20468b735525a266fdfd6c`](https://github.com/wevm/wagmi/commit/8736133a13eb82099e20468b735525a266fdfd6c)]: - @wagmi/connectors@5.10.0 - @wagmi/core@2.21.0 ## 0.2.5 ### Patch Changes - Updated dependencies [[`ce06e137e7bfaf000464b1cecd6c86e19a66ebcf`](https://github.com/wevm/wagmi/commit/ce06e137e7bfaf000464b1cecd6c86e19a66ebcf)]: - @wagmi/core@2.20.3 - @wagmi/connectors@5.9.9 ## 0.2.4 ### Patch Changes - Updated dependencies [[`a03da817a388646c9b4885792101a67eef3616e7`](https://github.com/wevm/wagmi/commit/a03da817a388646c9b4885792101a67eef3616e7)]: - @wagmi/connectors@5.9.8 ## 0.2.3 ### Patch Changes - Updated dependencies [[`986b96427a4bb743d2673dfbc7e8cb5041316db3`](https://github.com/wevm/wagmi/commit/986b96427a4bb743d2673dfbc7e8cb5041316db3)]: - @wagmi/core@2.20.2 - @wagmi/connectors@5.9.7 ## 0.2.2 ### Patch Changes - Updated dependencies [[`d4c367ca46c508598c997cf229a31593a1e2b8b8`](https://github.com/wevm/wagmi/commit/d4c367ca46c508598c997cf229a31593a1e2b8b8)]: - @wagmi/core@2.20.1 - @wagmi/connectors@5.9.6 ## 0.2.1 ### Patch Changes - Updated dependencies [[`a13aa2b68890f180f6ac3f741cbb9817494cb66c`](https://github.com/wevm/wagmi/commit/a13aa2b68890f180f6ac3f741cbb9817494cb66c)]: - @wagmi/core@2.20.0 - @wagmi/connectors@5.9.5 ## 0.2.0 ### Minor Changes - [#4737](https://github.com/wevm/wagmi/pull/4737) [`23bad767c5055f54d2a5a5179830e078282fa00f`](https://github.com/wevm/wagmi/commit/23bad767c5055f54d2a5a5179830e078282fa00f) Thanks [@microHoffman](https://github.com/microHoffman)! - Added support for Nuxt 4. ## 0.1.28 ### Patch Changes - Updated dependencies [[`f4039419b83b52b2984de149db85c11f503ffe39`](https://github.com/wevm/wagmi/commit/f4039419b83b52b2984de149db85c11f503ffe39)]: - @wagmi/connectors@5.9.4 ## 0.1.27 ### Patch Changes - Updated dependencies [[`909324d28c81e15c9df312b277dcff1983fbae4d`](https://github.com/wevm/wagmi/commit/909324d28c81e15c9df312b277dcff1983fbae4d)]: - @wagmi/connectors@5.9.3 ## 0.1.26 ### Patch Changes - Updated dependencies [[`b5f017dbc707729eb0b36d617352be224d1139d4`](https://github.com/wevm/wagmi/commit/b5f017dbc707729eb0b36d617352be224d1139d4)]: - @wagmi/core@2.19.0 - @wagmi/connectors@5.9.2 ## 0.1.25 ### Patch Changes - Updated dependencies [[`6fbafd425e488dbeee8404162dbeb3c737eeb8cf`](https://github.com/wevm/wagmi/commit/6fbafd425e488dbeee8404162dbeb3c737eeb8cf), [`6514ba29a5acb918773235fed0238d7d679d06d5`](https://github.com/wevm/wagmi/commit/6514ba29a5acb918773235fed0238d7d679d06d5)]: - @wagmi/connectors@5.9.1 - @wagmi/core@2.18.1 ## 0.1.24 ### Minor Changes - [#4734](https://github.com/wevm/wagmi/pull/4734) [`eac550ae5b49f96a7e3404a6d88adc62d3889013`](https://github.com/wevm/wagmi/commit/eac550ae5b49f96a7e3404a6d88adc62d3889013) Thanks [@jxom](https://github.com/jxom)! - Added `baseAccount` connector. ### Patch Changes - Updated dependencies [[`eac550ae5b49f96a7e3404a6d88adc62d3889013`](https://github.com/wevm/wagmi/commit/eac550ae5b49f96a7e3404a6d88adc62d3889013)]: - @wagmi/connectors@6.0.0 - @wagmi/core@2.18.0 ## 0.1.23 ### Patch Changes - Updated dependencies [[`e75bd89406e9b6ff5b7d3a7148ab34140fe6352a`](https://github.com/wevm/wagmi/commit/e75bd89406e9b6ff5b7d3a7148ab34140fe6352a)]: - @wagmi/connectors@5.8.6 ## 0.1.22 ### Patch Changes - Updated dependencies [[`7ce242b549d8cc78e6c319d9ee419693da36704c`](https://github.com/wevm/wagmi/commit/7ce242b549d8cc78e6c319d9ee419693da36704c)]: - @wagmi/core@2.17.3 - @wagmi/connectors@5.8.5 ## 0.1.21 ### Patch Changes - Updated dependencies [[`3a90f358820444a85bb727742b0a16eb943fc361`](https://github.com/wevm/wagmi/commit/3a90f358820444a85bb727742b0a16eb943fc361)]: - @wagmi/connectors@5.8.4 ## 0.1.20 ### Patch Changes - Updated dependencies [[`42b1fed58e9ac09da0f8ebf3e9271f98a707aaac`](https://github.com/wevm/wagmi/commit/42b1fed58e9ac09da0f8ebf3e9271f98a707aaac)]: - @wagmi/connectors@5.8.3 ## 0.1.19 ### Patch Changes - Updated dependencies [[`29297a48af72b537173d948ccd2fe37d39914c66`](https://github.com/wevm/wagmi/commit/29297a48af72b537173d948ccd2fe37d39914c66), [`07370106d5fb6b8fe300992d93abf25b3d0eaf57`](https://github.com/wevm/wagmi/commit/07370106d5fb6b8fe300992d93abf25b3d0eaf57)]: - @wagmi/core@2.17.2 - @wagmi/connectors@5.8.2 ## 0.1.18 ### Patch Changes - Updated dependencies [[`01f64e64fa4f85cdd30023903f972f4f9023681f`](https://github.com/wevm/wagmi/commit/01f64e64fa4f85cdd30023903f972f4f9023681f)]: - @wagmi/core@2.17.1 - @wagmi/connectors@5.8.1 ## 0.1.17 ### Patch Changes - Updated dependencies [[`cc5517ff6880bb630f1b201930acc20dd1a0b451`](https://github.com/wevm/wagmi/commit/cc5517ff6880bb630f1b201930acc20dd1a0b451)]: - @wagmi/connectors@5.8.0 ## 0.1.16 ### Patch Changes - Updated dependencies [[`88427b2bcd13ec375ef519e9ad1ccffef9f02a7b`](https://github.com/wevm/wagmi/commit/88427b2bcd13ec375ef519e9ad1ccffef9f02a7b), [`799ee4d4b23c2ecd64e3f3668e67634e81939719`](https://github.com/wevm/wagmi/commit/799ee4d4b23c2ecd64e3f3668e67634e81939719), [`3f8b2edc4f237cccff1009bcef03d51ca27a7324`](https://github.com/wevm/wagmi/commit/3f8b2edc4f237cccff1009bcef03d51ca27a7324)]: - @wagmi/connectors@6.0.0 - @wagmi/core@2.17.0 ## 0.1.15 ### Patch Changes - Updated dependencies [[`b59c024b23c69f5459b17390531207cfdf126ce4`](https://github.com/wevm/wagmi/commit/b59c024b23c69f5459b17390531207cfdf126ce4)]: - @wagmi/connectors@5.7.12 ## 0.1.14 ### Patch Changes - Updated dependencies [[`a4bd0623eed28e3761a27295831a60ad835f0ee0`](https://github.com/wevm/wagmi/commit/a4bd0623eed28e3761a27295831a60ad835f0ee0)]: - @wagmi/core@2.16.7 - @wagmi/connectors@5.7.11 ## 0.1.13 ### Patch Changes - Updated dependencies [[`edf47477b2f6385a1c3ae01d36a8498c47f30a0b`](https://github.com/wevm/wagmi/commit/edf47477b2f6385a1c3ae01d36a8498c47f30a0b), [`e944812ebc234a72c1417b77cff341166f5e0fef`](https://github.com/wevm/wagmi/commit/e944812ebc234a72c1417b77cff341166f5e0fef)]: - @wagmi/core@2.16.6 - @wagmi/connectors@5.7.10 ## 0.1.12 ### Patch Changes - Updated dependencies [[`5b7101fddb61df56e34b2e02b46bc409e496eaf9`](https://github.com/wevm/wagmi/commit/5b7101fddb61df56e34b2e02b46bc409e496eaf9)]: - @wagmi/connectors@5.7.9 ## 0.1.11 ### Patch Changes - Updated dependencies [[`d0c9a86921a4e939373cc6e763284e53f2a2e93c`](https://github.com/wevm/wagmi/commit/d0c9a86921a4e939373cc6e763284e53f2a2e93c)]: - @wagmi/core@2.16.5 - @wagmi/connectors@5.7.8 ## 0.1.10 ### Patch Changes - [`507f864d91238bfd423d0e36d3619eb9f6e52eec`](https://github.com/wevm/wagmi/commit/507f864d91238bfd423d0e36d3619eb9f6e52eec) Thanks [@jxom](https://github.com/jxom)! - Updated `@coinbase/wallet-sdk`. - Updated dependencies [[`507f864d91238bfd423d0e36d3619eb9f6e52eec`](https://github.com/wevm/wagmi/commit/507f864d91238bfd423d0e36d3619eb9f6e52eec)]: - @wagmi/connectors@5.7.7 - @wagmi/core@2.16.4 ## 0.1.9 ### Patch Changes - Updated dependencies [[`639952c97f0fe3927106f42d3c9f7f366cdf7f7a`](https://github.com/wevm/wagmi/commit/639952c97f0fe3927106f42d3c9f7f366cdf7f7a), [`5aa2c095f7bfb6dfcf91c6945c3e1f9c9dd05766`](https://github.com/wevm/wagmi/commit/5aa2c095f7bfb6dfcf91c6945c3e1f9c9dd05766)]: - @wagmi/connectors@5.7.6 ## 0.1.8 ### Patch Changes - Updated dependencies [[`a257e8d4f97431a4af872cda1817b4ae17c7bbed`](https://github.com/wevm/wagmi/commit/a257e8d4f97431a4af872cda1817b4ae17c7bbed)]: - @wagmi/connectors@5.7.5 ## 0.1.7 ### Patch Changes - Updated dependencies [[`c8a257e0f6d2ece013b873895c35769a8a804fdc`](https://github.com/wevm/wagmi/commit/c8a257e0f6d2ece013b873895c35769a8a804fdc)]: - @wagmi/connectors@5.7.4 ## 0.1.6 ### Patch Changes - [#4480](https://github.com/wevm/wagmi/pull/4480) [`384a1d91597622eb59e1c05dc13ce25017c5b6d8`](https://github.com/wevm/wagmi/commit/384a1d91597622eb59e1c05dc13ce25017c5b6d8) Thanks [@RodeRickIsWatching](https://github.com/RodeRickIsWatching)! - Fixed invocation of default storage. - Updated dependencies [[`384a1d91597622eb59e1c05dc13ce25017c5b6d8`](https://github.com/wevm/wagmi/commit/384a1d91597622eb59e1c05dc13ce25017c5b6d8)]: - @wagmi/core@2.16.3 - @wagmi/connectors@5.7.3 ## 0.1.5 ### Patch Changes - [`012907032b532a438fce48f407470250cbc8f0c6`](https://github.com/wevm/wagmi/commit/012907032b532a438fce48f407470250cbc8f0c6) Thanks [@jxom](https://github.com/jxom)! - Fixed assignment in `getDefaultStorage`. - Updated dependencies [[`012907032b532a438fce48f407470250cbc8f0c6`](https://github.com/wevm/wagmi/commit/012907032b532a438fce48f407470250cbc8f0c6)]: - @wagmi/core@2.16.2 - @wagmi/connectors@5.7.2 ## 0.1.4 ### Patch Changes - Updated dependencies [[`9c8c35a3b829f2c58edcd3a29e2dcd99974d7470`](https://github.com/wevm/wagmi/commit/9c8c35a3b829f2c58edcd3a29e2dcd99974d7470), [`3892ebd21c06beef4b28ece4e70d2a38807bce6f`](https://github.com/wevm/wagmi/commit/3892ebd21c06beef4b28ece4e70d2a38807bce6f)]: - @wagmi/connectors@5.7.1 - @wagmi/core@2.16.1 ## 0.1.3 ### Patch Changes - Updated dependencies [[`e3f63a02c1f7d80481804584f262bc98dab0400d`](https://github.com/wevm/wagmi/commit/e3f63a02c1f7d80481804584f262bc98dab0400d)]: - @wagmi/connectors@5.7.0 ## 0.1.2 ### Patch Changes - Updated dependencies [[`adf2253b10c6d4fc583e4bc9f01a8ef5ca267c85`](https://github.com/wevm/wagmi/commit/adf2253b10c6d4fc583e4bc9f01a8ef5ca267c85)]: - @wagmi/connectors@5.6.2 ## 0.1.1 ### Patch Changes - Updated dependencies [[`987404f590c1d29ebb3cb68928f5e54aa032793d`](https://github.com/wevm/wagmi/commit/987404f590c1d29ebb3cb68928f5e54aa032793d)]: - @wagmi/connectors@5.6.1 ## 0.1.0 ### Minor Changes - [#4453](https://github.com/wevm/wagmi/pull/4453) [`070e48480194c8d7f45bda1d7dd1346e6f5d7227`](https://github.com/wevm/wagmi/commit/070e48480194c8d7f45bda1d7dd1346e6f5d7227) Thanks [@tmm](https://github.com/tmm)! - Added support to `useConnect` for custom `connector.connect` parameters. ### Patch Changes - Updated dependencies [[`afea6b67822a7a2b96901ec851441d27ee0f7a52`](https://github.com/wevm/wagmi/commit/afea6b67822a7a2b96901ec851441d27ee0f7a52), [`070e48480194c8d7f45bda1d7dd1346e6f5d7227`](https://github.com/wevm/wagmi/commit/070e48480194c8d7f45bda1d7dd1346e6f5d7227), [`8b0726c1106fce88b782e676498eabf0718b2619`](https://github.com/wevm/wagmi/commit/8b0726c1106fce88b782e676498eabf0718b2619)]: - @wagmi/core@2.16.0 - @wagmi/connectors@5.6.0 ## 0.0.69 ### Patch Changes - [`2f79a3da4872d6158569017b1927a07a1ff5e7ba`](https://github.com/wevm/wagmi/commit/2f79a3da4872d6158569017b1927a07a1ff5e7ba) Thanks [@tmm](https://github.com/tmm)! - Exported `injected` and `mock`. ## 0.0.68 ### Patch Changes - [#4433](https://github.com/wevm/wagmi/pull/4433) [`06e186cd679b27fe195309110e766fcf46d4efbc`](https://github.com/wevm/wagmi/commit/06e186cd679b27fe195309110e766fcf46d4efbc) Thanks [@Aerilym](https://github.com/Aerilym)! - Bumped Metamask SDK version to `0.31.1`. - Updated dependencies [[`06e186cd679b27fe195309110e766fcf46d4efbc`](https://github.com/wevm/wagmi/commit/06e186cd679b27fe195309110e766fcf46d4efbc)]: - @wagmi/connectors@5.5.3 - @wagmi/core@2.15.2 ## 0.0.67 ### Patch Changes - Updated dependencies [[`e563ef69130a511fd6f3f72ed4cd4fbe1390541f`](https://github.com/wevm/wagmi/commit/e563ef69130a511fd6f3f72ed4cd4fbe1390541f)]: - @wagmi/connectors@5.5.2 ## 0.0.66 ### Patch Changes - [`b8bbb409f4934538e3dd6cac5aaf7346292d0693`](https://github.com/wevm/wagmi/commit/b8bbb409f4934538e3dd6cac5aaf7346292d0693) Thanks [@jxom](https://github.com/jxom)! - Fixed issue where `null` gas would accidentally pass through. - Updated dependencies [[`b8bbb409f4934538e3dd6cac5aaf7346292d0693`](https://github.com/wevm/wagmi/commit/b8bbb409f4934538e3dd6cac5aaf7346292d0693)]: - @wagmi/core@2.15.1 - @wagmi/connectors@5.5.1 ## 0.0.65 ### Minor Changes - [#4417](https://github.com/wevm/wagmi/pull/4417) [`42e65ea4fea99c639817088bba915e0933d17141`](https://github.com/wevm/wagmi/commit/42e65ea4fea99c639817088bba915e0933d17141) Thanks [@jxom](https://github.com/jxom)! - Removed simulation in `writeContract` & `sendTransaction`. ### Patch Changes - Updated dependencies [[`42e65ea4fea99c639817088bba915e0933d17141`](https://github.com/wevm/wagmi/commit/42e65ea4fea99c639817088bba915e0933d17141)]: - @wagmi/connectors@6.0.0 - @wagmi/core@2.15.0 ## 0.0.64 ### Patch Changes - Updated dependencies [[`7ca62b44cd997d48f92c2b81343726a5908aa00b`](https://github.com/wevm/wagmi/commit/7ca62b44cd997d48f92c2b81343726a5908aa00b)]: - @wagmi/connectors@5.4.0 ## 0.0.63 ### Patch Changes - Updated dependencies [[`a13aa8d7c38eb3cc8171a02d6302e6d12cf6bcb3`](https://github.com/wevm/wagmi/commit/a13aa8d7c38eb3cc8171a02d6302e6d12cf6bcb3), [`a13aa8d7c38eb3cc8171a02d6302e6d12cf6bcb3`](https://github.com/wevm/wagmi/commit/a13aa8d7c38eb3cc8171a02d6302e6d12cf6bcb3)]: - @wagmi/core@2.14.6 - @wagmi/connectors@5.3.10 ## 0.0.62 ### Patch Changes - Updated dependencies [[`b12a04eeec985c48d2feac94b011d41fb29ca23e`](https://github.com/wevm/wagmi/commit/b12a04eeec985c48d2feac94b011d41fb29ca23e)]: - @wagmi/connectors@5.3.9 ## 0.0.61 ### Patch Changes - Updated dependencies [[`6b9bbacdc7bffd44fc2165362a5e65fd434e7646`](https://github.com/wevm/wagmi/commit/6b9bbacdc7bffd44fc2165362a5e65fd434e7646), [`dac62dc99a0679fa632a0fae49873d6053d06b35`](https://github.com/wevm/wagmi/commit/dac62dc99a0679fa632a0fae49873d6053d06b35)]: - @wagmi/core@2.14.5 - @wagmi/connectors@5.3.8 ## 0.0.60 ### Patch Changes - Updated dependencies [[`e08681c81fbdf475213e2d0f4c5517d0abf4e743`](https://github.com/wevm/wagmi/commit/e08681c81fbdf475213e2d0f4c5517d0abf4e743)]: - @wagmi/core@2.14.4 - @wagmi/connectors@5.3.7 ## 0.0.59 ### Patch Changes - Updated dependencies [[`7558ff3133c11bc4c49473d08ee9a47eaa12df5b`](https://github.com/wevm/wagmi/commit/7558ff3133c11bc4c49473d08ee9a47eaa12df5b)]: - @wagmi/connectors@5.3.6 ## 0.0.58 ### Patch Changes - Updated dependencies [[`cb7dd2ebb871d0be8f1a11a8cd8ce592cd74b7c7`](https://github.com/wevm/wagmi/commit/cb7dd2ebb871d0be8f1a11a8cd8ce592cd74b7c7), [`7fe78f2d09778fc01fd0cffe85ba198e64999275`](https://github.com/wevm/wagmi/commit/7fe78f2d09778fc01fd0cffe85ba198e64999275)]: - @wagmi/core@2.14.3 - @wagmi/connectors@5.3.5 ## 0.0.57 ### Patch Changes - Updated dependencies [[`b6861a4c378dab78d8751ae0ac2aa425f3c24b8f`](https://github.com/wevm/wagmi/commit/b6861a4c378dab78d8751ae0ac2aa425f3c24b8f), [`d0d0963bb5904a15cf0355862d62dd141ce0c31c`](https://github.com/wevm/wagmi/commit/d0d0963bb5904a15cf0355862d62dd141ce0c31c), [`ecac0ba36243d94c9199d0bd21937104c835d9a0`](https://github.com/wevm/wagmi/commit/ecac0ba36243d94c9199d0bd21937104c835d9a0)]: - @wagmi/connectors@5.3.4 - @wagmi/core@2.14.2 ## 0.0.56 ### Patch Changes - Updated dependencies [[`83c6d16b7d6dddfa6bda036e04f00ec313c6248c`](https://github.com/wevm/wagmi/commit/83c6d16b7d6dddfa6bda036e04f00ec313c6248c)]: - @wagmi/connectors@5.3.3 ## 0.0.55 ### Patch Changes - Updated dependencies [[`8970cc51398e1ac713435533096215c6d31ffdf9`](https://github.com/wevm/wagmi/commit/8970cc51398e1ac713435533096215c6d31ffdf9)]: - @wagmi/connectors@5.3.2 ## 0.0.54 ### Patch Changes - Updated dependencies [[`052e72e1f8c1c14fcbdce04a9f8fa7ec28d83702`](https://github.com/wevm/wagmi/commit/052e72e1f8c1c14fcbdce04a9f8fa7ec28d83702), [`b250fc21ee577b2a75c5a34ff684f62fb4ad771a`](https://github.com/wevm/wagmi/commit/b250fc21ee577b2a75c5a34ff684f62fb4ad771a)]: - @wagmi/core@2.14.1 - @wagmi/connectors@5.3.1 ## 0.0.53 ### Patch Changes - Updated dependencies [[`f43e074f473820b208a6295d7c97f847332f1a1d`](https://github.com/wevm/wagmi/commit/f43e074f473820b208a6295d7c97f847332f1a1d)]: - @wagmi/connectors@6.0.0 - @wagmi/core@2.14.0 ## 0.0.52 ### Patch Changes - Updated dependencies [[`c05caabc20c3ced9682cfc7ba1f3f7dcfece0703`](https://github.com/wevm/wagmi/commit/c05caabc20c3ced9682cfc7ba1f3f7dcfece0703), [`5ae49af590ff168426c9c283d54c34ae5148fcd9`](https://github.com/wevm/wagmi/commit/5ae49af590ff168426c9c283d54c34ae5148fcd9), [`f3182b22e6e454d9bd74f1b940ef34431fd9555d`](https://github.com/wevm/wagmi/commit/f3182b22e6e454d9bd74f1b940ef34431fd9555d)]: - @wagmi/core@2.13.9 - @wagmi/connectors@5.2.2 ## 0.0.51 ### Patch Changes - Updated dependencies [[`91a40f2db08e3a91db421b8732a5511a1e6c88fd`](https://github.com/wevm/wagmi/commit/91a40f2db08e3a91db421b8732a5511a1e6c88fd)]: - @wagmi/connectors@5.2.1 ## 0.0.50 ### Patch Changes - Updated dependencies [[`34a0c3b7eea778aee7c27f7ace5e4b2be4e8a0a4`](https://github.com/wevm/wagmi/commit/34a0c3b7eea778aee7c27f7ace5e4b2be4e8a0a4)]: - @wagmi/connectors@5.2.0 ## 0.0.49 ### Patch Changes - Updated dependencies [[`3b2123664b7ac66848390739e855c3b9702ab60c`](https://github.com/wevm/wagmi/commit/3b2123664b7ac66848390739e855c3b9702ab60c)]: - @wagmi/connectors@5.1.15 ## 0.0.48 ### Patch Changes - Updated dependencies [[`56f2482508f2ba71bd6b0295c70c6abca7101e57`](https://github.com/wevm/wagmi/commit/56f2482508f2ba71bd6b0295c70c6abca7101e57)]: - @wagmi/connectors@5.1.14 - @wagmi/core@2.13.8 ## 0.0.47 ### Patch Changes - Updated dependencies [[`be75c2d4ef636d7362420ab0a106bfdf63f5d1e6`](https://github.com/wevm/wagmi/commit/be75c2d4ef636d7362420ab0a106bfdf63f5d1e6)]: - @wagmi/core@2.13.7 - @wagmi/connectors@5.1.13 ## 0.0.46 ### Patch Changes - Updated dependencies [[`edcbf5d6fbe92f639bead800502edda9e0aa39f1`](https://github.com/wevm/wagmi/commit/edcbf5d6fbe92f639bead800502edda9e0aa39f1)]: - @wagmi/core@2.13.6 - @wagmi/connectors@5.1.12 ## 0.0.45 ### Patch Changes - Updated dependencies [[`82404c960e04c83e0bae6e1e12459ef9debf9554`](https://github.com/wevm/wagmi/commit/82404c960e04c83e0bae6e1e12459ef9debf9554), [`d07ad7f63a018256908a673d078aaf79e47ac703`](https://github.com/wevm/wagmi/commit/d07ad7f63a018256908a673d078aaf79e47ac703)]: - @wagmi/connectors@5.1.11 ## 0.0.44 ### Patch Changes - [#4262](https://github.com/wevm/wagmi/pull/4262) [`8531f83db3a1fbb8202c3e426b7f85679f587a52`](https://github.com/wevm/wagmi/commit/8531f83db3a1fbb8202c3e426b7f85679f587a52) Thanks [@nezouse](https://github.com/nezouse)! - Added experimental actions entrypoint. ## 0.0.43 ### Patch Changes - [#4260](https://github.com/wevm/wagmi/pull/4260) [`969a208a110b760a13fd7263360320f52440a9b6`](https://github.com/wevm/wagmi/commit/969a208a110b760a13fd7263360320f52440a9b6) Thanks [@tmm](https://github.com/tmm)! - Fixed `useReadContract` deployless reads support. - [#4259](https://github.com/wevm/wagmi/pull/4259) [`f47ce8f6d263e49fdff90b8edb3190142d2657bb`](https://github.com/wevm/wagmi/commit/f47ce8f6d263e49fdff90b8edb3190142d2657bb) Thanks [@tmm](https://github.com/tmm)! - Disabled `useConnectorClient` during reconnection if connector is not fully restored. - Updated dependencies [[`81de006e66121a18c61945c1f9b8426c83a5713c`](https://github.com/wevm/wagmi/commit/81de006e66121a18c61945c1f9b8426c83a5713c), [`f47ce8f6d263e49fdff90b8edb3190142d2657bb`](https://github.com/wevm/wagmi/commit/f47ce8f6d263e49fdff90b8edb3190142d2657bb)]: - @wagmi/connectors@5.1.10 - @wagmi/core@2.13.5 ## 0.0.42 ### Patch Changes - [#4252](https://github.com/wevm/wagmi/pull/4252) [`67defb516bbd9b2c7b03e376ecd3aca8a001d065`](https://github.com/wevm/wagmi/commit/67defb516bbd9b2c7b03e376ecd3aca8a001d065) Thanks [@tmm](https://github.com/tmm)! - Added `useWatchContractEvent`. ## 0.0.41 ### Patch Changes - Updated dependencies [[`21bd0e473d374cbbd7a01bececa6022d529026ba`](https://github.com/wevm/wagmi/commit/21bd0e473d374cbbd7a01bececa6022d529026ba), [`5c89c6853e616437a3be2b019db895451fecfb3c`](https://github.com/wevm/wagmi/commit/5c89c6853e616437a3be2b019db895451fecfb3c)]: - @wagmi/connectors@5.1.9 ## 0.0.40 ### Patch Changes - Updated dependencies [[`b580ad4edff1721e0b9d138cf5ae2ec74d2374c7`](https://github.com/wevm/wagmi/commit/b580ad4edff1721e0b9d138cf5ae2ec74d2374c7)]: - @wagmi/connectors@5.1.8 ## 0.0.39 ### Patch Changes - Updated dependencies [[`91fd81a068789c5020e891f539bcad8f54a7a52f`](https://github.com/wevm/wagmi/commit/91fd81a068789c5020e891f539bcad8f54a7a52f)]: - @wagmi/connectors@5.1.7 ## 0.0.38 ### Patch Changes - Updated dependencies [[`3168616298cbb6135d0ffda771cba4126e83eba8`](https://github.com/wevm/wagmi/commit/3168616298cbb6135d0ffda771cba4126e83eba8), [`d7608ef9a79459465dc8c06a2ab740465c881907`](https://github.com/wevm/wagmi/commit/d7608ef9a79459465dc8c06a2ab740465c881907)]: - @wagmi/connectors@5.1.6 ## 0.0.37 ### Patch Changes - Updated dependencies [[`b4c8971788c70b09479946ecfa998cff2f1b3953`](https://github.com/wevm/wagmi/commit/b4c8971788c70b09479946ecfa998cff2f1b3953)]: - @wagmi/core@2.13.4 - @wagmi/connectors@5.1.5 ## 0.0.36 ### Patch Changes - Updated dependencies [[`871dbdbfe59ac8ad01d1ec6150ea7b091b7b7de4`](https://github.com/wevm/wagmi/commit/871dbdbfe59ac8ad01d1ec6150ea7b091b7b7de4)]: - @wagmi/core@2.13.3 - @wagmi/connectors@5.1.4 ## 0.0.35 ### Patch Changes - Updated dependencies [[`1b9b523fa9b9dfe839aecdf4b40caa9547d7e594`](https://github.com/wevm/wagmi/commit/1b9b523fa9b9dfe839aecdf4b40caa9547d7e594)]: - @wagmi/core@2.13.2 - @wagmi/connectors@5.1.3 ## 0.0.34 ### Patch Changes - Updated dependencies [[`abb490dac4f0f02f46cb0878e7ca9a0db6aada56`](https://github.com/wevm/wagmi/commit/abb490dac4f0f02f46cb0878e7ca9a0db6aada56), [`28e0e5c9a4f856583f9d36a807502bd51a0c6ec2`](https://github.com/wevm/wagmi/commit/28e0e5c9a4f856583f9d36a807502bd51a0c6ec2)]: - @wagmi/connectors@5.1.2 ## 0.0.33 ### Patch Changes - Updated dependencies [[`07c1227f306d0efb9421d4bb77a774f92f5fcf45`](https://github.com/wevm/wagmi/commit/07c1227f306d0efb9421d4bb77a774f92f5fcf45)]: - @wagmi/core@2.13.1 - @wagmi/connectors@5.1.1 ## 0.0.32 ### Patch Changes - [#4162](https://github.com/wevm/wagmi/pull/4162) [`a73a7737b756886b388f120ae423e72cca53e8a0`](https://github.com/wevm/wagmi/commit/a73a7737b756886b388f120ae423e72cca53e8a0) Thanks [@jxom](https://github.com/jxom)! - Added functionality for consumer-defined RPC URLs (`config.transports`) to be propagated to the WalletConnect & MetaMask Connectors. - Updated dependencies [[`a73a7737b756886b388f120ae423e72cca53e8a0`](https://github.com/wevm/wagmi/commit/a73a7737b756886b388f120ae423e72cca53e8a0)]: - @wagmi/connectors@6.0.0 - @wagmi/core@2.13.0 ## 0.0.31 ### Patch Changes - [#4124](https://github.com/wevm/wagmi/pull/4124) [`26616462db2e0140025f22c505c4541cfecb9308`](https://github.com/wevm/wagmi/commit/26616462db2e0140025f22c505c4541cfecb9308) Thanks [@t0rbik](https://github.com/t0rbik)! - Updated `useConnectorClient` to be enabled when status is `'reconnecting'` or `'connected'` (previously was also enabled when status was `'connecting'`). ## 0.0.30 ### Patch Changes - Updated dependencies [[`5bc8c8877810b2eec24a829df87dce40a51e6f20`](https://github.com/wevm/wagmi/commit/5bc8c8877810b2eec24a829df87dce40a51e6f20), [`8d81df5cc884d0a210dedd3c1ea0e2e9e52b83c5`](https://github.com/wevm/wagmi/commit/8d81df5cc884d0a210dedd3c1ea0e2e9e52b83c5)]: - @wagmi/core@2.12.2 - @wagmi/connectors@5.0.26 ## 0.0.29 ### Patch Changes - [#4146](https://github.com/wevm/wagmi/pull/4146) [`cc996e08e930c9e88cf753a1e874652059e81a3b`](https://github.com/wevm/wagmi/commit/cc996e08e930c9e88cf753a1e874652059e81a3b) Thanks [@jxom](https://github.com/jxom)! - Updated `@safe-global/safe-apps-sdk` + `@safe-global/safe-apps-provider` dependencies. - Updated dependencies [[`cc996e08e930c9e88cf753a1e874652059e81a3b`](https://github.com/wevm/wagmi/commit/cc996e08e930c9e88cf753a1e874652059e81a3b)]: - @wagmi/connectors@5.0.25 - @wagmi/core@2.12.1 ## 0.0.28 ### Patch Changes - [`b6cb1477e3e87984917b172a909f1968e0d77dc9`](https://github.com/wevm/wagmi/commit/b6cb1477e3e87984917b172a909f1968e0d77dc9) Thanks [@tmm](https://github.com/tmm)! - Added `useBytecode` composable. - Updated dependencies [[`5581a810ef70308e99c6f8b630cd4bca59f64afc`](https://github.com/wevm/wagmi/commit/5581a810ef70308e99c6f8b630cd4bca59f64afc)]: - @wagmi/core@2.12.0 - @wagmi/connectors@6.0.0 ## 0.0.27 ### Patch Changes - [`d3814ab4b88f9f0e052b53bc3d458df87b43f01d`](https://github.com/wevm/wagmi/commit/d3814ab4b88f9f0e052b53bc3d458df87b43f01d) Thanks [@jxom](https://github.com/jxom)! - Updated `mipd` dependency. - Updated dependencies [[`b08013eaa9ce97c02f8a7128ea400e3da7ef74bb`](https://github.com/wevm/wagmi/commit/b08013eaa9ce97c02f8a7128ea400e3da7ef74bb), [`d3814ab4b88f9f0e052b53bc3d458df87b43f01d`](https://github.com/wevm/wagmi/commit/d3814ab4b88f9f0e052b53bc3d458df87b43f01d)]: - @wagmi/core@2.11.8 - @wagmi/connectors@5.0.23 ## 0.0.26 ### Patch Changes - Updated dependencies [[`0bb8b562ae04ecfeb2d6b2f1b980ebae31dc127e`](https://github.com/wevm/wagmi/commit/0bb8b562ae04ecfeb2d6b2f1b980ebae31dc127e)]: - @wagmi/connectors@5.0.22 - @wagmi/core@2.11.7 ## 0.0.25 ### Patch Changes - [#4060](https://github.com/wevm/wagmi/pull/4060) [`95965c1f19d480b97f2b297a077a9e607dee32ad`](https://github.com/wevm/wagmi/commit/95965c1f19d480b97f2b297a077a9e607dee32ad) Thanks [@dalechyn](https://github.com/dalechyn)! - Bumped Tanstack Query dependencies to fix typing issues between exported Wagmi query options and TanStack Query suspense query methods (due to [`direction` property in `QueryFunctionContext` being deprecated](https://github.com/TanStack/query/pull/7410)). - Updated dependencies [[`ff0760b5900114bcfdf420a9fba3cc278ac95afe`](https://github.com/wevm/wagmi/commit/ff0760b5900114bcfdf420a9fba3cc278ac95afe), [`95965c1f19d480b97f2b297a077a9e607dee32ad`](https://github.com/wevm/wagmi/commit/95965c1f19d480b97f2b297a077a9e607dee32ad)]: - @wagmi/connectors@5.0.21 - @wagmi/core@2.11.6 ## 0.0.24 ### Patch Changes - Updated dependencies [[`43fa971d34cac57fa5a2898ad4d839b95d7af37c`](https://github.com/wevm/wagmi/commit/43fa971d34cac57fa5a2898ad4d839b95d7af37c)]: - @wagmi/connectors@5.0.20 ## 0.0.23 ### Patch Changes - Updated dependencies [[`b7ad208030d9f2e3f89912ff76b16cdbd848feda`](https://github.com/wevm/wagmi/commit/b7ad208030d9f2e3f89912ff76b16cdbd848feda)]: - @wagmi/connectors@5.0.19 ## 0.0.22 ### Patch Changes - Updated dependencies [[`44d24620c9e3957f3245d14d6a042736371df70b`](https://github.com/wevm/wagmi/commit/44d24620c9e3957f3245d14d6a042736371df70b)]: - @wagmi/connectors@5.0.18 ## 0.0.21 ### Patch Changes - Updated dependencies [[`04f2b846b113f3d300d82c9fa75212f1805817c5`](https://github.com/wevm/wagmi/commit/04f2b846b113f3d300d82c9fa75212f1805817c5)]: - @wagmi/core@2.11.5 - @wagmi/connectors@5.0.17 ## 0.0.20 ### Patch Changes - Updated dependencies [[`9e8345cd56186b997b5e56deaa2cfc69b30d15f6`](https://github.com/wevm/wagmi/commit/9e8345cd56186b997b5e56deaa2cfc69b30d15f6), [`02c38c28d1aa0ad7a61c33775de603ed974c5c1b`](https://github.com/wevm/wagmi/commit/02c38c28d1aa0ad7a61c33775de603ed974c5c1b)]: - @wagmi/core@2.11.4 - @wagmi/connectors@5.0.16 ## 0.0.19 ### Patch Changes - Updated dependencies [[`8974e6269bb5d7bfaa90db0246bc7d13e8bff798`](https://github.com/wevm/wagmi/commit/8974e6269bb5d7bfaa90db0246bc7d13e8bff798)]: - @wagmi/core@2.11.3 - @wagmi/connectors@5.0.15 ## 0.0.18 ### Patch Changes - Updated dependencies [[`b4d9ef79deb554ee20fed6666a474be5e7cdd522`](https://github.com/wevm/wagmi/commit/b4d9ef79deb554ee20fed6666a474be5e7cdd522)]: - @wagmi/core@2.11.2 - @wagmi/connectors@5.0.14 ## 0.0.17 ### Patch Changes - Updated dependencies [[`9c862d8d63e3d692a22cef2a90782b74a9103f17`](https://github.com/wevm/wagmi/commit/9c862d8d63e3d692a22cef2a90782b74a9103f17)]: - @wagmi/connectors@5.0.13 - @wagmi/core@2.11.1 ## 0.0.16 ### Patch Changes - Updated dependencies [[`06bb598a7f04c7b167f5b7ff6d46bd15886a6a14`](https://github.com/wevm/wagmi/commit/06bb598a7f04c7b167f5b7ff6d46bd15886a6a14), [`24a45b269bd0214a29d6f82a84ac66ef8c3f3822`](https://github.com/wevm/wagmi/commit/24a45b269bd0214a29d6f82a84ac66ef8c3f3822)]: - @wagmi/core@2.11.0 - @wagmi/connectors@6.0.0 ## 0.0.15 ### Patch Changes - Updated dependencies [[`f2a7cefab96691ebed8b8e45ffde071c47b58dbe`](https://github.com/wevm/wagmi/commit/f2a7cefab96691ebed8b8e45ffde071c47b58dbe), [`f0ea0b2a7fe193dadfeb49a4c8031ee451c638b5`](https://github.com/wevm/wagmi/commit/f0ea0b2a7fe193dadfeb49a4c8031ee451c638b5), [`e3b124ce414b8fd1b2214e2c5a28dc72158a13d1`](https://github.com/wevm/wagmi/commit/e3b124ce414b8fd1b2214e2c5a28dc72158a13d1)]: - @wagmi/core@2.10.6 - @wagmi/connectors@5.0.11 ## 0.0.14 ### Patch Changes - Updated dependencies [[`560952acd4bfe33db6c7c07b35c613cef278677c`](https://github.com/wevm/wagmi/commit/560952acd4bfe33db6c7c07b35c613cef278677c)]: - @wagmi/connectors@5.0.10 ## 0.0.13 ### Patch Changes - Updated dependencies [[`32cdd7b7dc5aff916c040628519562c3a99d418d`](https://github.com/wevm/wagmi/commit/32cdd7b7dc5aff916c040628519562c3a99d418d)]: - @wagmi/connectors@5.0.9 ## 0.0.12 ### Patch Changes - Updated dependencies [[`c1952d1ff7f0a491dc88595a49159451b07b5621`](https://github.com/wevm/wagmi/commit/c1952d1ff7f0a491dc88595a49159451b07b5621)]: - @wagmi/connectors@5.0.8 ## 0.0.11 ### Patch Changes - Updated dependencies [[`030c7c2cb380dfd67a2182f62e2aa7a6e1601898`](https://github.com/wevm/wagmi/commit/030c7c2cb380dfd67a2182f62e2aa7a6e1601898)]: - @wagmi/core@2.10.5 - @wagmi/connectors@5.0.7 ## 0.0.10 ### Patch Changes - Updated dependencies [[`51fde8a0433b4fff357c1a8d7e08b41b4c86c968`](https://github.com/wevm/wagmi/commit/51fde8a0433b4fff357c1a8d7e08b41b4c86c968)]: - @wagmi/core@2.10.4 - @wagmi/connectors@5.0.6 ## 0.0.9 ### Patch Changes - Updated dependencies [[`70dd28669dd8d2ce08217cd02e29a8fbba7a08d4`](https://github.com/wevm/wagmi/commit/70dd28669dd8d2ce08217cd02e29a8fbba7a08d4)]: - @wagmi/connectors@5.0.5 ## 0.0.8 ### Patch Changes - Updated dependencies [[`be9e1b8a9818b92eb0654a20d9471e9e39329e7e`](https://github.com/wevm/wagmi/commit/be9e1b8a9818b92eb0654a20d9471e9e39329e7e)]: - @wagmi/connectors@5.0.4 ## 0.0.7 ### Patch Changes - Updated dependencies [[`2804a8a583b1874271154898b4bae38756ef581c`](https://github.com/wevm/wagmi/commit/2804a8a583b1874271154898b4bae38756ef581c), [`2804a8a583b1874271154898b4bae38756ef581c`](https://github.com/wevm/wagmi/commit/2804a8a583b1874271154898b4bae38756ef581c)]: - @wagmi/connectors@5.0.3 - @wagmi/core@2.10.3 ## 0.0.6 ### Patch Changes - [`ec2f63f106fd468f28b43d3b88ab3e89aaf5e81a`](https://github.com/wevm/wagmi/commit/ec2f63f106fd468f28b43d3b88ab3e89aaf5e81a) Thanks [@tmm](https://github.com/tmm)! - Fixed `useSwitchChain` `chains` typing. ## 0.0.5 ### Patch Changes - [#3940](https://github.com/wevm/wagmi/pull/3940) [`a5071f581dfdfb961718873643a2fc629101c72a`](https://github.com/wevm/wagmi/commit/a5071f581dfdfb961718873643a2fc629101c72a) Thanks [@jxom](https://github.com/jxom)! - Fixed usage of `metaMask` connector in Vite environments. - Updated dependencies [[`a5071f581dfdfb961718873643a2fc629101c72a`](https://github.com/wevm/wagmi/commit/a5071f581dfdfb961718873643a2fc629101c72a)]: - @wagmi/connectors@5.0.2 - @wagmi/core@2.10.2 ## 0.0.4 ### Patch Changes - Updated dependencies []: - @wagmi/connectors@5.0.1 - @wagmi/core@2.10.1 ## 0.0.3 ### Patch Changes - Updated dependencies [[`3117e71825f9c58a0d718f3d1686f1a191fa9cb1`](https://github.com/wevm/wagmi/commit/3117e71825f9c58a0d718f3d1686f1a191fa9cb1), [`3117e71825f9c58a0d718f3d1686f1a191fa9cb1`](https://github.com/wevm/wagmi/commit/3117e71825f9c58a0d718f3d1686f1a191fa9cb1)]: - @wagmi/connectors@5.0.0 - @wagmi/core@2.10.0 ## 0.0.2 ### Patch Changes - [#3906](https://github.com/wevm/wagmi/pull/3906) [`32fcb4a31dde6b0206961d8ffe9c651f8a459c67`](https://github.com/wevm/wagmi/commit/32fcb4a31dde6b0206961d8ffe9c651f8a459c67) Thanks [@tmm](https://github.com/tmm)! - Added support for Vue. - Updated dependencies [[`32fcb4a31dde6b0206961d8ffe9c651f8a459c67`](https://github.com/wevm/wagmi/commit/32fcb4a31dde6b0206961d8ffe9c651f8a459c67)]: - @wagmi/connectors@4.3.10 - @wagmi/core@2.9.8 ================================================ FILE: packages/vue/README.md ================================================ # @wagmi/vue Vue Composables for Ethereum ## Installation ```bash pnpm add @wagmi/vue viem @tanstack/vue-query ``` ## Documentation For documentation and guides, visit [wagmi.sh](https://wagmi.sh). ================================================ FILE: packages/vue/package.json ================================================ { "name": "@wagmi/vue", "description": "Vue Composables for Ethereum", "version": "0.5.0", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/wevm/wagmi.git", "directory": "packages/vue" }, "scripts": { "build": "pnpm run build:esm+types", "build:esm+types": "tsc --project tsconfig.build.json --outDir ./dist/esm --declaration --declarationMap --declarationDir ./dist/types", "check:types": "tsc --noEmit", "clean": "rm -rf dist tsconfig.tsbuildinfo actions chains connectors nuxt query", "test:build": "publint --strict && attw --pack --ignore-rules cjs-resolves-to-esm" }, "files": [ "dist/**", "!dist/**/*.tsbuildinfo", "src/**/*.ts", "!src/**/*.test.ts", "!src/**/*.test-d.ts", "/actions", "/chains", "/connectors", "/nuxt", "/query" ], "sideEffects": false, "type": "module", "main": "./dist/esm/exports/index.js", "types": "./dist/types/exports/index.d.ts", "typings": "./dist/types/exports/index.d.ts", "exports": { ".": { "types": "./dist/types/exports/index.d.ts", "default": "./dist/esm/exports/index.js" }, "./actions": { "types": "./dist/types/exports/actions.d.ts", "default": "./dist/esm/exports/actions.js" }, "./chains": { "types": "./dist/types/exports/chains.d.ts", "default": "./dist/esm/exports/chains.js" }, "./connectors": { "types": "./dist/types/exports/connectors.d.ts", "default": "./dist/esm/exports/connectors.js" }, "./nuxt": { "types": "./dist/types/exports/nuxt.d.ts", "default": "./dist/esm/exports/nuxt.js" }, "./query": { "types": "./dist/types/exports/query.d.ts", "default": "./dist/esm/exports/query.js" }, "./package.json": "./package.json" }, "typesVersions": { "*": { "actions": [ "./dist/types/exports/actions.d.ts" ], "chains": [ "./dist/types/exports/chains.d.ts" ], "connectors": [ "./dist/types/exports/connectors.d.ts" ], "nuxt": [ "./dist/types/exports/nuxt.d.ts" ], "query": [ "./dist/types/exports/query.d.ts" ] } }, "peerDependencies": { "@tanstack/vue-query": ">=5.0.0", "nuxt": ">=3.0.0 || >=4.0.0", "typescript": ">=5.7.3", "viem": "2.x", "vue": ">=3" }, "peerDependenciesMeta": { "nuxt": { "optional": true }, "typescript": { "optional": true } }, "dependencies": { "@wagmi/connectors": "workspace:*", "@wagmi/core": "workspace:*" }, "devDependencies": { "@nuxt/schema": "catalog:", "@tanstack/vue-query": "catalog:", "@vue/test-utils": "^2.4.6", "nuxt": "catalog:", "vue": "catalog:" }, "contributors": [ "awkweb.eth ", "jxom.eth " ], "funding": "https://github.com/sponsors/wevm", "keywords": [ "wagmi", "vue", "composables", "eth", "ethereum", "dapps", "wallet", "web3" ] } ================================================ FILE: packages/vue/src/composables/useBalance.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import type { Ref } from 'vue' import { useBalance } from './useBalance.js' test('select data', () => { const result = useBalance({ query: { select(data) { return data?.value }, }, }) expectTypeOf(result.data).toEqualTypeOf | Ref>() }) ================================================ FILE: packages/vue/src/composables/useBalance.test.ts ================================================ import { accounts, chain, testClient, wait } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { parseEther } from 'viem' import { beforeEach, expect, test } from 'vitest' import { ref } from 'vue' import { useBalance } from './useBalance.js' const address = accounts[0] beforeEach(async () => { await testClient.mainnet.setBalance({ address, value: parseEther('10000') }) await testClient.mainnet.mine({ blocks: 1 }) await testClient.mainnet2.setBalance({ address, value: parseEther('69') }) await testClient.mainnet2.mine({ blocks: 1 }) }) test('default', async () => { const [query] = renderComposable(() => useBalance({ address })) await waitFor(query.isSuccess) expect(query.data.value).toMatchObject( expect.objectContaining({ decimals: expect.any(Number), symbol: expect.any(String), value: expect.any(BigInt), }), ) }) test('parameters: chainId', async () => { const [query] = renderComposable(() => useBalance({ address, chainId: chain.mainnet2.id }), ) await waitFor(query.isSuccess) expect(query.data.value).toMatchInlineSnapshot(` { "decimals": 18, "symbol": "WAG", "value": 69000000000000000000n, } `) }) test('behavior: address: undefined -> defined', async () => { const address = ref() const [query] = renderComposable(() => useBalance({ address })) await wait(100) expect(query.fetchStatus.value).toMatchInlineSnapshot(`"idle"`) address.value = accounts[0] await waitFor(query.isSuccess) expect(query.data.value).toMatchInlineSnapshot(` { "decimals": 18, "symbol": "ETH", "value": 10000000000000000000000n, } `) }) test('behavior: disabled when properties missing', async () => { const [query] = renderComposable(() => useBalance({ address })) await wait(100) expect(query.fetchStatus.value).toMatchInlineSnapshot(`"idle"`) }) ================================================ FILE: packages/vue/src/composables/useBalance.ts ================================================ import type { Config, GetBalanceErrorType, ResolvedRegister } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetBalanceData, type GetBalanceOptions, getBalanceQueryOptions, } from '@wagmi/core/query' import { computed } from 'vue' import type { DeepMaybeRef } from '../types/ref.js' import { deepUnref } from '../utils/cloneDeep.js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseBalanceParameters< config extends Config = Config, selectData = GetBalanceData, > = Compute< DeepMaybeRef & ConfigParameter> > export type UseBalanceReturnType = UseQueryReturnType /** https://wagmi.sh/vue/api/composables/useBalance */ export function useBalance< config extends Config = ResolvedRegister['config'], selectData = GetBalanceData, >( parameters: UseBalanceParameters = {}, ): UseBalanceReturnType { const params = computed(() => deepUnref(parameters)) const config = useConfig(params) const chainId = useChainId({ config }) const options = computed(() => getBalanceQueryOptions(config as any, { ...params.value, chainId: params.value.chainId ?? chainId.value, }), ) return useQuery(options as any) as any } ================================================ FILE: packages/vue/src/composables/useBlockNumber.test-d.ts ================================================ import { createConfig, http, webSocket } from '@wagmi/core' import { mainnet, optimism } from '@wagmi/core/chains' import { expectTypeOf, test } from 'vitest' import { useBlockNumber } from './useBlockNumber.js' test('select data', () => { const result = useBlockNumber({ query: { select(data) { expectTypeOf(data).toEqualTypeOf() return data?.toString() }, }, }) expectTypeOf(result.data.value).toEqualTypeOf() }) test('differing transports', () => { const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: webSocket(), }, }) useBlockNumber({ config, watch: { poll: false, }, }) useBlockNumber({ config, chainId: mainnet.id, watch: { poll: true, }, }) useBlockNumber({ config, chainId: mainnet.id, watch: { // @ts-expect-error poll: false, }, }) useBlockNumber({ config, chainId: optimism.id, watch: { poll: true, }, }) useBlockNumber({ config, chainId: optimism.id, watch: { poll: false, }, }) }) ================================================ FILE: packages/vue/src/composables/useBlockNumber.test.ts ================================================ import { config, testClient } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { ref } from 'vue' import { useBlockNumber } from './useBlockNumber.js' test('default', async () => { await testClient.mainnet.resetFork() const [blockNumberQuery] = renderComposable(() => useBlockNumber()) await waitFor(blockNumberQuery.status, (status) => status === 'success') expect(blockNumberQuery.data.value).toMatchInlineSnapshot('23535880n') }) test('parameters: chainId', async () => { config.setState((state) => ({ ...state, chainId: config.chains[0].id })) const [blockNumberQuery] = renderComposable(() => useBlockNumber()) await waitFor(blockNumberQuery.status, (status) => status === 'success') expect(blockNumberQuery.data.value).toBeTypeOf('bigint') config.setState((state) => ({ ...state, chainId: config.chains[2].id })) await waitFor(blockNumberQuery.status, (status) => status === 'success') expect(blockNumberQuery.data.value).toBeTypeOf('bigint') }) test('parameters: watch', async () => { const [blockNumberQuery] = renderComposable(() => useBlockNumber({ watch: true }), ) await waitFor(blockNumberQuery.status, (status) => status === 'success') const blockNumber = blockNumberQuery.data.value! await testClient.optimism.mine({ blocks: 1 }) await waitFor(blockNumberQuery.data, (data) => data === blockNumber + 1n) }) test('parameters: watch (reactive)', async () => { const watch = ref(true) const [blockNumberQuery] = renderComposable(() => useBlockNumber({ watch })) await waitFor(blockNumberQuery.status, (status) => status === 'success') const blockNumber = blockNumberQuery.data.value! await testClient.optimism.mine({ blocks: 1 }) await waitFor(blockNumberQuery.data, (data) => data === blockNumber + 1n) await testClient.optimism.mine({ blocks: 1 }) await waitFor(blockNumberQuery.data, (data) => data === blockNumber + 2n) watch.value = false await testClient.optimism.mine({ blocks: 1 }) await waitFor(blockNumberQuery.data, (data) => data === blockNumber + 2n, { timeout: 1_000, }) }) ================================================ FILE: packages/vue/src/composables/useBlockNumber.ts ================================================ import { useQueryClient } from '@tanstack/vue-query' import type { Config, GetBlockNumberErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter, UnionCompute, UnionStrictOmit, } from '@wagmi/core/internal' import { type GetBlockNumberData, type GetBlockNumberOptions, getBlockNumberQueryOptions, } from '@wagmi/core/query' import { computed } from 'vue' import type { DeepMaybeRef, DeepUnwrapRef } from '../types/ref.js' import { deepUnref } from '../utils/cloneDeep.js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' import { type UseWatchBlockNumberParameters, useWatchBlockNumber, } from './useWatchBlockNumber.js' export type UseBlockNumberParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetBlockNumberData, > = Compute< DeepMaybeRef< GetBlockNumberOptions & ConfigParameter & { watch?: | boolean | UnionCompute< UnionStrictOmit< DeepUnwrapRef>, 'chainId' | 'config' | 'onBlockNumber' | 'onError' > > | undefined } > > export type UseBlockNumberReturnType = UseQueryReturnType /** https://wagmi.sh/vue/api/composables/useBlockNumber */ export function useBlockNumber< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetBlockNumberData, >( parameters: UseBlockNumberParameters = {}, ): UseBlockNumberReturnType { const params = computed(() => deepUnref(parameters)) const config = useConfig(params) const chainId = useChainId({ config }) const options = computed(() => getBlockNumberQueryOptions(config as any, { ...params.value, chainId: params.value.chainId ?? chainId.value, }), ) const queryClient = useQueryClient() const watchBlockNumberArgs = computed(() => { return { ...({ config, chainId: params.value.chainId ?? chainId.value, ...(typeof params.value.watch === 'object' ? params.value.watch : {}), } as UseWatchBlockNumberParameters), enabled: (params.value.query?.enabled ?? true) && (typeof params.value.watch === 'object' ? params.value.watch.enabled : params.value.watch), onBlockNumber(blockNumber) { queryClient.setQueryData(options.value.queryKey, blockNumber) }, } satisfies UseWatchBlockNumberParameters }) useWatchBlockNumber(watchBlockNumberArgs) return useQuery(options as any) as any } ================================================ FILE: packages/vue/src/composables/useBytecode.test-d.ts ================================================ import type { Hex } from 'viem' import { expectTypeOf, test } from 'vitest' import { useBytecode } from './useBytecode.js' test('select data', () => { const result = useBytecode({ query: { select(data) { expectTypeOf(data).toEqualTypeOf() return data }, }, }) expectTypeOf(result.data.value).toEqualTypeOf() }) ================================================ FILE: packages/vue/src/composables/useBytecode.test.ts ================================================ import { address, chain, wait } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { ref } from 'vue' import { deepUnref } from '../utils/cloneDeep.js' import { useBytecode } from './useBytecode.js' test('default', async () => { const [result] = renderComposable(() => useBytecode({ address: address.wagmiMintExample, }), ) await waitFor(result.isSuccess) expect(deepUnref(result)).toMatchInlineSnapshot(` { "data": "0x608060405234801561001057600080fd5b50600436106101005760003560e01c80636352211e11610097578063a22cb46511610066578063a22cb46514610215578063b88d4fde14610228578063c87b56dd1461023b578063e985e9c51461024e57600080fd5b80636352211e146101d457806370a08231146101e757806395d89b41146101fa578063a0712d681461020257600080fd5b80631249c58b116100d35780631249c58b1461018f57806318160ddd1461019757806323b872dd146101ae57806342842e0e146101c157600080fd5b806301ffc9a71461010557806306fdde031461012d578063081812fc14610142578063095ea7b31461017a575b600080fd5b61011861011336600461178f565b610297565b60405190151581526020015b60405180910390f35b61013561037c565b6040516101249190611829565b61015561015036600461183c565b61040e565b60405173ffffffffffffffffffffffffffffffffffffffff9091168152602001610124565b61018d61018836600461187e565b6104d3565b005b61018d61062b565b6101a060065481565b604051908152602001610124565b61018d6101bc3660046118a8565b61067d565b61018d6101cf3660046118a8565b610704565b6101556101e236600461183c565b61071f565b6101a06101f53660046118e4565b6107b7565b61013561086b565b61018d61021036600461183c565b61087a565b61018d6102233660046118ff565b610902565b61018d61023636600461196a565b610911565b61013561024936600461183c565b61099f565b61011861025c366004611a64565b73ffffffffffffffffffffffffffffffffffffffff918216600090815260056020908152604080832093909416825291909152205460ff1690565b60007fffffffff0000000000000000000000000000000000000000000000000000000082167f80ac58cd00000000000000000000000000000000000000000000000000000000148061032a57507fffffffff0000000000000000000000000000000000000000000000000000000082167f5b5e139f00000000000000000000000000000000000000000000000000000000145b8061037657507f01ffc9a7000000000000000000000000000000000000000000000000000000007fffffffff000000000000000000000000000000000000000000000000000000008316145b92915050565b60606000805461038b90611a97565b80601f01602080910402602001604051908101604052809291908181526020018280546103b790611a97565b80156104045780601f106103d957610100808354040283529160200191610404565b820191906000526020600020905b8154815290600101906020018083116103e757829003601f168201915b5050505050905090565b60008181526002602052604081205473ffffffffffffffffffffffffffffffffffffffff166104aa5760405162461bcd60e51b815260206004820152602c60248201527f4552433732313a20617070726f76656420717565727920666f72206e6f6e657860448201527f697374656e7420746f6b656e000000000000000000000000000000000000000060648201526084015b60405180910390fd5b5060009081526004602052604090205473ffffffffffffffffffffffffffffffffffffffff1690565b60006104de8261071f565b90508073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16036105815760405162461bcd60e51b815260206004820152602160248201527f4552433732313a20617070726f76616c20746f2063757272656e74206f776e6560448201527f720000000000000000000000000000000000000000000000000000000000000060648201526084016104a1565b3373ffffffffffffffffffffffffffffffffffffffff821614806105aa57506105aa813361025c565b61061c5760405162461bcd60e51b815260206004820152603860248201527f4552433732313a20617070726f76652063616c6c6572206973206e6f74206f7760448201527f6e6572206e6f7220617070726f76656420666f7220616c6c000000000000000060648201526084016104a1565b6106268383610b07565b505050565b6007545b60008181526002602052604090205473ffffffffffffffffffffffffffffffffffffffff16156106615760010161062f565b61066b3382610ba7565b60068054600190810190915501600755565b6106873382610bc1565b6106f95760405162461bcd60e51b815260206004820152603160248201527f4552433732313a207472616e736665722063616c6c6572206973206e6f74206f60448201527f776e6572206e6f7220617070726f76656400000000000000000000000000000060648201526084016104a1565b610626838383610d17565b61062683838360405180602001604052806000815250610911565b60008181526002602052604081205473ffffffffffffffffffffffffffffffffffffffff16806103765760405162461bcd60e51b815260206004820152602960248201527f4552433732313a206f776e657220717565727920666f72206e6f6e657869737460448201527f656e7420746f6b656e000000000000000000000000000000000000000000000060648201526084016104a1565b600073ffffffffffffffffffffffffffffffffffffffff82166108425760405162461bcd60e51b815260206004820152602a60248201527f4552433732313a2062616c616e636520717565727920666f7220746865207a6560448201527f726f20616464726573730000000000000000000000000000000000000000000060648201526084016104a1565b5073ffffffffffffffffffffffffffffffffffffffff1660009081526003602052604090205490565b60606001805461038b90611a97565b60008181526002602052604090205473ffffffffffffffffffffffffffffffffffffffff16156108ec5760405162461bcd60e51b815260206004820152601160248201527f546f6b656e2049442069732074616b656e00000000000000000000000000000060448201526064016104a1565b6108f63382610ba7565b50600680546001019055565b61090d338383610f4a565b5050565b61091b3383610bc1565b61098d5760405162461bcd60e51b815260206004820152603160248201527f4552433732313a207472616e736665722063616c6c6572206973206e6f74206f60448201527f776e6572206e6f7220617070726f76656400000000000000000000000000000060648201526084016104a1565b6109998484848461105d565b50505050565b6040517f666f726567726f756e64000000000000000000000000000000000000000000006020820152602a810182905260609060009061016890604a016040516020818303038152906040528051906020012060001c6109ff9190611b19565b6040517f6261636b67726f756e64000000000000000000000000000000000000000000006020820152602a810185905290915060009061016890604a016040516020818303038152906040528051906020012060001c610a5f9190611b19565b90506000610aba610a6f866110e6565b610aa9610a7b866110e6565b610a84866110e6565b604051602001610a95929190611b2d565b60405160208183030381529060405261121b565b604051602001610a959291906125ba565b9050600081604051602001610acf919061268b565b604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08184030181529190529695505050505050565b600081815260046020526040902080547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff84169081179091558190610b618261071f565b73ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560405160405180910390a45050565b61090d82826040518060200160405280600081525061136e565b60008181526002602052604081205473ffffffffffffffffffffffffffffffffffffffff16610c585760405162461bcd60e51b815260206004820152602c60248201527f4552433732313a206f70657261746f7220717565727920666f72206e6f6e657860448201527f697374656e7420746f6b656e000000000000000000000000000000000000000060648201526084016104a1565b6000610c638361071f565b90508073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff161480610cd1575073ffffffffffffffffffffffffffffffffffffffff80821660009081526005602090815260408083209388168352929052205460ff165b80610d0f57508373ffffffffffffffffffffffffffffffffffffffff16610cf78461040e565b73ffffffffffffffffffffffffffffffffffffffff16145b949350505050565b8273ffffffffffffffffffffffffffffffffffffffff16610d378261071f565b73ffffffffffffffffffffffffffffffffffffffff1614610dc05760405162461bcd60e51b815260206004820152602560248201527f4552433732313a207472616e736665722066726f6d20696e636f72726563742060448201527f6f776e657200000000000000000000000000000000000000000000000000000060648201526084016104a1565b73ffffffffffffffffffffffffffffffffffffffff8216610e485760405162461bcd60e51b8152602060048201526024808201527f4552433732313a207472616e7366657220746f20746865207a65726f2061646460448201527f726573730000000000000000000000000000000000000000000000000000000060648201526084016104a1565b610e53600082610b07565b73ffffffffffffffffffffffffffffffffffffffff83166000908152600360205260408120805460019290610e899084906126ff565b909155505073ffffffffffffffffffffffffffffffffffffffff82166000908152600360205260408120805460019290610ec4908490612716565b909155505060008181526002602052604080822080547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff86811691821790925591518493918716917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a4505050565b8173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1603610fc55760405162461bcd60e51b815260206004820152601960248201527f4552433732313a20617070726f766520746f2063616c6c65720000000000000060448201526064016104a1565b73ffffffffffffffffffffffffffffffffffffffff83811660008181526005602090815260408083209487168084529482529182902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001686151590811790915591519182527f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31910160405180910390a3505050565b611068848484610d17565b611074848484846113f7565b6109995760405162461bcd60e51b815260206004820152603260248201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560448201527f63656976657220696d706c656d656e746572000000000000000000000000000060648201526084016104a1565b60608160000361112957505060408051808201909152600181527f3000000000000000000000000000000000000000000000000000000000000000602082015290565b8160005b8115611153578061113d8161272e565b915061114c9050600a83612766565b915061112d565b60008167ffffffffffffffff81111561116e5761116e61193b565b6040519080825280601f01601f191660200182016040528015611198576020820181803683370190505b5090505b8415610d0f576111ad6001836126ff565b91506111ba600a86611b19565b6111c5906030612716565b60f81b8183815181106111da576111da61277a565b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350611214600a86612766565b945061119c565b6060815160000361123a57505060408051602081019091526000815290565b600060405180606001604052806040815260200161284d60409139905060006003845160026112699190612716565b6112739190612766565b61127e9060046127a9565b67ffffffffffffffff8111156112965761129661193b565b6040519080825280601f01601f1916602001820160405280156112c0576020820181803683370190505b509050600182016020820185865187015b8082101561132c576003820191508151603f8160121c168501518453600184019350603f81600c1c168501518453600184019350603f8160061c168501518453600184019350603f81168501518453506001830192506112d1565b5050600386510660018114611348576002811461135b57611363565b603d6001830353603d6002830353611363565b603d60018303535b509195945050505050565b61137883836115d0565b61138560008484846113f7565b6106265760405162461bcd60e51b815260206004820152603260248201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560448201527f63656976657220696d706c656d656e746572000000000000000000000000000060648201526084016104a1565b600073ffffffffffffffffffffffffffffffffffffffff84163b156115c5576040517f150b7a0200000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff85169063150b7a029061146e9033908990889088906004016127e6565b6020604051808303816000875af19250505080156114c7575060408051601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01682019092526114c49181019061282f565b60015b61157a573d8080156114f5576040519150601f19603f3d011682016040523d82523d6000602084013e6114fa565b606091505b5080516000036115725760405162461bcd60e51b815260206004820152603260248201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560448201527f63656976657220696d706c656d656e746572000000000000000000000000000060648201526084016104a1565b805181602001fd5b7fffffffff00000000000000000000000000000000000000000000000000000000167f150b7a0200000000000000000000000000000000000000000000000000000000149050610d0f565b506001949350505050565b73ffffffffffffffffffffffffffffffffffffffff82166116335760405162461bcd60e51b815260206004820181905260248201527f4552433732313a206d696e7420746f20746865207a65726f206164647265737360448201526064016104a1565b60008181526002602052604090205473ffffffffffffffffffffffffffffffffffffffff16156116a55760405162461bcd60e51b815260206004820152601c60248201527f4552433732313a20746f6b656e20616c7265616479206d696e7465640000000060448201526064016104a1565b73ffffffffffffffffffffffffffffffffffffffff821660009081526003602052604081208054600192906116db908490612716565b909155505060008181526002602052604080822080547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff861690811790915590518392907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef908290a45050565b7fffffffff000000000000000000000000000000000000000000000000000000008116811461178c57600080fd5b50565b6000602082840312156117a157600080fd5b81356117ac8161175e565b9392505050565b60005b838110156117ce5781810151838201526020016117b6565b838111156109995750506000910152565b600081518084526117f78160208601602086016117b3565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b6020815260006117ac60208301846117df565b60006020828403121561184e57600080fd5b5035919050565b803573ffffffffffffffffffffffffffffffffffffffff8116811461187957600080fd5b919050565b6000806040838503121561189157600080fd5b61189a83611855565b946020939093013593505050565b6000806000606084860312156118bd57600080fd5b6118c684611855565b92506118d460208501611855565b9150604084013590509250925092565b6000602082840312156118f657600080fd5b6117ac82611855565b6000806040838503121561191257600080fd5b61191b83611855565b91506020830135801515811461193057600080fd5b809150509250929050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b6000806000806080858703121561198057600080fd5b61198985611855565b935061199760208601611855565b925060408501359150606085013567ffffffffffffffff808211156119bb57600080fd5b818701915087601f8301126119cf57600080fd5b8135818111156119e1576119e161193b565b604051601f82017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0908116603f01168101908382118183101715611a2757611a2761193b565b816040528281528a6020848701011115611a4057600080fd5b82602086016020830137600060208483010152809550505050505092959194509250565b60008060408385031215611a7757600080fd5b611a8083611855565b9150611a8e60208401611855565b90509250929050565b600181811c90821680611aab57607f821691505b602082108103611ae4577f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b50919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b600082611b2857611b28611aea565b500690565b7f3c73766720786d6c6e733d22687474703a2f2f7777772e77332e6f72672f323081527f30302f737667222077696474683d223130323422206865696768743d2231303260208201527f34222066696c6c3d226e6f6e65223e3c706174682066696c6c3d2268736c2800604082015260008351611bb181605f8501602088016117b3565b7f2c20313030252c20313025292220643d224d3020306831303234763130323448605f918401918201527f307a22202f3e3c672066696c6c3d2268736c2800000000000000000000000000607f8201528351611c148160928401602088016117b3565b7f2c20313030252c2039302529223e3c7061746820643d224d393033203433372e609292909101918201527f35633020392e3131332d372e3338382031362e352d31362e352031362e35732d60b28201527f31362e352d372e3338372d31362e352d31362e3520372e3338382d31362e352060d28201527f31362e352d31362e352031362e3520372e3338372031362e352031362e357a4d60f28201527f3639382e3532392035363663362e39323120302031322e35332d352e353936206101128201527f31322e35332d31322e35762d353063302d362e39303420352e3630392d31322e6101328201527f352031322e3532392d31322e356832352e30353963362e393220302031322e356101528201527f323920352e3539362031322e3532392031322e35763530633020362e393034206101728201527f352e3630392031322e352031322e35332031322e357331322e3532392d352e356101928201527f39362031322e3532392d31322e35762d353063302d362e39303420352e3630396101b28201527f2d31322e352031322e35332d31322e356832352e30353963362e3932203020316101d28201527f322e35323920352e3539362031322e3532392031322e35763530633020362e396101f28201527f303420352e3630392031322e352031322e3532392031322e356833372e3538396102128201527f63362e393220302031322e3532392d352e3539362031322e3532392d31322e356102328201527f762d373563302d362e3930342d352e3630392d31322e352d31322e3532392d316102528201527f322e35732d31322e353320352e3539362d31322e35332031322e357635362e326102728201527f3561362e32363420362e3236342030203120312d31322e3532392030563437386102928201527f2e3563302d362e3930342d352e3630392d31322e352d31322e35332d31322e356102b28201527f483639382e353239632d362e393220302d31322e35323920352e3539362d31326102d28201527f2e3532392031322e35763735633020362e39303420352e3630392031322e35206102f28201527f31322e3532392031322e357a22202f3e3c7061746820643d224d3135372e36356103128201527f3520353431632d362e39333220302d31322e3535322d352e3539362d31322e356103328201527f35322d31322e35762d353063302d362e3930342d352e3631392d31322e352d316103528201527f322e3535312d31322e3553313230203437312e35393620313230203437382e356103728201527f763735633020362e39303420352e36322031322e352031322e3535322031322e6103928201527f35683135302e363263362e39333320302031322e3535322d352e3539362031326103b28201527f2e3535322d31322e35762d353063302d362e39303420352e3631392d31322e356103d28201527f2031322e3535322d31322e35683134342e33343563332e343635203020362e326103f28201527f373620322e37393820362e32373620362e3235732d322e38313120362e32352d6104128201527f362e32373620362e3235483332302e383238632d362e39333320302d31322e356104328201527f353220352e3539362d31322e3535322031322e357633372e35633020362e39306104528201527f3420352e3631392031322e352031322e3535322031322e35683135302e3632636104728201527f362e39333320302031322e3535322d352e3539362031322e3535322d31322e356104928201527f762d373563302d362e3930342d352e3631392d31322e352d31322e3535322d316104b28201527f322e35483238332e313732632d362e39333220302d31322e35353120352e35396104d28201527f362d31322e3535312031322e35763530633020362e3930342d352e36313920316104f28201527f322e352d31322e3535322031322e35682d32352e313033632d362e39333320306105128201527f2d31322e3535322d352e3539362d31322e3535322d31322e35762d353063302d6105328201527f362e3930342d352e36322d31322e352d31322e3535322d31322e35732d31322e6105528201527f35353220352e3539362d31322e3535322031322e35763530633020362e3930346105728201527f2d352e3631392031322e352d31322e3535312031322e35682d32352e3130347a6105928201527f6d3330312e3234322d362e3235633020332e3435322d322e38313120362e32356105b28201527f2d362e32373620362e3235483333392e363535632d332e34363520302d362e326105d28201527f37362d322e3739382d362e3237362d362e323573322e3831312d362e323520366105f28201527f2e3237362d362e3235683131322e39363663332e343635203020362e323736206106128201527f322e37393820362e32373620362e32357a4d343937203535332e3831386330206106328201527f362e39323920352e3632382031322e3534362031322e3537312031322e3534366106528201527f6831333261362e323820362e323820302030203120362e32383620362e3237326106728201527f20362e323820362e32382030203020312d362e32383620362e323733682d31336106928201527f32632d362e39343320302d31322e35373120352e3631362d31322e35373120316106b28201527f322e3534364131322e35362031322e3536203020302030203530392e353731206106d28201527f363034683135302e38353863362e39343320302031322e3537312d352e3631366106f28201527f2031322e3537312d31322e353435762d3131322e393163302d362e3932382d356107128201527f2e3632382d31322e3534352d31322e3537312d31322e353435483530392e35376107328201527f31632d362e39343320302d31322e35373120352e3631372d31322e35373120316107528201527f322e3534357637352e3237337a6d33372e3731342d36322e373237632d362e396107728201527f343320302d31322e35373120352e3631372d31322e3537312031322e353435766107928201527f32352e303931633020362e39323920352e3632382031322e3534362031322e356107b28201527f37312031322e353436683130302e35373263362e39343320302031322e3537316107d28201527f2d352e3631372031322e3537312d31322e353436762d32352e30393163302d366107f28201527f2e3932382d352e3632382d31322e3534352d31322e3537312d31322e353435486108128201527f3533342e3731347a222066696c6c2d72756c653d226576656e6f646422202f3e6108328201527f3c2f673e3c2f7376673e0000000000000000000000000000000000000000000061085282015261085c01949350505050565b7f7b226e616d65223a20227761676d6920230000000000000000000000000000008152600083516125f28160118501602088016117b3565b7f222c2022696d616765223a2022646174613a696d6167652f7376672b786d6c3b6011918401918201527f6261736536342c00000000000000000000000000000000000000000000000000603182015283516126558160388401602088016117b3565b7f227d00000000000000000000000000000000000000000000000000000000000060389290910191820152603a01949350505050565b7f646174613a6170706c69636174696f6e2f6a736f6e3b6261736536342c0000008152600082516126c381601d8501602087016117b3565b91909101601d0192915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b600082821015612711576127116126d0565b500390565b60008219821115612729576127296126d0565b500190565b60007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff820361275f5761275f6126d0565b5060010190565b60008261277557612775611aea565b500490565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b6000817fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff04831182151516156127e1576127e16126d0565b500290565b600073ffffffffffffffffffffffffffffffffffffffff80871683528086166020840152508360408301526080606083015261282560808301846117df565b9695505050505050565b60006020828403121561284157600080fd5b81516117ac8161175e56fe4142434445464748494a4b4c4d4e4f505152535455565758595a6162636465666768696a6b6c6d6e6f707172737475767778797a303132333435363738392b2fa26469706673582212201665a4f9111990d7529375848d3fd02c0121091a940da59e763eba826e7b077064736f6c634300080d0033", "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getBytecode", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "chainId": 1, }, ], "refetch": [Function], "status": "success", "suspense": [Function], } `) }) test('parameters: blockNumber', async () => { const [result] = renderComposable(() => useBytecode({ address: address.wagmiMintExample, blockNumber: 15564163n, }), ) await waitFor(result.isSuccess) expect(deepUnref(result)).toMatchInlineSnapshot(` { "data": null, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getBytecode", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "blockNumber": 15564163n, "chainId": 1, }, ], "refetch": [Function], "status": "success", "suspense": [Function], } `) }) test('parameters: blockTag', async () => { const [result] = renderComposable(() => useBytecode({ address: address.wagmiMintExample, blockTag: 'earliest', }), ) await waitFor(result.isSuccess) expect(deepUnref(result)).toMatchInlineSnapshot(` { "data": null, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getBytecode", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "blockTag": "earliest", "chainId": 1, }, ], "refetch": [Function], "status": "success", "suspense": [Function], } `) }) test('parameters: chainId', async () => { const [result] = renderComposable(() => useBytecode({ address: address.wagmiMintExample, chainId: chain.optimism.id, }), ) await waitFor(result.isSuccess) expect(deepUnref(result)).toMatchInlineSnapshot(` { "data": null, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getBytecode", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "chainId": 10, }, ], "refetch": [Function], "status": "success", "suspense": [Function], } `) }) test('behavior: address: undefined -> defined', async () => { const contractAddress = ref() const [result] = renderComposable(() => useBytecode({ address: contractAddress }), ) await wait(100) expect(result.fetchStatus.value).toBe('idle') expect(deepUnref(result)).toMatchInlineSnapshot(` { "data": undefined, "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "getBytecode", { "address": undefined, "chainId": 1, }, ], "refetch": [Function], "status": "pending", "suspense": [Function], } `) contractAddress.value = address.wagmiMintExample await waitFor(result.isSuccess) expect(deepUnref(result)).toMatchInlineSnapshot(` { "data": "0x608060405234801561001057600080fd5b50600436106101005760003560e01c80636352211e11610097578063a22cb46511610066578063a22cb46514610215578063b88d4fde14610228578063c87b56dd1461023b578063e985e9c51461024e57600080fd5b80636352211e146101d457806370a08231146101e757806395d89b41146101fa578063a0712d681461020257600080fd5b80631249c58b116100d35780631249c58b1461018f57806318160ddd1461019757806323b872dd146101ae57806342842e0e146101c157600080fd5b806301ffc9a71461010557806306fdde031461012d578063081812fc14610142578063095ea7b31461017a575b600080fd5b61011861011336600461178f565b610297565b60405190151581526020015b60405180910390f35b61013561037c565b6040516101249190611829565b61015561015036600461183c565b61040e565b60405173ffffffffffffffffffffffffffffffffffffffff9091168152602001610124565b61018d61018836600461187e565b6104d3565b005b61018d61062b565b6101a060065481565b604051908152602001610124565b61018d6101bc3660046118a8565b61067d565b61018d6101cf3660046118a8565b610704565b6101556101e236600461183c565b61071f565b6101a06101f53660046118e4565b6107b7565b61013561086b565b61018d61021036600461183c565b61087a565b61018d6102233660046118ff565b610902565b61018d61023636600461196a565b610911565b61013561024936600461183c565b61099f565b61011861025c366004611a64565b73ffffffffffffffffffffffffffffffffffffffff918216600090815260056020908152604080832093909416825291909152205460ff1690565b60007fffffffff0000000000000000000000000000000000000000000000000000000082167f80ac58cd00000000000000000000000000000000000000000000000000000000148061032a57507fffffffff0000000000000000000000000000000000000000000000000000000082167f5b5e139f00000000000000000000000000000000000000000000000000000000145b8061037657507f01ffc9a7000000000000000000000000000000000000000000000000000000007fffffffff000000000000000000000000000000000000000000000000000000008316145b92915050565b60606000805461038b90611a97565b80601f01602080910402602001604051908101604052809291908181526020018280546103b790611a97565b80156104045780601f106103d957610100808354040283529160200191610404565b820191906000526020600020905b8154815290600101906020018083116103e757829003601f168201915b5050505050905090565b60008181526002602052604081205473ffffffffffffffffffffffffffffffffffffffff166104aa5760405162461bcd60e51b815260206004820152602c60248201527f4552433732313a20617070726f76656420717565727920666f72206e6f6e657860448201527f697374656e7420746f6b656e000000000000000000000000000000000000000060648201526084015b60405180910390fd5b5060009081526004602052604090205473ffffffffffffffffffffffffffffffffffffffff1690565b60006104de8261071f565b90508073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16036105815760405162461bcd60e51b815260206004820152602160248201527f4552433732313a20617070726f76616c20746f2063757272656e74206f776e6560448201527f720000000000000000000000000000000000000000000000000000000000000060648201526084016104a1565b3373ffffffffffffffffffffffffffffffffffffffff821614806105aa57506105aa813361025c565b61061c5760405162461bcd60e51b815260206004820152603860248201527f4552433732313a20617070726f76652063616c6c6572206973206e6f74206f7760448201527f6e6572206e6f7220617070726f76656420666f7220616c6c000000000000000060648201526084016104a1565b6106268383610b07565b505050565b6007545b60008181526002602052604090205473ffffffffffffffffffffffffffffffffffffffff16156106615760010161062f565b61066b3382610ba7565b60068054600190810190915501600755565b6106873382610bc1565b6106f95760405162461bcd60e51b815260206004820152603160248201527f4552433732313a207472616e736665722063616c6c6572206973206e6f74206f60448201527f776e6572206e6f7220617070726f76656400000000000000000000000000000060648201526084016104a1565b610626838383610d17565b61062683838360405180602001604052806000815250610911565b60008181526002602052604081205473ffffffffffffffffffffffffffffffffffffffff16806103765760405162461bcd60e51b815260206004820152602960248201527f4552433732313a206f776e657220717565727920666f72206e6f6e657869737460448201527f656e7420746f6b656e000000000000000000000000000000000000000000000060648201526084016104a1565b600073ffffffffffffffffffffffffffffffffffffffff82166108425760405162461bcd60e51b815260206004820152602a60248201527f4552433732313a2062616c616e636520717565727920666f7220746865207a6560448201527f726f20616464726573730000000000000000000000000000000000000000000060648201526084016104a1565b5073ffffffffffffffffffffffffffffffffffffffff1660009081526003602052604090205490565b60606001805461038b90611a97565b60008181526002602052604090205473ffffffffffffffffffffffffffffffffffffffff16156108ec5760405162461bcd60e51b815260206004820152601160248201527f546f6b656e2049442069732074616b656e00000000000000000000000000000060448201526064016104a1565b6108f63382610ba7565b50600680546001019055565b61090d338383610f4a565b5050565b61091b3383610bc1565b61098d5760405162461bcd60e51b815260206004820152603160248201527f4552433732313a207472616e736665722063616c6c6572206973206e6f74206f60448201527f776e6572206e6f7220617070726f76656400000000000000000000000000000060648201526084016104a1565b6109998484848461105d565b50505050565b6040517f666f726567726f756e64000000000000000000000000000000000000000000006020820152602a810182905260609060009061016890604a016040516020818303038152906040528051906020012060001c6109ff9190611b19565b6040517f6261636b67726f756e64000000000000000000000000000000000000000000006020820152602a810185905290915060009061016890604a016040516020818303038152906040528051906020012060001c610a5f9190611b19565b90506000610aba610a6f866110e6565b610aa9610a7b866110e6565b610a84866110e6565b604051602001610a95929190611b2d565b60405160208183030381529060405261121b565b604051602001610a959291906125ba565b9050600081604051602001610acf919061268b565b604080517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08184030181529190529695505050505050565b600081815260046020526040902080547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff84169081179091558190610b618261071f565b73ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560405160405180910390a45050565b61090d82826040518060200160405280600081525061136e565b60008181526002602052604081205473ffffffffffffffffffffffffffffffffffffffff16610c585760405162461bcd60e51b815260206004820152602c60248201527f4552433732313a206f70657261746f7220717565727920666f72206e6f6e657860448201527f697374656e7420746f6b656e000000000000000000000000000000000000000060648201526084016104a1565b6000610c638361071f565b90508073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff161480610cd1575073ffffffffffffffffffffffffffffffffffffffff80821660009081526005602090815260408083209388168352929052205460ff165b80610d0f57508373ffffffffffffffffffffffffffffffffffffffff16610cf78461040e565b73ffffffffffffffffffffffffffffffffffffffff16145b949350505050565b8273ffffffffffffffffffffffffffffffffffffffff16610d378261071f565b73ffffffffffffffffffffffffffffffffffffffff1614610dc05760405162461bcd60e51b815260206004820152602560248201527f4552433732313a207472616e736665722066726f6d20696e636f72726563742060448201527f6f776e657200000000000000000000000000000000000000000000000000000060648201526084016104a1565b73ffffffffffffffffffffffffffffffffffffffff8216610e485760405162461bcd60e51b8152602060048201526024808201527f4552433732313a207472616e7366657220746f20746865207a65726f2061646460448201527f726573730000000000000000000000000000000000000000000000000000000060648201526084016104a1565b610e53600082610b07565b73ffffffffffffffffffffffffffffffffffffffff83166000908152600360205260408120805460019290610e899084906126ff565b909155505073ffffffffffffffffffffffffffffffffffffffff82166000908152600360205260408120805460019290610ec4908490612716565b909155505060008181526002602052604080822080547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff86811691821790925591518493918716917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a4505050565b8173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1603610fc55760405162461bcd60e51b815260206004820152601960248201527f4552433732313a20617070726f766520746f2063616c6c65720000000000000060448201526064016104a1565b73ffffffffffffffffffffffffffffffffffffffff83811660008181526005602090815260408083209487168084529482529182902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001686151590811790915591519182527f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31910160405180910390a3505050565b611068848484610d17565b611074848484846113f7565b6109995760405162461bcd60e51b815260206004820152603260248201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560448201527f63656976657220696d706c656d656e746572000000000000000000000000000060648201526084016104a1565b60608160000361112957505060408051808201909152600181527f3000000000000000000000000000000000000000000000000000000000000000602082015290565b8160005b8115611153578061113d8161272e565b915061114c9050600a83612766565b915061112d565b60008167ffffffffffffffff81111561116e5761116e61193b565b6040519080825280601f01601f191660200182016040528015611198576020820181803683370190505b5090505b8415610d0f576111ad6001836126ff565b91506111ba600a86611b19565b6111c5906030612716565b60f81b8183815181106111da576111da61277a565b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350611214600a86612766565b945061119c565b6060815160000361123a57505060408051602081019091526000815290565b600060405180606001604052806040815260200161284d60409139905060006003845160026112699190612716565b6112739190612766565b61127e9060046127a9565b67ffffffffffffffff8111156112965761129661193b565b6040519080825280601f01601f1916602001820160405280156112c0576020820181803683370190505b509050600182016020820185865187015b8082101561132c576003820191508151603f8160121c168501518453600184019350603f81600c1c168501518453600184019350603f8160061c168501518453600184019350603f81168501518453506001830192506112d1565b5050600386510660018114611348576002811461135b57611363565b603d6001830353603d6002830353611363565b603d60018303535b509195945050505050565b61137883836115d0565b61138560008484846113f7565b6106265760405162461bcd60e51b815260206004820152603260248201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560448201527f63656976657220696d706c656d656e746572000000000000000000000000000060648201526084016104a1565b600073ffffffffffffffffffffffffffffffffffffffff84163b156115c5576040517f150b7a0200000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff85169063150b7a029061146e9033908990889088906004016127e6565b6020604051808303816000875af19250505080156114c7575060408051601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01682019092526114c49181019061282f565b60015b61157a573d8080156114f5576040519150601f19603f3d011682016040523d82523d6000602084013e6114fa565b606091505b5080516000036115725760405162461bcd60e51b815260206004820152603260248201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560448201527f63656976657220696d706c656d656e746572000000000000000000000000000060648201526084016104a1565b805181602001fd5b7fffffffff00000000000000000000000000000000000000000000000000000000167f150b7a0200000000000000000000000000000000000000000000000000000000149050610d0f565b506001949350505050565b73ffffffffffffffffffffffffffffffffffffffff82166116335760405162461bcd60e51b815260206004820181905260248201527f4552433732313a206d696e7420746f20746865207a65726f206164647265737360448201526064016104a1565b60008181526002602052604090205473ffffffffffffffffffffffffffffffffffffffff16156116a55760405162461bcd60e51b815260206004820152601c60248201527f4552433732313a20746f6b656e20616c7265616479206d696e7465640000000060448201526064016104a1565b73ffffffffffffffffffffffffffffffffffffffff821660009081526003602052604081208054600192906116db908490612716565b909155505060008181526002602052604080822080547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff861690811790915590518392907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef908290a45050565b7fffffffff000000000000000000000000000000000000000000000000000000008116811461178c57600080fd5b50565b6000602082840312156117a157600080fd5b81356117ac8161175e565b9392505050565b60005b838110156117ce5781810151838201526020016117b6565b838111156109995750506000910152565b600081518084526117f78160208601602086016117b3565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b6020815260006117ac60208301846117df565b60006020828403121561184e57600080fd5b5035919050565b803573ffffffffffffffffffffffffffffffffffffffff8116811461187957600080fd5b919050565b6000806040838503121561189157600080fd5b61189a83611855565b946020939093013593505050565b6000806000606084860312156118bd57600080fd5b6118c684611855565b92506118d460208501611855565b9150604084013590509250925092565b6000602082840312156118f657600080fd5b6117ac82611855565b6000806040838503121561191257600080fd5b61191b83611855565b91506020830135801515811461193057600080fd5b809150509250929050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b6000806000806080858703121561198057600080fd5b61198985611855565b935061199760208601611855565b925060408501359150606085013567ffffffffffffffff808211156119bb57600080fd5b818701915087601f8301126119cf57600080fd5b8135818111156119e1576119e161193b565b604051601f82017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0908116603f01168101908382118183101715611a2757611a2761193b565b816040528281528a6020848701011115611a4057600080fd5b82602086016020830137600060208483010152809550505050505092959194509250565b60008060408385031215611a7757600080fd5b611a8083611855565b9150611a8e60208401611855565b90509250929050565b600181811c90821680611aab57607f821691505b602082108103611ae4577f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b50919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b600082611b2857611b28611aea565b500690565b7f3c73766720786d6c6e733d22687474703a2f2f7777772e77332e6f72672f323081527f30302f737667222077696474683d223130323422206865696768743d2231303260208201527f34222066696c6c3d226e6f6e65223e3c706174682066696c6c3d2268736c2800604082015260008351611bb181605f8501602088016117b3565b7f2c20313030252c20313025292220643d224d3020306831303234763130323448605f918401918201527f307a22202f3e3c672066696c6c3d2268736c2800000000000000000000000000607f8201528351611c148160928401602088016117b3565b7f2c20313030252c2039302529223e3c7061746820643d224d393033203433372e609292909101918201527f35633020392e3131332d372e3338382031362e352d31362e352031362e35732d60b28201527f31362e352d372e3338372d31362e352d31362e3520372e3338382d31362e352060d28201527f31362e352d31362e352031362e3520372e3338372031362e352031362e357a4d60f28201527f3639382e3532392035363663362e39323120302031322e35332d352e353936206101128201527f31322e35332d31322e35762d353063302d362e39303420352e3630392d31322e6101328201527f352031322e3532392d31322e356832352e30353963362e393220302031322e356101528201527f323920352e3539362031322e3532392031322e35763530633020362e393034206101728201527f352e3630392031322e352031322e35332031322e357331322e3532392d352e356101928201527f39362031322e3532392d31322e35762d353063302d362e39303420352e3630396101b28201527f2d31322e352031322e35332d31322e356832352e30353963362e3932203020316101d28201527f322e35323920352e3539362031322e3532392031322e35763530633020362e396101f28201527f303420352e3630392031322e352031322e3532392031322e356833372e3538396102128201527f63362e393220302031322e3532392d352e3539362031322e3532392d31322e356102328201527f762d373563302d362e3930342d352e3630392d31322e352d31322e3532392d316102528201527f322e35732d31322e353320352e3539362d31322e35332031322e357635362e326102728201527f3561362e32363420362e3236342030203120312d31322e3532392030563437386102928201527f2e3563302d362e3930342d352e3630392d31322e352d31322e35332d31322e356102b28201527f483639382e353239632d362e393220302d31322e35323920352e3539362d31326102d28201527f2e3532392031322e35763735633020362e39303420352e3630392031322e35206102f28201527f31322e3532392031322e357a22202f3e3c7061746820643d224d3135372e36356103128201527f3520353431632d362e39333220302d31322e3535322d352e3539362d31322e356103328201527f35322d31322e35762d353063302d362e3930342d352e3631392d31322e352d316103528201527f322e3535312d31322e3553313230203437312e35393620313230203437382e356103728201527f763735633020362e39303420352e36322031322e352031322e3535322031322e6103928201527f35683135302e363263362e39333320302031322e3535322d352e3539362031326103b28201527f2e3535322d31322e35762d353063302d362e39303420352e3631392d31322e356103d28201527f2031322e3535322d31322e35683134342e33343563332e343635203020362e326103f28201527f373620322e37393820362e32373620362e3235732d322e38313120362e32352d6104128201527f362e32373620362e3235483332302e383238632d362e39333320302d31322e356104328201527f353220352e3539362d31322e3535322031322e357633372e35633020362e39306104528201527f3420352e3631392031322e352031322e3535322031322e35683135302e3632636104728201527f362e39333320302031322e3535322d352e3539362031322e3535322d31322e356104928201527f762d373563302d362e3930342d352e3631392d31322e352d31322e3535322d316104b28201527f322e35483238332e313732632d362e39333220302d31322e35353120352e35396104d28201527f362d31322e3535312031322e35763530633020362e3930342d352e36313920316104f28201527f322e352d31322e3535322031322e35682d32352e313033632d362e39333320306105128201527f2d31322e3535322d352e3539362d31322e3535322d31322e35762d353063302d6105328201527f362e3930342d352e36322d31322e352d31322e3535322d31322e35732d31322e6105528201527f35353220352e3539362d31322e3535322031322e35763530633020362e3930346105728201527f2d352e3631392031322e352d31322e3535312031322e35682d32352e3130347a6105928201527f6d3330312e3234322d362e3235633020332e3435322d322e38313120362e32356105b28201527f2d362e32373620362e3235483333392e363535632d332e34363520302d362e326105d28201527f37362d322e3739382d362e3237362d362e323573322e3831312d362e323520366105f28201527f2e3237362d362e3235683131322e39363663332e343635203020362e323736206106128201527f322e37393820362e32373620362e32357a4d343937203535332e3831386330206106328201527f362e39323920352e3632382031322e3534362031322e3537312031322e3534366106528201527f6831333261362e323820362e323820302030203120362e32383620362e3237326106728201527f20362e323820362e32382030203020312d362e32383620362e323733682d31336106928201527f32632d362e39343320302d31322e35373120352e3631362d31322e35373120316106b28201527f322e3534364131322e35362031322e3536203020302030203530392e353731206106d28201527f363034683135302e38353863362e39343320302031322e3537312d352e3631366106f28201527f2031322e3537312d31322e353435762d3131322e393163302d362e3932382d356107128201527f2e3632382d31322e3534352d31322e3537312d31322e353435483530392e35376107328201527f31632d362e39343320302d31322e35373120352e3631372d31322e35373120316107528201527f322e3534357637352e3237337a6d33372e3731342d36322e373237632d362e396107728201527f343320302d31322e35373120352e3631372d31322e3537312031322e353435766107928201527f32352e303931633020362e39323920352e3632382031322e3534362031322e356107b28201527f37312031322e353436683130302e35373263362e39343320302031322e3537316107d28201527f2d352e3631372031322e3537312d31322e353436762d32352e30393163302d366107f28201527f2e3932382d352e3632382d31322e3534352d31322e3537312d31322e353435486108128201527f3533342e3731347a222066696c6c2d72756c653d226576656e6f646422202f3e6108328201527f3c2f673e3c2f7376673e0000000000000000000000000000000000000000000061085282015261085c01949350505050565b7f7b226e616d65223a20227761676d6920230000000000000000000000000000008152600083516125f28160118501602088016117b3565b7f222c2022696d616765223a2022646174613a696d6167652f7376672b786d6c3b6011918401918201527f6261736536342c00000000000000000000000000000000000000000000000000603182015283516126558160388401602088016117b3565b7f227d00000000000000000000000000000000000000000000000000000000000060389290910191820152603a01949350505050565b7f646174613a6170706c69636174696f6e2f6a736f6e3b6261736536342c0000008152600082516126c381601d8501602087016117b3565b91909101601d0192915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b600082821015612711576127116126d0565b500390565b60008219821115612729576127296126d0565b500190565b60007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff820361275f5761275f6126d0565b5060010190565b60008261277557612775611aea565b500490565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b6000817fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff04831182151516156127e1576127e16126d0565b500290565b600073ffffffffffffffffffffffffffffffffffffffff80871683528086166020840152508360408301526080606083015261282560808301846117df565b9695505050505050565b60006020828403121561284157600080fd5b81516117ac8161175e56fe4142434445464748494a4b4c4d4e4f505152535455565758595a6162636465666768696a6b6c6d6e6f707172737475767778797a303132333435363738392b2fa26469706673582212201665a4f9111990d7529375848d3fd02c0121091a940da59e763eba826e7b077064736f6c634300080d0033", "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getBytecode", { "address": undefined, "chainId": 1, }, ], "refetch": [Function], "status": "success", "suspense": [Function], } `) }) test('behavior: disabled when properties missing', async () => { const [result] = renderComposable(() => useBytecode()) await wait(100) expect(result.isPending.value).toBe(true) }) ================================================ FILE: packages/vue/src/composables/useBytecode.ts ================================================ import type { Config, GetBytecodeErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetBytecodeData, type GetBytecodeOptions, getBytecodeQueryOptions, } from '@wagmi/core/query' import { computed } from 'vue' import type { DeepMaybeRef } from '../types/ref.js' import { deepUnref } from '../utils/cloneDeep.js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseBytecodeParameters< config extends Config = Config, selectData = GetBytecodeData, > = Compute< DeepMaybeRef & ConfigParameter> > export type UseBytecodeReturnType = UseQueryReturnType /** https://wagmi.sh/vue/api/hooks/useBytecode */ export function useBytecode< config extends Config = ResolvedRegister['config'], selectData = GetBytecodeData, >( parameters: UseBytecodeParameters = {}, ): UseBytecodeReturnType { const params = computed(() => deepUnref(parameters)) const config = useConfig(params) const chainId = useChainId({ config }) const options = computed(() => getBytecodeQueryOptions(config as any, { ...params.value, chainId: params.value.chainId ?? chainId.value, }), ) return useQuery(options as any) as any } ================================================ FILE: packages/vue/src/composables/useChainId.test-d.ts ================================================ import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useChainId } from './useChainId.js' test('default', () => { const chainId = useChainId() expectTypeOf(chainId.value).toEqualTypeOf() }) test('parameters: config', () => { const chainId = useChainId({ config }) expectTypeOf(chainId.value).toEqualTypeOf<1 | 456 | 10>() }) ================================================ FILE: packages/vue/src/composables/useChainId.test.ts ================================================ import { config } from '@wagmi/test' import { renderComposable } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { useChainId } from './useChainId.js' test('default', () => { const [chainId] = renderComposable(() => useChainId()) expect(chainId.value).toMatchInlineSnapshot('1') config.setState((x) => ({ ...x, chainId: 456 })) expect(chainId.value).toMatchInlineSnapshot('456') }) test('parameters: config', () => { const [chainId] = renderComposable(() => useChainId({ config }), { attach() {}, }) expect(chainId.value).toBeDefined() }) ================================================ FILE: packages/vue/src/composables/useChainId.ts ================================================ import { type Config, type GetChainIdReturnType, getChainId, type ResolvedRegister, watchChainId, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { onScopeDispose, type Ref, readonly, ref } from 'vue' import { useConfig } from './useConfig.js' export type UseChainIdParameters = ConfigParameter export type UseChainIdReturnType = Ref< GetChainIdReturnType > /** https://wagmi.sh/vue/api/composables/useChainId */ export function useChainId( parameters: UseChainIdParameters = {}, ): UseChainIdReturnType { const config = useConfig(parameters) const chainId = ref(getChainId(config)) const unsubscribe = watchChainId(config, { onChange(data) { chainId.value = data }, }) onScopeDispose(() => unsubscribe()) return readonly(chainId) } ================================================ FILE: packages/vue/src/composables/useChains.test.ts ================================================ import { config } from '@wagmi/test' import { renderComposable } from '@wagmi/test/vue' import { celo } from 'viem/chains' import { expect, test } from 'vitest' import { useChains } from './useChains.js' test('default', async () => { const [chains] = renderComposable(() => useChains()) expect(chains.value.length).toBe(3) config._internal.chains.setState((x) => [...x, celo]) expect(chains.value.length).toBe(4) }) ================================================ FILE: packages/vue/src/composables/useChains.ts ================================================ import { type Config, type GetChainsReturnType, getChains, type ResolvedRegister, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { watchChains } from '@wagmi/core/internal' import { onScopeDispose, type Ref, readonly, ref } from 'vue' import { useConfig } from './useConfig.js' export type UseChainsParameters = ConfigParameter export type UseChainsReturnType = Ref< GetChainsReturnType > /** https://wagmi.sh/vue/api/composables/useChains */ export function useChains( parameters: UseChainsParameters = {}, ): UseChainsReturnType { const config = useConfig(parameters) const chains = ref>(getChains(config)) const unsubscribe = watchChains(config, { onChange(data) { chains.value = data as any }, }) onScopeDispose(() => unsubscribe()) return readonly(chains) as UseChainsReturnType } ================================================ FILE: packages/vue/src/composables/useClient.test-d.ts ================================================ import { chain, config } from '@wagmi/test' import type { Chain } from 'viem' import { expectTypeOf, test } from 'vitest' import { useClient } from './useClient.js' test('default', () => { const client = useClient({ config }) expectTypeOf(client.value.chain).toEqualTypeOf< (typeof config)['chains'][number] >() expectTypeOf(client.value.transport.type).toEqualTypeOf<'http'>() }) test('parameters: chainId', () => { const client = useClient({ config, chainId: chain.mainnet.id, }) expectTypeOf(client.value.chain).toEqualTypeOf() expectTypeOf(client.value.chain).not.toEqualTypeOf() expectTypeOf(client.value.transport.type).toEqualTypeOf<'http'>() }) test('behavior: unconfigured chain', () => { { const client = useClient({ chainId: 123456 }) if (client.value) { expectTypeOf(client.value.chain).toEqualTypeOf() expectTypeOf(client.value.transport.type).toEqualTypeOf() } else { expectTypeOf(client.value).toEqualTypeOf() } } const client = useClient({ config, // @ts-expect-error chainId: 123456, }) expectTypeOf(client.value).toEqualTypeOf() }) ================================================ FILE: packages/vue/src/composables/useClient.test.ts ================================================ import { switchChain } from '@wagmi/core' import { config } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { ref } from 'vue' import { useClient } from './useClient.js' test('default', async () => { const [client] = renderComposable(() => useClient()) expect(client?.value?.chain.id).toEqual(1) await switchChain(config, { chainId: 456 }) expect(client.value?.chain?.id).toEqual(456) }) test('parameters: config', () => { const [chainId] = renderComposable(() => useClient({ config }), { attach() {}, }) expect(chainId.value).toBeDefined() }) test('behavior: controlled chainId', async () => { const chainId = ref(456) const [client] = renderComposable(() => useClient({ chainId })) expect(client?.value?.chain.id).toEqual(456) chainId.value = 1 await waitFor(client, (client) => client?.chain.id === 1) }) test('behavior: unconfigured chain', () => { const [client] = renderComposable(() => useClient({ chainId: 123456 })) expect(client.value).toBeUndefined() }) ================================================ FILE: packages/vue/src/composables/useClient.ts ================================================ import { type Config, type GetClientParameters, type GetClientReturnType, getClient, type ResolvedRegister, watchClient, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { computed, onScopeDispose, type Ref, readonly, ref, watchEffect, } from 'vue' import type { DeepMaybeRef } from '../types/ref.js' import { deepUnref } from '../utils/cloneDeep.js' import { useConfig } from './useConfig.js' export type UseClientParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] | number | undefined = | config['chains'][number]['id'] | undefined, > = Compute< DeepMaybeRef & ConfigParameter> > export type UseClientReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] | number | undefined = | config['chains'][number]['id'] | undefined, > = Ref> /** https://wagmi.sh/vue/api/composables/useClient */ export function useClient< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] | number | undefined = | config['chains'][number]['id'] | undefined, >( parameters: UseClientParameters = {}, ): UseClientReturnType { const params = computed(() => deepUnref(parameters)) const config = useConfig(params) const client = ref(getClient(config, params.value as GetClientParameters)) watchEffect(() => { client.value = getClient(config, params.value as GetClientParameters) }) const unsubscribe = watchClient(config, { onChange(data) { if (client.value?.uid === data?.uid) return client.value = data }, }) onScopeDispose(() => unsubscribe()) return readonly(client) as UseClientReturnType } ================================================ FILE: packages/vue/src/composables/useConfig.test-d.ts ================================================ import type { Config } from '@wagmi/core' import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useConfig } from './useConfig.js' test('default', async () => { const result = useConfig() expectTypeOf(result).toEqualTypeOf() }) test('parameters: config', async () => { const result = useConfig({ config }) expectTypeOf(result).not.toEqualTypeOf() expectTypeOf(result).toEqualTypeOf() }) ================================================ FILE: packages/vue/src/composables/useConfig.test.ts ================================================ import { renderComposable } from '@wagmi/test/vue' import { expect, test, vi } from 'vitest' import { useConfig } from './useConfig.js' test('default', () => { const [config] = renderComposable(() => useConfig()) expect(config).toBeDefined() }) test('behavior: throws when not provided via WagmiPlugin', () => { vi.spyOn(console, 'error').mockImplementation(() => {}) try { renderComposable(() => useConfig(), { attach() {} }) } catch (error) { expect(error).toMatchInlineSnapshot(` [WagmiPluginNotFoundError: No \`config\` found in Vue context, use \`WagmiPlugin\` to properly initialize the library. Docs: https://wagmi.sh/vue/api/Nuxt.html Version: @wagmi/vue@x.y.z] `) } }) ================================================ FILE: packages/vue/src/composables/useConfig.ts ================================================ import type { Config, ResolvedRegister } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { hasInjectionContext, inject, unref } from 'vue' import { WagmiInjectionContextError, WagmiPluginNotFoundError, } from '../errors/plugin.js' import { configKey } from '../plugin.js' import type { DeepMaybeRef } from '../types/ref.js' export type UseConfigParameters = DeepMaybeRef< ConfigParameter > export type UseConfigReturnType = config /** https://wagmi.sh/vue/api/composables/useConfig */ export function useConfig( parameters_: UseConfigParameters = {}, ): UseConfigReturnType { const parameters = unref(parameters_) // passthrough config if provided if (parameters.config) return parameters.config as UseConfigReturnType // ensures that `inject()` can be used if (!hasInjectionContext()) throw new WagmiInjectionContextError() const config = inject(configKey) if (!config) throw new WagmiPluginNotFoundError() return config as UseConfigReturnType } ================================================ FILE: packages/vue/src/composables/useConnect.test-d.ts ================================================ import type { ConnectErrorType, Connector, CreateConnectorFn, } from '@wagmi/core' import { config } from '@wagmi/test' import type { Address, Hex } from 'viem' import { assertType, expectTypeOf, test } from 'vitest' import { useConnect } from './useConnect.js' const connector = config.connectors[0]! const contextValue = { foo: 'bar' } as const test('context', () => { const connect = useConnect({ mutation: { onMutate(variables) { assertType<{ chainId?: number | undefined connector: Connector | CreateConnectorFn withCapabilities?: boolean | undefined }>(variables) return contextValue }, onError(error, variables, context) { assertType<{ chainId?: number | undefined connector: Connector | CreateConnectorFn withCapabilities?: boolean | undefined }>(variables) expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { assertType<{ chainId?: number | undefined connector: Connector | CreateConnectorFn withCapabilities?: boolean | undefined }>(variables) expectTypeOf(data).toEqualTypeOf<{ accounts: | readonly [Address, ...Address[]] | readonly [ { address: Address; capabilities: Record }, ...{ address: Address capabilities: Record }[], ] chainId: number }>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf< | { accounts: | readonly [Address, ...Address[]] | readonly [ { address: Address capabilities: Record }, ...{ address: Address capabilities: Record }[], ] chainId: number } | undefined >() expectTypeOf(error).toEqualTypeOf() assertType<{ chainId?: number | undefined connector: Connector | CreateConnectorFn withCapabilities?: boolean | undefined }>(variables) expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(connect.data.value).toEqualTypeOf< | { accounts: | readonly [Address, ...Address[]] | readonly [ { address: Address; capabilities: Record }, ...{ address: Address capabilities: Record }[], ] chainId: number } | undefined >() expectTypeOf(connect.error.value).toEqualTypeOf() expectTypeOf(connect.variables.value).toMatchTypeOf< | { chainId?: number | undefined connector: Connector | CreateConnectorFn } | undefined >() expectTypeOf(connect.context.value).toEqualTypeOf< typeof contextValue | undefined >() connect.mutate( { connector }, { onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ chainId?: number | undefined connector: typeof connector | CreateConnectorFn foo?: string | undefined withCapabilities?: boolean | undefined }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ chainId?: number | undefined connector: typeof connector | CreateConnectorFn foo?: string | undefined withCapabilities?: boolean | undefined }>() expectTypeOf(data).toEqualTypeOf<{ accounts: readonly [Address, ...Address[]] chainId: number }>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf<{ chainId?: number | undefined connector: typeof connector | CreateConnectorFn foo?: string | undefined withCapabilities?: boolean | undefined }>() expectTypeOf(context).toEqualTypeOf() }, }, ) connect.mutate( { connector, foo: 'bar', withCapabilities: true, }, { onSuccess(data, _variables, _context) { expectTypeOf(data).toEqualTypeOf<{ accounts: readonly [ { address: Address capabilities: { foo: { bar: Hex } } }, ...{ address: Address capabilities: { foo: { bar: Hex } } }[], ] chainId: number }>() }, onSettled(data, _error, _variables, _context) { expectTypeOf(data).toEqualTypeOf< | { accounts: readonly [ { address: Address capabilities: { foo: { bar: Hex } } }, ...{ address: Address capabilities: { foo: { bar: Hex } } }[], ] chainId: number } | undefined >() }, }, ) ;(async () => { const res = await connect.mutateAsync({ connector, foo: 'bar', withCapabilities: true, }) expectTypeOf(res).toEqualTypeOf<{ accounts: readonly [ { address: Address capabilities: { foo: { bar: Hex } } }, ...{ address: Address capabilities: { foo: { bar: Hex } } }[], ] chainId: number }>() })() }) ================================================ FILE: packages/vue/src/composables/useConnect.test.ts ================================================ import { disconnect } from '@wagmi/core' import { config } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { afterEach, expect, test } from 'vitest' import { useConnect } from './useConnect.js' import { useConnection } from './useConnection.js' import { useConnectors } from './useConnectors.js' const connector = config.connectors[0]! afterEach(async () => { if (config.state.current === connector.uid) await disconnect(config, { connector }) }) test('default', async () => { const [connection] = renderComposable(() => useConnection()) const [connect] = renderComposable(() => useConnect()) const [connectors] = renderComposable(() => useConnectors()) expect(connection.address.value).not.toBeDefined() expect(connection.status.value).toEqual('disconnected') connect.mutate({ connector: connectors.value[0]!, }) await waitFor(connection.isConnected, (isConnected) => Boolean(isConnected)) expect(connection.address.value).toBeDefined() expect(connection.status.value).toEqual('connected') }) ================================================ FILE: packages/vue/src/composables/useConnect.ts ================================================ import { useMutation } from '@tanstack/vue-query' import type { Config, ConnectErrorType, GetConnectorsReturnType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type ConnectData, type ConnectMutate, type ConnectMutateAsync, type ConnectOptions, type ConnectVariables, connectMutationOptions, } from '@wagmi/core/query' import { onScopeDispose } from 'vue' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' import { useConnectors } from './useConnectors.js' export type UseConnectParameters< config extends Config = Config, context = unknown, > = Compute & ConnectOptions> export type UseConnectReturnType< config extends Config = Config, context = unknown, > = Compute< UseMutationReturnType< ConnectData, ConnectErrorType, ConnectVariables, context, ConnectMutate, ConnectMutateAsync > & { /** @deprecated use `mutate` instead */ connect: ConnectMutate /** @deprecated use `mutateAsync` instead */ connectAsync: ConnectMutateAsync /** @deprecated use `useConnectors` instead */ connectors: Compute | config['connectors'] } > /** https://wagmi.sh/vue/api/composables/useConnect */ export function useConnect< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: UseConnectParameters = {}, ): UseConnectReturnType { const config = useConfig(parameters) const options = connectMutationOptions(config, parameters) const mutation = useMutation(options) // Reset mutation back to an idle state when the connector disconnects. const unsubscribe = config.subscribe( ({ status }) => status, (status, previousStatus) => { if (previousStatus === 'connected' && status === 'disconnected') mutation.reset() }, ) onScopeDispose(() => unsubscribe()) type Return = UseConnectReturnType return { ...(mutation as Return), connect: mutation.mutate as Return['mutate'], connectAsync: mutation.mutateAsync as Return['mutateAsync'], connectors: useConnectors({ config }).value, } } ================================================ FILE: packages/vue/src/composables/useConnection.test-d.ts ================================================ import type { Connector } from '@wagmi/core' import type { Address, Chain } from 'viem' import { expectTypeOf, test } from 'vitest' import { deepUnref } from '../utils/cloneDeep.js' import { useConnection } from './useConnection.js' test('states', () => { const result = deepUnref(useConnection()) switch (result.status) { case 'reconnecting': { expectTypeOf(result).toMatchTypeOf<{ address: Address | undefined chain: Chain | undefined chainId: number | undefined connector: Connector | undefined isConnected: boolean isConnecting: false isDisconnected: false isReconnecting: true status: 'reconnecting' }>() break } case 'connecting': { expectTypeOf(result).toMatchTypeOf<{ address: Address | undefined chain: Chain | undefined chainId: number | undefined connector: Connector | undefined isConnected: false isReconnecting: false isConnecting: true isDisconnected: false status: 'connecting' }>() break } case 'connected': { expectTypeOf(result).toMatchTypeOf<{ address: Address chain: Chain | undefined chainId: number connector: Connector isConnected: true isConnecting: false isDisconnected: false isReconnecting: false status: 'connected' }>() break } case 'disconnected': { expectTypeOf(result).toMatchTypeOf<{ address: undefined chain: undefined chainId: undefined connector: undefined isConnected: false isReconnecting: false isConnecting: false isDisconnected: true status: 'disconnected' }>() break } } }) ================================================ FILE: packages/vue/src/composables/useConnection.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { config } from '@wagmi/test' import { renderComposable } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { useConnection } from './useConnection.js' test('default', async () => { const [connection] = renderComposable(() => useConnection()) expect(connection.address.value).not.toBeDefined() expect(connection.status.value).toEqual('disconnected') await connect(config, { connector: config.connectors[0]! }) expect(connection.address.value).toBeDefined() expect(connection.status.value).toEqual('connected') await disconnect(config) }) ================================================ FILE: packages/vue/src/composables/useConnection.ts ================================================ import { type Config, type GetConnectionReturnType, getConnection, type ResolvedRegister, watchConnection, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { onScopeDispose, reactive, readonly, type ToRefs, toRefs } from 'vue' import { updateState } from '../utils/updateState.js' import { useConfig } from './useConfig.js' export type UseConnectionParameters = ConfigParameter export type UseConnectionReturnType = ToRefs< GetConnectionReturnType > /** https://wagmi.sh/vue/api/composables/useConnection */ export function useConnection< config extends Config = ResolvedRegister['config'], >( parameters: UseConnectionParameters = {}, ): UseConnectionReturnType { const config = useConfig(parameters) const connection = reactive(getConnection(config)) const unsubscribe = watchConnection(config, { onChange(data) { updateState(connection, data) }, }) onScopeDispose(() => unsubscribe()) return toRefs(readonly(connection)) as UseConnectionReturnType } ================================================ FILE: packages/vue/src/composables/useConnectionEffect.test.ts ================================================ import { VueQueryPlugin } from '@tanstack/vue-query' import { mock } from '@wagmi/connectors' import { connect, createConfig, disconnect, http } from '@wagmi/core' import { accounts, chain } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { expect, test, vi } from 'vitest' import type { App } from 'vue' import { WagmiPlugin } from '../plugin.js' import { useConnect } from './useConnect.js' import { useConnection } from './useConnection.js' import { useConnectionEffect } from './useConnectionEffect.js' import { useConnectors } from './useConnectors.js' import { useDisconnect } from './useDisconnect.js' test('behavior: connect and disconnect called once', async () => { const onConnect = vi.fn() const onDisconnect = vi.fn() renderComposable(() => useConnectionEffect({ onConnect, onDisconnect })) const [connect] = renderComposable(() => useConnect()) const [connectors] = renderComposable(() => useConnectors()) const [disconnect] = renderComposable(() => useDisconnect()) connect.mutate({ connector: connectors.value[0]!, }) await waitFor(connect.isSuccess) connect.mutate({ connector: connectors.value[0]!, }) disconnect.mutate() await waitFor(disconnect.isSuccess) disconnect.mutate() expect(onConnect).toBeCalledTimes(1) expect(onDisconnect).toBeCalledTimes(1) }) test('behavior: connect called on reconnect', async () => { const config = createConfig({ chains: [chain.mainnet], connectors: [ mock({ accounts, features: { reconnect: true }, }), ], transports: { [chain.mainnet.id]: http() }, }) function attach(app: App) { app .use(WagmiPlugin, { config, reconnectOnMount: true, }) .use(VueQueryPlugin, {}) } await connect(config, { connector: config.connectors[0]! }) const onConnect = vi.fn((data) => { expect(data.isReconnected).toBeTruthy() }) renderComposable(() => useConnectionEffect({ onConnect }), { attach, }) const [connection] = renderComposable(() => useConnection(), { attach }) await waitFor(connection.status, (status) => status === 'connected') expect(onConnect).toBeCalledTimes(1) await disconnect(config) }) ================================================ FILE: packages/vue/src/composables/useConnectionEffect.ts ================================================ import { type GetConnectionReturnType, watchConnection } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { watchEffect } from 'vue' import type { DeepMaybeRef } from '../types/ref.js' import { deepUnref } from '../utils/cloneDeep.js' import { useConfig } from './useConfig.js' export type UseConnectionEffectParameters = Compute< DeepMaybeRef< { onConnect?( data: Compute< Pick< Extract, 'address' | 'addresses' | 'chain' | 'chainId' | 'connector' > & { isReconnected: boolean } >, ): void onDisconnect?(): void } & ConfigParameter > > /** https://wagmi.sh/vue/api/composables/useConnectionEffect */ export function useConnectionEffect( parameters: UseConnectionEffectParameters = {}, ) { const config = useConfig(parameters) watchEffect((onCleanup) => { const { onConnect, onDisconnect } = deepUnref(parameters) const unwatch = watchConnection(config, { onChange(data, prevData) { if ( (prevData.status === 'reconnecting' || (prevData.status === 'connecting' && prevData.address === undefined)) && data.status === 'connected' ) { const { address, addresses, chain, chainId, connector } = data const isReconnected = prevData.status === 'reconnecting' || // if `previousAccount.status` is `undefined`, the connector connected immediately. prevData.status === undefined onConnect?.({ address, addresses, chain, chainId, connector, isReconnected, }) } else if ( prevData.status === 'connected' && data.status === 'disconnected' ) onDisconnect?.() }, }) onCleanup(() => unwatch()) }) } ================================================ FILE: packages/vue/src/composables/useConnections.test.ts ================================================ import { connect } from '@wagmi/core' import { config } from '@wagmi/test' import { renderComposable } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { useConnections } from './useConnections.js' test('default', async () => { const [connections] = renderComposable(() => useConnections()) expect(connections.value).toEqual([]) await connect(config, { connector: config.connectors[0]! }) expect(connections.value.length).toBe(1) }) ================================================ FILE: packages/vue/src/composables/useConnections.ts ================================================ import { type GetConnectionsReturnType, getConnections, watchConnections, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { onScopeDispose, type Ref, readonly, ref } from 'vue' import { useConfig } from './useConfig.js' export type UseConnectionsParameters = ConfigParameter export type UseConnectionsReturnType = Ref /** https://wagmi.sh/vue/api/composables/useConnections */ export function useConnections( parameters: UseConnectionsParameters = {}, ): UseConnectionsReturnType { const config = useConfig(parameters) const connections = ref(getConnections(config)) const unsubscribe = watchConnections(config, { onChange(data) { connections.value = data }, }) onScopeDispose(() => unsubscribe()) return readonly(connections) as UseConnectionsReturnType } ================================================ FILE: packages/vue/src/composables/useConnectorClient.test-d.ts ================================================ import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useConnectorClient } from './useConnectorClient.js' test('parameters: config', async () => { const client = useConnectorClient({ config }) expectTypeOf(client.data?.value?.chain?.id!).toEqualTypeOf<1 | 456 | 10>() const client2 = useConnectorClient({ config, chainId: 1 }) expectTypeOf(client2.data?.value?.chain?.id!).toEqualTypeOf<1>() }) ================================================ FILE: packages/vue/src/composables/useConnectorClient.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { config, wait } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { deepUnref } from '../utils/cloneDeep.js' import { useConnect } from './useConnect.js' import { useConnectorClient } from './useConnectorClient.js' import { useConnectors } from './useConnectors.js' import { useDisconnect } from './useDisconnect.js' import { useSwitchChain } from './useSwitchChain.js' const connector = config.connectors[0]! test('default', async () => { const [client] = renderComposable(() => useConnectorClient()) expect(deepUnref(client)).toMatchInlineSnapshot(` { "data": undefined, "dataUpdatedAt": 0, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": false, "isFetchedAfterMount": false, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": true, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": false, "queryKey": [ "connectorClient", { "chainId": 1, }, ], "refetch": [Function], "status": "pending", "suspense": [Function], } `) }) test('behavior: connected on mount', async () => { await connect(config, { connector }) const [client] = renderComposable(() => useConnectorClient()) await waitFor(client.isSuccess, (isSuccess) => isSuccess === true) const { data, queryKey: _, ...rest } = deepUnref(client) expect(data).toMatchObject( expect.objectContaining({ account: expect.any(Object), chain: expect.any(Object), }), ) expect(rest).toMatchInlineSnapshot(` { "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": false, "isSuccess": true, "refetch": [Function], "status": "success", "suspense": [Function], } `) await disconnect(config, { connector }) }) test('behavior: connect and disconnect', async () => { const [connect] = renderComposable(() => useConnect()) const [connectors] = renderComposable(() => useConnectors()) const [client] = renderComposable(() => useConnectorClient()) const [disconnect] = renderComposable(() => useDisconnect()) expect(client.data.value).not.toBeDefined() connect.mutate({ connector: connectors.value[0]!, }) await waitFor(client.data, (data) => data !== undefined) disconnect.mutate() await waitFor(client.data, (data) => data === undefined) }) test('behavior: switch chains', async () => { await connect(config, { connector }) const [connectorClient] = renderComposable(() => useConnectorClient()) const [switchChain] = renderComposable(() => useSwitchChain()) expect(connectorClient.data.value).not.toBeDefined() await waitFor(connectorClient.data, (data) => data !== undefined) switchChain.mutate({ chainId: 456 }) await waitFor(switchChain.isSuccess, (isSuccess) => isSuccess === true) await waitFor(connectorClient.data, (data) => data !== undefined) expect(connectorClient.data?.value?.chain.id).toEqual(456) await switchChain.mutateAsync({ chainId: 1 }) expect(connectorClient.data?.value?.chain.id).toEqual(1) await disconnect(config, { connector }) }) test('behavior: disabled when properties missing', async () => { const [connectorClient] = renderComposable(() => useConnectorClient()) await wait(100) expect(connectorClient.isPending.value).toBe(true) }) test('behavior: disabled when connecting', async () => { const [connectorClient] = renderComposable(() => useConnectorClient()) config.setState((x) => ({ ...x, status: 'connecting' })) await wait(100) expect(connectorClient.isLoading.value).not.toBeTruthy() }) ================================================ FILE: packages/vue/src/composables/useConnectorClient.ts ================================================ import { useQueryClient } from '@tanstack/vue-query' import type { Config, Connector, GetConnectorClientErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetConnectorClientData, type GetConnectorClientOptions, getConnectorClientQueryOptions, } from '@wagmi/core/query' import { computed, ref, watchEffect } from 'vue' import type { DeepMaybeRef } from '../types/ref.js' import { deepUnref } from '../utils/cloneDeep.js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' import { useConnection } from './useConnection.js' export type UseConnectorClientParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetConnectorClientData, > = Compute< DeepMaybeRef< GetConnectorClientOptions & ConfigParameter > > export type UseConnectorClientReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetConnectorClientData, > = UseQueryReturnType /** https://wagmi.sh/vue/api/composables/useConnectorClient */ export function useConnectorClient< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetConnectorClientData, >( parameters: UseConnectorClientParameters = {}, ): UseConnectorClientReturnType { const params = computed(() => deepUnref(parameters)) const config = useConfig(params) const chainId = useChainId({ config }) const { address, connector } = useConnection({ config }) const options = computed(() => getConnectorClientQueryOptions(config as any, { ...(params.value as any), chainId: params.value.chainId ?? chainId.value, connector: (params.value.connector ?? connector.value) as Connector, }), ) const addressRef = ref(address) const queryClient = useQueryClient() watchEffect(() => { const previousAddress = addressRef.value if (!address && previousAddress) { queryClient.removeQueries({ queryKey: options.value.queryKey }) addressRef.value = undefined } else if (address.value !== previousAddress) { queryClient.invalidateQueries({ queryKey: options.value.queryKey }) addressRef.value = address.value } }) return useQuery(options as any) as any } ================================================ FILE: packages/vue/src/composables/useConnectors.test.ts ================================================ import { mock } from '@wagmi/connectors' import { accounts, config } from '@wagmi/test' import { renderComposable } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { useConnectors } from './useConnectors.js' test('default', async () => { const [connectors] = renderComposable(() => useConnectors()) const count = config.connectors.length expect(connectors.value.length).toBe(count) expect(connectors.value).toEqual(config.connectors) config._internal.connectors.setState(() => [ ...config.connectors, config._internal.connectors.setup(mock({ accounts })), ]) expect(connectors.value.length).toBe(count + 1) }) ================================================ FILE: packages/vue/src/composables/useConnectors.ts ================================================ import { type Config, type GetConnectorsReturnType, getConnectors, type ResolvedRegister, watchConnectors, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { onScopeDispose, type Ref, ref } from 'vue' import { useConfig } from './useConfig.js' export type UseConnectorsParameters = ConfigParameter export type UseConnectorsReturnType = Ref< GetConnectorsReturnType > /** https://wagmi.sh/vue/api/composables/useConnectors */ export function useConnectors< config extends Config = ResolvedRegister['config'], >( parameters: UseConnectorsParameters = {}, ): UseConnectorsReturnType { const config = useConfig(parameters) const connectors = ref(getConnectors(config)) const unsubscribe = watchConnectors(config, { onChange(data) { connectors.value = data as never }, }) onScopeDispose(() => unsubscribe()) return connectors } ================================================ FILE: packages/vue/src/composables/useDisconnect.test-d.ts ================================================ import type { Connector, DisconnectErrorType } from '@wagmi/core' import { config } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useDisconnect } from './useDisconnect.js' const connector = config.connectors[0]! const contextValue = { foo: 'bar' } as const test('parameter', () => { expectTypeOf(useDisconnect().mutate) .parameter(0) .toEqualTypeOf<{ connector?: Connector | undefined } | undefined>() expectTypeOf(useDisconnect().mutateAsync) .parameter(0) .toEqualTypeOf<{ connector?: Connector | undefined } | undefined>() }) test('context', () => { const disconnect = useDisconnect({ mutation: { onMutate(variables) { expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(disconnect.data.value).toEqualTypeOf() expectTypeOf( disconnect.error.value, ).toEqualTypeOf() expectTypeOf(disconnect.variables.value).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(disconnect.context.value).toEqualTypeOf< typeof contextValue | undefined >() disconnect.mutate( { connector }, { onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf< { connector?: Connector | undefined } | undefined >() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/vue/src/composables/useDisconnect.test.ts ================================================ import { connect } from '@wagmi/core' import { config } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { beforeEach, expect, test } from 'vitest' import { useConnection } from './useConnection.js' import { useDisconnect } from './useDisconnect.js' const connector = config.connectors[0]! beforeEach(async () => { await connect(config, { connector }) }) test('default', async () => { const [connection] = renderComposable(() => useConnection()) const [disconnect] = renderComposable(() => useDisconnect()) expect(connection.address.value).toBeDefined() expect(connection.status.value).toEqual('connected') disconnect.mutate() await waitFor(connection.isDisconnected, (isDisconnected) => Boolean(isDisconnected), ) expect(connection.address.value).not.toBeDefined() expect(connection.status.value).toEqual('disconnected') }) ================================================ FILE: packages/vue/src/composables/useDisconnect.ts ================================================ import { useMutation } from '@tanstack/vue-query' import type { Connector, DisconnectErrorType } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type DisconnectData, type DisconnectMutate, type DisconnectMutateAsync, type DisconnectOptions, type DisconnectVariables, disconnectMutationOptions, } from '@wagmi/core/query' import { computed, type Ref } from 'vue' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' import { useConnections } from './useConnections.js' export type UseDisconnectParameters = Compute< ConfigParameter & DisconnectOptions > export type UseDisconnectReturnType = Compute< UseMutationReturnType< DisconnectData, DisconnectErrorType, DisconnectVariables, context, DisconnectMutate, DisconnectMutateAsync > & { /** @deprecated use `useConnections` instead */ connectors: Ref /** @deprecated use `mutate` instead */ disconnect: DisconnectMutate /** @deprecated use `mutateAsync` instead */ disconnectAsync: DisconnectMutateAsync } > /** https://wagmi.sh/vue/api/composables/useDisconnect */ export function useDisconnect( parameters: UseDisconnectParameters = {}, ): UseDisconnectReturnType { const config = useConfig(parameters) const connections = useConnections({ config }) const options = disconnectMutationOptions(config, parameters as any) const mutation = useMutation(options) type Return = UseDisconnectReturnType return { ...(mutation as Return), connectors: computed(() => connections.value.map((connection) => connection.connector), ), disconnect: mutation.mutate as Return['mutate'], disconnectAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/vue/src/composables/useEnsAddress.test.ts ================================================ import { renderComposable, waitFor } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { deepUnref } from '../utils/cloneDeep.js' import { useEnsAddress } from './useEnsAddress.js' test('default', async () => { const [result] = renderComposable(() => useEnsAddress({ name: 'wevm.eth', }), ) await waitFor(result.isSuccess) expect(deepUnref(result)).toMatchInlineSnapshot(` { "data": "0xd2135CfB216b74109775236E36d4b433F1DF507B", "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "ensAddress", { "chainId": 1, "name": "wevm.eth", }, ], "refetch": [Function], "status": "success", "suspense": [Function], } `) }) ================================================ FILE: packages/vue/src/composables/useEnsAddress.ts ================================================ import type { Config, GetEnsAddressErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetEnsAddressData, type GetEnsAddressOptions, getEnsAddressQueryOptions, } from '@wagmi/core/query' import { computed } from 'vue' import type { DeepMaybeRef } from '../types/ref.js' import { deepUnref } from '../utils/cloneDeep.js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseEnsAddressParameters< config extends Config = Config, selectData = GetEnsAddressData, > = Compute< DeepMaybeRef< GetEnsAddressOptions & ConfigParameter > > export type UseEnsAddressReturnType = UseQueryReturnType /** https://wagmi.sh/vue/api/composables/useEnsAddress */ export function useEnsAddress< config extends Config = ResolvedRegister['config'], selectData = GetEnsAddressData, >( parameters: UseEnsAddressParameters = {}, ): UseEnsAddressReturnType { const params = computed(() => deepUnref(parameters)) const config = useConfig(params) const chainId = useChainId({ config }) const options = computed(() => getEnsAddressQueryOptions(config as any, { ...params.value, chainId: params.value.chainId ?? chainId.value, }), ) return useQuery(options as any) as any } ================================================ FILE: packages/vue/src/composables/useEnsAvatar.test.ts ================================================ import { renderComposable, waitFor } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { deepUnref } from '../utils/cloneDeep.js' import { useEnsAvatar } from './useEnsAvatar.js' test.skip('default', async () => { const [result] = renderComposable(() => useEnsAvatar({ name: 'wevm.eth', }), ) await waitFor(result.isSuccess) expect(deepUnref(result)).toMatchInlineSnapshot(` { "data": "https://euc.li/wevm.eth", "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "ensAvatar", { "chainId": 1, "name": "wevm.eth", }, ], "refetch": [Function], "status": "success", "suspense": [Function], } `) }) ================================================ FILE: packages/vue/src/composables/useEnsAvatar.ts ================================================ import type { Config, GetEnsAvatarErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetEnsAvatarData, type GetEnsAvatarOptions, getEnsAvatarQueryOptions, } from '@wagmi/core/query' import { computed } from 'vue' import type { DeepMaybeRef } from '../types/ref.js' import { deepUnref } from '../utils/cloneDeep.js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseEnsAvatarParameters< config extends Config = Config, selectData = GetEnsAvatarData, > = Compute< DeepMaybeRef< GetEnsAvatarOptions & ConfigParameter > > export type UseEnsAvatarReturnType = UseQueryReturnType /** https://wagmi.sh/vue/api/composables/useEnsAvatar */ export function useEnsAvatar< config extends Config = ResolvedRegister['config'], selectData = GetEnsAvatarData, >( parameters: UseEnsAvatarParameters = {}, ): UseEnsAvatarReturnType { const params = computed(() => deepUnref(parameters)) const config = useConfig(params) const chainId = useChainId({ config }) const options = computed(() => getEnsAvatarQueryOptions(config as any, { ...params.value, chainId: params.value.chainId ?? chainId.value, }), ) return useQuery(options as any) as any } ================================================ FILE: packages/vue/src/composables/useEnsName.test.ts ================================================ import { renderComposable, waitFor } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { deepUnref } from '../utils/cloneDeep.js' import { useEnsName } from './useEnsName.js' test('default', async () => { const [result] = renderComposable(() => useEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', }), ) await waitFor(result.isSuccess) expect(deepUnref(result)).toMatchInlineSnapshot(` { "data": "wevm.eth", "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "ensName", { "address": "0xd2135CfB216b74109775236E36d4b433F1DF507B", "chainId": 1, }, ], "refetch": [Function], "status": "success", "suspense": [Function], } `) }) ================================================ FILE: packages/vue/src/composables/useEnsName.ts ================================================ import type { Config, GetEnsNameErrorType, ResolvedRegister } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetEnsNameData, type GetEnsNameOptions, getEnsNameQueryOptions, } from '@wagmi/core/query' import { computed } from 'vue' import type { DeepMaybeRef } from '../types/ref.js' import { deepUnref } from '../utils/cloneDeep.js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseEnsNameParameters< config extends Config = Config, selectData = GetEnsNameData, > = Compute< DeepMaybeRef & ConfigParameter> > export type UseEnsNameReturnType = UseQueryReturnType /** https://wagmi.sh/vue/api/composables/useEnsName */ export function useEnsName< config extends Config = ResolvedRegister['config'], selectData = GetEnsNameData, >( parameters: UseEnsNameParameters = {}, ): UseEnsNameReturnType { const params = computed(() => deepUnref(parameters)) const config = useConfig(params) const chainId = useChainId({ config }) const options = computed(() => getEnsNameQueryOptions(config as any, { ...params.value, chainId: params.value.chainId ?? chainId.value, }), ) return useQuery(options as any) as any } ================================================ FILE: packages/vue/src/composables/useEstimateGas.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useEstimateGas } from './useEstimateGas.js' test('select data', () => { const result = useEstimateGas({ query: { select(data) { return data.toString() }, }, }) expectTypeOf(result.data.value).toEqualTypeOf() }) ================================================ FILE: packages/vue/src/composables/useEstimateGas.test.ts ================================================ import { accounts, wait } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { parseEther } from 'viem' import { expect, test } from 'vitest' import { ref } from 'vue' import { deepUnref } from '../utils/cloneDeep.js' import { useEstimateGas } from './useEstimateGas.js' test('default', async () => { const [result] = renderComposable(() => useEstimateGas({ account: accounts[0], to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }), ) await waitFor(result.isSuccess) expect(deepUnref(result)).toMatchInlineSnapshot(` { "data": 21000n, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "estimateGas", { "account": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "chainId": 1, "to": "0xd2135CfB216b74109775236E36d4b433F1DF507B", "value": 10000000000000000n, }, ], "refetch": [Function], "status": "success", "suspense": [Function], } `) }) test('behavior: address: undefined -> defined', async () => { const address = ref() const [result] = renderComposable(() => useEstimateGas({ account: address, to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }), ) await wait(100) expect(result.fetchStatus.value).toBe('idle') address.value = accounts[0] await waitFor(result.isSuccess) expect(deepUnref(result)).toMatchInlineSnapshot(` { "data": 21000n, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "estimateGas", { "account": undefined, "chainId": 1, "to": "0xd2135CfB216b74109775236E36d4b433F1DF507B", "value": 10000000000000000n, }, ], "refetch": [Function], "status": "success", "suspense": [Function], } `) }) ================================================ FILE: packages/vue/src/composables/useEstimateGas.ts ================================================ import type { Config, EstimateGasErrorType, ResolvedRegister, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { type EstimateGasData, type EstimateGasOptions, estimateGasQueryOptions, } from '@wagmi/core/query' import { computed } from 'vue' import type { DeepMaybeRef } from '../types/ref.js' import { deepUnref } from '../utils/cloneDeep.js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' import { useConnection } from './useConnection.js' export type UseEstimateGasParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = EstimateGasData, > = DeepMaybeRef< EstimateGasOptions & ConfigParameter > export type UseEstimateGasReturnType = UseQueryReturnType /** https://wagmi.sh/react/api/hooks/useEstimateGas */ export function useEstimateGas< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = EstimateGasData, >( parameters?: UseEstimateGasParameters, ): UseEstimateGasReturnType export function useEstimateGas( parameters: UseEstimateGasParameters = {}, ): UseEstimateGasReturnType { const params = computed(() => deepUnref(parameters)) const config = useConfig(params) const { address, connector } = useConnection({ config }) const chainId = useChainId({ config }) const options = computed(() => estimateGasQueryOptions(config as any, { ...params.value, account: params.value.account ?? address.value, chainId: params.value.chainId ?? chainId.value, connector: params.value.connector ?? connector.value, }), ) return useQuery(options as any) as any } ================================================ FILE: packages/vue/src/composables/useReadContract.test-d.ts ================================================ import { abi } from '@wagmi/test' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' import { ref } from 'vue' import type { DeepUnwrapRef } from '../types/ref.js' import { type UseReadContractParameters, type UseReadContractReturnType, useReadContract, } from './useReadContract.js' test('select data', () => { const result = useReadContract({ address: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], query: { select(data) { expectTypeOf(data).toEqualTypeOf() return data?.toString() }, }, }) expectTypeOf(result.data.value).toEqualTypeOf() }) test('UseReadContractParameters', () => { type Result = DeepUnwrapRef< UseReadContractParameters > expectTypeOf<{ functionName?: | 'symbol' | 'name' | 'allowance' | 'balanceOf' | 'decimals' | 'totalSupply' | undefined args?: readonly [Address] | undefined }>().toEqualTypeOf>() }) test('UseReadContractReturnType', () => { type Result = UseReadContractReturnType expectTypeOf().toEqualTypeOf() }) test('overloads', () => { useReadContract({ address: '0x', abi: abi.viewOverloads, functionName: 'foo', query: { select(data) { expectTypeOf(data).toEqualTypeOf() return data }, }, }) useReadContract({ address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: [], query: { select(data) { expectTypeOf(data).toEqualTypeOf() return data }, }, }) useReadContract({ address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x'], query: { select(data) { expectTypeOf(data).toEqualTypeOf() return data }, }, }) useReadContract({ address: '0x', abi: abi.viewOverloads, functionName: 'foo', args: ['0x', '0x'], query: { select(data) { expectTypeOf(data).toEqualTypeOf<{ foo: `0x${string}` bar: `0x${string}` }>() return data }, }, }) }) test('deployless read (bytecode)', () => { const result = useReadContract({ code: '0x', abi: abi.erc20, functionName: 'balanceOf', args: ['0x'], }) expectTypeOf(result.data.value).toEqualTypeOf() }) test('loose parameters with refs', () => { const abiRef = abi.erc20 const addressRef = ref<`0x${string}`>('0x') const functionNameRef = 'balanceOf' useReadContract({ abi: abiRef, address: addressRef, functionName: functionNameRef, args: ['0x'], query: { select(data) { expectTypeOf(data).toEqualTypeOf() return data }, }, }) }) ================================================ FILE: packages/vue/src/composables/useReadContract.test.ts ================================================ import { abi, address, bytecode, chain, wait } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { ref } from 'vue' import { useReadContract } from './useReadContract.js' test('default', async () => { const [result] = renderComposable(() => useReadContract({ address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], }), ) await waitFor(result.isSuccess) expect(result.data.value).toBe(10n) expect(result.queryKey).toMatchInlineSnapshot(` [ "readContract", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": [ "0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC", ], "chainId": 1, "functionName": "balanceOf", }, ] `) }) test('parameters: chainId', async () => { const [result] = renderComposable(() => useReadContract({ address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'balanceOf', args: ['0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC'], chainId: chain.mainnet2.id, }), ) await waitFor(result.isSuccess) expect(result.data.value).toBe(10n) expect(result.queryKey).toMatchInlineSnapshot(` [ "readContract", { "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": [ "0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC", ], "chainId": 456, "functionName": "balanceOf", }, ] `) }) test('parameters: deployless read (bytecode)', async () => { const [result] = renderComposable(() => useReadContract({ abi: abi.wagmiMintExample, functionName: 'name', code: bytecode.wagmiMintExample, }), ) await waitFor(result.isSuccess) expect(result.data.value).toMatchInlineSnapshot(`"wagmi"`) }) test.skip('behavior: disabled when missing properties', async () => { const addressRef = ref() const abiRef = ref() const functionNameRef = ref() const [result] = renderComposable(() => useReadContract({ abi: abiRef, address: addressRef, functionName: functionNameRef, }), ) await wait(100) expect(result.fetchStatus.value).toBe('idle') addressRef.value = '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2' await wait(100) expect(result.fetchStatus.value).toBe('idle') abiRef.value = abi.wagmiMintExample functionNameRef.value = 'totalSupply' await wait(100) expect(result.fetchStatus.value).toBe('fetching') }) ================================================ FILE: packages/vue/src/composables/useReadContract.ts ================================================ import type { Config, ReadContractErrorType, ResolvedRegister, } from '@wagmi/core' import type { ConfigParameter, UnionCompute } from '@wagmi/core/internal' import { type ReadContractData, type ReadContractOptions, readContractQueryOptions, } from '@wagmi/core/query' import type { Abi, ContractFunctionArgs, ContractFunctionName } from 'viem' import { computed, type MaybeRef } from 'vue' import type { DeepMaybeRef } from '../types/ref.js' import { deepUnref } from '../utils/cloneDeep.js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseReadContractParameters< abi extends Abi | readonly unknown[] = Abi, functionName extends ContractFunctionName< abi, 'pure' | 'view' > = ContractFunctionName, args extends ContractFunctionArgs< abi, 'pure' | 'view', functionName > = ContractFunctionArgs, config extends Config = Config, selectData = ReadContractData, > = MaybeRef< UnionCompute< ReadContractOptions & ConfigParameter > > type UseReadContractParametersLoose< abi extends Abi | readonly unknown[] = Abi, functionName extends ContractFunctionName< abi, 'pure' | 'view' > = ContractFunctionName, args extends ContractFunctionArgs< abi, 'pure' | 'view', functionName > = ContractFunctionArgs, config extends Config = Config, selectData = ReadContractData, > = DeepMaybeRef< ReadContractOptions & ConfigParameter > export type UseReadContractReturnType< abi extends Abi | readonly unknown[] = Abi, functionName extends ContractFunctionName< abi, 'pure' | 'view' > = ContractFunctionName, args extends ContractFunctionArgs< abi, 'pure' | 'view', functionName > = ContractFunctionArgs, selectData = ReadContractData, > = UseQueryReturnType /** https://wagmi.sh/vue/api/hooks/useReadContract */ export function useReadContract< const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, const args extends ContractFunctionArgs, config extends Config = ResolvedRegister['config'], selectData = ReadContractData, >( parameters: UseReadContractParameters< abi, functionName, args, config, selectData >, ): UseReadContractReturnType export function useReadContract< const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, const args extends ContractFunctionArgs, config extends Config = ResolvedRegister['config'], selectData = ReadContractData, >( parameters: UseReadContractParametersLoose< abi, functionName, args, config, selectData >, ): UseReadContractReturnType export function useReadContract( parameters: UseReadContractParametersLoose = {}, ): UseReadContractReturnType { const params = computed(() => deepUnref(parameters)) as any const config = useConfig(params) const chainId = useChainId({ config }) const options = computed(() => readContractQueryOptions(config as any, { ...params.value, chainId: params.value.chainId ?? chainId.value, }), ) return useQuery(options as any) as any } ================================================ FILE: packages/vue/src/composables/useReconnect.test-d.ts ================================================ import type { Connector, CreateConnectorFn, ReconnectErrorType, } from '@wagmi/core' import { config } from '@wagmi/test' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' import { useReconnect } from './useReconnect.js' const connectors = [config.connectors[0]!] const contextValue = { foo: 'bar' } as const test('context', () => { const { context, data, error, reconnect, variables } = useReconnect({ mutation: { onMutate(variables) { expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(data).toEqualTypeOf< { accounts: readonly [Address, ...Address[]] chainId: number connector: Connector }[] >() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number connector: Connector }[] | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(data.value).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number connector: Connector }[] | undefined >() expectTypeOf(error.value).toEqualTypeOf() expectTypeOf(variables.value).toEqualTypeOf< | { connectors?: readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(context.value).toEqualTypeOf() reconnect( { connectors }, { onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(data).toEqualTypeOf< { accounts: readonly [Address, ...Address[]] chainId: number connector: Connector }[] >() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number connector: Connector }[] | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf< | { connectors?: | readonly (CreateConnectorFn | Connector)[] | undefined } | undefined >() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/vue/src/composables/useReconnect.test.ts ================================================ import { mock } from '@wagmi/connectors' import { connect, disconnect } from '@wagmi/core' import { accounts, config } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { afterEach, expect, test } from 'vitest' import { useReconnect } from './useReconnect.js' const connector = config._internal.connectors.setup( mock({ accounts, features: { reconnect: true }, }), ) afterEach(async () => { if (config.state.current) await disconnect(config) }) test('default', async () => { await connect(config, { connector }) const [reconnect] = renderComposable(() => useReconnect()) reconnect.mutate() await waitFor(reconnect.isSuccess) expect(reconnect.data.value).toStrictEqual([]) }) test('parameters: connectors (Connector)', async () => { await connect(config, { connector }) const [reconnect] = renderComposable(() => useReconnect()) reconnect.mutate({ connectors: [connector] }) await waitFor(reconnect.isSuccess) expect(reconnect.data.value).toMatchObject( expect.arrayContaining([ expect.objectContaining({ accounts: expect.any(Array), chainId: expect.any(Number), }), ]), ) }) test('parameters: connectors (CreateConnectorFn)', async () => { const connector = mock({ accounts, features: { reconnect: true }, }) await connect(config, { connector }) const [reconnect] = renderComposable(() => useReconnect()) reconnect.mutate({ connectors: [connector] }) await waitFor(reconnect.isSuccess) expect(reconnect.data.value).toMatchObject( expect.arrayContaining([ expect.objectContaining({ accounts: expect.any(Array), chainId: expect.any(Number), }), ]), ) }) test("behavior: doesn't reconnect if already reconnecting", async () => { const previousStatus = config.state.status config.setState((x) => ({ ...x, status: 'reconnecting' })) const [reconnect] = renderComposable(() => useReconnect()) await expect( reconnect.mutateAsync({ connectors: [connector] }), ).resolves.toStrictEqual([]) config.setState((x) => ({ ...x, status: previousStatus })) }) ================================================ FILE: packages/vue/src/composables/useReconnect.ts ================================================ import type { Connector, ReconnectErrorType } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type ReconnectData, type ReconnectMutate, type ReconnectMutateAsync, type ReconnectOptions, type ReconnectVariables, reconnectMutationOptions, } from '@wagmi/core/query' import { type UseMutationReturnType, useMutation } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseReconnectParameters = Compute< ConfigParameter & ReconnectOptions > export type UseReconnectReturnType = Compute< UseMutationReturnType< ReconnectData, ReconnectErrorType, ReconnectVariables, context, ReconnectMutate, ReconnectMutateAsync > & { connectors: readonly Connector[] /** @deprecated use `mutate` instead */ reconnect: ReconnectMutate /** @deprecated use `mutateAsync` instead */ reconnectAsync: ReconnectMutateAsync } > /** https://wagmi.sh/vue/api/composables/useReconnect */ export function useReconnect( parameters: UseReconnectParameters = {}, ): UseReconnectReturnType { const config = useConfig(parameters) const options = reconnectMutationOptions(config, parameters as any) const mutation = useMutation(options) type Return = UseReconnectReturnType return { ...(mutation as Return), connectors: config.connectors, reconnect: mutation.mutate as Return['mutate'], reconnectAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/vue/src/composables/useSendTransaction.test-d.ts ================================================ import type { SendTransactionErrorType } from '@wagmi/core' import type { Hash } from 'viem' import { expectTypeOf, test } from 'vitest' import { useSendTransaction } from './useSendTransaction.js' const contextValue = { foo: 'bar' } as const test('context', () => { const sendTransaction = useSendTransaction({ mutation: { onMutate(variables) { expectTypeOf(variables).toMatchTypeOf< { chainId?: number | undefined } | undefined >() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(sendTransaction.data.value).toEqualTypeOf() expectTypeOf( sendTransaction.error.value, ).toEqualTypeOf() expectTypeOf(sendTransaction.variables.value).toMatchTypeOf< { chainId?: number | undefined } | undefined >() expectTypeOf(sendTransaction.context.value).toEqualTypeOf< typeof contextValue | undefined >() sendTransaction.mutate( { to: '0x' }, { onError(error, variables, context) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/vue/src/composables/useSendTransaction.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { config, transactionHashRegex } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { parseEther } from 'viem' import { expect, test } from 'vitest' import { useSendTransaction } from './useSendTransaction.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const [result] = renderComposable(() => useSendTransaction()) result.mutate({ to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) await waitFor(result.isSuccess) expect(result.data.value).toMatch(transactionHashRegex) await disconnect(config, { connector }) }) ================================================ FILE: packages/vue/src/composables/useSendTransaction.ts ================================================ import { useMutation } from '@tanstack/vue-query' import type { Config, ResolvedRegister, SendTransactionErrorType, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type SendTransactionData, type SendTransactionMutate, type SendTransactionMutateAsync, type SendTransactionOptions, type SendTransactionVariables, sendTransactionMutationOptions, } from '@wagmi/core/query' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseSendTransactionParameters< config extends Config = Config, context = unknown, > = Compute & SendTransactionOptions> export type UseSendTransactionReturnType< config extends Config = Config, context = unknown, > = Compute< UseMutationReturnType< SendTransactionData, SendTransactionErrorType, SendTransactionVariables, context, SendTransactionMutate, SendTransactionMutateAsync > & { /** @deprecated use `mutate` instead */ sendTransaction: SendTransactionMutate /** @deprecated use `mutateAsync` instead */ sendTransactionAsync: SendTransactionMutateAsync } > /** https://wagmi.sh/vue/api/composables/useSendTransaction */ export function useSendTransaction< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: UseSendTransactionParameters = {}, ): UseSendTransactionReturnType { const config = useConfig(parameters) const options = sendTransactionMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseSendTransactionReturnType return { ...(mutation as Return), sendTransaction: mutation.mutate as Return['mutate'], sendTransactionAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/vue/src/composables/useSignMessage.test-d.ts ================================================ import type { SignMessageErrorType } from '@wagmi/core' import type { SignMessageVariables } from '@wagmi/core/query' import { expectTypeOf, test } from 'vitest' import { useSignMessage } from './useSignMessage.js' const message = 'hello world' const contextValue = { foo: 'bar' } as const test('context', () => { const signMessage = useSignMessage({ mutation: { onMutate(variables) { expectTypeOf(variables).toEqualTypeOf() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf() expectTypeOf(data).toEqualTypeOf<`0x${string}`>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf<`0x${string}` | undefined>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(signMessage.data.value).toEqualTypeOf< `0x${string}` | undefined >() expectTypeOf( signMessage.error.value, ).toEqualTypeOf() expectTypeOf(signMessage.variables.value).toEqualTypeOf< SignMessageVariables | undefined >() expectTypeOf(signMessage.context.value).toEqualTypeOf< typeof contextValue | undefined >() signMessage.mutate( { message }, { onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf() expectTypeOf(data).toEqualTypeOf<`0x${string}`>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf<`0x${string}` | undefined>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/vue/src/composables/useSignMessage.test.ts ================================================ import { connect, disconnect, getConnection } from '@wagmi/core' import { config, privateKey } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { recoverMessageAddress } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { expect, test } from 'vitest' import { useSignMessage } from './useSignMessage.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const [result] = renderComposable(() => useSignMessage()) result.mutate({ message: 'foo bar baz' }) await waitFor(result.isSuccess) await expect( recoverMessageAddress({ message: 'foo bar baz', signature: result.data.value!, }), ).resolves.toEqual(getConnection(config).address) await disconnect(config, { connector }) }) test('behavior: local account', async () => { const [result] = renderComposable(() => useSignMessage()) const account = privateKeyToAccount(privateKey) result.mutate({ account, message: 'foo bar baz' }) await waitFor(result.isSuccess) await expect( recoverMessageAddress({ message: 'foo bar baz', signature: result.data.value!, }), ).resolves.toEqual(account.address) }) ================================================ FILE: packages/vue/src/composables/useSignMessage.ts ================================================ import type { SignMessageErrorType } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type SignMessageData, type SignMessageMutate, type SignMessageMutateAsync, type SignMessageOptions, type SignMessageVariables, signMessageMutationOptions, } from '@wagmi/core/query' import { type UseMutationReturnType, useMutation } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseSignMessageParameters = Compute< ConfigParameter & SignMessageOptions > export type UseSignMessageReturnType = Compute< UseMutationReturnType< SignMessageData, SignMessageErrorType, SignMessageVariables, context, SignMessageMutate, SignMessageMutateAsync > & { /** @deprecated use `mutate` instead */ signMessage: SignMessageMutate /** @deprecated use `mutateAsync` instead */ signMessageAsync: SignMessageMutateAsync } > /** https://wagmi.sh/vue/api/composables/useSignMessage */ export function useSignMessage( parameters: UseSignMessageParameters = {}, ): UseSignMessageReturnType { const config = useConfig(parameters) const options = signMessageMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseSignMessageReturnType return { ...(mutation as Return), signMessage: mutation.mutate as Return['mutate'], signMessageAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/vue/src/composables/useSignTransaction.test-d.ts ================================================ import type { SignTransactionErrorType } from '@wagmi/core' import type { Hash, TransactionSerializedEIP1559, TransactionSerializedEIP2930, TransactionSerializedEIP4844, TransactionSerializedEIP7702, TransactionSerializedLegacy, } from 'viem' import { expectTypeOf, test } from 'vitest' import { useSignTransaction } from './useSignTransaction.js' const contextValue = { foo: 'bar' } as const test('context', () => { const signTransaction = useSignTransaction({ mutation: { onMutate(variables) { expectTypeOf(variables).toMatchTypeOf< { chainId?: number | undefined } | undefined >() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(data).toMatchTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toMatchTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(signTransaction.data.value).toMatchTypeOf() expectTypeOf( signTransaction.error.value, ).toEqualTypeOf() expectTypeOf(signTransaction.variables.value).toMatchTypeOf< { chainId?: number | undefined } | undefined >() expectTypeOf(signTransaction.context.value).toEqualTypeOf< typeof contextValue | undefined >() signTransaction.mutate( { to: '0x' }, { onError(error, variables, context) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(data).toMatchTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toMatchTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined }>() expectTypeOf(context).toEqualTypeOf() }, }, ) }) test('legacy', () => { const { mutateAsync } = useSignTransaction() const result1 = mutateAsync({ gasPrice: 0n }) const result2 = mutateAsync({ type: 'legacy' }) expectTypeOf(result1).toEqualTypeOf>() expectTypeOf(result2).toEqualTypeOf>() // @ts-expect-error mutateAsync({ gasPrice: 0n, maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, }) // @ts-expect-error mutateAsync({ gasPrice: 0n, maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, type: 'legacy', }) // @ts-expect-error mutateAsync({ maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, type: 'legacy', }) }) test('eip7702', () => { const { mutateAsync } = useSignTransaction() const result1 = mutateAsync({ authorizationList: [], }) const result2 = mutateAsync({ authorizationList: [], type: 'eip7702', }) expectTypeOf(result1).toEqualTypeOf>() expectTypeOf(result2).toEqualTypeOf>() }) test('eip4844', () => { const { mutateAsync } = useSignTransaction() const result1 = mutateAsync({ blobVersionedHashes: [], maxFeePerBlobGas: 0n, to: '0x0000000000000000000000000000000000000000', }) const result2 = mutateAsync({ blobVersionedHashes: [], maxFeePerBlobGas: 0n, to: '0x0000000000000000000000000000000000000000', type: 'eip4844', }) expectTypeOf(result1).toEqualTypeOf>() expectTypeOf(result2).toEqualTypeOf>() }) test('eip1559', () => { const { mutateAsync } = useSignTransaction() const result1 = mutateAsync({ maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, }) const result2 = mutateAsync({ type: 'eip1559', }) expectTypeOf(result1).toEqualTypeOf>() expectTypeOf(result2).toEqualTypeOf>() // @ts-expect-error mutateAsync({ gasPrice: 0n, maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, }) // @ts-expect-error mutateAsync({ gasPrice: 0n, maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, type: 'eip1559', }) // @ts-expect-error mutateAsync({ gasPrice: 0n, type: 'eip1559', }) }) test('eip2930', () => { const { mutateAsync } = useSignTransaction() const result1 = mutateAsync({ accessList: [], gasPrice: 0n, }) const result2 = mutateAsync({ type: 'eip2930', }) expectTypeOf(result1).toEqualTypeOf>() expectTypeOf(result2).toEqualTypeOf>() // @ts-expect-error mutateAsync({ accessList: [], gasPrice: 0n, maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, }) // @ts-expect-error mutateAsync({ accessList: [], gasPrice: 0n, maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, type: 'eip2930', }) // @ts-expect-error mutateAsync({ accessList: [], maxFeePerGas: 0n, maxPriorityFeePerGas: 0n, type: 'eip2930', }) }) ================================================ FILE: packages/vue/src/composables/useSignTransaction.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { config, signedTransactionRegex } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { parseEther } from 'viem' import { expect, test } from 'vitest' import { useSignTransaction } from './useSignTransaction.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const [result] = renderComposable(() => useSignTransaction()) result.mutate({ to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) await waitFor(result.isSuccess) expect(result.data.value).toMatch(signedTransactionRegex) await disconnect(config, { connector }) }) ================================================ FILE: packages/vue/src/composables/useSignTransaction.ts ================================================ import { useMutation } from '@tanstack/vue-query' import type { Config, ResolvedRegister, SelectChains, SignTransactionErrorType, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type SignTransactionData, type SignTransactionMutate, type SignTransactionMutateAsync, type SignTransactionOptions, type SignTransactionVariables, signTransactionMutationOptions, } from '@wagmi/core/query' import type { SignTransactionRequest as viem_SignTransactionRequest } from 'viem' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseSignTransactionParameters< config extends Config = Config, request extends viem_SignTransactionRequest< SelectChains[0], SelectChains[0] > = viem_SignTransactionRequest< SelectChains[0], SelectChains[0] >, context = unknown, > = Compute< ConfigParameter & SignTransactionOptions< config, config['chains'][number]['id'], request, context > > export type UseSignTransactionReturnType< config extends Config = Config, request extends viem_SignTransactionRequest< SelectChains[0], SelectChains[0] > = viem_SignTransactionRequest< SelectChains[0], SelectChains[0] >, context = unknown, > = Compute< UseMutationReturnType< SignTransactionData, SignTransactionErrorType, SignTransactionVariables, context, SignTransactionMutate, SignTransactionMutateAsync > & { /** @deprecated use `mutate` instead */ signTransaction: SignTransactionMutate /** @deprecated use `mutateAsync` instead */ signTransactionAsync: SignTransactionMutateAsync } > /** https://wagmi.sh/vue/api/composables/useSignTransaction */ export function useSignTransaction< config extends Config = ResolvedRegister['config'], request extends viem_SignTransactionRequest< SelectChains[0], SelectChains[0] > = viem_SignTransactionRequest< SelectChains[0], SelectChains[0] >, context = unknown, >( parameters: UseSignTransactionParameters = {}, ): UseSignTransactionReturnType { const config = useConfig(parameters) const options = signTransactionMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseSignTransactionReturnType return { ...(mutation as unknown as Return), signTransaction: mutation.mutate as Return['mutate'], signTransactionAsync: mutation.mutateAsync as unknown as Return['mutateAsync'], } } ================================================ FILE: packages/vue/src/composables/useSignTypedData.test-d.ts ================================================ import type { SignTypedDataErrorType, SignTypedDataReturnType, } from '@wagmi/core' import type { SignTypedDataVariables } from '@wagmi/core/query' import { typedData } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useSignTypedData } from './useSignTypedData.js' const contextValue = { foo: 'bar' } as const test('context', () => { const signTypedData = useSignTypedData({ mutation: { onMutate(variables) { expectTypeOf(variables).toMatchTypeOf() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toMatchTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toMatchTypeOf() expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(signTypedData.data.value).toEqualTypeOf< SignTypedDataReturnType | undefined >() expectTypeOf( signTypedData.error.value, ).toEqualTypeOf() expectTypeOf(signTypedData.variables.value).toMatchTypeOf< SignTypedDataVariables | undefined >() expectTypeOf(signTypedData.context.value).toEqualTypeOf< typeof contextValue | undefined >() signTypedData.mutate( { types: typedData.basic.types, primaryType: 'Person', message: { name: 'Bob', wallet: '0x', }, }, { onError(error, variables, context) { expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ types: typeof typedData.basic.types primaryType: 'Person' message: { name: string wallet: `0x${string}` } }>() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ types: typeof typedData.basic.types primaryType: 'Person' message: { name: string wallet: `0x${string}` } }>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ types: typeof typedData.basic.types primaryType: 'Person' message: { name: string wallet: `0x${string}` } }>() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/vue/src/composables/useSignTypedData.test.ts ================================================ import { connect, disconnect, getConnection } from '@wagmi/core' import { config, privateKey, typedData } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { recoverTypedDataAddress } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { expect, test } from 'vitest' import { useSignTypedData } from './useSignTypedData.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const [result] = renderComposable(() => useSignTypedData()) result.mutate({ types: typedData.basic.types, primaryType: 'Mail', message: typedData.basic.message, }) await waitFor(result.isSuccess) await expect( recoverTypedDataAddress({ types: typedData.basic.types, primaryType: 'Mail', message: typedData.basic.message, signature: result.data.value!, }), ).resolves.toEqual(getConnection(config).address) await disconnect(config, { connector }) }) test('behavior: local account', async () => { const [result] = renderComposable(() => useSignTypedData()) const account = privateKeyToAccount(privateKey) result.mutate({ account, types: typedData.basic.types, primaryType: 'Mail', message: typedData.basic.message, }) await waitFor(result.isSuccess) await expect( recoverTypedDataAddress({ types: typedData.basic.types, primaryType: 'Mail', message: typedData.basic.message, signature: result.data.value!, }), ).resolves.toEqual(account.address) }) ================================================ FILE: packages/vue/src/composables/useSignTypedData.ts ================================================ import type { SignTypedDataErrorType } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type SignTypedDataData, type SignTypedDataMutate, type SignTypedDataMutateAsync, type SignTypedDataOptions, type SignTypedDataVariables, signTypedDataMutationOptions, } from '@wagmi/core/query' import { type UseMutationReturnType, useMutation } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseSignTypedDataParameters = Compute< ConfigParameter & SignTypedDataOptions > export type UseSignTypedDataReturnType = Compute< UseMutationReturnType< SignTypedDataData, SignTypedDataErrorType, SignTypedDataVariables, context, SignTypedDataMutate, SignTypedDataMutateAsync > & { /** @deprecated use `mutate` instead */ signTypedData: SignTypedDataMutate /** @deprecated use `mutateAsync` instead */ signTypedDataAsync: SignTypedDataMutateAsync } > /** https://wagmi.sh/vue/api/composables/useSignTypedData */ export function useSignTypedData( parameters: UseSignTypedDataParameters = {}, ): UseSignTypedDataReturnType { const config = useConfig(parameters) const options = signTypedDataMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseSignTypedDataReturnType return { ...(mutation as Return), signTypedData: mutation.mutate as Return['mutate'], signTypedDataAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/vue/src/composables/useSimulateContract.test-d.ts ================================================ import { abi, type config } from '@wagmi/test' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' import { type UseSimulateContractReturnType, useSimulateContract, } from './useSimulateContract.js' test('default', () => { const result = useSimulateContract({ address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], }) expectTypeOf(result.data.value).toMatchTypeOf< | { result: boolean request: { chainId?: undefined abi: readonly [ { readonly name: 'transferFrom' readonly type: 'function' readonly stateMutability: 'nonpayable' readonly inputs: readonly [ { readonly type: 'address'; readonly name: 'sender' }, { readonly type: 'address'; readonly name: 'recipient' }, { readonly type: 'uint256'; readonly name: 'amount' }, ] readonly outputs: readonly [{ type: 'bool' }] }, ] functionName: 'transferFrom' args: readonly [Address, Address, bigint] } } | undefined >() }) test('select data', () => { // @ts-ignore TODO: Type instantiation is excessively deep and possibly infinite. const result = useSimulateContract({ address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], chainId: 1, query: { select(data) { expectTypeOf(data.result).toEqualTypeOf() return data.request.args }, }, }) expectTypeOf(result.data.value).toEqualTypeOf< readonly [Address, Address, bigint] | undefined >() }) test('UseSimulateContractReturnType', () => { type Result = UseSimulateContractReturnType< typeof abi.erc20, 'transferFrom', ['0x', '0x', 123n], typeof config, 1 > expectTypeOf().toMatchTypeOf< | { result: boolean request: { chainId: number abi: readonly [ { readonly name: 'transferFrom' readonly type: 'function' readonly stateMutability: 'nonpayable' readonly inputs: readonly [ { readonly type: 'address'; readonly name: 'sender' }, { readonly type: 'address'; readonly name: 'recipient' }, { readonly type: 'uint256'; readonly name: 'amount' }, ] readonly outputs: readonly [{ type: 'bool' }] }, ] functionName: 'approve' | 'transfer' | 'transferFrom' args: readonly [Address, Address, bigint] } } | undefined >() }) ================================================ FILE: packages/vue/src/composables/useSimulateContract.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { abi, address, config, wait } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { useSimulateContract } from './useSimulateContract.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const [result] = renderComposable(() => useSimulateContract({ address: address.wagmiMintExample, abi: abi.wagmiMintExample, functionName: 'mint', }), ) await waitFor(result.isSuccess) expect(result.data.value).toMatchInlineSnapshot(` { "chainId": 1, "request": { "abi": [ { "inputs": [], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function", }, ], "account": { "address": "0x95132632579b073D12a6673e18Ab05777a6B86f8", "type": "json-rpc", }, "address": "0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2", "args": undefined, "chainId": 1, "dataSuffix": undefined, "functionName": "mint", }, "result": undefined, } `) await disconnect(config, { connector }) }) test('behavior: disabled when properties missing', async () => { const [result] = renderComposable(() => useSimulateContract()) await wait(100) expect(result.fetchStatus.value).toBe('idle') }) ================================================ FILE: packages/vue/src/composables/useSimulateContract.ts ================================================ import type { Config, ResolvedRegister, SimulateContractErrorType, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { type SimulateContractData, type SimulateContractOptions, simulateContractQueryOptions, } from '@wagmi/core/query' import type { Abi, ContractFunctionArgs, ContractFunctionName } from 'viem' import { computed, type MaybeRef } from 'vue' import { deepUnref } from '../utils/cloneDeep.js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' import { useConnection } from './useConnection.js' export type UseSimulateContractParameters< abi extends Abi | readonly unknown[] = Abi, functionName extends ContractFunctionName< abi, 'nonpayable' | 'payable' > = ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName > = ContractFunctionArgs, config extends Config = Config, chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = SimulateContractData, > = MaybeRef< SimulateContractOptions< abi, functionName, args, config, chainId, selectData > & ConfigParameter > export type UseSimulateContractReturnType< abi extends Abi | readonly unknown[] = Abi, functionName extends ContractFunctionName< abi, 'nonpayable' | 'payable' > = ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName > = ContractFunctionArgs, config extends Config = Config, chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = SimulateContractData, > = UseQueryReturnType /** https://wagmi.sh/vue/api/composables/useSimulateContract */ export function useSimulateContract< const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName, args extends ContractFunctionArgs< abi, 'nonpayable' | 'payable', functionName >, config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] | undefined = undefined, selectData = SimulateContractData, >( parameters: UseSimulateContractParameters< abi, functionName, args, config, chainId, selectData > = {} as any, ): UseSimulateContractReturnType< abi, functionName, args, config, chainId, selectData > { const params = computed(() => deepUnref(parameters)) as any const config = useConfig(params) const { address, connector } = useConnection() const chainId = useChainId({ config }) const options = computed(() => simulateContractQueryOptions(config as any, { ...params.value, account: params.value.account ?? address.value, chainId: params.value.chainId ?? chainId.value, connector: params.value.connector ?? connector.value, }), ) return useQuery(options as any) as any } ================================================ FILE: packages/vue/src/composables/useSwitchChain.test-d.ts ================================================ import type { Connector, SwitchChainErrorType } from '@wagmi/core' import type { Chain } from '@wagmi/core/chains' import type { Compute, ExactPartial } from '@wagmi/core/internal' import { chain } from '@wagmi/test' import type { AddEthereumChainParameter } from 'viem' import { expectTypeOf, test } from 'vitest' import { useSwitchChain } from './useSwitchChain.js' const chainId = chain.mainnet.id const contextValue = { foo: 'bar' } as const test('context', () => { const switchChain = useSwitchChain({ mutation: { onMutate(variables) { expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() expectTypeOf(data).toEqualTypeOf>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf | undefined>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(switchChain.data.value).toEqualTypeOf< Compute | undefined >() expectTypeOf( switchChain.error.value, ).toEqualTypeOf() expectTypeOf(switchChain.variables.value).toEqualTypeOf< | { addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined } | undefined >() expectTypeOf(switchChain.context.value).toEqualTypeOf< typeof contextValue | undefined >() switchChain.mutate( { chainId }, { onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() expectTypeOf(data).toEqualTypeOf>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf | undefined>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf<{ addEthereumChainParameter?: | ExactPartial> | undefined chainId: number connector?: Connector | undefined }>() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/vue/src/composables/useSwitchChain.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { chain, config } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { useConnection } from './useConnection.js' import { useSwitchChain } from './useSwitchChain.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const [connection] = renderComposable(() => useConnection()) const [switchChain] = renderComposable(() => useSwitchChain()) const chainId1 = connection.chainId.value expect(chainId1).toBeDefined() switchChain.mutate({ chainId: chain.mainnet2.id }) await waitFor(switchChain.isSuccess) const chainId2 = connection.chainId.value expect(chainId2).toBeDefined() expect(chainId1).not.toBe(chainId2) switchChain.mutate({ chainId: chain.mainnet.id }) await waitFor(switchChain.isSuccess) const chainId3 = connection.chainId.value expect(chainId3).toBeDefined() expect(chainId1).toBe(chainId3) await disconnect(config, { connector }) }) ================================================ FILE: packages/vue/src/composables/useSwitchChain.ts ================================================ import type { Config, ResolvedRegister, SwitchChainErrorType, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type SwitchChainData, type SwitchChainMutate, type SwitchChainMutateAsync, type SwitchChainOptions, type SwitchChainVariables, switchChainMutationOptions, } from '@wagmi/core/query' import type { Ref } from 'vue' import { type UseMutationReturnType, useMutation } from '../utils/query.js' import { useChains } from './useChains.js' import { useConfig } from './useConfig.js' export type UseSwitchChainParameters< config extends Config = Config, context = unknown, > = Compute & SwitchChainOptions> export type UseSwitchChainReturnType< config extends Config = Config, context = unknown, > = Compute< UseMutationReturnType< SwitchChainData, SwitchChainErrorType, SwitchChainVariables, context, SwitchChainMutate, SwitchChainMutateAsync > & { /** @deprecated use `useChains` instead */ chains: Ref /** @deprecated use `mutate` instead */ switchChain: SwitchChainMutate /** @deprecated use `mutateAsync` instead */ switchChainAsync: SwitchChainMutateAsync } > /** https://wagmi.sh/vue/api/composables/useSwitchChain */ export function useSwitchChain< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: UseSwitchChainParameters = {}, ): UseSwitchChainReturnType { const config = useConfig(parameters) const options = switchChainMutationOptions(config, parameters as any) const mutation = useMutation(options) type Return = UseSwitchChainReturnType return { ...(mutation as unknown as Return), chains: useChains({ config }) as unknown as Ref, switchChain: mutation.mutate as Return['mutate'], switchChainAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/vue/src/composables/useSwitchConnection.test-d.ts ================================================ import type { Connector, SwitchAccountErrorType } from '@wagmi/core' import { config } from '@wagmi/test' import type { Address } from 'viem' import { expectTypeOf, test } from 'vitest' import { useSwitchConnection } from './useSwitchConnection.js' const connector = config.connectors[0]! const contextValue = { foo: 'bar' } as const test('context', () => { const { context, data, error, switchConnection, variables } = useSwitchConnection({ mutation: { onMutate(variables) { expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() return contextValue }, onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() expectTypeOf(data).toEqualTypeOf<{ accounts: readonly [Address, ...Address[]] chainId: number }>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() expectTypeOf(context).toEqualTypeOf() }, }, }) expectTypeOf(data.value).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number } | undefined >() expectTypeOf(error.value).toEqualTypeOf() expectTypeOf(variables.value).toEqualTypeOf< { connector: Connector } | undefined >() expectTypeOf(context.value).toEqualTypeOf() switchConnection( { connector }, { onError(error, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() }, onSuccess(data, variables, context) { expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() expectTypeOf(data).toEqualTypeOf<{ accounts: readonly [Address, ...Address[]] chainId: number }>() expectTypeOf(context).toEqualTypeOf() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf< | { accounts: readonly [Address, ...Address[]] chainId: number } | undefined >() expectTypeOf(error).toEqualTypeOf() expectTypeOf(variables).toEqualTypeOf<{ connector: Connector }>() expectTypeOf(context).toEqualTypeOf() }, }, ) }) ================================================ FILE: packages/vue/src/composables/useSwitchConnection.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { config } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { useConnection } from './useConnection.js' import { useConnections } from './useConnections.js' import { useSwitchConnection } from './useSwitchConnection.js' const connector1 = config.connectors[0]! const connector2 = config.connectors[1]! test('default', async () => { const [connection] = renderComposable(() => useConnection()) const [switchConnection] = renderComposable(() => useSwitchConnection()) const [connections] = renderComposable(() => useConnections()) expect(connections.value).toEqual([]) await connect(config, { connector: connector2 }) await connect(config, { connector: connector1 }) expect(connections.value.length).toEqual(2) const address1 = connection.address.value expect(address1).toBeDefined() switchConnection.mutate({ connector: connector2 }) await waitFor(switchConnection.isSuccess) const address2 = connection.address.value expect(address2).toBeDefined() expect(address1).not.toBe(address2) switchConnection.mutate({ connector: connector1 }) await waitFor(switchConnection.isSuccess) const address3 = connection.address.value expect(address3).toBeDefined() expect(address1).toBe(address3) await disconnect(config, { connector: connector1 }) await disconnect(config, { connector: connector2 }) }) ================================================ FILE: packages/vue/src/composables/useSwitchConnection.ts ================================================ import type { Config, Connector, ResolvedRegister, SwitchConnectionErrorType, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type SwitchConnectionData, type SwitchConnectionMutate, type SwitchConnectionMutateAsync, type SwitchConnectionOptions, type SwitchConnectionVariables, switchConnectionMutationOptions, } from '@wagmi/core/query' import { computed, type Ref } from 'vue' import { type UseMutationReturnType, useMutation } from '../utils/query.js' import { useConfig } from './useConfig.js' import { useConnections } from './useConnections.js' export type UseSwitchConnectionParameters< config extends Config = Config, context = unknown, > = Compute & SwitchConnectionOptions> export type UseSwitchConnectionReturnType< config extends Config = Config, context = unknown, > = Compute< UseMutationReturnType< SwitchConnectionData, SwitchConnectionErrorType, SwitchConnectionVariables, context, SwitchConnectionMutate, SwitchConnectionMutateAsync > & { /** @deprecated use `useConnections` instead */ connectors: Ref /** @deprecated use `switchConnection` instead */ switchAccount: SwitchConnectionMutate /** @deprecated use `switchConnectionAsync` instead */ switchAccountAsync: SwitchConnectionMutateAsync /** @deprecated use `mutate` instead */ switchConnection: SwitchConnectionMutate /** @deprecated use `mutateAsync` instead */ switchConnectionAsync: SwitchConnectionMutateAsync } > /** https://wagmi.sh/vue/api/composables/useSwitchConnection */ export function useSwitchConnection< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: UseSwitchConnectionParameters = {}, ): UseSwitchConnectionReturnType { const config = useConfig(parameters) const connections = useConnections({ config }) const options = switchConnectionMutationOptions(config, parameters as any) const mutation = useMutation(options) type Return = UseSwitchConnectionReturnType return { ...(mutation as Return), connectors: computed(() => connections.value.map((connection) => connection.connector), ), switchAccount: mutation.mutate as Return['mutate'], switchAccountAsync: mutation.mutateAsync as Return['mutateAsync'], switchConnection: mutation.mutate as Return['mutate'], switchConnectionAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/vue/src/composables/useTransaction.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useTransaction } from './useTransaction.js' test('select data', () => { const result = useTransaction({ query: { select(data) { return data?.nonce }, }, }) expectTypeOf(result.data.value).toEqualTypeOf() }) ================================================ FILE: packages/vue/src/composables/useTransaction.test.ts ================================================ import { renderComposable, waitFor } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { deepUnref } from '../utils/cloneDeep.js' import { useTransaction } from './useTransaction.js' test('default', async () => { const [result] = renderComposable(() => useTransaction({ hash: '0x60668ed8c2dc110d61d945a936fcd45b8f13654e5c78481c8c825d1148c7ef30', }), ) await waitFor(result.isSuccess) expect(deepUnref(result)).toMatchInlineSnapshot(` { "data": { "accessList": [], "blockHash": "0xd725a38b51e5ceec8c5f6c9ccfdb2cc423af993bb650af5eedca5e4be7156ba7", "blockNumber": 15189204n, "chainId": 1, "from": "0xa0cf798816d4b9b9866b5330eea46a18382f251e", "gas": 21000n, "gasPrice": 9371645552n, "hash": "0x60668ed8c2dc110d61d945a936fcd45b8f13654e5c78481c8c825d1148c7ef30", "input": "0x", "maxFeePerGas": 13644824566n, "maxPriorityFeePerGas": 1500000000n, "nonce": 86, "r": "0x40174f9a38df876c1a7ce2587848819d4082ccd6d67a88aa5cabe59bf594e14f", "s": "0x7c0c82f62a8a5a9b0e9cf30a54a72fdae8fc54b5b79ddafef0acd30e94e83872", "to": "0xd2135cfb216b74109775236e36d4b433f1df507b", "transactionIndex": 144, "type": "eip1559", "typeHex": "0x2", "v": 0n, "value": 100000000000000000n, "yParity": 0, }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "transaction", { "chainId": 1, "hash": "0x60668ed8c2dc110d61d945a936fcd45b8f13654e5c78481c8c825d1148c7ef30", }, ], "refetch": [Function], "status": "success", "suspense": [Function], } `) }) ================================================ FILE: packages/vue/src/composables/useTransaction.ts ================================================ import type { Config, GetTransactionErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetTransactionData, type GetTransactionOptions, getTransactionQueryOptions, } from '@wagmi/core/query' import { computed } from 'vue' import type { DeepMaybeRef } from '../types/ref.js' import { deepUnref } from '../utils/cloneDeep.js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseTransactionParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetTransactionData, > = Compute< DeepMaybeRef< GetTransactionOptions & ConfigParameter > > export type UseTransactionReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetTransactionData, > = UseQueryReturnType /** https://wagmi.sh/vue/api/composables/useTransaction */ export function useTransaction< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetTransactionData, >( parameters: UseTransactionParameters = {}, ): UseTransactionReturnType { const params = computed(() => deepUnref(parameters)) const config = useConfig(params) const chainId = useChainId({ config }) const options = computed(() => getTransactionQueryOptions(config as any, { ...(params.value as any), chainId: params.value.chainId ?? chainId.value, }), ) return useQuery(options as any) as any } ================================================ FILE: packages/vue/src/composables/useTransactionReceipt.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useTransactionReceipt } from './useTransactionReceipt.js' test('select data', () => { const result = useTransactionReceipt({ query: { select(data) { return data?.blockNumber }, }, }) expectTypeOf(result.data.value).toEqualTypeOf() }) ================================================ FILE: packages/vue/src/composables/useTransactionReceipt.test.ts ================================================ import { chain, wait } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { ref } from 'vue' import { deepUnref } from '../utils/cloneDeep.js' import { useTransactionReceipt } from './useTransactionReceipt.js' test('default', async () => { const [result] = renderComposable(() => useTransactionReceipt({ hash: '0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871', }), ) await waitFor(result.isSuccess) expect(deepUnref(result)).toMatchInlineSnapshot(` { "data": { "blockHash": "0xb932f77cf770d1d1c8f861153eec1e990f5d56b6ffdb4ac06aef3cca51ef37d4", "blockNumber": 16280769n, "contractAddress": null, "cumulativeGasUsed": 21000n, "effectiveGasPrice": 33427926161n, "from": "0x043022ef9fca1066024d19d681e2ccf44ff90de3", "gasUsed": 21000n, "logs": [], "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "status": "success", "to": "0x318a5fb4f1604fc46375a1db9a9018b6e423b345", "transactionHash": "0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871", "transactionIndex": 0, "type": "legacy", }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getTransactionReceipt", { "chainId": 1, "hash": "0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871", }, ], "refetch": [Function], "status": "success", "suspense": [Function], } `) }) test('parameters: chainId', async () => { const [result] = renderComposable(() => useTransactionReceipt({ chainId: chain.mainnet2.id, hash: '0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871', }), ) await waitFor(result.isSuccess) expect(deepUnref(result)).toMatchInlineSnapshot(` { "data": { "blockHash": "0xb932f77cf770d1d1c8f861153eec1e990f5d56b6ffdb4ac06aef3cca51ef37d4", "blockNumber": 16280769n, "contractAddress": null, "cumulativeGasUsed": 21000n, "effectiveGasPrice": 33427926161n, "from": "0x043022ef9fca1066024d19d681e2ccf44ff90de3", "gasUsed": 21000n, "logs": [], "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "status": "success", "to": "0x318a5fb4f1604fc46375a1db9a9018b6e423b345", "transactionHash": "0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871", "transactionIndex": 0, "type": "legacy", }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getTransactionReceipt", { "chainId": 456, "hash": "0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871", }, ], "refetch": [Function], "status": "success", "suspense": [Function], } `) }) test('behavior: hash: undefined -> defined', async () => { const hash = ref() const [result] = renderComposable(() => useTransactionReceipt({ hash, }), ) await wait(100) expect(result.fetchStatus.value).toBe('idle') hash.value = '0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871' await waitFor(result.isSuccess) expect(deepUnref(result)).toMatchInlineSnapshot(` { "data": { "blockHash": "0xb932f77cf770d1d1c8f861153eec1e990f5d56b6ffdb4ac06aef3cca51ef37d4", "blockNumber": 16280769n, "contractAddress": null, "cumulativeGasUsed": 21000n, "effectiveGasPrice": 33427926161n, "from": "0x043022ef9fca1066024d19d681e2ccf44ff90de3", "gasUsed": 21000n, "logs": [], "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "status": "success", "to": "0x318a5fb4f1604fc46375a1db9a9018b6e423b345", "transactionHash": "0xbf7d27700d053765c9638d3b9d39eb3c56bfc48377583e8be483d61f9f18a871", "transactionIndex": 0, "type": "legacy", }, "dataUpdatedAt": 1675209600000, "error": null, "errorUpdateCount": 0, "errorUpdatedAt": 0, "failureCount": 0, "failureReason": null, "fetchStatus": "idle", "isError": false, "isFetched": true, "isFetchedAfterMount": true, "isFetching": false, "isInitialLoading": false, "isLoading": false, "isLoadingError": false, "isPaused": false, "isPending": false, "isPlaceholderData": false, "isRefetchError": false, "isRefetching": false, "isStale": true, "isSuccess": true, "queryKey": [ "getTransactionReceipt", { "chainId": 1, "hash": undefined, }, ], "refetch": [Function], "status": "success", "suspense": [Function], } `) }) test('behavior: disabled when properties missing', async () => { const [result] = renderComposable(() => useTransactionReceipt()) await wait(100) expect(result.fetchStatus.value).toBe('idle') }) ================================================ FILE: packages/vue/src/composables/useTransactionReceipt.ts ================================================ import type { Config, GetTransactionReceiptErrorType, ResolvedRegister, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type GetTransactionReceiptData, type GetTransactionReceiptOptions, getTransactionReceiptQueryOptions, } from '@wagmi/core/query' import { computed } from 'vue' import type { DeepMaybeRef } from '../types/ref.js' import { deepUnref } from '../utils/cloneDeep.js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseTransactionReceiptParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetTransactionReceiptData, > = Compute< DeepMaybeRef< GetTransactionReceiptOptions & ConfigParameter > > export type UseTransactionReceiptReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetTransactionReceiptData, > = UseQueryReturnType /** https://wagmi.sh/vue/api/composables/useTransactionReceipt */ export function useTransactionReceipt< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = GetTransactionReceiptData, >( parameters: UseTransactionReceiptParameters = {}, ): UseTransactionReceiptReturnType { const params = computed(() => deepUnref(parameters)) const config = useConfig(params) const chainId = useChainId({ config }) const options = computed(() => getTransactionReceiptQueryOptions(config as any, { ...(params.value as any), chainId: params.value.chainId ?? chainId.value, }), ) return useQuery(options as any) as any } ================================================ FILE: packages/vue/src/composables/useWaitForTransactionReceipt.test-d.ts ================================================ import { expectTypeOf, test } from 'vitest' import { useWaitForTransactionReceipt } from './useWaitForTransactionReceipt.js' test('select data', () => { const result = useWaitForTransactionReceipt({ query: { select(data) { return data?.blockNumber }, }, }) expectTypeOf(result.data.value).toEqualTypeOf() }) ================================================ FILE: packages/vue/src/composables/useWaitForTransactionReceipt.test.ts ================================================ import { renderComposable, waitFor } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { wait } from '../../../test/src/utils.js' import { useWaitForTransactionReceipt } from './useWaitForTransactionReceipt.js' test('default', async () => { const [result] = renderComposable(() => useWaitForTransactionReceipt({ hash: '0x60668ed8c2dc110d61d945a936fcd45b8f13654e5c78481c8c825d1148c7ef30', }), ) await waitFor(result.isSuccess) expect(result.data.value).toMatchInlineSnapshot(` { "blockHash": "0xd725a38b51e5ceec8c5f6c9ccfdb2cc423af993bb650af5eedca5e4be7156ba7", "blockNumber": 15189204n, "chainId": 1, "contractAddress": null, "cumulativeGasUsed": 12949744n, "effectiveGasPrice": 9371645552n, "from": "0xa0cf798816d4b9b9866b5330eea46a18382f251e", "gasUsed": 21000n, "logs": [], "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "status": "success", "to": "0xd2135cfb216b74109775236e36d4b433f1df507b", "transactionHash": "0x60668ed8c2dc110d61d945a936fcd45b8f13654e5c78481c8c825d1148c7ef30", "transactionIndex": 144, "type": "eip1559", } `) }) test('disabled when hash is undefined', async () => { const [result] = renderComposable(() => useWaitForTransactionReceipt({ hash: undefined, }), ) await wait(100) expect(result.isPending.value).toBe(true) }) ================================================ FILE: packages/vue/src/composables/useWaitForTransactionReceipt.ts ================================================ import type { Config, ResolvedRegister, WaitForTransactionReceiptErrorType, } from '@wagmi/core' import type { Compute, ConfigParameter } from '@wagmi/core/internal' import { type WaitForTransactionReceiptData, type WaitForTransactionReceiptOptions, waitForTransactionReceiptQueryOptions, } from '@wagmi/core/query' import { computed } from 'vue' import type { DeepMaybeRef } from '../types/ref.js' import { deepUnref } from '../utils/cloneDeep.js' import { type UseQueryReturnType, useQuery } from '../utils/query.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseWaitForTransactionReceiptParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = WaitForTransactionReceiptData, > = Compute< DeepMaybeRef< WaitForTransactionReceiptOptions & ConfigParameter > > export type UseWaitForTransactionReceiptReturnType< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = WaitForTransactionReceiptData, > = UseQueryReturnType /** https://wagmi.sh/vue/api/composables/useWaitForTransactionReceipt */ export function useWaitForTransactionReceipt< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], selectData = WaitForTransactionReceiptData, >( parameters: UseWaitForTransactionReceiptParameters< config, chainId, selectData > = {}, ): UseWaitForTransactionReceiptReturnType { const params = computed(() => deepUnref(parameters)) const config = useConfig(params) const chainId = useChainId({ config }) const options = computed(() => waitForTransactionReceiptQueryOptions(config as any, { ...(params.value as any), chainId: params.value.chainId ?? chainId.value, }), ) return useQuery(options as any) as any } ================================================ FILE: packages/vue/src/composables/useWatchBlockNumber.test-d.ts ================================================ import { createConfig } from '@wagmi/core' import { http, webSocket } from 'viem' import { mainnet, optimism } from 'viem/chains' import { expectTypeOf, test } from 'vitest' import type { DeepUnwrapRef } from '../types/ref.js' import { type UseWatchBlockNumberParameters, useWatchBlockNumber, } from './useWatchBlockNumber.js' test('default', () => { useWatchBlockNumber({ poll: false, onBlockNumber() {}, }) }) test('differing transports', () => { const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: webSocket(), }, }) type Result = DeepUnwrapRef< UseWatchBlockNumberParameters< typeof config, typeof mainnet.id | typeof optimism.id > > expectTypeOf().toEqualTypeOf() useWatchBlockNumber({ config, poll: false, onBlockNumber() {}, }) type Result2 = DeepUnwrapRef< UseWatchBlockNumberParameters > expectTypeOf().toEqualTypeOf() useWatchBlockNumber({ config, chainId: mainnet.id, poll: true, onBlockNumber() {}, }) useWatchBlockNumber({ config, chainId: mainnet.id, // @ts-expect-error poll: false, onBlockNumber() {}, }) type Result3 = DeepUnwrapRef< UseWatchBlockNumberParameters > expectTypeOf().toEqualTypeOf() useWatchBlockNumber({ config, chainId: optimism.id, poll: true, onBlockNumber() {}, }) useWatchBlockNumber({ config, chainId: optimism.id, poll: false, onBlockNumber() {}, }) }) ================================================ FILE: packages/vue/src/composables/useWatchBlockNumber.test.ts ================================================ import { testClient, wait } from '@wagmi/test' import { renderComposable } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { ref } from 'vue' import { useWatchBlockNumber } from './useWatchBlockNumber.js' test('default', async () => { const blockNumbers: bigint[] = [] renderComposable(() => useWatchBlockNumber({ onBlockNumber(blockNumber) { blockNumbers.push(blockNumber) }, }), ) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) expect(blockNumbers.length).toBe(3) expect( blockNumbers.map((blockNumber) => blockNumber - blockNumbers[0]!), ).toEqual([0n, 1n, 2n]) await wait(500) }) test('parameters: enabled', async () => { const enabled = ref(true) const blockNumbers: bigint[] = [] renderComposable(() => useWatchBlockNumber({ enabled, onBlockNumber(blockNumber) { blockNumbers.push(blockNumber) }, }), ) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) expect(blockNumbers.length).toBe(3) expect( blockNumbers.map((blockNumber) => blockNumber - blockNumbers[0]!), ).toEqual([0n, 1n, 2n]) enabled.value = false await testClient.mainnet.mine({ blocks: 1 }) await wait(100) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) expect( blockNumbers.map((blockNumber) => blockNumber - blockNumbers[0]!), ).toEqual([0n, 1n, 2n]) await wait(500) }) ================================================ FILE: packages/vue/src/composables/useWatchBlockNumber.ts ================================================ import { type Config, type ResolvedRegister, type WatchBlockNumberParameters, watchBlockNumber, } from '@wagmi/core' import type { ConfigParameter, UnionCompute, UnionExactPartial, } from '@wagmi/core/internal' import { computed, watchEffect } from 'vue' import type { EnabledParameter } from '../types/properties.js' import type { DeepMaybeRef } from '../types/ref.js' import { deepUnref } from '../utils/cloneDeep.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseWatchBlockNumberParameters< config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = DeepMaybeRef< UnionCompute< UnionExactPartial> & ConfigParameter & EnabledParameter > > export type UseWatchBlockNumberReturnType = void /** https://wagmi.sh/vue/api/composables/useWatchBlockNumber */ export function useWatchBlockNumber< config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], >( parameters_: UseWatchBlockNumberParameters = {} as any, ): UseWatchBlockNumberReturnType { const parameters = computed(() => deepUnref(parameters_)) const config = useConfig(parameters) const configChainId = useChainId({ config }) watchEffect((onCleanup) => { const { chainId = configChainId.value, enabled = true, onBlockNumber, config: _, ...rest } = parameters.value if (!enabled) return if (!onBlockNumber) return const unwatch = watchBlockNumber(config, { ...(rest as any), chainId, onBlockNumber, emitOnBegin: true, }) onCleanup(unwatch) }) } ================================================ FILE: packages/vue/src/composables/useWatchContractEvent.test-d.ts ================================================ import { createConfig, http, webSocket } from '@wagmi/core' import { mainnet, optimism } from '@wagmi/core/chains' import { abi } from '@wagmi/test' import { expectTypeOf, test } from 'vitest' import { useWatchContractEvent } from './useWatchContractEvent.js' test('default', () => { useWatchContractEvent({ address: '0x', abi: abi.erc20, eventName: 'Transfer', poll: false, args: { from: '0x', to: '0x', }, onLogs(logs) { expectTypeOf(logs[0]!.eventName).toEqualTypeOf<'Transfer'>() expectTypeOf(logs[0]!.args).toEqualTypeOf<{ from?: `0x${string}` | undefined to?: `0x${string}` | undefined value?: bigint | undefined }>() }, }) }) test('behavior: no eventName', () => { useWatchContractEvent({ address: '0x', abi: abi.erc20, args: { // TODO: Figure out why this is not working // @ts-ignore from: '0x', to: '0x', }, onLogs(logs) { expectTypeOf(logs[0]!.eventName).toEqualTypeOf<'Transfer' | 'Approval'>() expectTypeOf(logs[0]!.args).toEqualTypeOf< | { from?: `0x${string}` | undefined to?: `0x${string}` | undefined value?: bigint | undefined } | { owner?: `0x${string}` | undefined spender?: `0x${string}` | undefined value?: bigint | undefined } >() }, }) }) test('differing transports', () => { const config = createConfig({ chains: [mainnet, optimism], transports: { [mainnet.id]: http(), [optimism.id]: webSocket(), }, }) // TODO: Fix inference for `poll` (`DeepMaybeRef` wrapping `UseWatchContractEventParameters` not working as expected) // type Result = UseWatchContractEventParameters< // typeof abi.erc20, // 'Transfer' | 'Approval', // true, // typeof config, // typeof mainnet.id | typeof optimism.id // > // expectTypeOf().toEqualTypeOf() useWatchContractEvent({ config, poll: false, address: '0x', abi: abi.erc20, onLogs() {}, }) // type Result2 = UseWatchContractEventParameters< // typeof abi.erc20, // 'Transfer' | 'Approval', // true, // typeof config, // typeof mainnet.id // > // expectTypeOf().toEqualTypeOf() useWatchContractEvent({ config, chainId: mainnet.id, poll: true, address: '0x', abi: abi.erc20, onLogs() {}, }) // type Result3 = UseWatchContractEventParameters< // typeof abi.erc20, // 'Transfer' | 'Approval', // true, // typeof config, // typeof optimism.id // > // expectTypeOf().toEqualTypeOf() useWatchContractEvent({ config, chainId: optimism.id, poll: true, address: '0x', abi: abi.erc20, onLogs() {}, }) useWatchContractEvent({ config, chainId: optimism.id, poll: false, address: '0x', abi: abi.erc20, onLogs() {}, }) }) ================================================ FILE: packages/vue/src/composables/useWatchContractEvent.test.ts ================================================ import { connect, disconnect, readContract, writeContract } from '@wagmi/core' import { abi, accounts, address, config, testClient, transactionHashRegex, wait, } from '@wagmi/test' import { renderComposable } from '@wagmi/test/vue' import { createWalletClient, erc20Abi, http, parseEther } from 'viem' import type { WatchEventOnLogsParameter } from 'viem/actions' import { expect, test } from 'vitest' import { ref } from 'vue' import { useWatchContractEvent } from './useWatchContractEvent.js' const connector = config.connectors[0]! test('default', async () => { const data = await connect(config, { connector }) const connectedAddress = data.accounts[0] // impersonate usdc holder account and transfer usdc to connected account await testClient.mainnet.impersonateAccount({ address: address.usdcHolder }) await testClient.mainnet.setBalance({ address: address.usdcHolder, value: 10000000000000000000000n, }) await createWalletClient({ account: address.usdcHolder, chain: testClient.mainnet.chain, transport: http(), }).writeContract({ address: address.usdc, abi: abi.erc20, functionName: 'transfer', args: [connectedAddress, parseEther('10', 'gwei')], }) await testClient.mainnet.mine({ blocks: 1 }) await testClient.mainnet.stopImpersonatingAccount({ address: address.usdcHolder, }) const balance = await readContract(config, { abi: erc20Abi, address: address.usdc, functionName: 'balanceOf', args: [connectedAddress], }) expect(balance).toBeGreaterThan(0n) // start watching transfer events let logs: WatchEventOnLogsParameter = [] renderComposable(() => useWatchContractEvent({ address: address.usdc, abi: abi.erc20, eventName: 'Transfer', onLogs(next) { logs = logs.concat(next) }, }), ) await writeContract(config, { address: address.usdc, abi: abi.erc20, functionName: 'transfer', args: [accounts[1], parseEther('1', 'gwei')], }) await writeContract(config, { address: address.usdc, abi: abi.erc20, functionName: 'transfer', args: [accounts[3], parseEther('1', 'gwei')], }) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) await testClient.mainnet.mine({ blocks: 1 }) await wait(100) expect(logs.length).toBe(2) expect(logs[0]?.transactionHash).toMatch(transactionHashRegex) await disconnect(config, { connector }) await wait(500) }) test('parameters: enabled', async () => { const enabled = ref(true) renderComposable(() => useWatchContractEvent({ address: address.usdc, abi: abi.erc20, eventName: 'Transfer', }), ) renderComposable(() => useWatchContractEvent({ enabled, }), ) await wait(500) }) ================================================ FILE: packages/vue/src/composables/useWatchContractEvent.ts ================================================ import { type Config, type ResolvedRegister, type WatchContractEventParameters, watchContractEvent, } from '@wagmi/core' import type { ConfigParameter, UnionCompute, UnionExactPartial, } from '@wagmi/core/internal' import type { Abi, ContractEventName } from 'viem' import { computed, watchEffect } from 'vue' import type { EnabledParameter } from '../types/properties.js' import type { DeepMaybeRef } from '../types/ref.js' import { deepUnref } from '../utils/cloneDeep.js' import { useChainId } from './useChainId.js' import { useConfig } from './useConfig.js' export type UseWatchContractEventParameters< abi extends Abi | readonly unknown[] = Abi, eventName extends ContractEventName = ContractEventName, strict extends boolean | undefined = undefined, config extends Config = Config, chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], > = DeepMaybeRef< UnionCompute< UnionExactPartial< WatchContractEventParameters > & ConfigParameter & EnabledParameter > > export type UseWatchContractEventReturnType = void /** https://wagmi.sh/vue/api/composables/useWatchContractEvent */ export function useWatchContractEvent< const abi extends Abi | readonly unknown[], eventName extends ContractEventName, strict extends boolean | undefined = undefined, config extends Config = ResolvedRegister['config'], chainId extends config['chains'][number]['id'] = config['chains'][number]['id'], >( parameters: UseWatchContractEventParameters< abi, eventName, strict, config, chainId > = {} as any, ): UseWatchContractEventReturnType { const parameters_ = computed(() => deepUnref(parameters)) const config = useConfig(parameters_) const configChainId = useChainId({ config }) watchEffect((onCleanup) => { const { chainId = configChainId.value, enabled = true, onLogs, config: _, ...rest } = parameters_.value if (!enabled) return if (!onLogs) return const unwatch = watchContractEvent(config, { ...(rest as any), chainId, onLogs, }) onCleanup(unwatch) }) } ================================================ FILE: packages/vue/src/composables/useWriteContract.test-d.ts ================================================ import type { WriteContractErrorType } from '@wagmi/core' import { abi } from '@wagmi/test' import type { Abi, Address, Hash } from 'viem' import { expectTypeOf, test } from 'vitest' import { useSimulateContract } from './useSimulateContract.js' import { useWriteContract } from './useWriteContract.js' const contextValue = { foo: 'bar' } as const test('context', () => { const writeContract = useWriteContract({ mutation: { onMutate(variables) { expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: Abi functionName: string args?: readonly unknown[] | undefined }>() return contextValue }, onError(error, variables, context) { expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: Abi functionName: string args?: readonly unknown[] | undefined }>() }, onSuccess(data, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: Abi functionName: string args?: readonly unknown[] | undefined }>() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: Abi functionName: string args?: readonly unknown[] | undefined }>() }, }, }) expectTypeOf(writeContract.data.value).toEqualTypeOf() expectTypeOf( writeContract.error.value, ).toEqualTypeOf() expectTypeOf(writeContract.variables.value).toMatchTypeOf< { chainId?: number | undefined } | undefined >() expectTypeOf(writeContract.context.value).toEqualTypeOf< typeof contextValue | undefined >() writeContract.mutate( { address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], chainId: 1, }, { onError(error, variables, context) { expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: typeof abi.erc20 functionName: 'transferFrom' args: readonly [Address, Address, bigint] }>() }, onSuccess(data, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() expectTypeOf(variables.functionName).toEqualTypeOf<'transferFrom'>() expectTypeOf(variables.args).toEqualTypeOf< readonly [Address, Address, bigint] >() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: typeof abi.erc20 functionName: 'transferFrom' args: readonly [Address, Address, bigint] }>() }, onSettled(data, error, variables, context) { expectTypeOf(data).toEqualTypeOf() expectTypeOf(error).toEqualTypeOf() expectTypeOf(context).toEqualTypeOf() expectTypeOf(variables).toMatchTypeOf<{ chainId?: number | undefined abi: typeof abi.erc20 functionName: 'transferFrom' args: readonly [Address, Address, bigint] }>() }, }, ) }) test('useSimulateContract', () => { const { data } = useSimulateContract({ address: '0x', abi: abi.erc20, functionName: 'transferFrom', args: ['0x', '0x', 123n], chainId: 1, }) const writeContract = useWriteContract() const request = data?.value?.request if (request) writeContract.mutate(request) }) ================================================ FILE: packages/vue/src/composables/useWriteContract.test.ts ================================================ import { connect, disconnect } from '@wagmi/core' import { abi, address, config } from '@wagmi/test' import { renderComposable, waitFor } from '@wagmi/test/vue' import { expect, test } from 'vitest' import { useWriteContract } from './useWriteContract.js' const connector = config.connectors[0]! test('default', async () => { await connect(config, { connector }) const [result] = renderComposable(() => useWriteContract()) result.mutate({ abi: abi.wagmiMintExample, address: address.wagmiMintExample, functionName: 'mint', }) await waitFor(result.isSuccess) expect(result.data.value).toBeDefined() await disconnect(config, { connector }) }) ================================================ FILE: packages/vue/src/composables/useWriteContract.ts ================================================ import { useMutation } from '@tanstack/vue-query' import type { Config, ResolvedRegister, WriteContractErrorType, } from '@wagmi/core' import type { ConfigParameter } from '@wagmi/core/internal' import { type WriteContractData, type WriteContractMutate, type WriteContractMutateAsync, type WriteContractOptions, type WriteContractVariables, writeContractMutationOptions, } from '@wagmi/core/query' import type { Abi } from 'viem' import type { UseMutationReturnType } from '../utils/query.js' import { useConfig } from './useConfig.js' export type UseWriteContractParameters< config extends Config = Config, context = unknown, > = ConfigParameter & WriteContractOptions export type UseWriteContractReturnType< config extends Config = Config, context = unknown, > = UseMutationReturnType< WriteContractData, WriteContractErrorType, WriteContractVariables< Abi, string, readonly unknown[], config, config['chains'][number]['id'] >, context, WriteContractMutate, WriteContractMutateAsync > & { /** @deprecated use `mutate` instead */ writeContract: WriteContractMutate /** @deprecated use `mutateAsync` instead */ writeContractAsync: WriteContractMutateAsync } /** https://wagmi.sh/vue/api/composables/useWriteContract */ export function useWriteContract< config extends Config = ResolvedRegister['config'], context = unknown, >( parameters: UseWriteContractParameters = {}, ): UseWriteContractReturnType { const config = useConfig(parameters) const options = writeContractMutationOptions(config, parameters) const mutation = useMutation(options) type Return = UseWriteContractReturnType return { ...(mutation as Return), writeContract: mutation.mutate as Return['mutate'], writeContractAsync: mutation.mutateAsync as Return['mutateAsync'], } } ================================================ FILE: packages/vue/src/errors/base.test.ts ================================================ import { expect, test } from 'vitest' import { BaseError } from './base.js' test('BaseError', () => { expect(new BaseError('An error occurred.')).toMatchInlineSnapshot(` [WagmiError: An error occurred. Version: @wagmi/vue@x.y.z] `) expect( new BaseError('An error occurred.', { details: 'details' }), ).toMatchInlineSnapshot(` [WagmiError: An error occurred. Details: details Version: @wagmi/vue@x.y.z] `) expect(new BaseError('', { details: 'details' })).toMatchInlineSnapshot(` [WagmiError: An error occurred. Details: details Version: @wagmi/vue@x.y.z] `) }) test('BaseError (w/ docsPath)', () => { expect( new BaseError('An error occurred.', { details: 'details', docsPath: '/lol', }), ).toMatchInlineSnapshot(` [WagmiError: An error occurred. Docs: https://wagmi.sh/vue/lol.html Details: details Version: @wagmi/vue@x.y.z] `) expect( new BaseError('An error occurred.', { cause: new BaseError('error', { docsPath: '/docs' }), }), ).toMatchInlineSnapshot(` [WagmiError: An error occurred. Docs: https://wagmi.sh/vue/docs.html Version: @wagmi/vue@x.y.z] `) expect( new BaseError('An error occurred.', { cause: new BaseError('error'), docsPath: '/lol', }), ).toMatchInlineSnapshot(` [WagmiError: An error occurred. Docs: https://wagmi.sh/vue/lol.html Version: @wagmi/vue@x.y.z] `) expect( new BaseError('An error occurred.', { details: 'details', docsPath: '/lol', docsSlug: 'test', }), ).toMatchInlineSnapshot(` [WagmiError: An error occurred. Docs: https://wagmi.sh/vue/lol.html#test Details: details Version: @wagmi/vue@x.y.z] `) }) test('BaseError (w/ metaMessages)', () => { expect( new BaseError('An error occurred.', { details: 'details', metaMessages: ['Reason: idk', 'Cause: lol'], }), ).toMatchInlineSnapshot(` [WagmiError: An error occurred. Reason: idk Cause: lol Details: details Version: @wagmi/vue@x.y.z] `) }) test('inherited BaseError', () => { const err = new BaseError('An error occurred.', { details: 'details', docsPath: '/lol', }) expect( new BaseError('An internal error occurred.', { cause: err, }), ).toMatchInlineSnapshot(` [WagmiError: An internal error occurred. Docs: https://wagmi.sh/vue/lol.html Details: details Version: @wagmi/vue@x.y.z] `) }) test('inherited Error', () => { const err = new Error('details') expect( new BaseError('An internal error occurred.', { cause: err, docsPath: '/lol', }), ).toMatchInlineSnapshot(` [WagmiError: An internal error occurred. Docs: https://wagmi.sh/vue/lol.html Details: details Version: @wagmi/vue@x.y.z] `) }) test('walk: no predicate fn (walks to leaf)', () => { class FooError extends BaseError {} class BarError extends BaseError {} const err = new BaseError('test1', { cause: new FooError('test2', { cause: new BarError('test3') }), }) expect(err.walk()).toMatchInlineSnapshot(` [WagmiError: test3 Version: @wagmi/vue@x.y.z] `) }) test('walk: predicate fn', () => { class FooError extends BaseError {} class BarError extends BaseError {} const err = new BaseError('test1', { cause: new FooError('test2', { cause: new BarError('test3') }), }) expect(err.walk((err) => err instanceof FooError)).toMatchInlineSnapshot(` [WagmiError: test2 Version: @wagmi/vue@x.y.z] `) }) ================================================ FILE: packages/vue/src/errors/base.ts ================================================ import { BaseError as CoreError } from '@wagmi/core' import { getVersion } from '../utils/getVersion.js' export type BaseErrorType = BaseError & { name: 'WagmiError' } export class BaseError extends CoreError { override name = 'WagmiError' override get docsBaseUrl() { return 'https://wagmi.sh/vue' } override get version() { return getVersion() } } ================================================ FILE: packages/vue/src/errors/plugin.test.ts ================================================ import { expect, test } from 'vitest' import { WagmiInjectionContextError, WagmiPluginNotFoundError, } from './plugin.js' test('WagmiPluginNotFoundError', () => { expect(new WagmiPluginNotFoundError()).toMatchInlineSnapshot(` [WagmiPluginNotFoundError: No \`config\` found in Vue context, use \`WagmiPlugin\` to properly initialize the library. Docs: https://wagmi.sh/vue/api/Nuxt.html Version: @wagmi/vue@x.y.z] `) }) test('WagmiInjectionContextError', () => { expect(new WagmiInjectionContextError()).toMatchInlineSnapshot(` [WagmiInjectionContextError: Wagmi composables can only be used inside \`setup()\` function or functions that support injection context. Docs: https://wagmi.sh/vue/api/Nuxt.html Version: @wagmi/vue@x.y.z] `) }) ================================================ FILE: packages/vue/src/errors/plugin.ts ================================================ import { BaseError } from './base.js' export type WagmiPluginNotFoundErrorType = WagmiPluginNotFoundError & { name: 'WagmiPluginNotFoundError' } export class WagmiPluginNotFoundError extends BaseError { override name = 'WagmiPluginNotFoundError' constructor() { super( 'No `config` found in Vue context, use `WagmiPlugin` to properly initialize the library.', { docsPath: '/api/Nuxt', }, ) } } export type WagmiInjectionContextErrorType = WagmiInjectionContextError & { name: 'WagmiInjectionContextError' } export class WagmiInjectionContextError extends BaseError { override name = 'WagmiInjectionContextError' constructor() { super( 'Wagmi composables can only be used inside `setup()` function or functions that support injection context.', { docsPath: '/api/Nuxt', }, ) } } ================================================ FILE: packages/vue/src/exports/actions.test.ts ================================================ import { expect, test } from 'vitest' import * as actions from './actions.js' test('exports', () => { expect(Object.keys(actions)).toMatchInlineSnapshot(` [ "call", "connect", "deployContract", "disconnect", "estimateFeesPerGas", "estimateGas", "estimateMaxPriorityFeePerGas", "getBalance", "getBlobBaseFee", "getBlock", "getBlockNumber", "getBlockTransactionCount", "getBytecode", "getCallsStatus", "getCapabilities", "getChainId", "getChains", "getClient", "getAccount", "getConnection", "getConnections", "getConnectorClient", "getConnectors", "getContractEvents", "getEnsAddress", "getEnsAvatar", "getEnsName", "getEnsResolver", "getEnsText", "getFeeHistory", "getGasPrice", "getProof", "getPublicClient", "getStorageAt", "getTransaction", "getTransactionConfirmations", "getTransactionCount", "getTransactionReceipt", "getWalletClient", "multicall", "prepareTransactionRequest", "readContract", "readContracts", "reconnect", "sendCalls", "sendTransaction", "showCallsStatus", "signMessage", "signTransaction", "signTypedData", "simulateContract", "switchChain", "switchAccount", "switchConnection", "verifyMessage", "verifyTypedData", "waitForCallsStatus", "waitForTransactionReceipt", "watchAsset", "watchBlockNumber", "watchBlocks", "watchChainId", "watchClient", "watchAccount", "watchConnection", "watchConnections", "watchConnectors", "watchContractEvent", "watchPendingTransactions", "watchPublicClient", "writeContract", ] `) }) ================================================ FILE: packages/vue/src/exports/actions.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // @wagmi/core/actions //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module // biome-ignore lint/performance/noReExportAll: entrypoint module export * from '@wagmi/core/actions' ================================================ FILE: packages/vue/src/exports/chains.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // viem/chains //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module // biome-ignore lint/performance/noReExportAll: entrypoint module export * from 'viem/chains' ================================================ FILE: packages/vue/src/exports/connectors.test.ts ================================================ import { expect, test } from 'vitest' import * as connectors from './connectors.js' test('exports', () => { expect(Object.keys(connectors)).toMatchInlineSnapshot(` [ "injected", "mock", "baseAccount", "coinbaseWallet", "metaMask", "porto", "safe", "version", "walletConnect", ] `) }) ================================================ FILE: packages/vue/src/exports/connectors.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // @wagmi/connectors //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module // biome-ignore lint/performance/noReExportAll: entrypoint module export * from '@wagmi/connectors' ================================================ FILE: packages/vue/src/exports/index.test.ts ================================================ import { expect, test } from 'vitest' import * as vue from './index.js' test('exports', () => { expect(Object.keys(vue)).toMatchInlineSnapshot(` [ "configKey", "WagmiPlugin", "BaseError", "WagmiInjectionContextError", "WagmiPluginNotFoundError", "useBalance", "useBlockNumber", "useBytecode", "useChainId", "useChains", "useClient", "useConfig", "useConnect", "useAccount", "useConnection", "useAccountEffect", "useConnectionEffect", "useConnections", "useConnectorClient", "useConnectors", "useDisconnect", "useEnsAddress", "useEnsAvatar", "useEnsName", "useEstimateGas", "useReadContract", "useReconnect", "useSendTransaction", "useSignMessage", "useSignTransaction", "useSignTypedData", "useSimulateContract", "useSwitchChain", "useSwitchAccount", "useSwitchConnection", "useTransaction", "useTransactionReceipt", "useWaitForTransactionReceipt", "useWatchBlockNumber", "useWatchContractEvent", "useWriteContract", "ChainNotConfiguredError", "ConnectorAccountNotFoundError", "ConnectorAlreadyConnectedError", "ConnectorChainMismatchError", "ConnectorNotFoundError", "ConnectorUnavailableReconnectingError", "cookieStorage", "cookieToInitialState", "createConfig", "createConnector", "createStorage", "custom", "deepEqual", "deserialize", "fallback", "http", "injected", "mock", "noopStorage", "ProviderNotFoundError", "parseCookie", "SwitchChainNotSupportedError", "serialize", "unstable_connector", "webSocket", "version", ] `) }) ================================================ FILE: packages/vue/src/exports/index.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // Plugin //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module export { configKey, WagmiPlugin, type WagmiPluginOptions } from '../plugin.js' //////////////////////////////////////////////////////////////////////////////// // Errors //////////////////////////////////////////////////////////////////////////////// export { BaseError, type BaseErrorType } from '../errors/base.js' export { WagmiInjectionContextError, type WagmiInjectionContextErrorType, WagmiPluginNotFoundError, type WagmiPluginNotFoundErrorType, } from '../errors/plugin.js' //////////////////////////////////////////////////////////////////////////////// // Composables //////////////////////////////////////////////////////////////////////////////// export { type UseBalanceParameters, type UseBalanceReturnType, useBalance, } from '../composables/useBalance.js' export { type UseBlockNumberParameters, type UseBlockNumberReturnType, useBlockNumber, } from '../composables/useBlockNumber.js' export { type UseBytecodeParameters, type UseBytecodeReturnType, useBytecode, } from '../composables/useBytecode.js' export { type UseChainIdParameters, type UseChainIdReturnType, useChainId, } from '../composables/useChainId.js' export { type UseChainsParameters, type UseChainsReturnType, useChains, } from '../composables/useChains.js' export { type UseClientParameters, type UseClientReturnType, useClient, } from '../composables/useClient.js' export { type UseConfigParameters, type UseConfigReturnType, useConfig, } from '../composables/useConfig.js' export { type UseConnectParameters, type UseConnectReturnType, useConnect, } from '../composables/useConnect.js' export { /** @deprecated use `UseConnectionParameters` instead */ type UseConnectionParameters as UseAccountParameters, type UseConnectionParameters, /** @deprecated use `UseConnectionReturnType` instead */ type UseConnectionReturnType as UseAccountReturnType, type UseConnectionReturnType, /** @deprecated use `useConnection` instead */ useConnection as useAccount, useConnection, } from '../composables/useConnection.js' export { /** @deprecated use `UseConnectionEffectParameters` instead */ type UseConnectionEffectParameters as UseAccountEffectParameters, type UseConnectionEffectParameters, /** @deprecated use `useConnectionEffect` instead */ useConnectionEffect as useAccountEffect, useConnectionEffect, } from '../composables/useConnectionEffect.js' export { type UseConnectionsParameters, type UseConnectionsReturnType, useConnections, } from '../composables/useConnections.js' export { type UseConnectorClientParameters, type UseConnectorClientReturnType, useConnectorClient, } from '../composables/useConnectorClient.js' export { type UseConnectorsParameters, type UseConnectorsReturnType, useConnectors, } from '../composables/useConnectors.js' export { type UseDisconnectParameters, type UseDisconnectReturnType, useDisconnect, } from '../composables/useDisconnect.js' export { type UseEnsAddressParameters, type UseEnsAddressReturnType, useEnsAddress, } from '../composables/useEnsAddress.js' export { type UseEnsAvatarParameters, type UseEnsAvatarReturnType, useEnsAvatar, } from '../composables/useEnsAvatar.js' export { type UseEnsNameParameters, type UseEnsNameReturnType, useEnsName, } from '../composables/useEnsName.js' export { type UseEstimateGasParameters, type UseEstimateGasReturnType, useEstimateGas, } from '../composables/useEstimateGas.js' export { type UseReadContractParameters, type UseReadContractReturnType, useReadContract, } from '../composables/useReadContract.js' export { type UseReconnectParameters, type UseReconnectReturnType, useReconnect, } from '../composables/useReconnect.js' export { type UseSendTransactionParameters, type UseSendTransactionReturnType, useSendTransaction, } from '../composables/useSendTransaction.js' export { type UseSignMessageParameters, type UseSignMessageReturnType, useSignMessage, } from '../composables/useSignMessage.js' export { type UseSignTransactionParameters, type UseSignTransactionReturnType, useSignTransaction, } from '../composables/useSignTransaction.js' export { type UseSignTypedDataParameters, type UseSignTypedDataReturnType, useSignTypedData, } from '../composables/useSignTypedData.js' export { type UseSimulateContractParameters, type UseSimulateContractReturnType, useSimulateContract, } from '../composables/useSimulateContract.js' export { type UseSwitchChainParameters, type UseSwitchChainReturnType, useSwitchChain, } from '../composables/useSwitchChain.js' export { /** @deprecated use `UseSwitchConnectionParameters` instead */ type UseSwitchConnectionParameters as UseSwitchAccountParameters, type UseSwitchConnectionParameters, /** @deprecated use `UseSwitchConnectionReturnType` instead */ type UseSwitchConnectionReturnType as UseSwitchAccountReturnType, type UseSwitchConnectionReturnType, /** @deprecated use `useSwitchConnection` instead */ useSwitchConnection as useSwitchAccount, useSwitchConnection, } from '../composables/useSwitchConnection.js' export { type UseTransactionParameters, type UseTransactionReturnType, useTransaction, } from '../composables/useTransaction.js' export { type UseTransactionReceiptParameters, type UseTransactionReceiptReturnType, useTransactionReceipt, } from '../composables/useTransactionReceipt.js' export { type UseWaitForTransactionReceiptParameters, type UseWaitForTransactionReceiptReturnType, useWaitForTransactionReceipt, } from '../composables/useWaitForTransactionReceipt.js' export { type UseWatchBlockNumberParameters, type UseWatchBlockNumberReturnType, useWatchBlockNumber, } from '../composables/useWatchBlockNumber.js' export { type UseWatchContractEventParameters, type UseWatchContractEventReturnType, useWatchContractEvent, } from '../composables/useWatchContractEvent.js' export { type UseWriteContractParameters, type UseWriteContractReturnType, useWriteContract, } from '../composables/useWriteContract.js' //////////////////////////////////////////////////////////////////////////////// // @wagmi/core //////////////////////////////////////////////////////////////////////////////// export { ChainNotConfiguredError, // Errors type ChainNotConfiguredErrorType, type Config, // Config type Connection, type Connector, ConnectorAccountNotFoundError, type ConnectorAccountNotFoundErrorType, ConnectorAlreadyConnectedError, type ConnectorAlreadyConnectedErrorType, ConnectorChainMismatchError, type ConnectorChainMismatchErrorType, // Connector type ConnectorEventMap, ConnectorNotFoundError, type ConnectorNotFoundErrorType, ConnectorUnavailableReconnectingError, type ConnectorUnavailableReconnectingErrorType, type CreateConfigParameters, type CreateConnectorFn, // Storage type CreateStorageParameters, // Utilities cookieStorage, cookieToInitialState, createConfig, createConnector, createStorage, // Transports custom, deepEqual, deserialize, fallback, http, injected, mock, noopStorage, type PartializedState, ProviderNotFoundError, type ProviderNotFoundErrorType, parseCookie, // Types type Register, type ResolvedRegister, type State, type Storage, SwitchChainNotSupportedError, type SwitchChainNotSupportedErrorType, serialize, unstable_connector, webSocket, } from '@wagmi/core' //////////////////////////////////////////////////////////////////////////////// // Version //////////////////////////////////////////////////////////////////////////////// export { version } from '../version.js' ================================================ FILE: packages/vue/src/exports/nuxt.test.ts ================================================ import { expect, test } from 'vitest' import * as nuxt from './nuxt.js' test('exports', () => { expect(Object.keys(nuxt)).toMatchInlineSnapshot(` [ "default", ] `) }) ================================================ FILE: packages/vue/src/exports/nuxt.ts ================================================ import { wagmiModule } from '../nuxt/module.js' export type { WagmiModuleOptions } from '../nuxt/module.js' export default wagmiModule ================================================ FILE: packages/vue/src/exports/query.test.ts ================================================ import { expect, test } from 'vitest' import * as query from './query.js' test('exports', () => { expect(Object.keys(query)).toMatchInlineSnapshot(` [ "useMutation", "useQuery", "callQueryKey", "callQueryOptions", "connectMutationOptions", "deployContractMutationOptions", "disconnectMutationOptions", "estimateFeesPerGasQueryKey", "estimateFeesPerGasQueryOptions", "estimateGasQueryKey", "estimateGasQueryOptions", "estimateMaxPriorityFeePerGasQueryKey", "estimateMaxPriorityFeePerGasQueryOptions", "getBalanceQueryKey", "getBalanceQueryOptions", "getBlobBaseFeeQueryKey", "getBlobBaseFeeQueryOptions", "getBlockQueryKey", "getBlockQueryOptions", "getBlockNumberQueryKey", "getBlockNumberQueryOptions", "getBlockTransactionCountQueryKey", "getBlockTransactionCountQueryOptions", "getBytecodeQueryKey", "getBytecodeQueryOptions", "getCallsStatusQueryKey", "getCallsStatusQueryOptions", "getCapabilitiesQueryKey", "getCapabilitiesQueryOptions", "getConnectorClientQueryKey", "getConnectorClientQueryOptions", "getContractEventsQueryKey", "getContractEventsQueryOptions", "getEnsAddressQueryKey", "getEnsAddressQueryOptions", "getEnsAvatarQueryKey", "getEnsAvatarQueryOptions", "getEnsNameQueryKey", "getEnsNameQueryOptions", "getEnsResolverQueryKey", "getEnsResolverQueryOptions", "getEnsTextQueryKey", "getEnsTextQueryOptions", "getFeeHistoryQueryKey", "getFeeHistoryQueryOptions", "getGasPriceQueryKey", "getGasPriceQueryOptions", "getProofQueryKey", "getProofQueryOptions", "getStorageAtQueryKey", "getStorageAtQueryOptions", "getTransactionQueryKey", "getTransactionQueryOptions", "getTransactionConfirmationsQueryKey", "getTransactionConfirmationsQueryOptions", "getTransactionCountQueryKey", "getTransactionCountQueryOptions", "getTransactionReceiptQueryKey", "getTransactionReceiptQueryOptions", "getWalletClientQueryKey", "getWalletClientQueryOptions", "infiniteReadContractsQueryKey", "infiniteReadContractsQueryOptions", "prepareTransactionRequestQueryKey", "prepareTransactionRequestQueryOptions", "readContractQueryKey", "readContractQueryOptions", "readContractsQueryKey", "readContractsQueryOptions", "reconnectMutationOptions", "sendCallsMutationOptions", "sendCallsSyncMutationOptions", "sendTransactionMutationOptions", "sendTransactionSyncMutationOptions", "showCallsStatusMutationOptions", "signMessageMutationOptions", "signTransactionMutationOptions", "signTypedDataMutationOptions", "simulateContractQueryKey", "simulateContractQueryOptions", "switchChainMutationOptions", "switchAccountMutationOptions", "switchConnectionMutationOptions", "hashFn", "structuralSharing", "verifyMessageQueryKey", "verifyMessageQueryOptions", "verifyTypedDataQueryKey", "verifyTypedDataQueryOptions", "waitForCallsStatusQueryKey", "waitForCallsStatusQueryOptions", "waitForTransactionReceiptQueryKey", "waitForTransactionReceiptQueryOptions", "watchAssetMutationOptions", "writeContractMutationOptions", "writeContractSyncMutationOptions", ] `) }) ================================================ FILE: packages/vue/src/exports/query.ts ================================================ //////////////////////////////////////////////////////////////////////////////// // @wagmi/core/query //////////////////////////////////////////////////////////////////////////////// // biome-ignore lint/performance/noBarrelFile: entrypoint module // biome-ignore lint/performance/noReExportAll: entrypoint module export * from '@wagmi/core/query' export { type UseMutationParameters, type UseMutationReturnType, type UseQueryParameters, type UseQueryReturnType, useMutation, useQuery, } from '../utils/query.js' ================================================ FILE: packages/vue/src/nuxt/module.ts ================================================ import type { NuxtModule } from '@nuxt/schema' import { addImports, createResolver, defineNuxtModule } from 'nuxt/kit' // biome-ignore lint/complexity/noBannedTypes: allowed export type WagmiModuleOptions = {} export const wagmiModule: NuxtModule = defineNuxtModule({ meta: { name: '@wagmi/vue', configKey: 'wagmi', compatibility: { nuxt: '^3.0.0 || ^4.0.0', }, }, setup(_options, nuxt) { const { resolve } = createResolver(import.meta.url) // Add types nuxt.hook('prepare:types', ({ references }) => { references.push({ types: '@wagmi/vue/nuxt' }) }) // Add auto imports const composables = resolve('./runtime/composables') const names = [ 'useAccount' /** @deprecated */, 'useAccountEffect' /** @deprecated */, 'useBalance', 'useBlockNumber', 'useChainId', 'useChains', 'useClient', 'useConfig', 'useConnect', 'useConnection', 'useConnectionEffect', 'useConnections', 'useConnectorClient', 'useConnectors', 'useDisconnect', 'useEnsAddress', 'useEnsAvatar', 'useEnsName', 'useEstimateGas', 'useReadContract', 'useReconnect', 'useSendTransaction', 'useSignMessage', 'useSignTypedData', 'useSimulateContract', 'useSwitchAccount' /** @deprecated */, 'useSwitchChain', 'useSwitchConnection', 'useTransaction', 'useTransactionReceipt', 'useWaitForTransactionReceipt', 'useWatchBlockNumber', 'useWriteContract', ] addImports(names.map((name) => ({ from: composables, name }))) }, }) ================================================ FILE: packages/vue/src/nuxt/runtime/composables.ts ================================================ // biome-ignore lint/performance/noBarrelFile: entrypoint module // biome-ignore lint/performance/noReExportAll: entrypoint module export * from '../../exports/index.js' ================================================ FILE: packages/vue/src/plugin.ts ================================================ import { hydrate, type ResolvedRegister, type State } from '@wagmi/core' import type { Plugin } from 'vue' export const configKey = Symbol() export type WagmiPluginOptions = { config: ResolvedRegister['config'] initialState?: State | undefined reconnectOnMount?: boolean | undefined } export const WagmiPlugin = { install(app, options) { const { config, reconnectOnMount = true } = options app.provide(configKey, config) // TODO: check this works in SSR env. // - reconnect on mount. // - hydrate initial state. const { onMount } = hydrate(config, { ...options, reconnectOnMount }) onMount() }, } satisfies Plugin ================================================ FILE: packages/vue/src/types/properties.ts ================================================ import type { MaybeRef } from 'vue' export type EnabledParameter = { enabled?: MaybeRef | undefined } ================================================ FILE: packages/vue/src/types/ref.ts ================================================ // Credit: https://github.com/TanStack/query/blob/01ce023826b81e6c41e354f27691f65c9725af67/packages/vue-query/src/types.ts import type { Config, Connector } from '@wagmi/core' import type { MaybeRef, Ref, UnwrapRef } from 'vue' type Primitive = string | number | boolean | bigint | symbol | undefined | null type UnwrapLeaf = | Primitive // biome-ignore lint/complexity/noBannedTypes: we need to support all types | Function | Date | Error | RegExp | Map | WeakMap | Set | WeakSet export type DeepMaybeRef = MaybeRef< // biome-ignore lint/complexity/noBannedTypes: allowed value extends Function | Config | Connector ? value : value extends object | any[] ? { [key in keyof value]: DeepMaybeRef } : value > export type DeepUnwrapRef = T extends UnwrapLeaf ? T : T extends Ref ? DeepUnwrapRef : // biome-ignore lint/complexity/noBannedTypes: allowed T extends {} ? { [Property in keyof T]: DeepUnwrapRef } : UnwrapRef ================================================ FILE: packages/vue/src/utils/cloneDeep.ts ================================================ // Credit: https://github.com/TanStack/query/blob/01ce023826b81e6c41e354f27691f65c9725af67/packages/vue-query/src/utils.ts import { isRef, unref } from 'vue' import type { DeepMaybeRef, DeepUnwrapRef } from '../types/ref.js' function cloneDeep( value: DeepMaybeRef, customize?: (val: DeepMaybeRef) => value | undefined, ): value { if (customize) { const result = customize(value) // If it's a ref of undefined, return undefined if (result === undefined && isRef(value)) return result as value if (result !== undefined) return result } if (Array.isArray(value)) return value.map((val) => cloneDeep(val, customize)) as unknown as value if (typeof value === 'object' && isPlainObject(value)) { const entries = Object.entries(value).map(([key, val]) => [ key, cloneDeep(val, customize), ]) return Object.fromEntries(entries) } return value as value } export function deepUnref(value: value): DeepUnwrapRef { return cloneDeep(value as any, (val) => { if (isRef(val)) return deepUnref(unref(val)) return undefined }) } // biome-ignore lint/complexity/noBannedTypes: allowed function isPlainObject(value: unknown): value is Object { if (Object.prototype.toString.call(value) !== '[object Object]') return false const prototype = Object.getPrototypeOf(value) return prototype === null || prototype === Object.prototype } ================================================ FILE: packages/vue/src/utils/getVersion.test.ts ================================================ import { expect, test } from 'vitest' import { getVersion } from './getVersion.js' test('default', () => { expect(getVersion()).toMatchInlineSnapshot(`"@wagmi/vue@x.y.z"`) }) ================================================ FILE: packages/vue/src/utils/getVersion.ts ================================================ import { version } from '../version.js' export const getVersion = () => `@wagmi/vue@${version}` ================================================ FILE: packages/vue/src/utils/query.ts ================================================ import { type DefaultError, type MutateFunction, type MutationObserverOptions, type QueryKey, type UseMutationReturnType as tanstack_UseMutationReturnType, type UseQueryReturnType as tanstack_UseQueryReturnType, useQuery as tanstack_useQuery, type UseQueryOptions, useMutation, } from '@tanstack/vue-query' import type { Compute, ExactPartial, Omit, UnionStrictOmit, } from '@wagmi/core/internal' import { hashFn } from '@wagmi/core/query' import { computed, type MaybeRef, unref } from 'vue' import type { DeepMaybeRef, DeepUnwrapRef } from '../types/ref.js' export { useMutation } export type UseMutationParameters< data = unknown, error = Error, variables = void, context = unknown, > = Compute< DeepMaybeRef< Omit< DeepUnwrapRef< MutationObserverOptions, context> >, 'mutationFn' | 'mutationKey' | 'throwOnError' > > > export type UseMutationReturnType< data = unknown, error = Error, variables = void, context = unknown, mutate = MutateFunction, mutateAsync = MutateFunction, > = Compute< UnionStrictOmit< tanstack_UseMutationReturnType, 'mutate' | 'mutateAsync' > & { mutate: mutate mutateAsync: mutateAsync } > //////////////////////////////////////////////////////////////////////////////// // Adding some basic customization. // Ideally we don't have this function, but `import('@tanstack/vue-query').useQuery` currently has some quirks where it is super hard to // pass down the inferred `initialData` type because of it's discriminated overload in the on `useQuery`. export function useQuery( parameters: MaybeRef< UseQueryParameters & { queryKey: QueryKey } >, ): UseQueryReturnType { const options = computed(() => ({ ...(unref(parameters) as any), queryKeyHashFn: hashFn, })) const result = tanstack_useQuery(options) as UseQueryReturnType result.queryKey = unref(options).queryKey as QueryKey return result } export type UseQueryParameters< queryFnData = unknown, error = DefaultError, data = queryFnData, queryKey extends QueryKey = QueryKey, > = Compute< DeepMaybeRef< ExactPartial< Omit< DeepUnwrapRef< UseQueryOptions >, 'initialData' > > & { // Fix `initialData` type initialData?: | DeepUnwrapRef< UseQueryOptions >['initialData'] | undefined } > > export type UseQueryReturnType = Compute< tanstack_UseQueryReturnType & { queryKey: QueryKey } > ================================================ FILE: packages/vue/src/utils/updateState.ts ================================================ // Credit: https://github.com/TanStack/query/blob/01ce023826b81e6c41e354f27691f65c9725af67/packages/vue-query/src/utils.ts#L11-L18 export function updateState( state: Record, update: Record, ): void { for (const key of Object.keys(state)) { state[key] = update[key] } } ================================================ FILE: packages/vue/src/version.ts ================================================ export const version = '0.5.0' ================================================ FILE: packages/vue/test/setup.ts ================================================ import { vi } from 'vitest' // Make dates stable across runs Date.now = vi.fn(() => new Date(Date.UTC(2023, 1, 1)).valueOf()) vi.mock('../src/version.ts', () => { return { version: 'x.y.z' } }) ================================================ FILE: packages/vue/tsconfig.build.json ================================================ { "extends": "../../tsconfig.base.json", "include": ["src/**/*.ts"], "exclude": ["src/**/*.test.ts", "src/**/*.test-d.ts"], "compilerOptions": { "sourceMap": true } } ================================================ FILE: packages/vue/tsconfig.json ================================================ { "extends": "./tsconfig.build.json", "include": ["src/**/*.ts", "test/**/*.ts"], "exclude": [] } ================================================ FILE: playgrounds/next/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # next.js /.next/ /out/ # production /build # misc .DS_Store *.pem # debug npm-debug.log* yarn-debug.log* yarn-error.log* # local env files .env*.local # vercel .vercel # typescript *.tsbuildinfo next-env.d.ts ================================================ FILE: playgrounds/next/next.config.ts ================================================ import type { NextConfig } from 'next' const nextConfig = { experimental: { externalDir: true, }, // TODO: Remove and switch to turbopack once Next supports extensionAliases // https://github.com/vercel/next.js/issues/82945 webpack(config) { config.resolve.extensionAlias = { '.js': ['.js', '.ts'], } return config }, } satisfies NextConfig export default nextConfig ================================================ FILE: playgrounds/next/package.json ================================================ { "name": "next-app", "private": true, "type": "module", "scripts": { "dev": "next dev --webpack", "build": "next build --webpack", "start": "next start", "lint": "next lint" }, "dependencies": { "@next/bundle-analyzer": "^14.2.3", "@tanstack/react-query": "catalog:", "next": "^16.1.7", "react": "catalog:", "react-dom": "catalog:", "viem": "2.*", "wagmi": "workspace:*" }, "devDependencies": { "@types/node": "^24.5.1", "@types/react": "catalog:", "@types/react-dom": "catalog:" } } ================================================ FILE: playgrounds/next/src/app/contracts.ts ================================================ export const wagmiContractConfig = { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: [ { inputs: [], stateMutability: 'nonpayable', type: 'constructor' }, { anonymous: false, inputs: [ { indexed: true, name: 'owner', type: 'address', }, { indexed: true, name: 'approved', type: 'address', }, { indexed: true, name: 'tokenId', type: 'uint256', }, ], name: 'Approval', type: 'event', }, { anonymous: false, inputs: [ { indexed: true, name: 'owner', type: 'address', }, { indexed: true, name: 'operator', type: 'address', }, { indexed: false, name: 'approved', type: 'bool', }, ], name: 'ApprovalForAll', type: 'event', }, { anonymous: false, inputs: [ { indexed: true, name: 'from', type: 'address', }, { indexed: true, name: 'to', type: 'address' }, { indexed: true, name: 'tokenId', type: 'uint256', }, ], name: 'Transfer', type: 'event', }, { inputs: [ { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, ], name: 'approve', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ name: 'owner', type: 'address' }], name: 'balanceOf', outputs: [{ name: '', type: 'uint256' }], stateMutability: 'view', type: 'function', }, { inputs: [{ name: 'tokenId', type: 'uint256' }], name: 'getApproved', outputs: [{ name: '', type: 'address' }], stateMutability: 'view', type: 'function', }, { inputs: [ { name: 'owner', type: 'address' }, { name: 'operator', type: 'address' }, ], name: 'isApprovedForAll', outputs: [{ name: '', type: 'bool' }], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'mint', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ internalType: 'uint256', name: 'tokenId', type: 'uint256' }], name: 'mint', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [], name: 'name', outputs: [{ name: '', type: 'string' }], stateMutability: 'view', type: 'function', }, { inputs: [{ name: 'tokenId', type: 'uint256' }], name: 'ownerOf', outputs: [{ name: '', type: 'address' }], stateMutability: 'view', type: 'function', }, { inputs: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, ], name: 'safeTransferFrom', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, { name: '_data', type: 'bytes' }, ], name: 'safeTransferFrom', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { name: 'operator', type: 'address' }, { name: 'approved', type: 'bool' }, ], name: 'setApprovalForAll', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ name: 'interfaceId', type: 'bytes4' }], name: 'supportsInterface', outputs: [{ name: '', type: 'bool' }], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'symbol', outputs: [{ name: '', type: 'string' }], stateMutability: 'view', type: 'function', }, { inputs: [{ name: 'tokenId', type: 'uint256' }], name: 'tokenURI', outputs: [{ name: '', type: 'string' }], stateMutability: 'pure', type: 'function', }, { inputs: [], name: 'totalSupply', outputs: [{ name: '', type: 'uint256' }], stateMutability: 'view', type: 'function', }, { inputs: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, ], name: 'transferFrom', outputs: [], stateMutability: 'nonpayable', type: 'function', }, ], } as const ================================================ FILE: playgrounds/next/src/app/globals.css ================================================ :root { background-color: #181818; color: rgba(255, 255, 255, 0.87); color-scheme: light dark; font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; font-synthesis: none; font-weight: 400; line-height: 1.5; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-text-size-adjust: 100%; } @media (prefers-color-scheme: light) { :root { background-color: #f8f8f8; color: #181818; } } ================================================ FILE: playgrounds/next/src/app/layout.tsx ================================================ import type { Metadata } from 'next' import { Inter } from 'next/font/google' import { headers } from 'next/headers' import type { ReactNode } from 'react' import { cookieToInitialState } from 'wagmi' import './globals.css' import { getConfig } from '../wagmi' import { Providers } from './providers' const inter = Inter({ subsets: ['latin'] }) export const metadata: Metadata = { title: 'Create Wagmi', description: 'Generated by create-wagmi', } export default async function RootLayout(props: { children: ReactNode }) { const initialState = cookieToInitialState( getConfig(), (await headers()).get('cookie'), ) return ( {props.children} ) } ================================================ FILE: playgrounds/next/src/app/page.tsx ================================================ 'use client' import type { FormEvent } from 'react' import { formatEther, type Hex, parseAbi, parseEther } from 'viem' import { type BaseError, useBalance, useBlockNumber, useChainId, useChains, useConfig, useConnect, useConnection, useConnectionEffect, useConnections, useConnectorClient, useConnectors, useDisconnect, useEnsName, useReadContract, useReadContracts, useSendTransaction, useSignMessage, useSwitchChain, useSwitchConnection, useWaitForTransactionReceipt, useWriteContract, } from 'wagmi' import { switchChain } from 'wagmi/actions' import { optimism, sepolia } from 'wagmi/chains' import { wagmiContractConfig } from './contracts' export default function App() { useConnectionEffect({ onConnect(_data) { // console.log('onConnect', data) }, onDisconnect() { // console.log('onDisconnect') }, }) return ( <> ) } function Connection() { const connection = useConnection() const { disconnect } = useDisconnect() const { data: ensName } = useEnsName({ address: connection.address, }) return (

Connection

account: {connection.address} {ensName}
chainId: {connection.chainId}
status: {connection.status}
{connection.status === 'connected' && ( )}
) } function Connect() { const chainId = useChainId() const { connect, status, error } = useConnect() const connectors = useConnectors() return (

Connect

{connectors.map((connector) => ( ))}
{status}
{error?.message}
) } function SwitchConnection() { const connection = useConnection() const { switchConnection } = useSwitchConnection() const connections = useConnections() return (

Switch Connection

{connections.map(({ connector }) => ( ))}
) } function SwitchChain() { const chainId = useChainId() const { switchChain, error } = useSwitchChain() const chains = useChains() return (

Switch Chain

{chains.map((chain) => ( ))} {error?.message}
) } function SignMessage() { const { data, signMessage } = useSignMessage() return (

Sign Message

{ event.preventDefault() const formData = new FormData(event.target as HTMLFormElement) signMessage({ message: formData.get('message') as string }) }} >
{data}
) } function Connections() { const connections = useConnections() return (

Connections

{connections.map((connection) => (
connector {connection.connector.name}
accounts: {JSON.stringify(connection.accounts)}
chainId: {connection.chainId}
))}
) } function Balance() { const { address } = useConnection() const { data: default_ } = useBalance({ address }) const { data: account_ } = useBalance({ address }) const { data: optimism_ } = useBalance({ address, chainId: optimism.id, }) return (

Balance

Balance (Default Chain):{' '} {!!default_?.value && formatEther(default_.value)}
Balance (Connection Chain):{' '} {!!account_?.value && formatEther(account_.value)}
Balance (Optimism Chain):{' '} {!!optimism_?.value && formatEther(optimism_.value)}
) } function BlockNumber() { const { data: default_ } = useBlockNumber({ watch: true }) const { data: account_ } = useBlockNumber({ watch: true, }) const { data: optimism_ } = useBlockNumber({ chainId: optimism.id, watch: true, }) return (

Block Number

Block Number (Default Chain): {default_?.toString()}
Block Number (Connection Chain): {account_?.toString()}
Block Number (Optimism): {optimism_?.toString()}
) } function ConnectorClient() { const { data, error } = useConnectorClient() return (

Connector Client

client {data?.account?.address} {data?.chain?.id} {error?.message}
) } function SendTransaction() { const { data: hash, error, isPending, sendTransaction } = useSendTransaction() async function submit(e: FormEvent) { e.preventDefault() const formData = new FormData(e.target as HTMLFormElement) const to = formData.get('address') as Hex const value = formData.get('value') as string sendTransaction({ to, value: parseEther(value) }) } const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({ hash, }) return (

Send Transaction

{hash &&
Transaction Hash: {hash}
} {isConfirming && 'Waiting for confirmation...'} {isConfirmed && 'Transaction confirmed.'} {error && (
Error: {(error as BaseError).shortMessage || error.message}
)}
) } function ReadContract() { const { data: balance } = useReadContract({ ...wagmiContractConfig, functionName: 'balanceOf', args: ['0x03A71968491d55603FFe1b11A9e23eF013f75bCF'], }) return (

Read Contract

Balance: {balance?.toString()}
) } function ReadContracts() { const { data } = useReadContracts({ allowFailure: false, contracts: [ { ...wagmiContractConfig, functionName: 'balanceOf', args: ['0x03A71968491d55603FFe1b11A9e23eF013f75bCF'], }, { ...wagmiContractConfig, functionName: 'ownerOf', args: [69n], }, { ...wagmiContractConfig, functionName: 'totalSupply', }, ], }) const [balance, ownerOf, totalSupply] = data || [] return (

Read Contract

Balance: {balance?.toString()}
Owner of Token 69: {ownerOf?.toString()}
Total Supply: {totalSupply?.toString()}
) } function WriteContract() { const { data: hash, error, isPending, writeContract } = useWriteContract() async function submit(e: FormEvent) { e.preventDefault() const formData = new FormData(e.target as HTMLFormElement) const tokenId = formData.get('tokenId') as string writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: parseAbi(['function mint(uint256 tokenId)']), functionName: 'mint', args: [BigInt(tokenId)], }) } const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({ hash, }) return (

Write Contract

{hash &&
Transaction Hash: {hash}
} {isConfirming && 'Waiting for confirmation...'} {isConfirmed && 'Transaction confirmed.'} {error && (
Error: {(error as BaseError).shortMessage || error.message}
)}
) } function Repro() { const config = useConfig() const chainId = useChainId() console.log('chainId from useChainId is', chainId) return (
Current Chain Id: {chainId}
) } ================================================ FILE: playgrounds/next/src/app/providers.tsx ================================================ 'use client' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { type ReactNode, useState } from 'react' import { type State, WagmiProvider } from 'wagmi' import { getConfig } from '../wagmi' export function Providers(props: { children: ReactNode initialState?: State }) { const [config] = useState(() => getConfig()) const [queryClient] = useState(() => new QueryClient()) return ( {props.children} ) } ================================================ FILE: playgrounds/next/src/wagmi.ts ================================================ import { cookieStorage, createConfig, createStorage, http } from 'wagmi' import { mainnet, optimism, sepolia } from 'wagmi/chains' import { injected, metaMask, walletConnect } from 'wagmi/connectors' export function getConfig() { return createConfig({ chains: [mainnet, sepolia, optimism], connectors: [ injected(), walletConnect({ projectId: process.env.NEXT_PUBLIC_WC_PROJECT_ID!, }), metaMask(), ], storage: createStorage({ storage: cookieStorage, }), ssr: true, transports: { [mainnet.id]: http(), [sepolia.id]: http(), [optimism.id]: http(), }, }) } declare module 'wagmi' { interface Register { config: ReturnType } } ================================================ FILE: playgrounds/next/tsconfig.json ================================================ { "compilerOptions": { "target": "ESNext", "lib": ["dom", "dom.iterable", "esnext"], "allowImportingTsExtensions": true, "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "react-jsx", "incremental": true, "plugins": [ { "name": "next" } ] }, "include": [ "next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts" ], "exclude": ["node_modules"] } ================================================ FILE: playgrounds/nuxt/.gitignore ================================================ # Nuxt dev/build outputs .output .data .nuxt .nitro .cache dist # Node dependencies node_modules # Logs logs *.log # Misc .DS_Store .fleet .idea # Local env files .env .env.* !.env.example ================================================ FILE: playgrounds/nuxt/app.vue ================================================ ================================================ FILE: playgrounds/nuxt/components/Connect.vue ================================================ ================================================ FILE: playgrounds/nuxt/components/Connection.vue ================================================ ================================================ FILE: playgrounds/nuxt/nuxt.config.ts ================================================ import { defineNuxtConfig } from 'nuxt/config' // https://nuxt.com/docs/api/configuration/nuxt-config export default defineNuxtConfig({ devtools: { enabled: true }, modules: ['@wagmi/vue/nuxt'], }) ================================================ FILE: playgrounds/nuxt/package.json ================================================ { "name": "nuxt-app", "private": true, "type": "module", "scripts": { "build": "nuxt build", "dev": "nuxt dev", "generate": "nuxt generate", "preview": "nuxt preview", "_postinstall": "nuxt prepare" }, "dependencies": { "@tanstack/vue-query": "catalog:", "@wagmi/vue": "workspace:*", "nuxt": "catalog:", "viem": "2.*", "vue": "catalog:", "vue-router": "^4.3.2" } } ================================================ FILE: playgrounds/nuxt/plugins/wagmi.ts ================================================ import { VueQueryPlugin } from '@tanstack/vue-query' import { WagmiPlugin } from '@wagmi/vue' import { defineNuxtPlugin } from 'nuxt/app' import { config } from '../wagmi' // TODO: Move to @wagmi/vue/nuxt nitro plugin export default defineNuxtPlugin((nuxtApp) => { nuxtApp.vueApp.use(WagmiPlugin, { config }).use(VueQueryPlugin, {}) }) ================================================ FILE: playgrounds/nuxt/server/tsconfig.json ================================================ { "extends": "../.nuxt/tsconfig.server.json" } ================================================ FILE: playgrounds/nuxt/tsconfig.json ================================================ { "extends": "./.nuxt/tsconfig.json" } ================================================ FILE: playgrounds/nuxt/wagmi.ts ================================================ import { cookieStorage, createConfig, createStorage, http } from '@wagmi/vue' import { mainnet, optimism, sepolia } from '@wagmi/vue/chains' import { injected, metaMask, walletConnect } from '@wagmi/vue/connectors' export const config = createConfig({ chains: [mainnet, sepolia, optimism], connectors: [ injected(), walletConnect({ projectId: process.env.NUXT_PUBLIC_WC_PROJECT_ID!, }), metaMask(), ], storage: createStorage({ storage: cookieStorage, }), ssr: true, transports: { [mainnet.id]: http(), [sepolia.id]: http(), [optimism.id]: http(), }, }) declare module '@wagmi/vue' { interface Register { config: typeof config } } ================================================ FILE: playgrounds/solid-start/.gitignore ================================================ dist .wrangler .output .vercel .netlify .vinxi app.config.timestamp_*.js # Environment .env .env*.local # dependencies /node_modules # IDEs and editors /.idea .project .classpath *.launch .settings/ # Temp gitignore # System Files .DS_Store Thumbs.db ================================================ FILE: playgrounds/solid-start/app.config.ts ================================================ import { defineConfig } from '@solidjs/start/config' export default defineConfig({}) ================================================ FILE: playgrounds/solid-start/package.json ================================================ { "name": "solid-start-app", "private": true, "type": "module", "scripts": { "dev": "vinxi dev", "build": "vinxi build", "start": "vinxi start" }, "dependencies": { "@solidjs/start": "^1.1.0", "@tanstack/solid-query": "catalog:", "@wagmi/solid": "workspace:*", "solid-js": "catalog:", "viem": "2.*", "vinxi": "^0.5.7" } } ================================================ FILE: playgrounds/solid-start/src/app.css ================================================ :root { background-color: #181818; color: rgba(255, 255, 255, 0.87); color-scheme: light dark; font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; font-synthesis: none; font-weight: 400; line-height: 1.5; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-text-size-adjust: 100%; } @media (prefers-color-scheme: light) { :root { background-color: #f8f8f8; color: #181818; } } ================================================ FILE: playgrounds/solid-start/src/app.tsx ================================================ import { QueryClient, QueryClientProvider } from '@tanstack/solid-query' import { cookieToInitialState, useBalance, useBlockNumber, useChainId, useChains, useConnect, useConnection, useConnections, useConnectorClient, useConnectors, useDisconnect, useSwitchChain, useSwitchConnection, WagmiProvider, } from '@wagmi/solid' import { optimism } from '@wagmi/solid/chains' import { For, Show } from 'solid-js' import { getRequestEvent, isServer } from 'solid-js/web' import { formatEther, stringify } from 'viem' import { config } from './wagmi' function getInitialState() { if (!isServer) return undefined const event = getRequestEvent() const cookie = event?.request.headers.get('cookie') return cookieToInitialState(config, cookie) } export default function App() { const initialState = getInitialState() const queryClient = new QueryClient() return ( {/* */} {/* */} {/* */} {/* */} {/* */} ) } function Connection() { const connection = useConnection() const disconnect = useDisconnect() return (

Connection

account: {connection().address}
chainId: {connection().chainId}
status: {connection().status}
) } function Connect() { const chainId = useChainId() const connect = useConnect() const connectors = useConnectors() return (

Connect

{(connector) => ( )}
{connect.status}
{connect.error?.message}
) } function SwitchConnection() { const connection = useConnection() const { mutate: switchConnection } = useSwitchConnection() const connections = useConnections() return (

Switch Connection

{(conn) => ( )}
) } function SwitchChain() { const chainId = useChainId() const switchChain = useSwitchChain() const chains = useChains() return (

Switch Chain

{(chain) => ( )} {switchChain.error?.message}
) } function Connections() { const connections = useConnections() return (

Connections

{(connection) => (
connector {connection.connector.name}
accounts: {stringify(connection.accounts)}
chainId: {connection.chainId}
)}
) } function BlockNumber() { const default_ = useBlockNumber(() => ({ watch: true })) const account_ = useBlockNumber(() => ({ watch: true })) const optimism_ = useBlockNumber(() => ({ chainId: optimism.id, watch: true, })) return (

Block Number

Block Number (Default Chain): {default_.data?.toString()}
Block Number (Connection Chain): {account_.data?.toString()}
Block Number (Optimism): {optimism_.data?.toString()}
) } function Balance() { const connection = useConnection() const default_ = useBalance(() => ({ address: connection().address, })) const account_ = useBalance(() => ({ address: connection().address, })) const optimism_ = useBalance(() => ({ address: connection().address, chainId: optimism.id, })) return (

Balance

Balance (Default Chain):{' '} {!!default_?.data?.value && formatEther(default_.data.value)}
Balance (Connection Chain):{' '} {!!account_?.data?.value && formatEther(account_.data.value)}
Balance (Optimism Chain):{' '} {!!optimism_?.data?.value && formatEther(optimism_.data.value)}
) } function ConnectorClient() { const connectorClient = useConnectorClient() return (

Connector Client

client {connectorClient.data?.account?.address}{' '} {connectorClient.data?.chain?.id} {connectorClient.error?.message}
) } ================================================ FILE: playgrounds/solid-start/src/contracts.ts ================================================ export const wagmiContractConfig = { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: [ { inputs: [], stateMutability: 'nonpayable', type: 'constructor' }, { anonymous: false, inputs: [ { indexed: true, name: 'owner', type: 'address', }, { indexed: true, name: 'approved', type: 'address', }, { indexed: true, name: 'tokenId', type: 'uint256', }, ], name: 'Approval', type: 'event', }, { anonymous: false, inputs: [ { indexed: true, name: 'owner', type: 'address', }, { indexed: true, name: 'operator', type: 'address', }, { indexed: false, name: 'approved', type: 'bool', }, ], name: 'ApprovalForAll', type: 'event', }, { anonymous: false, inputs: [ { indexed: true, name: 'from', type: 'address', }, { indexed: true, name: 'to', type: 'address' }, { indexed: true, name: 'tokenId', type: 'uint256', }, ], name: 'Transfer', type: 'event', }, { inputs: [ { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, ], name: 'approve', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ name: 'owner', type: 'address' }], name: 'balanceOf', outputs: [{ name: '', type: 'uint256' }], stateMutability: 'view', type: 'function', }, { inputs: [{ name: 'tokenId', type: 'uint256' }], name: 'getApproved', outputs: [{ name: '', type: 'address' }], stateMutability: 'view', type: 'function', }, { inputs: [ { name: 'owner', type: 'address' }, { name: 'operator', type: 'address' }, ], name: 'isApprovedForAll', outputs: [{ name: '', type: 'bool' }], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'mint', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ internalType: 'uint256', name: 'tokenId', type: 'uint256' }], name: 'mint', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [], name: 'name', outputs: [{ name: '', type: 'string' }], stateMutability: 'view', type: 'function', }, { inputs: [{ name: 'tokenId', type: 'uint256' }], name: 'ownerOf', outputs: [{ name: '', type: 'address' }], stateMutability: 'view', type: 'function', }, { inputs: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, ], name: 'safeTransferFrom', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, { name: '_data', type: 'bytes' }, ], name: 'safeTransferFrom', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { name: 'operator', type: 'address' }, { name: 'approved', type: 'bool' }, ], name: 'setApprovalForAll', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ name: 'interfaceId', type: 'bytes4' }], name: 'supportsInterface', outputs: [{ name: '', type: 'bool' }], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'symbol', outputs: [{ name: '', type: 'string' }], stateMutability: 'view', type: 'function', }, { inputs: [{ name: 'tokenId', type: 'uint256' }], name: 'tokenURI', outputs: [{ name: '', type: 'string' }], stateMutability: 'pure', type: 'function', }, { inputs: [], name: 'totalSupply', outputs: [{ name: '', type: 'uint256' }], stateMutability: 'view', type: 'function', }, { inputs: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, ], name: 'transferFrom', outputs: [], stateMutability: 'nonpayable', type: 'function', }, ], } as const ================================================ FILE: playgrounds/solid-start/src/entry-client.tsx ================================================ // @refresh reload import { mount, StartClient } from '@solidjs/start/client' mount(() => , document.getElementById('app')!) ================================================ FILE: playgrounds/solid-start/src/entry-server.tsx ================================================ // @refresh reload import { createHandler, StartServer } from '@solidjs/start/server' export default createHandler(() => ( ( {assets}
{children}
{scripts} )} /> )) ================================================ FILE: playgrounds/solid-start/src/global.d.ts ================================================ /// ================================================ FILE: playgrounds/solid-start/src/wagmi.ts ================================================ import { createConfig, http } from '@wagmi/solid' import { celo, mainnet, optimism, sepolia } from '@wagmi/solid/chains' import { baseAccount, metaMask, porto, walletConnect, } from '@wagmi/solid/connectors' export const config = createConfig({ chains: [mainnet, sepolia, optimism, celo], connectors: [ walletConnect({ projectId: import.meta.env.VITE_WC_PROJECT_ID, }), porto(), baseAccount(), metaMask(), ], transports: { [mainnet.id]: http(), [sepolia.id]: http(), [optimism.id]: http(), [celo.id]: http(), }, ssr: true, }) declare module '@wagmi/solid' { interface Register { config: typeof config } } ================================================ FILE: playgrounds/solid-start/tsconfig.json ================================================ { "compilerOptions": { "target": "ESNext", "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true, "esModuleInterop": true, "jsx": "preserve", "jsxImportSource": "solid-js", "allowJs": true, "strict": true, "noEmit": true, "types": ["vinxi/types/client"], "isolatedModules": true, "paths": { "~/*": ["./src/*"], "@wagmi/connectors": ["../../packages/connectors/src/exports"], "@wagmi/core": ["../../packages/core/src/exports"], "@wagmi/core/*": ["../../packages/core/src/exports/*"], "@wagmi/solid": ["../../packages/solid/src/exports"], "@wagmi/solid/*": ["../../packages/solid/src/exports/*"] } } } ================================================ FILE: playgrounds/tanstack-start/package.json ================================================ { "name": "tanstack-start", "private": true, "type": "module", "scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview", "deploy": "pnpm build && wrangler deploy" }, "dependencies": { "@cloudflare/vite-plugin": "^1.20.0", "@tanstack/react-query": "catalog:", "@tanstack/react-query-devtools": "^5.91.2", "@tanstack/react-router": "^1.145.7", "@tanstack/react-router-ssr-query": "^1.145.7", "@tanstack/react-start": "^1.166.16", "@tanstack/router-plugin": "^1.145.7", "react": "catalog:", "react-dom": "catalog:", "viem": "2.*", "wagmi": "workspace:*" }, "devDependencies": { "@tanstack/devtools-vite": "^0.4.1", "@tanstack/react-devtools": "^0.9.1", "@tanstack/react-router-devtools": "^1.145.7", "@types/node": "^24.5.1", "@types/react": "catalog:", "@types/react-dom": "catalog:", "@vitejs/plugin-react": "catalog:", "typescript": "^5.9.3", "vite": "catalog:", "wrangler": "^4.59.1" } } ================================================ FILE: playgrounds/tanstack-start/src/contracts.ts ================================================ export const wagmiContractConfig = { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: [ { inputs: [], stateMutability: 'nonpayable', type: 'constructor' }, { anonymous: false, inputs: [ { indexed: true, name: 'owner', type: 'address', }, { indexed: true, name: 'approved', type: 'address', }, { indexed: true, name: 'tokenId', type: 'uint256', }, ], name: 'Approval', type: 'event', }, { anonymous: false, inputs: [ { indexed: true, name: 'owner', type: 'address', }, { indexed: true, name: 'operator', type: 'address', }, { indexed: false, name: 'approved', type: 'bool', }, ], name: 'ApprovalForAll', type: 'event', }, { anonymous: false, inputs: [ { indexed: true, name: 'from', type: 'address', }, { indexed: true, name: 'to', type: 'address' }, { indexed: true, name: 'tokenId', type: 'uint256', }, ], name: 'Transfer', type: 'event', }, { inputs: [ { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, ], name: 'approve', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ name: 'owner', type: 'address' }], name: 'balanceOf', outputs: [{ name: '', type: 'uint256' }], stateMutability: 'view', type: 'function', }, { inputs: [{ name: 'tokenId', type: 'uint256' }], name: 'getApproved', outputs: [{ name: '', type: 'address' }], stateMutability: 'view', type: 'function', }, { inputs: [ { name: 'owner', type: 'address' }, { name: 'operator', type: 'address' }, ], name: 'isApprovedForAll', outputs: [{ name: '', type: 'bool' }], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'mint', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ internalType: 'uint256', name: 'tokenId', type: 'uint256' }], name: 'mint', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [], name: 'name', outputs: [{ name: '', type: 'string' }], stateMutability: 'view', type: 'function', }, { inputs: [{ name: 'tokenId', type: 'uint256' }], name: 'ownerOf', outputs: [{ name: '', type: 'address' }], stateMutability: 'view', type: 'function', }, { inputs: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, ], name: 'safeTransferFrom', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, { name: '_data', type: 'bytes' }, ], name: 'safeTransferFrom', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { name: 'operator', type: 'address' }, { name: 'approved', type: 'bool' }, ], name: 'setApprovalForAll', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ name: 'interfaceId', type: 'bytes4' }], name: 'supportsInterface', outputs: [{ name: '', type: 'bool' }], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'symbol', outputs: [{ name: '', type: 'string' }], stateMutability: 'view', type: 'function', }, { inputs: [{ name: 'tokenId', type: 'uint256' }], name: 'tokenURI', outputs: [{ name: '', type: 'string' }], stateMutability: 'pure', type: 'function', }, { inputs: [], name: 'totalSupply', outputs: [{ name: '', type: 'uint256' }], stateMutability: 'view', type: 'function', }, { inputs: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, ], name: 'transferFrom', outputs: [], stateMutability: 'nonpayable', type: 'function', }, ], } as const ================================================ FILE: playgrounds/tanstack-start/src/index.css ================================================ :root { background-color: #181818; color: rgba(255, 255, 255, 0.87); color-scheme: light dark; font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; font-synthesis: none; font-weight: 400; line-height: 1.5; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-text-size-adjust: 100%; } @media (prefers-color-scheme: light) { :root { background-color: #f8f8f8; color: #181818; } } ================================================ FILE: playgrounds/tanstack-start/src/routeTree.gen.ts ================================================ /* eslint-disable */ // @ts-nocheck // noinspection JSUnusedGlobalSymbols // This file was automatically generated by TanStack Router. // You should NOT make any changes in this file as it will be overwritten. // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute } export interface FileRoutesByTo { '/': typeof IndexRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath fullPaths: '/' fileRoutesByTo: FileRoutesByTo to: '/' id: '__root__' | '/' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute } declare module '@tanstack/react-router' { interface FileRoutesByPath { '/': { id: '/' path: '/' fullPath: '/' preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } } } const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) ._addFileTypes() import type { getRouter } from './router.tsx' import type { createStart } from '@tanstack/react-start' declare module '@tanstack/react-start' { interface Register { ssr: true router: Awaited> } } ================================================ FILE: playgrounds/tanstack-start/src/router.tsx ================================================ import { QueryClient } from '@tanstack/react-query' import { createRouter } from '@tanstack/react-router' import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query' import { hashFn } from 'wagmi/query' import { routeTree } from './routeTree.gen' export const getRouter = () => { const queryClient: QueryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 60 * 1_000, gcTime: 1_000 * 60 * 60 * 24, queryKeyHashFn: hashFn, refetchOnWindowFocus: false, refetchOnReconnect: () => !queryClient.isMutating(), }, }, }) const router = createRouter({ routeTree, context: { queryClient, }, defaultPreload: 'intent', }) setupRouterSsrQueryIntegration({ router, queryClient, wrapQueryClient: false, }) return router } ================================================ FILE: playgrounds/tanstack-start/src/routes/__root.tsx ================================================ import { TanStackDevtools } from '@tanstack/react-devtools' import { type QueryClient, QueryClientProvider } from '@tanstack/react-query' import { ReactQueryDevtools as TanStackQueryDevtoolsPanel } from '@tanstack/react-query-devtools' import { createRootRouteWithContext, HeadContent, Scripts, } from '@tanstack/react-router' import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools' import * as React from 'react' import { deserialize, type State, WagmiProvider } from 'wagmi' import appCss from '../index.css?url' import { getConfig, getWagmiStateSSR } from '../wagmi' export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()( { head: () => ({ meta: [ { charSet: 'utf-8' }, { title: 'TanStack Start Example' }, { name: 'viewport', content: 'width=device-width, initial-scale=1' }, ], links: [ { rel: 'stylesheet', href: appCss, }, ], }), notFoundComponent: () =>
Not Found
, loader: () => getWagmiStateSSR(), shellComponent: RootDocument, }, ) function RootDocument({ children }: { children: React.ReactNode }) { const { queryClient } = Route.useRouteContext() const [config] = React.useState(() => getConfig()) const wagmiState = Route.useLoaderData({ select: deserialize }) return ( {children} , }, { name: 'Tanstack Query', render: , }, ]} /> ) } ================================================ FILE: playgrounds/tanstack-start/src/routes/index.tsx ================================================ import { ClientOnly, createFileRoute } from '@tanstack/react-router' import { getRequestHeader } from '@tanstack/react-start/server' import type { FormEvent } from 'react' import * as React from 'react' import { formatEther, type Hex, parseAbi, parseEther } from 'viem' import { type BaseError, useBalance, useBlockNumber, useChainId, useChains, useConfig, useConnect, useConnection, useConnectionEffect, useConnections, useConnectorClient, useConnectors, useDisconnect, useEnsName, useReadContract, useReadContracts, useSendTransaction, useSignMessage, useSwitchChain, useSwitchConnection, useWaitForTransactionReceipt, useWriteContract, } from 'wagmi' import { switchChain } from 'wagmi/actions' import { optimism, sepolia } from 'wagmi/chains' import { wagmiContractConfig } from '../contracts' export const Route = createFileRoute('/')({ server: { handlers: { GET: async ({ next }) => { const headers = getRequestHeader('cookie') // biome-ignore lint/suspicious/noConsole: _ console.info(headers) return next() }, }, }, component: RouteComponent, }) function RouteComponent() { useConnectionEffect({ onConnect(data) { console.log('onConnect', data) }, onDisconnect() { console.log('onDisconnect') }, }) return ( <> }> ) } function Connection() { const { address, chainId } = useConnection() const disconnect = useDisconnect() const { data: ensName } = useEnsName({ address }) return (

Connection

account: {address} {ensName}
chainId: {chainId}
{/* status: {isMounted ? connection.status : 'disconnected'} */}
) } function Connect() { const chainId = useChainId() const connect = useConnect() const connectors = useConnectors() return (

Connect

{connectors.map((connector) => ( ))}
{connect.status}
{connect.error?.message}
) } function SwitchConnection() { const connection = useConnection() const { mutate: switchConnection } = useSwitchConnection() const connections = useConnections() return (

Switch Connection

{connections.map(({ connector }) => ( ))}
) } function SwitchChain() { const chainId = useChainId() const { mutate: switchChain, error } = useSwitchChain() const chains = useChains() return (

Switch Chain

{chains.map((chain) => ( ))} {error?.message}
) } function SignMessage() { const { data, mutate: signMessage } = useSignMessage() return (

Sign Message

{ event.preventDefault() const formData = new FormData(event.target as HTMLFormElement) signMessage({ message: formData.get('message') as string }) }} >
{data}
) } function Connections() { const connections = useConnections() return (

Connections

{connections.map((connection) => (
connector {connection.connector.name}
accounts: {JSON.stringify(connection.accounts)}
chainId: {connection.chainId}
))}
) } function Balance() { const { address } = useConnection() const { data: default_ } = useBalance({ address }) const { data: account_ } = useBalance({ address }) const { data: optimism_ } = useBalance({ address, chainId: optimism.id, }) return (

Balance

Balance (Default Chain):{' '} {!!default_?.value && formatEther(default_.value)}
Balance (Connection Chain):{' '} {!!account_?.value && formatEther(account_.value)}
Balance (Optimism Chain):{' '} {!!optimism_?.value && formatEther(optimism_.value)}
) } function BlockNumber() { const { data: default_ } = useBlockNumber({ watch: true }) const { data: account_ } = useBlockNumber({ watch: true, }) const { data: optimism_ } = useBlockNumber({ chainId: optimism.id, watch: true, }) return (

Block Number

Block Number (Default Chain): {default_?.toString()}
Block Number (Connection Chain): {account_?.toString()}
Block Number (Optimism): {optimism_?.toString()}
) } function ConnectorClient() { const { data, error } = useConnectorClient() return (

Connector Client

client {data?.account?.address} {data?.chain?.id} {error?.message}
) } function SendTransaction() { const { data: hash, error, isPending, mutate } = useSendTransaction() async function submit(e: FormEvent) { e.preventDefault() const formData = new FormData(e.target as HTMLFormElement) const to = formData.get('address') as Hex const value = formData.get('value') as string mutate({ to, value: parseEther(value) }) } const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({ hash, }) return (

Send Transaction

{hash &&
Transaction Hash: {hash}
} {isConfirming && 'Waiting for confirmation...'} {isConfirmed && 'Transaction confirmed.'} {error && (
Error: {(error as BaseError).shortMessage || error.message}
)}
) } function ReadContract() { const { data: balance } = useReadContract({ ...wagmiContractConfig, functionName: 'balanceOf', args: ['0x03A71968491d55603FFe1b11A9e23eF013f75bCF'], }) return (

Read Contract

Balance: {balance?.toString()}
) } function ReadContracts() { const { data } = useReadContracts({ allowFailure: false, contracts: [ { ...wagmiContractConfig, functionName: 'balanceOf', args: ['0x03A71968491d55603FFe1b11A9e23eF013f75bCF'], }, { ...wagmiContractConfig, functionName: 'ownerOf', args: [69n], }, { ...wagmiContractConfig, functionName: 'totalSupply', }, ], }) const [balance, ownerOf, totalSupply] = data || [] return (

Read Contract

Balance: {balance?.toString()}
Owner of Token 69: {ownerOf?.toString()}
Total Supply: {totalSupply?.toString()}
) } function WriteContract() { const { data: hash, error, isPending, mutate: writeContract, } = useWriteContract() async function submit(e: FormEvent) { e.preventDefault() const formData = new FormData(e.target as HTMLFormElement) const tokenId = formData.get('tokenId') as string writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: parseAbi(['function mint(uint256 tokenId)']), functionName: 'mint', args: [BigInt(tokenId)], }) } const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({ hash, }) return (

Write Contract

{hash &&
Transaction Hash: {hash}
} {isConfirming && 'Waiting for confirmation...'} {isConfirmed && 'Transaction confirmed.'} {error && (
Error: {(error as BaseError).shortMessage || error.message}
)}
) } function Repro() { const config = useConfig() const chainId = useChainId() console.log('chainId from useChainId is', chainId) return (
Current Chain Id: {chainId}
) } ================================================ FILE: playgrounds/tanstack-start/src/wagmi.ts ================================================ import { createServerFn } from '@tanstack/react-start' import { getRequestHeader } from '@tanstack/react-start/server' import { cookieStorage, cookieToInitialState, createConfig, createStorage, http, serialize, } from 'wagmi' import { mainnet, optimism, sepolia } from 'wagmi/chains' import { injected, metaMask } from 'wagmi/connectors' export function getConfig() { return createConfig({ chains: [mainnet, sepolia, optimism], connectors: [injected(), metaMask()], storage: createStorage({ storage: cookieStorage, }), ssr: true, transports: { [mainnet.id]: http(), [sepolia.id]: http(), [optimism.id]: http(), }, }) } export const getWagmiStateSSR = createServerFn().handler(() => { const cookie = getRequestHeader('cookie') const initialState = cookieToInitialState(getConfig(), cookie) return serialize(initialState || {}) }) declare module 'wagmi' { interface Register { config: ReturnType } } ================================================ FILE: playgrounds/tanstack-start/tsconfig.json ================================================ { "include": ["**/*.ts", "**/*.tsx"], "compilerOptions": { "target": "ES2022", "jsx": "react-jsx", "module": "ESNext", "lib": ["ES2022", "DOM", "DOM.Iterable"], "types": ["vite/client"], /* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "verbatimModuleSyntax": false, "noEmit": true, /* Linting */ "skipLibCheck": true, "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true, "baseUrl": "." }, "files": ["./worker-configuration.d.ts"] } ================================================ FILE: playgrounds/tanstack-start/vite.config.ts ================================================ import { cloudflare } from '@cloudflare/vite-plugin' import { devtools } from '@tanstack/devtools-vite' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' import { defineConfig } from 'vite' export default defineConfig({ plugins: [ devtools(), cloudflare({ viteEnvironment: { name: 'ssr' } }), tanstackStart(), viteReact(), ], }) ================================================ FILE: playgrounds/tanstack-start/worker-configuration.d.ts ================================================ /* eslint-disable */ // Generated by Wrangler by running `wrangler types` (hash: c12347f6456cb051ac2112c49b405c15) // Runtime types generated with workerd@1.20260103.0 2025-12-10 nodejs_compat declare namespace Cloudflare { interface Env { VITE_PUBLIC_WC_PROJECT_ID: 'your-project-id' } } interface Env extends Cloudflare.Env {} type StringifyValues> = { [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string } declare namespace NodeJS { interface ProcessEnv extends StringifyValues< Pick > {} } // Begin runtime types /*! ***************************************************************************** Copyright (c) Cloudflare. All rights reserved. Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* eslint-disable */ // noinspection JSUnusedGlobalSymbols declare var onmessage: never /** * The **`DOMException`** interface represents an abnormal event (called an **exception**) that occurs as a result of calling a method or accessing a property of a web API. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException) */ declare class DOMException extends Error { constructor(message?: string, name?: string) /** * The **`message`** read-only property of the a message or description associated with the given error name. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ readonly message: string /** * The **`name`** read-only property of the one of the strings associated with an error name. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ readonly name: string /** * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or `0` if none match. * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) */ readonly code: number static readonly INDEX_SIZE_ERR: number static readonly DOMSTRING_SIZE_ERR: number static readonly HIERARCHY_REQUEST_ERR: number static readonly WRONG_DOCUMENT_ERR: number static readonly INVALID_CHARACTER_ERR: number static readonly NO_DATA_ALLOWED_ERR: number static readonly NO_MODIFICATION_ALLOWED_ERR: number static readonly NOT_FOUND_ERR: number static readonly NOT_SUPPORTED_ERR: number static readonly INUSE_ATTRIBUTE_ERR: number static readonly INVALID_STATE_ERR: number static readonly SYNTAX_ERR: number static readonly INVALID_MODIFICATION_ERR: number static readonly NAMESPACE_ERR: number static readonly INVALID_ACCESS_ERR: number static readonly VALIDATION_ERR: number static readonly TYPE_MISMATCH_ERR: number static readonly SECURITY_ERR: number static readonly NETWORK_ERR: number static readonly ABORT_ERR: number static readonly URL_MISMATCH_ERR: number static readonly QUOTA_EXCEEDED_ERR: number static readonly TIMEOUT_ERR: number static readonly INVALID_NODE_TYPE_ERR: number static readonly DATA_CLONE_ERR: number get stack(): any set stack(value: any) } type WorkerGlobalScopeEventMap = { fetch: FetchEvent scheduled: ScheduledEvent queue: QueueEvent unhandledrejection: PromiseRejectionEvent rejectionhandled: PromiseRejectionEvent } declare abstract class WorkerGlobalScope extends EventTarget { EventTarget: typeof EventTarget } /* The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). * * The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ interface Console { assert(condition?: boolean, ...data: any[]): void /** * The **`console.clear()`** static method clears the console if possible. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ clear(): void /** * The **`console.count()`** static method logs the number of times that this particular call to `count()` has been called. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ count(label?: string): void /** * The **`console.countReset()`** static method resets counter used with console/count_static. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ countReset(label?: string): void /** * The **`console.debug()`** static method outputs a message to the console at the 'debug' log level. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ debug(...data: any[]): void /** * The **`console.dir()`** static method displays a list of the properties of the specified JavaScript object. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ dir(item?: any, options?: any): void /** * The **`console.dirxml()`** static method displays an interactive tree of the descendant elements of the specified XML/HTML element. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ dirxml(...data: any[]): void /** * The **`console.error()`** static method outputs a message to the console at the 'error' log level. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ error(...data: any[]): void /** * The **`console.group()`** static method creates a new inline group in the Web console log, causing any subsequent console messages to be indented by an additional level, until console/groupEnd_static is called. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ group(...data: any[]): void /** * The **`console.groupCollapsed()`** static method creates a new inline group in the console. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ groupCollapsed(...data: any[]): void /** * The **`console.groupEnd()`** static method exits the current inline group in the console. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ groupEnd(): void /** * The **`console.info()`** static method outputs a message to the console at the 'info' log level. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ info(...data: any[]): void /** * The **`console.log()`** static method outputs a message to the console. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ log(...data: any[]): void /** * The **`console.table()`** static method displays tabular data as a table. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ table(tabularData?: any, properties?: string[]): void /** * The **`console.time()`** static method starts a timer you can use to track how long an operation takes. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ time(label?: string): void /** * The **`console.timeEnd()`** static method stops a timer that was previously started by calling console/time_static. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ timeEnd(label?: string): void /** * The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling console/time_static. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ timeLog(label?: string, ...data: any[]): void timeStamp(label?: string): void /** * The **`console.trace()`** static method outputs a stack trace to the console. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ trace(...data: any[]): void /** * The **`console.warn()`** static method outputs a warning message to the console at the 'warning' log level. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ warn(...data: any[]): void } declare const console: Console type BufferSource = ArrayBufferView | ArrayBuffer type TypedArray = | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array declare namespace WebAssembly { class CompileError extends Error { constructor(message?: string) } class RuntimeError extends Error { constructor(message?: string) } type ValueType = | 'anyfunc' | 'externref' | 'f32' | 'f64' | 'i32' | 'i64' | 'v128' interface GlobalDescriptor { value: ValueType mutable?: boolean } class Global { constructor(descriptor: GlobalDescriptor, value?: any) value: any valueOf(): any } type ImportValue = ExportValue | number type ModuleImports = Record type Imports = Record type ExportValue = Function | Global | Memory | Table type Exports = Record class Instance { constructor(module: Module, imports?: Imports) readonly exports: Exports } interface MemoryDescriptor { initial: number maximum?: number shared?: boolean } class Memory { constructor(descriptor: MemoryDescriptor) readonly buffer: ArrayBuffer grow(delta: number): number } type ImportExportKind = 'function' | 'global' | 'memory' | 'table' interface ModuleExportDescriptor { kind: ImportExportKind name: string } interface ModuleImportDescriptor { kind: ImportExportKind module: string name: string } abstract class Module { static customSections(module: Module, sectionName: string): ArrayBuffer[] static exports(module: Module): ModuleExportDescriptor[] static imports(module: Module): ModuleImportDescriptor[] } type TableKind = 'anyfunc' | 'externref' interface TableDescriptor { element: TableKind initial: number maximum?: number } class Table { constructor(descriptor: TableDescriptor, value?: any) readonly length: number get(index: number): any grow(delta: number, value?: any): number set(index: number, value?: any): void } function instantiate(module: Module, imports?: Imports): Promise function validate(bytes: BufferSource): boolean } /** * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker. * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) */ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { DOMException: typeof DOMException WorkerGlobalScope: typeof WorkerGlobalScope btoa(data: string): string atob(data: string): string setTimeout(callback: (...args: any[]) => void, msDelay?: number): number setTimeout( callback: (...args: Args) => void, msDelay?: number, ...args: Args ): number clearTimeout(timeoutId: number | null): void setInterval(callback: (...args: any[]) => void, msDelay?: number): number setInterval( callback: (...args: Args) => void, msDelay?: number, ...args: Args ): number clearInterval(timeoutId: number | null): void queueMicrotask(task: Function): void structuredClone(value: T, options?: StructuredSerializeOptions): T reportError(error: any): void fetch( input: RequestInfo | URL, init?: RequestInit, ): Promise self: ServiceWorkerGlobalScope crypto: Crypto caches: CacheStorage scheduler: Scheduler performance: Performance Cloudflare: Cloudflare readonly origin: string Event: typeof Event ExtendableEvent: typeof ExtendableEvent CustomEvent: typeof CustomEvent PromiseRejectionEvent: typeof PromiseRejectionEvent FetchEvent: typeof FetchEvent TailEvent: typeof TailEvent TraceEvent: typeof TailEvent ScheduledEvent: typeof ScheduledEvent MessageEvent: typeof MessageEvent CloseEvent: typeof CloseEvent ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader ReadableStream: typeof ReadableStream WritableStream: typeof WritableStream WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter TransformStream: typeof TransformStream ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy CountQueuingStrategy: typeof CountQueuingStrategy ErrorEvent: typeof ErrorEvent MessageChannel: typeof MessageChannel MessagePort: typeof MessagePort EventSource: typeof EventSource ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest ReadableStreamDefaultController: typeof ReadableStreamDefaultController ReadableByteStreamController: typeof ReadableByteStreamController WritableStreamDefaultController: typeof WritableStreamDefaultController TransformStreamDefaultController: typeof TransformStreamDefaultController CompressionStream: typeof CompressionStream DecompressionStream: typeof DecompressionStream TextEncoderStream: typeof TextEncoderStream TextDecoderStream: typeof TextDecoderStream Headers: typeof Headers Body: typeof Body Request: typeof Request Response: typeof Response WebSocket: typeof WebSocket WebSocketPair: typeof WebSocketPair WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair AbortController: typeof AbortController AbortSignal: typeof AbortSignal TextDecoder: typeof TextDecoder TextEncoder: typeof TextEncoder navigator: Navigator Navigator: typeof Navigator URL: typeof URL URLSearchParams: typeof URLSearchParams URLPattern: typeof URLPattern Blob: typeof Blob File: typeof File FormData: typeof FormData Crypto: typeof Crypto SubtleCrypto: typeof SubtleCrypto CryptoKey: typeof CryptoKey CacheStorage: typeof CacheStorage Cache: typeof Cache FixedLengthStream: typeof FixedLengthStream IdentityTransformStream: typeof IdentityTransformStream HTMLRewriter: typeof HTMLRewriter } declare function addEventListener( type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean, ): void declare function removeEventListener< Type extends keyof WorkerGlobalScopeEventMap, >( type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean, ): void /** * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) */ declare function dispatchEvent( event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], ): boolean /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */ declare function btoa(data: string): string /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */ declare function atob(data: string): string /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ declare function setTimeout( callback: (...args: any[]) => void, msDelay?: number, ): number /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ declare function setTimeout( callback: (...args: Args) => void, msDelay?: number, ...args: Args ): number /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */ declare function clearTimeout(timeoutId: number | null): void /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ declare function setInterval( callback: (...args: any[]) => void, msDelay?: number, ): number /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ declare function setInterval( callback: (...args: Args) => void, msDelay?: number, ...args: Args ): number /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */ declare function clearInterval(timeoutId: number | null): void /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */ declare function queueMicrotask(task: Function): void /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ declare function structuredClone( value: T, options?: StructuredSerializeOptions, ): T /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */ declare function reportError(error: any): void /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ declare function fetch( input: RequestInfo | URL, init?: RequestInit, ): Promise declare const self: ServiceWorkerGlobalScope /** * The Web Crypto API provides a set of low-level functions for common cryptographic tasks. * The Workers runtime implements the full surface of this API, but with some differences in * the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) * compared to those implemented in most browsers. * * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) */ declare const crypto: Crypto /** * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. * * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) */ declare const caches: CacheStorage declare const scheduler: Scheduler /** * The Workers runtime supports a subset of the Performance API, used to measure timing and performance, * as well as timing of subrequests and other operations. * * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) */ declare const performance: Performance declare const Cloudflare: Cloudflare declare const origin: string declare const navigator: Navigator type TestController = {} interface ExecutionContext { waitUntil(promise: Promise): void passThroughOnException(): void readonly exports: Cloudflare.Exports readonly props: Props } type ExportedHandlerFetchHandler = ( request: Request>, env: Env, ctx: ExecutionContext, ) => Response | Promise type ExportedHandlerTailHandler = ( events: TraceItem[], env: Env, ctx: ExecutionContext, ) => void | Promise type ExportedHandlerTraceHandler = ( traces: TraceItem[], env: Env, ctx: ExecutionContext, ) => void | Promise type ExportedHandlerTailStreamHandler = ( event: TailStream.TailEvent, env: Env, ctx: ExecutionContext, ) => TailStream.TailEventHandlerType | Promise type ExportedHandlerScheduledHandler = ( controller: ScheduledController, env: Env, ctx: ExecutionContext, ) => void | Promise type ExportedHandlerQueueHandler = ( batch: MessageBatch, env: Env, ctx: ExecutionContext, ) => void | Promise type ExportedHandlerTestHandler = ( controller: TestController, env: Env, ctx: ExecutionContext, ) => void | Promise interface ExportedHandler< Env = unknown, QueueHandlerMessage = unknown, CfHostMetadata = unknown, > { fetch?: ExportedHandlerFetchHandler tail?: ExportedHandlerTailHandler trace?: ExportedHandlerTraceHandler tailStream?: ExportedHandlerTailStreamHandler scheduled?: ExportedHandlerScheduledHandler test?: ExportedHandlerTestHandler email?: EmailExportedHandler queue?: ExportedHandlerQueueHandler } interface StructuredSerializeOptions { transfer?: any[] } declare abstract class Navigator { sendBeacon(url: string, body?: BodyInit): boolean readonly userAgent: string readonly hardwareConcurrency: number readonly language: string readonly languages: string[] } interface AlarmInvocationInfo { readonly isRetry: boolean readonly retryCount: number } interface Cloudflare { readonly compatibilityFlags: Record } interface DurableObject { fetch(request: Request): Response | Promise alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise webSocketMessage?( ws: WebSocket, message: string | ArrayBuffer, ): void | Promise webSocketClose?( ws: WebSocket, code: number, reason: string, wasClean: boolean, ): void | Promise webSocketError?(ws: WebSocket, error: unknown): void | Promise } type DurableObjectStub< T extends Rpc.DurableObjectBranded | undefined = undefined, > = Fetcher< T, 'alarm' | 'webSocketMessage' | 'webSocketClose' | 'webSocketError' > & { readonly id: DurableObjectId readonly name?: string } interface DurableObjectId { toString(): string equals(other: DurableObjectId): boolean readonly name?: string } declare abstract class DurableObjectNamespace< T extends Rpc.DurableObjectBranded | undefined = undefined, > { newUniqueId( options?: DurableObjectNamespaceNewUniqueIdOptions, ): DurableObjectId idFromName(name: string): DurableObjectId idFromString(id: string): DurableObjectId get( id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions, ): DurableObjectStub getByName( name: string, options?: DurableObjectNamespaceGetDurableObjectOptions, ): DurableObjectStub jurisdiction( jurisdiction: DurableObjectJurisdiction, ): DurableObjectNamespace } type DurableObjectJurisdiction = 'eu' | 'fedramp' | 'fedramp-high' interface DurableObjectNamespaceNewUniqueIdOptions { jurisdiction?: DurableObjectJurisdiction } type DurableObjectLocationHint = | 'wnam' | 'enam' | 'sam' | 'weur' | 'eeur' | 'apac' | 'oc' | 'afr' | 'me' type DurableObjectRoutingMode = 'primary-only' interface DurableObjectNamespaceGetDurableObjectOptions { locationHint?: DurableObjectLocationHint routingMode?: DurableObjectRoutingMode } type DurableObjectClass< _T extends Rpc.DurableObjectBranded | undefined = undefined, > = {} interface DurableObjectState { waitUntil(promise: Promise): void readonly exports: Cloudflare.Exports readonly props: Props readonly id: DurableObjectId readonly storage: DurableObjectStorage container?: Container blockConcurrencyWhile(callback: () => Promise): Promise acceptWebSocket(ws: WebSocket, tags?: string[]): void getWebSockets(tag?: string): WebSocket[] setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void getWebSocketAutoResponse(): WebSocketRequestResponsePair | null getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null setHibernatableWebSocketEventTimeout(timeoutMs?: number): void getHibernatableWebSocketEventTimeout(): number | null getTags(ws: WebSocket): string[] abort(reason?: string): void } interface DurableObjectTransaction { get( key: string, options?: DurableObjectGetOptions, ): Promise get( keys: string[], options?: DurableObjectGetOptions, ): Promise> list(options?: DurableObjectListOptions): Promise> put( key: string, value: T, options?: DurableObjectPutOptions, ): Promise put( entries: Record, options?: DurableObjectPutOptions, ): Promise delete(key: string, options?: DurableObjectPutOptions): Promise delete(keys: string[], options?: DurableObjectPutOptions): Promise rollback(): void getAlarm(options?: DurableObjectGetAlarmOptions): Promise setAlarm( scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions, ): Promise deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise } interface DurableObjectStorage { get( key: string, options?: DurableObjectGetOptions, ): Promise get( keys: string[], options?: DurableObjectGetOptions, ): Promise> list(options?: DurableObjectListOptions): Promise> put( key: string, value: T, options?: DurableObjectPutOptions, ): Promise put( entries: Record, options?: DurableObjectPutOptions, ): Promise delete(key: string, options?: DurableObjectPutOptions): Promise delete(keys: string[], options?: DurableObjectPutOptions): Promise deleteAll(options?: DurableObjectPutOptions): Promise transaction( closure: (txn: DurableObjectTransaction) => Promise, ): Promise getAlarm(options?: DurableObjectGetAlarmOptions): Promise setAlarm( scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions, ): Promise deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise sync(): Promise sql: SqlStorage kv: SyncKvStorage transactionSync(closure: () => T): T getCurrentBookmark(): Promise getBookmarkForTime(timestamp: number | Date): Promise onNextSessionRestoreBookmark(bookmark: string): Promise } interface DurableObjectListOptions { start?: string startAfter?: string end?: string prefix?: string reverse?: boolean limit?: number allowConcurrency?: boolean noCache?: boolean } interface DurableObjectGetOptions { allowConcurrency?: boolean noCache?: boolean } interface DurableObjectGetAlarmOptions { allowConcurrency?: boolean } interface DurableObjectPutOptions { allowConcurrency?: boolean allowUnconfirmed?: boolean noCache?: boolean } interface DurableObjectSetAlarmOptions { allowConcurrency?: boolean allowUnconfirmed?: boolean } declare class WebSocketRequestResponsePair { constructor(request: string, response: string) get request(): string get response(): string } interface AnalyticsEngineDataset { writeDataPoint(event?: AnalyticsEngineDataPoint): void } interface AnalyticsEngineDataPoint { indexes?: ((ArrayBuffer | string) | null)[] doubles?: number[] blobs?: ((ArrayBuffer | string) | null)[] } /** * The **`Event`** interface represents an event which takes place on an `EventTarget`. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) */ declare class Event { constructor(type: string, init?: EventInit) /** * The **`type`** read-only property of the Event interface returns a string containing the event's type. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) */ get type(): string /** * The **`eventPhase`** read-only property of the being evaluated. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) */ get eventPhase(): number /** * The read-only **`composed`** property of the or not the event will propagate across the shadow DOM boundary into the standard DOM. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) */ get composed(): boolean /** * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) */ get bubbles(): boolean /** * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) */ get cancelable(): boolean /** * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) */ get defaultPrevented(): boolean /** * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not. * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) */ get returnValue(): boolean /** * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) */ get currentTarget(): EventTarget | undefined /** * The read-only **`target`** property of the dispatched. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) */ get target(): EventTarget | undefined /** * The deprecated **`Event.srcElement`** is an alias for the Event.target property. * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) */ get srcElement(): EventTarget | undefined /** * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) */ get timeStamp(): number /** * The **`isTrusted`** read-only property of the when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and `false` when the event was dispatched via The only exception is the `click` event, which initializes the `isTrusted` property to `false` in user agents. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) */ get isTrusted(): boolean /** * The **`cancelBubble`** property of the Event interface is deprecated. * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) */ get cancelBubble(): boolean /** * The **`cancelBubble`** property of the Event interface is deprecated. * @deprecated * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) */ set cancelBubble(value: boolean) /** * The **`stopImmediatePropagation()`** method of the If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) */ stopImmediatePropagation(): void /** * The **`preventDefault()`** method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) */ preventDefault(): void /** * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) */ stopPropagation(): void /** * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) */ composedPath(): EventTarget[] static readonly NONE: number static readonly CAPTURING_PHASE: number static readonly AT_TARGET: number static readonly BUBBLING_PHASE: number } interface EventInit { bubbles?: boolean cancelable?: boolean composed?: boolean } type EventListener = (event: EventType) => void interface EventListenerObject { handleEvent(event: EventType): void } type EventListenerOrEventListenerObject = | EventListener | EventListenerObject /** * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget) */ declare class EventTarget< EventMap extends Record = Record, > { constructor() /** * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) */ addEventListener( type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean, ): void /** * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) */ removeEventListener( type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean, ): void /** * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) */ dispatchEvent(event: EventMap[keyof EventMap]): boolean } interface EventTargetEventListenerOptions { capture?: boolean } interface EventTargetAddEventListenerOptions { capture?: boolean passive?: boolean once?: boolean signal?: AbortSignal } interface EventTargetHandlerObject { handleEvent: (event: Event) => any | undefined } /** * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) */ declare class AbortController { constructor() /** * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) */ get signal(): AbortSignal /** * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) */ abort(reason?: any): void } /** * The **`AbortSignal`** interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an AbortController object. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal) */ declare abstract class AbortSignal extends EventTarget { /** * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an AbortSignal/abort_event event). * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ static abort(reason?: any): AbortSignal /** * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ static timeout(delay: number): AbortSignal /** * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) */ static any(signals: AbortSignal[]): AbortSignal /** * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (`true`) or not (`false`). * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) */ get aborted(): boolean /** * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ get reason(): any /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ get onabort(): any | null /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ set onabort(value: any | null) /** * The **`throwIfAborted()`** method throws the signal's abort AbortSignal.reason if the signal has been aborted; otherwise it does nothing. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ throwIfAborted(): void } interface Scheduler { wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise } interface SchedulerWaitOptions { signal?: AbortSignal } /** * The **`ExtendableEvent`** interface extends the lifetime of the `install` and `activate` events dispatched on the global scope as part of the service worker lifecycle. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent) */ declare abstract class ExtendableEvent extends Event { /** * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ waitUntil(promise: Promise): void } /** * The **`CustomEvent`** interface represents events initialized by an application for any purpose. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) */ declare class CustomEvent extends Event { constructor(type: string, init?: CustomEventCustomEventInit) /** * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) */ get detail(): T } interface CustomEventCustomEventInit { bubbles?: boolean cancelable?: boolean composed?: boolean detail?: any } /** * The **`Blob`** interface represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) */ declare class Blob { constructor( type?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions, ) /** * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ get size(): number /** * The **`type`** read-only property of the Blob interface returns the MIME type of the file. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ get type(): string /** * The **`slice()`** method of the Blob interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ slice(start?: number, end?: number, type?: string): Blob /** * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ arrayBuffer(): Promise /** * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) */ bytes(): Promise /** * The **`text()`** method of the string containing the contents of the blob, interpreted as UTF-8. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ text(): Promise /** * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the `Blob`. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ stream(): ReadableStream } interface BlobOptions { type?: string } /** * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File) */ declare class File extends Blob { constructor( bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions, ) /** * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ get name(): string /** * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ get lastModified(): number } interface FileOptions { type?: string lastModified?: number } /** * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. * * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) */ declare abstract class CacheStorage { /** * The **`open()`** method of the the Cache object matching the `cacheName`. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ open(cacheName: string): Promise readonly default: Cache } /** * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. * * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) */ declare abstract class Cache { /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ delete( request: RequestInfo | URL, options?: CacheQueryOptions, ): Promise /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ match( request: RequestInfo | URL, options?: CacheQueryOptions, ): Promise /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ put(request: RequestInfo | URL, response: Response): Promise } interface CacheQueryOptions { ignoreMethod?: boolean } /** * The Web Crypto API provides a set of low-level functions for common cryptographic tasks. * The Workers runtime implements the full surface of this API, but with some differences in * the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) * compared to those implemented in most browsers. * * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) */ declare abstract class Crypto { /** * The **`Crypto.subtle`** read-only property returns a cryptographic operations. * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) */ get subtle(): SubtleCrypto /** * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ getRandomValues< T extends | Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | BigInt64Array | BigUint64Array, >(buffer: T): T /** * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator. * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) */ randomUUID(): string DigestStream: typeof DigestStream } /** * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions. * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) */ declare abstract class SubtleCrypto { /** * The **`encrypt()`** method of the SubtleCrypto interface encrypts data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) */ encrypt( algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView, ): Promise /** * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) */ decrypt( algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView, ): Promise /** * The **`sign()`** method of the SubtleCrypto interface generates a digital signature. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) */ sign( algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView, ): Promise /** * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) */ verify( algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView, ): Promise /** * The **`digest()`** method of the SubtleCrypto interface generates a _digest_ of the given data, using the specified hash function. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) */ digest( algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView, ): Promise /** * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms). * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ generateKey( algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[], ): Promise /** * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ deriveKey( algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[], ): Promise /** * The **`deriveBits()`** method of the key. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) */ deriveBits( algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null, ): Promise /** * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ importKey( format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[], ): Promise /** * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) */ exportKey(format: string, key: CryptoKey): Promise /** * The **`wrapKey()`** method of the SubtleCrypto interface 'wraps' a key. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) */ wrapKey( format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, ): Promise /** * The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ unwrapKey( format: string, wrappedKey: ArrayBuffer | ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[], ): Promise timingSafeEqual( a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView, ): boolean } /** * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods SubtleCrypto.generateKey, SubtleCrypto.deriveKey, SubtleCrypto.importKey, or SubtleCrypto.unwrapKey. * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) */ declare abstract class CryptoKey { /** * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ readonly type: string /** * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using `SubtleCrypto.exportKey()` or `SubtleCrypto.wrapKey()`. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ readonly extractable: boolean /** * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ readonly algorithm: | CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm /** * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ readonly usages: string[] } interface CryptoKeyPair { publicKey: CryptoKey privateKey: CryptoKey } interface JsonWebKey { kty: string use?: string key_ops?: string[] alg?: string ext?: boolean crv?: string x?: string y?: string d?: string n?: string e?: string p?: string q?: string dp?: string dq?: string qi?: string oth?: RsaOtherPrimesInfo[] k?: string } interface RsaOtherPrimesInfo { r?: string d?: string t?: string } interface SubtleCryptoDeriveKeyAlgorithm { name: string salt?: ArrayBuffer | ArrayBufferView iterations?: number hash?: string | SubtleCryptoHashAlgorithm $public?: CryptoKey info?: ArrayBuffer | ArrayBufferView } interface SubtleCryptoEncryptAlgorithm { name: string iv?: ArrayBuffer | ArrayBufferView additionalData?: ArrayBuffer | ArrayBufferView tagLength?: number counter?: ArrayBuffer | ArrayBufferView length?: number label?: ArrayBuffer | ArrayBufferView } interface SubtleCryptoGenerateKeyAlgorithm { name: string hash?: string | SubtleCryptoHashAlgorithm modulusLength?: number publicExponent?: ArrayBuffer | ArrayBufferView length?: number namedCurve?: string } interface SubtleCryptoHashAlgorithm { name: string } interface SubtleCryptoImportKeyAlgorithm { name: string hash?: string | SubtleCryptoHashAlgorithm length?: number namedCurve?: string compressed?: boolean } interface SubtleCryptoSignAlgorithm { name: string hash?: string | SubtleCryptoHashAlgorithm dataLength?: number saltLength?: number } interface CryptoKeyKeyAlgorithm { name: string } interface CryptoKeyAesKeyAlgorithm { name: string length: number } interface CryptoKeyHmacKeyAlgorithm { name: string hash: CryptoKeyKeyAlgorithm length: number } interface CryptoKeyRsaKeyAlgorithm { name: string modulusLength: number publicExponent: ArrayBuffer | ArrayBufferView hash?: CryptoKeyKeyAlgorithm } interface CryptoKeyEllipticKeyAlgorithm { name: string namedCurve: string } interface CryptoKeyArbitraryKeyAlgorithm { name: string hash?: CryptoKeyKeyAlgorithm namedCurve?: string length?: number } declare class DigestStream extends WritableStream< ArrayBuffer | ArrayBufferView > { constructor(algorithm: string | SubtleCryptoHashAlgorithm) readonly digest: Promise get bytesWritten(): number | bigint } /** * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as `UTF-8`, `ISO-8859-2`, `KOI8-R`, `GBK`, etc. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder) */ declare class TextDecoder { constructor(label?: string, options?: TextDecoderConstructorOptions) /** * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) */ decode( input?: ArrayBuffer | ArrayBufferView, options?: TextDecoderDecodeOptions, ): string get encoding(): string get fatal(): boolean get ignoreBOM(): boolean } /** * The **`TextEncoder`** interface takes a stream of code points as input and emits a stream of UTF-8 bytes. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder) */ declare class TextEncoder { constructor() /** * The **`TextEncoder.encode()`** method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) */ encode(input?: string): Uint8Array /** * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) */ encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult get encoding(): string } interface TextDecoderConstructorOptions { fatal: boolean ignoreBOM: boolean } interface TextDecoderDecodeOptions { stream: boolean } interface TextEncoderEncodeIntoResult { read: number written: number } /** * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent) */ declare class ErrorEvent extends Event { constructor(type: string, init?: ErrorEventErrorEventInit) /** * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ get filename(): string /** * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ get message(): string /** * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ get lineno(): number /** * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ get colno(): number /** * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ get error(): any } interface ErrorEventErrorEventInit { message?: string filename?: string lineno?: number colno?: number error?: any } /** * The **`MessageEvent`** interface represents a message received by a target object. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent) */ declare class MessageEvent extends Event { constructor(type: string, initializer: MessageEventInit) /** * The **`data`** read-only property of the The data sent by the message emitter; this can be any data type, depending on what originated this event. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) */ readonly data: any /** * The **`origin`** read-only property of the origin of the message emitter. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) */ readonly origin: string | null /** * The **`lastEventId`** read-only property of the unique ID for the event. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) */ readonly lastEventId: string /** * The **`source`** read-only property of the a WindowProxy, MessagePort, or a `MessageEventSource` (which can be a WindowProxy, message emitter. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) */ readonly source: MessagePort | null /** * The **`ports`** read-only property of the containing all MessagePort objects sent with the message, in order. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) */ readonly ports: MessagePort[] } interface MessageEventInit { data: ArrayBuffer | string } /** * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) */ declare abstract class PromiseRejectionEvent extends Event { /** * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript rejected. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ readonly promise: Promise /** * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ readonly reason: any } /** * The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the Window/fetch, XMLHttpRequest.send() or navigator.sendBeacon() methods. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) */ declare class FormData { constructor() /** * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) */ append(name: string, value: string): void /** * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) */ append(name: string, value: Blob, filename?: string): void /** * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a `FormData` object. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) */ delete(name: string): void /** * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a `FormData` object. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) */ get(name: string): (File | string) | null /** * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a `FormData` object. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) */ getAll(name: string): (File | string)[] /** * The **`has()`** method of the FormData interface returns whether a `FormData` object contains a certain key. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) */ has(name: string): boolean /** * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) */ set(name: string, value: string): void /** * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) */ set(name: string, value: Blob, filename?: string): void /* Returns an array of key, value pairs for every entry in the list. */ entries(): IterableIterator<[key: string, value: File | string]> /* Returns a list of keys in the list. */ keys(): IterableIterator /* Returns a list of values in the list. */ values(): IterableIterator forEach( callback: ( this: This, value: File | string, key: string, parent: FormData, ) => void, thisArg?: This, ): void [Symbol.iterator](): IterableIterator<[key: string, value: File | string]> } interface ContentOptions { html?: boolean } declare class HTMLRewriter { constructor() on( selector: string, handlers: HTMLRewriterElementContentHandlers, ): HTMLRewriter onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter transform(response: Response): Response } interface HTMLRewriterElementContentHandlers { element?(element: Element): void | Promise comments?(comment: Comment): void | Promise text?(element: Text): void | Promise } interface HTMLRewriterDocumentContentHandlers { doctype?(doctype: Doctype): void | Promise comments?(comment: Comment): void | Promise text?(text: Text): void | Promise end?(end: DocumentEnd): void | Promise } interface Doctype { readonly name: string | null readonly publicId: string | null readonly systemId: string | null } interface Element { tagName: string readonly attributes: IterableIterator readonly removed: boolean readonly namespaceURI: string getAttribute(name: string): string | null hasAttribute(name: string): boolean setAttribute(name: string, value: string): Element removeAttribute(name: string): Element before( content: string | ReadableStream | Response, options?: ContentOptions, ): Element after( content: string | ReadableStream | Response, options?: ContentOptions, ): Element prepend( content: string | ReadableStream | Response, options?: ContentOptions, ): Element append( content: string | ReadableStream | Response, options?: ContentOptions, ): Element replace( content: string | ReadableStream | Response, options?: ContentOptions, ): Element remove(): Element removeAndKeepContent(): Element setInnerContent( content: string | ReadableStream | Response, options?: ContentOptions, ): Element onEndTag(handler: (tag: EndTag) => void | Promise): void } interface EndTag { name: string before( content: string | ReadableStream | Response, options?: ContentOptions, ): EndTag after( content: string | ReadableStream | Response, options?: ContentOptions, ): EndTag remove(): EndTag } interface Comment { text: string readonly removed: boolean before(content: string, options?: ContentOptions): Comment after(content: string, options?: ContentOptions): Comment replace(content: string, options?: ContentOptions): Comment remove(): Comment } interface Text { readonly text: string readonly lastInTextNode: boolean readonly removed: boolean before( content: string | ReadableStream | Response, options?: ContentOptions, ): Text after( content: string | ReadableStream | Response, options?: ContentOptions, ): Text replace( content: string | ReadableStream | Response, options?: ContentOptions, ): Text remove(): Text } interface DocumentEnd { append(content: string, options?: ContentOptions): DocumentEnd } /** * This is the event type for `fetch` events dispatched on the ServiceWorkerGlobalScope. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) */ declare abstract class FetchEvent extends ExtendableEvent { /** * The **`request`** read-only property of the the event handler. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ readonly request: Request /** * The **`respondWith()`** method of allows you to provide a promise for a Response yourself. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ respondWith(promise: Response | Promise): void passThroughOnException(): void } type HeadersInit = Headers | Iterable> | Record /** * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response headers. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers) */ declare class Headers { constructor(init?: HeadersInit) /** * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a `Headers` object with a given name. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) */ get(name: string): string | null getAll(name: string): string[] /** * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) */ getSetCookie(): string[] /** * The **`has()`** method of the Headers interface returns a boolean stating whether a `Headers` object contains a certain header. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) */ has(name: string): boolean /** * The **`set()`** method of the Headers interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) */ set(name: string, value: string): void /** * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) */ append(name: string, value: string): void /** * The **`delete()`** method of the Headers interface deletes a header from the current `Headers` object. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) */ delete(name: string): void forEach( callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This, ): void /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ entries(): IterableIterator<[key: string, value: string]> /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ keys(): IterableIterator /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ values(): IterableIterator [Symbol.iterator](): IterableIterator<[key: string, value: string]> } type BodyInit = | ReadableStream | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData declare abstract class Body { /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ get body(): ReadableStream | null /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ get bodyUsed(): boolean /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ arrayBuffer(): Promise /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ bytes(): Promise /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ text(): Promise /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ json(): Promise /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ formData(): Promise /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ blob(): Promise } /** * The **`Response`** interface of the Fetch API represents the response to a request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) */ declare var Response: { prototype: Response new (body?: BodyInit | null, init?: ResponseInit): Response error(): Response redirect(url: string, status?: number): Response json(any: any, maybeInit?: ResponseInit | Response): Response } /** * The **`Response`** interface of the Fetch API represents the response to a request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) */ interface Response extends Body { /** * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ clone(): Response /** * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ status: number /** * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ statusText: string /** * The **`headers`** read-only property of the with the response. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ headers: Headers /** * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ ok: boolean /** * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ redirected: boolean /** * The **`url`** read-only property of the Response interface contains the URL of the response. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ url: string webSocket: WebSocket | null cf: any | undefined /** * The **`type`** read-only property of the Response interface contains the type of the response. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) */ type: 'default' | 'error' } interface ResponseInit { status?: number statusText?: string headers?: HeadersInit cf?: any webSocket?: WebSocket | null encodeBody?: 'automatic' | 'manual' } type RequestInfo> = | Request | string /** * The **`Request`** interface of the Fetch API represents a resource request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) */ declare var Request: { prototype: Request new >( input: RequestInfo | URL, init?: RequestInit, ): Request } /** * The **`Request`** interface of the Fetch API represents a resource request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) */ interface Request> extends Body { /** * The **`clone()`** method of the Request interface creates a copy of the current `Request` object. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ clone(): Request /** * The **`method`** read-only property of the `POST`, etc.) A String indicating the method of the request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) */ method: string /** * The **`url`** read-only property of the Request interface contains the URL of the request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) */ url: string /** * The **`headers`** read-only property of the with the request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) */ headers: Headers /** * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) */ redirect: string fetcher: Fetcher | null /** * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) */ signal: AbortSignal cf: Cf | undefined /** * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) */ integrity: string /** * The **`keepalive`** read-only property of the Request interface contains the request's `keepalive` setting (`true` or `false`), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) */ keepalive: boolean /** * The **`cache`** read-only property of the Request interface contains the cache mode of the request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) */ cache?: 'no-store' | 'no-cache' } interface RequestInit { /* A string to set request's method. */ method?: string /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ headers?: HeadersInit /* A BodyInit object or null to set request's body. */ body?: BodyInit | null /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ redirect?: string fetcher?: Fetcher | null cf?: Cf /* A string indicating how the request will interact with the browser's cache to set request's cache. */ cache?: 'no-store' | 'no-cache' /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ integrity?: string /* An AbortSignal to set request's signal. */ signal?: AbortSignal | null encodeResponseBody?: 'automatic' | 'manual' } type Service< T extends | (new ( ...args: any[] ) => Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler | undefined = undefined, > = T extends new ( ...args: any[] ) => Rpc.WorkerEntrypointBranded ? Fetcher> : T extends Rpc.WorkerEntrypointBranded ? Fetcher : T extends Exclude ? never : Fetcher type Fetcher< T extends Rpc.EntrypointBranded | undefined = undefined, Reserved extends string = never, > = (T extends Rpc.EntrypointBranded ? Rpc.Provider : unknown) & { fetch(input: RequestInfo | URL, init?: RequestInit): Promise connect(address: SocketAddress | string, options?: SocketOptions): Socket } interface KVNamespaceListKey { name: Key expiration?: number metadata?: Metadata } type KVNamespaceListResult = | { list_complete: false keys: KVNamespaceListKey[] cursor: string cacheStatus: string | null } | { list_complete: true keys: KVNamespaceListKey[] cacheStatus: string | null } interface KVNamespace { get( key: Key, options?: Partial>, ): Promise get(key: Key, type: 'text'): Promise get( key: Key, type: 'json', ): Promise get(key: Key, type: 'arrayBuffer'): Promise get(key: Key, type: 'stream'): Promise get(key: Key, options?: KVNamespaceGetOptions<'text'>): Promise get( key: Key, options?: KVNamespaceGetOptions<'json'>, ): Promise get( key: Key, options?: KVNamespaceGetOptions<'arrayBuffer'>, ): Promise get( key: Key, options?: KVNamespaceGetOptions<'stream'>, ): Promise get(key: Array, type: 'text'): Promise> get( key: Array, type: 'json', ): Promise> get( key: Array, options?: Partial>, ): Promise> get( key: Array, options?: KVNamespaceGetOptions<'text'>, ): Promise> get( key: Array, options?: KVNamespaceGetOptions<'json'>, ): Promise> list( options?: KVNamespaceListOptions, ): Promise> put( key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions, ): Promise getWithMetadata( key: Key, options?: Partial>, ): Promise> getWithMetadata( key: Key, type: 'text', ): Promise> getWithMetadata( key: Key, type: 'json', ): Promise> getWithMetadata( key: Key, type: 'arrayBuffer', ): Promise> getWithMetadata( key: Key, type: 'stream', ): Promise> getWithMetadata( key: Key, options: KVNamespaceGetOptions<'text'>, ): Promise> getWithMetadata( key: Key, options: KVNamespaceGetOptions<'json'>, ): Promise> getWithMetadata( key: Key, options: KVNamespaceGetOptions<'arrayBuffer'>, ): Promise> getWithMetadata( key: Key, options: KVNamespaceGetOptions<'stream'>, ): Promise> getWithMetadata( key: Array, type: 'text', ): Promise>> getWithMetadata( key: Array, type: 'json', ): Promise< Map> > getWithMetadata( key: Array, options?: Partial>, ): Promise>> getWithMetadata( key: Array, options?: KVNamespaceGetOptions<'text'>, ): Promise>> getWithMetadata( key: Array, options?: KVNamespaceGetOptions<'json'>, ): Promise< Map> > delete(key: Key): Promise } interface KVNamespaceListOptions { limit?: number prefix?: string | null cursor?: string | null } interface KVNamespaceGetOptions { type: Type cacheTtl?: number } interface KVNamespacePutOptions { expiration?: number expirationTtl?: number metadata?: any | null } interface KVNamespaceGetWithMetadataResult { value: Value | null metadata: Metadata | null cacheStatus: string | null } type QueueContentType = 'text' | 'bytes' | 'json' | 'v8' interface Queue { send(message: Body, options?: QueueSendOptions): Promise sendBatch( messages: Iterable>, options?: QueueSendBatchOptions, ): Promise } interface QueueSendOptions { contentType?: QueueContentType delaySeconds?: number } interface QueueSendBatchOptions { delaySeconds?: number } interface MessageSendRequest { body: Body contentType?: QueueContentType delaySeconds?: number } interface QueueRetryOptions { delaySeconds?: number } interface Message { readonly id: string readonly timestamp: Date readonly body: Body readonly attempts: number retry(options?: QueueRetryOptions): void ack(): void } interface QueueEvent extends ExtendableEvent { readonly messages: readonly Message[] readonly queue: string retryAll(options?: QueueRetryOptions): void ackAll(): void } interface MessageBatch { readonly messages: readonly Message[] readonly queue: string retryAll(options?: QueueRetryOptions): void ackAll(): void } interface R2Error extends Error { readonly name: string readonly code: number readonly message: string readonly action: string readonly stack: any } interface R2ListOptions { limit?: number prefix?: string cursor?: string delimiter?: string startAfter?: string include?: ('httpMetadata' | 'customMetadata')[] } declare abstract class R2Bucket { head(key: string): Promise get( key: string, options: R2GetOptions & { onlyIf: R2Conditional | Headers }, ): Promise get(key: string, options?: R2GetOptions): Promise put( key: string, value: | ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & { onlyIf: R2Conditional | Headers }, ): Promise put( key: string, value: | ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions, ): Promise createMultipartUpload( key: string, options?: R2MultipartOptions, ): Promise resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload delete(keys: string | string[]): Promise list(options?: R2ListOptions): Promise } interface R2MultipartUpload { readonly key: string readonly uploadId: string uploadPart( partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions, ): Promise abort(): Promise complete(uploadedParts: R2UploadedPart[]): Promise } interface R2UploadedPart { partNumber: number etag: string } declare abstract class R2Object { readonly key: string readonly version: string readonly size: number readonly etag: string readonly httpEtag: string readonly checksums: R2Checksums readonly uploaded: Date readonly httpMetadata?: R2HTTPMetadata readonly customMetadata?: Record readonly range?: R2Range readonly storageClass: string readonly ssecKeyMd5?: string writeHttpMetadata(headers: Headers): void } interface R2ObjectBody extends R2Object { get body(): ReadableStream get bodyUsed(): boolean arrayBuffer(): Promise bytes(): Promise text(): Promise json(): Promise blob(): Promise } type R2Range = | { offset: number length?: number } | { offset?: number length: number } | { suffix: number } interface R2Conditional { etagMatches?: string etagDoesNotMatch?: string uploadedBefore?: Date uploadedAfter?: Date secondsGranularity?: boolean } interface R2GetOptions { onlyIf?: R2Conditional | Headers range?: R2Range | Headers ssecKey?: ArrayBuffer | string } interface R2PutOptions { onlyIf?: R2Conditional | Headers httpMetadata?: R2HTTPMetadata | Headers customMetadata?: Record md5?: (ArrayBuffer | ArrayBufferView) | string sha1?: (ArrayBuffer | ArrayBufferView) | string sha256?: (ArrayBuffer | ArrayBufferView) | string sha384?: (ArrayBuffer | ArrayBufferView) | string sha512?: (ArrayBuffer | ArrayBufferView) | string storageClass?: string ssecKey?: ArrayBuffer | string } interface R2MultipartOptions { httpMetadata?: R2HTTPMetadata | Headers customMetadata?: Record storageClass?: string ssecKey?: ArrayBuffer | string } interface R2Checksums { readonly md5?: ArrayBuffer readonly sha1?: ArrayBuffer readonly sha256?: ArrayBuffer readonly sha384?: ArrayBuffer readonly sha512?: ArrayBuffer toJSON(): R2StringChecksums } interface R2StringChecksums { md5?: string sha1?: string sha256?: string sha384?: string sha512?: string } interface R2HTTPMetadata { contentType?: string contentLanguage?: string contentDisposition?: string contentEncoding?: string cacheControl?: string cacheExpiry?: Date } type R2Objects = { objects: R2Object[] delimitedPrefixes: string[] } & ( | { truncated: true cursor: string } | { truncated: false } ) interface R2UploadPartOptions { ssecKey?: ArrayBuffer | string } declare abstract class ScheduledEvent extends ExtendableEvent { readonly scheduledTime: number readonly cron: string noRetry(): void } interface ScheduledController { readonly scheduledTime: number readonly cron: string noRetry(): void } interface QueuingStrategy { highWaterMark?: number | bigint size?: (chunk: T) => number | bigint } interface UnderlyingSink { type?: string start?: (controller: WritableStreamDefaultController) => void | Promise write?: ( chunk: W, controller: WritableStreamDefaultController, ) => void | Promise abort?: (reason: any) => void | Promise close?: () => void | Promise } interface UnderlyingByteSource { type: 'bytes' autoAllocateChunkSize?: number start?: (controller: ReadableByteStreamController) => void | Promise pull?: (controller: ReadableByteStreamController) => void | Promise cancel?: (reason: any) => void | Promise } interface UnderlyingSource { type?: '' | undefined start?: ( controller: ReadableStreamDefaultController, ) => void | Promise pull?: ( controller: ReadableStreamDefaultController, ) => void | Promise cancel?: (reason: any) => void | Promise expectedLength?: number | bigint } interface Transformer { readableType?: string writableType?: string start?: ( controller: TransformStreamDefaultController, ) => void | Promise transform?: ( chunk: I, controller: TransformStreamDefaultController, ) => void | Promise flush?: ( controller: TransformStreamDefaultController, ) => void | Promise cancel?: (reason: any) => void | Promise expectedLength?: number } interface StreamPipeOptions { preventAbort?: boolean preventCancel?: boolean /** * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. * * Errors and closures of the source and destination streams propagate as follows: * * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. * * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. * * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. * * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. * * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. */ preventClose?: boolean signal?: AbortSignal } type ReadableStreamReadResult = | { done: false value: R } | { done: true value?: undefined } /** * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) */ interface ReadableStream { /** * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ get locked(): boolean /** * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ cancel(reason?: any): Promise /** * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ getReader(): ReadableStreamDefaultReader /** * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader /** * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ pipeThrough( transform: ReadableWritablePair, options?: StreamPipeOptions, ): ReadableStream /** * The **`pipeTo()`** method of the ReadableStream interface pipes the current `ReadableStream` to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ pipeTo( destination: WritableStream, options?: StreamPipeOptions, ): Promise /** * The **`tee()`** method of the two-element array containing the two resulting branches as new ReadableStream instances. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ tee(): [ReadableStream, ReadableStream] values(options?: ReadableStreamValuesOptions): AsyncIterableIterator [Symbol.asyncIterator]( options?: ReadableStreamValuesOptions, ): AsyncIterableIterator } /** * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) */ declare const ReadableStream: { prototype: ReadableStream new ( underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy, ): ReadableStream new ( underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy, ): ReadableStream } /** * The **`ReadableStreamDefaultReader`** interface of the Streams API represents a default reader that can be used to read stream data supplied from a network (such as a fetch request). * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) */ declare class ReadableStreamDefaultReader { constructor(stream: ReadableStream) get closed(): Promise cancel(reason?: any): Promise /** * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ read(): Promise> /** * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ releaseLock(): void } /** * The `ReadableStreamBYOBReader` interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ declare class ReadableStreamBYOBReader { constructor(stream: ReadableStream) get closed(): Promise cancel(reason?: any): Promise /** * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ read(view: T): Promise> /** * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ releaseLock(): void readAtLeast( minElements: number, view: T, ): Promise> } interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { min?: number } interface ReadableStreamGetReaderOptions { /** * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. * * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. */ mode: 'byob' } /** * The **`ReadableStreamBYOBRequest`** interface of the Streams API represents a 'pull request' for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues). * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ declare abstract class ReadableStreamBYOBRequest { /** * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ get view(): Uint8Array | null /** * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ respond(bytesWritten: number): void /** * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ respondWithNewView(view: ArrayBuffer | ArrayBufferView): void get atLeast(): number | null } /** * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ declare abstract class ReadableStreamDefaultController { /** * The **`desiredSize`** read-only property of the required to fill the stream's internal queue. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ get desiredSize(): number | null /** * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ close(): void /** * The **`enqueue()`** method of the ```js-nolint enqueue(chunk) ``` - `chunk` - : The chunk to enqueue. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ enqueue(chunk?: R): void /** * The **`error()`** method of the with the associated stream to error. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ error(reason: any): void } /** * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ declare abstract class ReadableByteStreamController { /** * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or `null` if there are no pending requests. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ get byobRequest(): ReadableStreamBYOBRequest | null /** * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its 'desired size'. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ get desiredSize(): number | null /** * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ close(): void /** * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ enqueue(chunk: ArrayBuffer | ArrayBufferView): void /** * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ error(reason: any): void } /** * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) */ declare abstract class WritableStreamDefaultController { /** * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ get signal(): AbortSignal /** * The **`error()`** method of the with the associated stream to error. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ error(reason?: any): void } /** * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ declare abstract class TransformStreamDefaultController { /** * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ get desiredSize(): number | null /** * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ enqueue(chunk?: O): void /** * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ error(reason: any): void /** * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ terminate(): void } interface ReadableWritablePair { readable: ReadableStream /** * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. */ writable: WritableStream } /** * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) */ declare class WritableStream { constructor( underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy, ) /** * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the `WritableStream` is locked to a writer. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ get locked(): boolean /** * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ abort(reason?: any): Promise /** * The **`close()`** method of the WritableStream interface closes the associated stream. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ close(): Promise /** * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ getWriter(): WritableStreamDefaultWriter } /** * The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by WritableStream.getWriter() and once created locks the writer to the `WritableStream` ensuring that no other streams can write to the underlying sink. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter) */ declare class WritableStreamDefaultWriter { constructor(stream: WritableStream) /** * The **`closed`** read-only property of the the stream errors or the writer's lock is released. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ get closed(): Promise /** * The **`ready`** read-only property of the that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ get ready(): Promise /** * The **`desiredSize`** read-only property of the to fill the stream's internal queue. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ get desiredSize(): number | null /** * The **`abort()`** method of the the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ abort(reason?: any): Promise /** * The **`close()`** method of the stream. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ close(): Promise /** * The **`write()`** method of the operation. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ write(chunk?: W): Promise /** * The **`releaseLock()`** method of the corresponding stream. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ releaseLock(): void } /** * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain _transform stream_ concept. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) */ declare class TransformStream { constructor( transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy, ) /** * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this `TransformStream`. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ get readable(): ReadableStream /** * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this `TransformStream`. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ get writable(): WritableStream } declare class FixedLengthStream extends IdentityTransformStream { constructor( expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy, ) } declare class IdentityTransformStream extends TransformStream< ArrayBuffer | ArrayBufferView, Uint8Array > { constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy) } interface IdentityTransformStreamQueuingStrategy { highWaterMark?: number | bigint } interface ReadableStreamValuesOptions { preventCancel?: boolean } /** * The **`CompressionStream`** interface of the Compression Streams API is an API for compressing a stream of data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) */ declare class CompressionStream extends TransformStream< ArrayBuffer | ArrayBufferView, Uint8Array > { constructor(format: 'gzip' | 'deflate' | 'deflate-raw') } /** * The **`DecompressionStream`** interface of the Compression Streams API is an API for decompressing a stream of data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) */ declare class DecompressionStream extends TransformStream< ArrayBuffer | ArrayBufferView, Uint8Array > { constructor(format: 'gzip' | 'deflate' | 'deflate-raw') } /** * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) */ declare class TextEncoderStream extends TransformStream { constructor() get encoding(): string } /** * The **`TextDecoderStream`** interface of the Encoding API converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) */ declare class TextDecoderStream extends TransformStream< ArrayBuffer | ArrayBufferView, string > { constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit) get encoding(): string get fatal(): boolean get ignoreBOM(): boolean } interface TextDecoderStreamTextDecoderStreamInit { fatal?: boolean ignoreBOM?: boolean } /** * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy) */ declare class ByteLengthQueuingStrategy implements QueuingStrategy { constructor(init: QueuingStrategyInit) /** * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ get highWaterMark(): number /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ get size(): (chunk?: any) => number } /** * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy) */ declare class CountQueuingStrategy implements QueuingStrategy { constructor(init: QueuingStrategyInit) /** * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ get highWaterMark(): number /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ get size(): (chunk?: any) => number } interface QueuingStrategyInit { /** * Creates a new ByteLengthQueuingStrategy with the provided high water mark. * * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. */ highWaterMark: number } interface ScriptVersion { id?: string tag?: string message?: string } declare abstract class TailEvent extends ExtendableEvent { readonly events: TraceItem[] readonly traces: TraceItem[] } interface TraceItem { readonly event: | ( | TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo ) | null readonly eventTimestamp: number | null readonly logs: TraceLog[] readonly exceptions: TraceException[] readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[] readonly scriptName: string | null readonly entrypoint?: string readonly scriptVersion?: ScriptVersion readonly dispatchNamespace?: string readonly scriptTags?: string[] readonly durableObjectId?: string readonly outcome: string readonly executionModel: string readonly truncated: boolean readonly cpuTime: number readonly wallTime: number } interface TraceItemAlarmEventInfo { readonly scheduledTime: Date } type TraceItemCustomEventInfo = {} interface TraceItemScheduledEventInfo { readonly scheduledTime: number readonly cron: string } interface TraceItemQueueEventInfo { readonly queue: string readonly batchSize: number } interface TraceItemEmailEventInfo { readonly mailFrom: string readonly rcptTo: string readonly rawSize: number } interface TraceItemTailEventInfo { readonly consumedEvents: TraceItemTailEventInfoTailItem[] } interface TraceItemTailEventInfoTailItem { readonly scriptName: string | null } interface TraceItemFetchEventInfo { readonly response?: TraceItemFetchEventInfoResponse readonly request: TraceItemFetchEventInfoRequest } interface TraceItemFetchEventInfoRequest { readonly cf?: any readonly headers: Record readonly method: string readonly url: string getUnredacted(): TraceItemFetchEventInfoRequest } interface TraceItemFetchEventInfoResponse { readonly status: number } interface TraceItemJsRpcEventInfo { readonly rpcMethod: string } interface TraceItemHibernatableWebSocketEventInfo { readonly getWebSocketEvent: | TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError } interface TraceItemHibernatableWebSocketEventInfoMessage { readonly webSocketEventType: string } interface TraceItemHibernatableWebSocketEventInfoClose { readonly webSocketEventType: string readonly code: number readonly wasClean: boolean } interface TraceItemHibernatableWebSocketEventInfoError { readonly webSocketEventType: string } interface TraceLog { readonly timestamp: number readonly level: string readonly message: any } interface TraceException { readonly timestamp: number readonly message: string readonly name: string readonly stack?: string } interface TraceDiagnosticChannelEvent { readonly timestamp: number readonly channel: string readonly message: any } interface TraceMetrics { readonly cpuTime: number readonly wallTime: number } interface UnsafeTraceMetrics { fromTrace(item: TraceItem): TraceMetrics } /** * The **`URL`** interface is used to parse, construct, normalize, and encode URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) */ declare class URL { constructor(url: string | URL, base?: string | URL) /** * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ get origin(): string /** * The **`href`** property of the URL interface is a string containing the whole URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ get href(): string /** * The **`href`** property of the URL interface is a string containing the whole URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ set href(value: string) /** * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ get protocol(): string /** * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ set protocol(value: string) /** * The **`username`** property of the URL interface is a string containing the username component of the URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ get username(): string /** * The **`username`** property of the URL interface is a string containing the username component of the URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ set username(value: string) /** * The **`password`** property of the URL interface is a string containing the password component of the URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ get password(): string /** * The **`password`** property of the URL interface is a string containing the password component of the URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ set password(value: string) /** * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ get host(): string /** * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ set host(value: string) /** * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ get hostname(): string /** * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ set hostname(value: string) /** * The **`port`** property of the URL interface is a string containing the port number of the URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ get port(): string /** * The **`port`** property of the URL interface is a string containing the port number of the URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ set port(value: string) /** * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ get pathname(): string /** * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ set pathname(value: string) /** * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ get search(): string /** * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ set search(value: string) /** * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ get hash(): string /** * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ set hash(value: string) /** * The **`searchParams`** read-only property of the access to the [MISSING: httpmethod('GET')] decoded query arguments contained in the URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ get searchParams(): URLSearchParams /** * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as ```js-nolint toJSON() ``` None. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ toJSON(): string /*function toString() { [native code] }*/ toString(): string /** * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */ static canParse(url: string, base?: string): boolean /** * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) */ static parse(url: string, base?: string): URL | null /** * The **`createObjectURL()`** static method of the URL interface creates a string containing a URL representing the object given in the parameter. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) */ static createObjectURL(object: File | Blob): string /** * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) */ static revokeObjectURL(object_url: string): void } /** * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) */ declare class URLSearchParams { constructor( init?: Iterable> | Record | string, ) /** * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) */ get size(): number /** * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) */ append(name: string, value: string): void /** * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) */ delete(name: string, value?: string): void /** * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get) */ get(name: string): string | null /** * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) */ getAll(name: string): string[] /** * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) */ has(name: string, value?: string): boolean /** * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) */ set(name: string, value: string): void /** * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) */ sort(): void /* Returns an array of key, value pairs for every entry in the search params. */ entries(): IterableIterator<[key: string, value: string]> /* Returns a list of keys in the search params. */ keys(): IterableIterator /* Returns a list of values in the search params. */ values(): IterableIterator forEach( callback: ( this: This, value: string, key: string, parent: URLSearchParams, ) => void, thisArg?: This, ): void /*function toString() { [native code] }*/ toString(): string [Symbol.iterator](): IterableIterator<[key: string, value: string]> } declare class URLPattern { constructor( input?: string | URLPatternInit, baseURL?: string | URLPatternOptions, patternOptions?: URLPatternOptions, ) get protocol(): string get username(): string get password(): string get hostname(): string get port(): string get pathname(): string get search(): string get hash(): string get hasRegExpGroups(): boolean test(input?: string | URLPatternInit, baseURL?: string): boolean exec( input?: string | URLPatternInit, baseURL?: string, ): URLPatternResult | null } interface URLPatternInit { protocol?: string username?: string password?: string hostname?: string port?: string pathname?: string search?: string hash?: string baseURL?: string } interface URLPatternComponentResult { input: string groups: Record } interface URLPatternResult { inputs: (string | URLPatternInit)[] protocol: URLPatternComponentResult username: URLPatternComponentResult password: URLPatternComponentResult hostname: URLPatternComponentResult port: URLPatternComponentResult pathname: URLPatternComponentResult search: URLPatternComponentResult hash: URLPatternComponentResult } interface URLPatternOptions { ignoreCase?: boolean } /** * A `CloseEvent` is sent to clients using WebSockets when the connection is closed. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) */ declare class CloseEvent extends Event { constructor(type: string, initializer?: CloseEventInit) /** * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) */ readonly code: number /** * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) */ readonly reason: string /** * The **`wasClean`** read-only property of the CloseEvent interface returns `true` if the connection closed cleanly. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) */ readonly wasClean: boolean } interface CloseEventInit { code?: number reason?: string wasClean?: boolean } type WebSocketEventMap = { close: CloseEvent message: MessageEvent open: Event error: ErrorEvent } /** * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) */ declare var WebSocket: { prototype: WebSocket new (url: string, protocols?: string[] | string): WebSocket readonly READY_STATE_CONNECTING: number readonly CONNECTING: number readonly READY_STATE_OPEN: number readonly OPEN: number readonly READY_STATE_CLOSING: number readonly CLOSING: number readonly READY_STATE_CLOSED: number readonly CLOSED: number } /** * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) */ interface WebSocket extends EventTarget { accept(): void /** * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) */ send(message: (ArrayBuffer | ArrayBufferView) | string): void /** * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) */ close(code?: number, reason?: string): void serializeAttachment(attachment: any): void deserializeAttachment(): any | null /** * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) */ readyState: number /** * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) */ url: string | null /** * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the `protocols` parameter when creating the WebSocket object, or the empty string if no connection is established. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) */ protocol: string | null /** * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) */ extensions: string | null } declare const WebSocketPair: { new (): { 0: WebSocket 1: WebSocket } } interface SqlStorage { exec>( query: string, ...bindings: any[] ): SqlStorageCursor get databaseSize(): number Cursor: typeof SqlStorageCursor Statement: typeof SqlStorageStatement } declare abstract class SqlStorageStatement {} type SqlStorageValue = ArrayBuffer | string | number | null declare abstract class SqlStorageCursor< T extends Record, > { next(): | { done?: false value: T } | { done: true value?: never } toArray(): T[] one(): T raw(): IterableIterator columnNames: string[] get rowsRead(): number get rowsWritten(): number [Symbol.iterator](): IterableIterator } interface Socket { get readable(): ReadableStream get writable(): WritableStream get closed(): Promise get opened(): Promise get upgraded(): boolean get secureTransport(): 'on' | 'off' | 'starttls' close(): Promise startTls(options?: TlsOptions): Socket } interface SocketOptions { secureTransport?: string allowHalfOpen: boolean highWaterMark?: number | bigint } interface SocketAddress { hostname: string port: number } interface TlsOptions { expectedServerHostname?: string } interface SocketInfo { remoteAddress?: string localAddress?: string } /** * The **`EventSource`** interface is web content's interface to server-sent events. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) */ declare class EventSource extends EventTarget { constructor(url: string, init?: EventSourceEventSourceInit) /** * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the ```js-nolint close() ``` None. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) */ close(): void /** * The **`url`** read-only property of the URL of the source. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) */ get url(): string /** * The **`withCredentials`** read-only property of the the `EventSource` object was instantiated with CORS credentials set. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) */ get withCredentials(): boolean /** * The **`readyState`** read-only property of the connection. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) */ get readyState(): number /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ get onopen(): any | null /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ set onopen(value: any | null) /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ get onmessage(): any | null /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ set onmessage(value: any | null) /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ get onerror(): any | null /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ set onerror(value: any | null) static readonly CONNECTING: number static readonly OPEN: number static readonly CLOSED: number static from(stream: ReadableStream): EventSource } interface EventSourceEventSourceInit { withCredentials?: boolean fetcher?: Fetcher } interface Container { get running(): boolean start(options?: ContainerStartupOptions): void monitor(): Promise destroy(error?: any): Promise signal(signo: number): void getTcpPort(port: number): Fetcher setInactivityTimeout(durationMs: number | bigint): Promise } interface ContainerStartupOptions { entrypoint?: string[] enableInternet: boolean env?: Record hardTimeout?: number | bigint } /** * The **`MessagePort`** interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) */ declare abstract class MessagePort extends EventTarget { /** * The **`postMessage()`** method of the transfers ownership of objects to other browsing contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) */ postMessage(data?: any, options?: any[] | MessagePortPostMessageOptions): void /** * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) */ close(): void /** * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) */ start(): void get onmessage(): any | null set onmessage(value: any | null) } /** * The **`MessageChannel`** interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel) */ declare class MessageChannel { constructor() /** * The **`port1`** read-only property of the the port attached to the context that originated the channel. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1) */ readonly port1: MessagePort /** * The **`port2`** read-only property of the the port attached to the context at the other end of the channel, which the message is initially sent to. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2) */ readonly port2: MessagePort } interface MessagePortPostMessageOptions { transfer?: any[] } type LoopbackForExport< T extends | (new ( ...args: any[] ) => Rpc.EntrypointBranded) | ExportedHandler | undefined = undefined, > = T extends new ( ...args: any[] ) => Rpc.WorkerEntrypointBranded ? LoopbackServiceStub> : T extends new ( ...args: any[] ) => Rpc.DurableObjectBranded ? LoopbackDurableObjectClass> : T extends ExportedHandler ? LoopbackServiceStub : undefined type LoopbackServiceStub< T extends Rpc.WorkerEntrypointBranded | undefined = undefined, > = Fetcher & (T extends CloudflareWorkersModule.WorkerEntrypoint ? (opts: { props?: Props }) => Fetcher : (opts: { props?: any }) => Fetcher) type LoopbackDurableObjectClass< T extends Rpc.DurableObjectBranded | undefined = undefined, > = DurableObjectClass & (T extends CloudflareWorkersModule.DurableObject ? (opts: { props?: Props }) => DurableObjectClass : (opts: { props?: any }) => DurableObjectClass) interface SyncKvStorage { get(key: string): T | undefined list(options?: SyncKvListOptions): Iterable<[string, T]> put(key: string, value: T): void delete(key: string): boolean } interface SyncKvListOptions { start?: string startAfter?: string end?: string prefix?: string reverse?: boolean limit?: number } interface WorkerStub { getEntrypoint( name?: string, options?: WorkerStubEntrypointOptions, ): Fetcher } interface WorkerStubEntrypointOptions { props?: any } interface WorkerLoader { get( name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise, ): WorkerStub } interface WorkerLoaderModule { js?: string cjs?: string text?: string data?: ArrayBuffer json?: any py?: string wasm?: ArrayBuffer } interface WorkerLoaderWorkerCode { compatibilityDate: string compatibilityFlags?: string[] allowExperimental?: boolean mainModule: string modules: Record env?: any globalOutbound?: Fetcher | null tails?: Fetcher[] streamingTails?: Fetcher[] } /** * The Workers runtime supports a subset of the Performance API, used to measure timing and performance, * as well as timing of subrequests and other operations. * * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) */ declare abstract class Performance { /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */ get timeOrigin(): number /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ now(): number } type AiImageClassificationInput = { image: number[] } type AiImageClassificationOutput = { score?: number label?: string }[] declare abstract class BaseAiImageClassification { inputs: AiImageClassificationInput postProcessedOutputs: AiImageClassificationOutput } type AiImageToTextInput = { image: number[] prompt?: string max_tokens?: number temperature?: number top_p?: number top_k?: number seed?: number repetition_penalty?: number frequency_penalty?: number presence_penalty?: number raw?: boolean messages?: RoleScopedChatInput[] } type AiImageToTextOutput = { description: string } declare abstract class BaseAiImageToText { inputs: AiImageToTextInput postProcessedOutputs: AiImageToTextOutput } type AiImageTextToTextInput = { image: string prompt?: string max_tokens?: number temperature?: number ignore_eos?: boolean top_p?: number top_k?: number seed?: number repetition_penalty?: number frequency_penalty?: number presence_penalty?: number raw?: boolean messages?: RoleScopedChatInput[] } type AiImageTextToTextOutput = { description: string } declare abstract class BaseAiImageTextToText { inputs: AiImageTextToTextInput postProcessedOutputs: AiImageTextToTextOutput } type AiMultimodalEmbeddingsInput = { image: string text: string[] } type AiIMultimodalEmbeddingsOutput = { data: number[][] shape: number[] } declare abstract class BaseAiMultimodalEmbeddings { inputs: AiImageTextToTextInput postProcessedOutputs: AiImageTextToTextOutput } type AiObjectDetectionInput = { image: number[] } type AiObjectDetectionOutput = { score?: number label?: string }[] declare abstract class BaseAiObjectDetection { inputs: AiObjectDetectionInput postProcessedOutputs: AiObjectDetectionOutput } type AiSentenceSimilarityInput = { source: string sentences: string[] } type AiSentenceSimilarityOutput = number[] declare abstract class BaseAiSentenceSimilarity { inputs: AiSentenceSimilarityInput postProcessedOutputs: AiSentenceSimilarityOutput } type AiAutomaticSpeechRecognitionInput = { audio: number[] } type AiAutomaticSpeechRecognitionOutput = { text?: string words?: { word: string start: number end: number }[] vtt?: string } declare abstract class BaseAiAutomaticSpeechRecognition { inputs: AiAutomaticSpeechRecognitionInput postProcessedOutputs: AiAutomaticSpeechRecognitionOutput } type AiSummarizationInput = { input_text: string max_length?: number } type AiSummarizationOutput = { summary: string } declare abstract class BaseAiSummarization { inputs: AiSummarizationInput postProcessedOutputs: AiSummarizationOutput } type AiTextClassificationInput = { text: string } type AiTextClassificationOutput = { score?: number label?: string }[] declare abstract class BaseAiTextClassification { inputs: AiTextClassificationInput postProcessedOutputs: AiTextClassificationOutput } type AiTextEmbeddingsInput = { text: string | string[] } type AiTextEmbeddingsOutput = { shape: number[] data: number[][] } declare abstract class BaseAiTextEmbeddings { inputs: AiTextEmbeddingsInput postProcessedOutputs: AiTextEmbeddingsOutput } type RoleScopedChatInput = { role: | 'user' | 'assistant' | 'system' | 'tool' | (string & NonNullable) content: string name?: string } type AiTextGenerationToolLegacyInput = { name: string description: string parameters?: { type: 'object' | (string & NonNullable) properties: { [key: string]: { type: string description?: string } } required: string[] } } type AiTextGenerationToolInput = { type: 'function' | (string & NonNullable) function: { name: string description: string parameters?: { type: 'object' | (string & NonNullable) properties: { [key: string]: { type: string description?: string } } required: string[] } } } type AiTextGenerationFunctionsInput = { name: string code: string } type AiTextGenerationResponseFormat = { type: string json_schema?: any } type AiTextGenerationInput = { prompt?: string raw?: boolean stream?: boolean max_tokens?: number temperature?: number top_p?: number top_k?: number seed?: number repetition_penalty?: number frequency_penalty?: number presence_penalty?: number messages?: RoleScopedChatInput[] response_format?: AiTextGenerationResponseFormat tools?: | AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable) functions?: AiTextGenerationFunctionsInput[] } type AiTextGenerationToolLegacyOutput = { name: string arguments: unknown } type AiTextGenerationToolOutput = { id: string type: 'function' function: { name: string arguments: string } } type UsageTags = { prompt_tokens: number completion_tokens: number total_tokens: number } type AiTextGenerationOutput = { response?: string tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[] usage?: UsageTags } declare abstract class BaseAiTextGeneration { inputs: AiTextGenerationInput postProcessedOutputs: AiTextGenerationOutput } type AiTextToSpeechInput = { prompt: string lang?: string } type AiTextToSpeechOutput = | Uint8Array | { audio: string } declare abstract class BaseAiTextToSpeech { inputs: AiTextToSpeechInput postProcessedOutputs: AiTextToSpeechOutput } type AiTextToImageInput = { prompt: string negative_prompt?: string height?: number width?: number image?: number[] image_b64?: string mask?: number[] num_steps?: number strength?: number guidance?: number seed?: number } type AiTextToImageOutput = ReadableStream declare abstract class BaseAiTextToImage { inputs: AiTextToImageInput postProcessedOutputs: AiTextToImageOutput } type AiTranslationInput = { text: string target_lang: string source_lang?: string } type AiTranslationOutput = { translated_text?: string } declare abstract class BaseAiTranslation { inputs: AiTranslationInput postProcessedOutputs: AiTranslationOutput } /** * Workers AI support for OpenAI's Responses API * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts * * It's a stripped down version from its source. * It currently supports basic function calling, json mode and accepts images as input. * * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools. * We plan to add those incrementally as model + platform capabilities evolve. */ type ResponsesInput = { background?: boolean | null conversation?: string | ResponseConversationParam | null include?: Array | null input?: string | ResponseInput instructions?: string | null max_output_tokens?: number | null parallel_tool_calls?: boolean | null previous_response_id?: string | null prompt_cache_key?: string reasoning?: Reasoning | null safety_identifier?: string service_tier?: 'auto' | 'default' | 'flex' | 'scale' | 'priority' | null stream?: boolean | null stream_options?: StreamOptions | null temperature?: number | null text?: ResponseTextConfig tool_choice?: ToolChoiceOptions | ToolChoiceFunction tools?: Array top_p?: number | null truncation?: 'auto' | 'disabled' | null } type ResponsesOutput = { id?: string created_at?: number output_text?: string error?: ResponseError | null incomplete_details?: ResponseIncompleteDetails | null instructions?: string | Array | null object?: 'response' output?: Array parallel_tool_calls?: boolean temperature?: number | null tool_choice?: ToolChoiceOptions | ToolChoiceFunction tools?: Array top_p?: number | null max_output_tokens?: number | null previous_response_id?: string | null prompt?: ResponsePrompt | null reasoning?: Reasoning | null safety_identifier?: string service_tier?: 'auto' | 'default' | 'flex' | 'scale' | 'priority' | null status?: ResponseStatus text?: ResponseTextConfig truncation?: 'auto' | 'disabled' | null usage?: ResponseUsage } type EasyInputMessage = { content: string | ResponseInputMessageContentList role: 'user' | 'assistant' | 'system' | 'developer' type?: 'message' } type ResponsesFunctionTool = { name: string parameters: { [key: string]: unknown } | null strict: boolean | null type: 'function' description?: string | null } type ResponseIncompleteDetails = { reason?: 'max_output_tokens' | 'content_filter' } type ResponsePrompt = { id: string variables?: { [key: string]: string | ResponseInputText | ResponseInputImage } | null version?: string | null } type Reasoning = { effort?: ReasoningEffort | null generate_summary?: 'auto' | 'concise' | 'detailed' | null summary?: 'auto' | 'concise' | 'detailed' | null } type ResponseContent = | ResponseInputText | ResponseInputImage | ResponseOutputText | ResponseOutputRefusal | ResponseContentReasoningText type ResponseContentReasoningText = { text: string type: 'reasoning_text' } type ResponseConversationParam = { id: string } type ResponseCreatedEvent = { response: Response sequence_number: number type: 'response.created' } type ResponseCustomToolCallOutput = { call_id: string output: string | Array type: 'custom_tool_call_output' id?: string } type ResponseError = { code: | 'server_error' | 'rate_limit_exceeded' | 'invalid_prompt' | 'vector_store_timeout' | 'invalid_image' | 'invalid_image_format' | 'invalid_base64_image' | 'invalid_image_url' | 'image_too_large' | 'image_too_small' | 'image_parse_error' | 'image_content_policy_violation' | 'invalid_image_mode' | 'image_file_too_large' | 'unsupported_image_media_type' | 'empty_image_file' | 'failed_to_download_image' | 'image_file_not_found' message: string } type ResponseErrorEvent = { code: string | null message: string param: string | null sequence_number: number type: 'error' } type ResponseFailedEvent = { response: Response sequence_number: number type: 'response.failed' } type ResponseFormatText = { type: 'text' } type ResponseFormatJSONObject = { type: 'json_object' } type ResponseFormatTextConfig = | ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject type ResponseFormatTextJSONSchemaConfig = { name: string schema: { [key: string]: unknown } type: 'json_schema' description?: string strict?: boolean | null } type ResponseFunctionCallArgumentsDeltaEvent = { delta: string item_id: string output_index: number sequence_number: number type: 'response.function_call_arguments.delta' } type ResponseFunctionCallArgumentsDoneEvent = { arguments: string item_id: string name: string output_index: number sequence_number: number type: 'response.function_call_arguments.done' } type ResponseFunctionCallOutputItem = | ResponseInputTextContent | ResponseInputImageContent type ResponseFunctionCallOutputItemList = Array type ResponseFunctionToolCall = { arguments: string call_id: string name: string type: 'function_call' id?: string status?: 'in_progress' | 'completed' | 'incomplete' } interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { id: string } type ResponseFunctionToolCallOutputItem = { id: string call_id: string output: string | Array type: 'function_call_output' status?: 'in_progress' | 'completed' | 'incomplete' } type ResponseIncludable = | 'message.input_image.image_url' | 'message.output_text.logprobs' type ResponseIncompleteEvent = { response: Response sequence_number: number type: 'response.incomplete' } type ResponseInput = Array type ResponseInputContent = ResponseInputText | ResponseInputImage type ResponseInputImage = { detail: 'low' | 'high' | 'auto' type: 'input_image' /** * Base64 encoded image */ image_url?: string | null } type ResponseInputImageContent = { type: 'input_image' detail?: 'low' | 'high' | 'auto' | null /** * Base64 encoded image */ image_url?: string | null } type ResponseInputItem = | EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem type ResponseInputItemFunctionCallOutput = { call_id: string output: string | ResponseFunctionCallOutputItemList type: 'function_call_output' id?: string | null status?: 'in_progress' | 'completed' | 'incomplete' | null } type ResponseInputItemMessage = { content: ResponseInputMessageContentList role: 'user' | 'system' | 'developer' status?: 'in_progress' | 'completed' | 'incomplete' type?: 'message' } type ResponseInputMessageContentList = Array type ResponseInputMessageItem = { id: string content: ResponseInputMessageContentList role: 'user' | 'system' | 'developer' status?: 'in_progress' | 'completed' | 'incomplete' type?: 'message' } type ResponseInputText = { text: string type: 'input_text' } type ResponseInputTextContent = { text: string type: 'input_text' } type ResponseItem = | ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem type ResponseOutputItem = | ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem type ResponseOutputItemAddedEvent = { item: ResponseOutputItem output_index: number sequence_number: number type: 'response.output_item.added' } type ResponseOutputItemDoneEvent = { item: ResponseOutputItem output_index: number sequence_number: number type: 'response.output_item.done' } type ResponseOutputMessage = { id: string content: Array role: 'assistant' status: 'in_progress' | 'completed' | 'incomplete' type: 'message' } type ResponseOutputRefusal = { refusal: string type: 'refusal' } type ResponseOutputText = { text: string type: 'output_text' logprobs?: Array } type ResponseReasoningItem = { id: string summary: Array type: 'reasoning' content?: Array encrypted_content?: string | null status?: 'in_progress' | 'completed' | 'incomplete' } type ResponseReasoningSummaryItem = { text: string type: 'summary_text' } type ResponseReasoningContentItem = { text: string type: 'reasoning_text' } type ResponseReasoningTextDeltaEvent = { content_index: number delta: string item_id: string output_index: number sequence_number: number type: 'response.reasoning_text.delta' } type ResponseReasoningTextDoneEvent = { content_index: number item_id: string output_index: number sequence_number: number text: string type: 'response.reasoning_text.done' } type ResponseRefusalDeltaEvent = { content_index: number delta: string item_id: string output_index: number sequence_number: number type: 'response.refusal.delta' } type ResponseRefusalDoneEvent = { content_index: number item_id: string output_index: number refusal: string sequence_number: number type: 'response.refusal.done' } type ResponseStatus = | 'completed' | 'failed' | 'in_progress' | 'cancelled' | 'queued' | 'incomplete' type ResponseStreamEvent = | ResponseCompletedEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent type ResponseCompletedEvent = { response: Response sequence_number: number type: 'response.completed' } type ResponseTextConfig = { format?: ResponseFormatTextConfig verbosity?: 'low' | 'medium' | 'high' | null } type ResponseTextDeltaEvent = { content_index: number delta: string item_id: string logprobs: Array output_index: number sequence_number: number type: 'response.output_text.delta' } type ResponseTextDoneEvent = { content_index: number item_id: string logprobs: Array output_index: number sequence_number: number text: string type: 'response.output_text.done' } type Logprob = { token: string logprob: number top_logprobs?: Array } type TopLogprob = { token?: string logprob?: number } type ResponseUsage = { input_tokens: number output_tokens: number total_tokens: number } type Tool = ResponsesFunctionTool type ToolChoiceFunction = { name: string type: 'function' } type ToolChoiceOptions = 'none' type ReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | null type StreamOptions = { include_obfuscation?: boolean } type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = | { text: string | string[] /** * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. */ pooling?: 'mean' | 'cls' } | { /** * Batch of the embeddings requests to run using async-queue */ requests: { text: string | string[] /** * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. */ pooling?: 'mean' | 'cls' }[] } type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = | { shape?: number[] /** * Embeddings of the requested text values */ data?: number[][] /** * The pooling method used in the embedding process. */ pooling?: 'mean' | 'cls' } | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse { /** * The async request id that can be used to obtain the results. */ request_id?: string } declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 { inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output } type Ai_Cf_Openai_Whisper_Input = | string | { /** * An array of integers that represent the audio data constrained to 8-bit unsigned integer values */ audio: number[] } interface Ai_Cf_Openai_Whisper_Output { /** * The transcription */ text: string word_count?: number words?: { word?: string /** * The second this word begins in the recording */ start?: number /** * The ending second when the word completes */ end?: number }[] vtt?: string } declare abstract class Base_Ai_Cf_Openai_Whisper { inputs: Ai_Cf_Openai_Whisper_Input postProcessedOutputs: Ai_Cf_Openai_Whisper_Output } type Ai_Cf_Meta_M2M100_1_2B_Input = | { /** * The text to be translated */ text: string /** * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified */ source_lang?: string /** * The language code to translate the text into (e.g., 'es' for Spanish) */ target_lang: string } | { /** * Batch of the embeddings requests to run using async-queue */ requests: { /** * The text to be translated */ text: string /** * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified */ source_lang?: string /** * The language code to translate the text into (e.g., 'es' for Spanish) */ target_lang: string }[] } type Ai_Cf_Meta_M2M100_1_2B_Output = | { /** * The translated text in the target language */ translated_text?: string } | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse { /** * The async request id that can be used to obtain the results. */ request_id?: string } declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { inputs: Ai_Cf_Meta_M2M100_1_2B_Input postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output } type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = | { text: string | string[] /** * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. */ pooling?: 'mean' | 'cls' } | { /** * Batch of the embeddings requests to run using async-queue */ requests: { text: string | string[] /** * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. */ pooling?: 'mean' | 'cls' }[] } type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = | { shape?: number[] /** * Embeddings of the requested text values */ data?: number[][] /** * The pooling method used in the embedding process. */ pooling?: 'mean' | 'cls' } | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse { /** * The async request id that can be used to obtain the results. */ request_id?: string } declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output } type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = | { text: string | string[] /** * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. */ pooling?: 'mean' | 'cls' } | { /** * Batch of the embeddings requests to run using async-queue */ requests: { text: string | string[] /** * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. */ pooling?: 'mean' | 'cls' }[] } type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = | { shape?: number[] /** * Embeddings of the requested text values */ data?: number[][] /** * The pooling method used in the embedding process. */ pooling?: 'mean' | 'cls' } | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse { /** * The async request id that can be used to obtain the results. */ request_id?: string } declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output } type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = | string | { /** * The input text prompt for the model to generate a response. */ prompt?: string /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number image: number[] | (string & NonNullable) /** * The maximum number of tokens to generate in the response. */ max_tokens?: number } interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output { description?: string } declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M { inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output } type Ai_Cf_Openai_Whisper_Tiny_En_Input = | string | { /** * An array of integers that represent the audio data constrained to 8-bit unsigned integer values */ audio: number[] } interface Ai_Cf_Openai_Whisper_Tiny_En_Output { /** * The transcription */ text: string word_count?: number words?: { word?: string /** * The second this word begins in the recording */ start?: number /** * The ending second when the word completes */ end?: number }[] vtt?: string } declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En { inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output } interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input { /** * Base64 encoded value of the audio data. */ audio: string /** * Supported tasks are 'translate' or 'transcribe'. */ task?: string /** * The language of the audio being transcribed or translated. */ language?: string /** * Preprocess the audio with a voice activity detection model. */ vad_filter?: boolean /** * A text prompt to help provide context to the model on the contents of the audio. */ initial_prompt?: string /** * The prefix it appended the the beginning of the output of the transcription and can guide the transcription result. */ prefix?: string } interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { transcription_info?: { /** * The language of the audio being transcribed or translated. */ language?: string /** * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. */ language_probability?: number /** * The total duration of the original audio file, in seconds. */ duration?: number /** * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. */ duration_after_vad?: number } /** * The complete transcription of the audio. */ text: string /** * The total number of words in the transcription. */ word_count?: number segments?: { /** * The starting time of the segment within the audio, in seconds. */ start?: number /** * The ending time of the segment within the audio, in seconds. */ end?: number /** * The transcription of the segment. */ text?: string /** * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. */ temperature?: number /** * The average log probability of the predictions for the words in this segment, indicating overall confidence. */ avg_logprob?: number /** * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. */ compression_ratio?: number /** * The probability that the segment contains no speech, represented as a decimal between 0 and 1. */ no_speech_prob?: number words?: { /** * The individual word transcribed from the audio. */ word?: string /** * The starting time of the word within the audio, in seconds. */ start?: number /** * The ending time of the word within the audio, in seconds. */ end?: number }[] }[] /** * The transcription in WebVTT format, which includes timing and text information for use in subtitles. */ vtt?: string } declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output } type Ai_Cf_Baai_Bge_M3_Input = | Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts | Ai_Cf_Baai_Bge_M3_Input_Embedding | { /** * Batch of the embeddings requests to run using async-queue */ requests: ( | Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 | Ai_Cf_Baai_Bge_M3_Input_Embedding_1 )[] } interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts { /** * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts */ query?: string /** * List of provided contexts. Note that the index in this array is important, as the response will refer to it. */ contexts: { /** * One of the provided context content */ text?: string }[] /** * When provided with too long context should the model error out or truncate the context to fit? */ truncate_inputs?: boolean } interface Ai_Cf_Baai_Bge_M3_Input_Embedding { text: string | string[] /** * When provided with too long context should the model error out or truncate the context to fit? */ truncate_inputs?: boolean } interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 { /** * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts */ query?: string /** * List of provided contexts. Note that the index in this array is important, as the response will refer to it. */ contexts: { /** * One of the provided context content */ text?: string }[] /** * When provided with too long context should the model error out or truncate the context to fit? */ truncate_inputs?: boolean } interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 { text: string | string[] /** * When provided with too long context should the model error out or truncate the context to fit? */ truncate_inputs?: boolean } type Ai_Cf_Baai_Bge_M3_Output = | Ai_Cf_Baai_Bge_M3_Ouput_Query | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts | Ai_Cf_Baai_Bge_M3_Ouput_Embedding | Ai_Cf_Baai_Bge_M3_AsyncResponse interface Ai_Cf_Baai_Bge_M3_Ouput_Query { response?: { /** * Index of the context in the request */ id?: number /** * Score of the context under the index. */ score?: number }[] } interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { response?: number[][] shape?: number[] /** * The pooling method used in the embedding process. */ pooling?: 'mean' | 'cls' } interface Ai_Cf_Baai_Bge_M3_Ouput_Embedding { shape?: number[] /** * Embeddings of the requested text values */ data?: number[][] /** * The pooling method used in the embedding process. */ pooling?: 'mean' | 'cls' } interface Ai_Cf_Baai_Bge_M3_AsyncResponse { /** * The async request id that can be used to obtain the results. */ request_id?: string } declare abstract class Base_Ai_Cf_Baai_Bge_M3 { inputs: Ai_Cf_Baai_Bge_M3_Input postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output } interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input { /** * A text description of the image you want to generate. */ prompt: string /** * The number of diffusion steps; higher values can improve quality but take longer. */ steps?: number } interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output { /** * The generated image in Base64 format. */ image?: string } declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output } type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ prompt: string image?: number[] | (string & NonNullable) /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number /** * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ lora?: string } interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { /** * An array of message objects representing the conversation history. */ messages: { /** * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ role?: string /** * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 */ tool_call_id?: string content?: | string | { /** * Type of the content provided */ type?: string text?: string image_url?: { /** * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ url?: string } }[] | { /** * Type of the content provided */ type?: string text?: string image_url?: { /** * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ url?: string } } }[] image?: number[] | (string & NonNullable) functions?: { name: string code: string }[] /** * A list of tools available for the assistant to use. */ tools?: ( | { /** * The name of the tool. More descriptive the better. */ name: string /** * A brief description of what the tool does. */ description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } | { /** * Specifies the type of tool (e.g., 'function'). */ type: string /** * Details of the function tool. */ function: { /** * The name of the function. */ name: string /** * A brief description of what the function does. */ description: string /** * Schema defining the parameters accepted by the function. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } } )[] /** * If true, the response will be streamed back incrementally. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = { /** * The generated text response from the model */ response?: string /** * An array of tool calls requests made during the response generation */ tool_calls?: { /** * The arguments passed to be passed to the tool call request */ arguments?: object /** * The name of the tool to be called */ name?: string }[] } declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output } type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { /** * The input text prompt for the model to generate a response. */ prompt: string /** * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ lora?: string response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { type?: 'json_object' | 'json_schema' json_schema?: unknown } interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { /** * An array of message objects representing the conversation history. */ messages: { /** * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ role: string /** * The content of the message as a string. */ content: string }[] functions?: { name: string code: string }[] /** * A list of tools available for the assistant to use. */ tools?: ( | { /** * The name of the tool. More descriptive the better. */ name: string /** * A brief description of what the tool does. */ description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } | { /** * Specifies the type of tool (e.g., 'function'). */ type: string /** * Details of the function tool. */ function: { /** * The name of the function. */ name: string /** * A brief description of what the function does. */ description: string /** * Schema defining the parameters accepted by the function. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } } )[] response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 { type?: 'json_object' | 'json_schema' json_schema?: unknown } interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { requests?: { /** * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. */ external_reference?: string /** * Prompt for the text generation model */ prompt?: string /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 }[] } interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 { type?: 'json_object' | 'json_schema' json_schema?: unknown } type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = | { /** * The generated text response from the model */ response: string /** * Usage statistics for the inference request */ usage?: { /** * Total number of tokens in input */ prompt_tokens?: number /** * Total number of tokens in output */ completion_tokens?: number /** * Total number of input and output tokens */ total_tokens?: number } /** * An array of tool calls requests made during the response generation */ tool_calls?: { /** * The arguments passed to be passed to the tool call request */ arguments?: object /** * The name of the tool to be called */ name?: string }[] } | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse { /** * The async request id that can be used to obtain the results. */ request_id?: string } declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output } interface Ai_Cf_Meta_Llama_Guard_3_8B_Input { /** * An array of message objects representing the conversation history. */ messages: { /** * The role of the message sender must alternate between 'user' and 'assistant'. */ role: 'user' | 'assistant' /** * The content of the message as a string. */ content: string }[] /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Dictate the output format of the generated response. */ response_format?: { /** * Set to json_object to process and output generated text as JSON. */ type?: string } } interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { response?: | string | { /** * Whether the conversation is safe or not. */ safe?: boolean /** * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. */ categories?: string[] } /** * Usage statistics for the inference request */ usage?: { /** * Total number of tokens in input */ prompt_tokens?: number /** * Total number of tokens in output */ completion_tokens?: number /** * Total number of input and output tokens */ total_tokens?: number } } declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B { inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output } interface Ai_Cf_Baai_Bge_Reranker_Base_Input { /** * A query you wish to perform against the provided contexts. */ /** * Number of returned results starting with the best score. */ top_k?: number /** * List of provided contexts. Note that the index in this array is important, as the response will refer to it. */ contexts: { /** * One of the provided context content */ text?: string }[] } interface Ai_Cf_Baai_Bge_Reranker_Base_Output { response?: { /** * Index of the context in the request */ id?: number /** * Score of the context under the index. */ score?: number }[] } declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output } type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ prompt: string /** * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ lora?: string response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode { type?: 'json_object' | 'json_schema' json_schema?: unknown } interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { /** * An array of message objects representing the conversation history. */ messages: { /** * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ role: string /** * The content of the message as a string. */ content: string }[] functions?: { name: string code: string }[] /** * A list of tools available for the assistant to use. */ tools?: ( | { /** * The name of the tool. More descriptive the better. */ name: string /** * A brief description of what the tool does. */ description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } | { /** * Specifies the type of tool (e.g., 'function'). */ type: string /** * Details of the function tool. */ function: { /** * The name of the function. */ name: string /** * A brief description of what the function does. */ description: string /** * Schema defining the parameters accepted by the function. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } } )[] response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { type?: 'json_object' | 'json_schema' json_schema?: unknown } type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { /** * The generated text response from the model */ response: string /** * Usage statistics for the inference request */ usage?: { /** * Total number of tokens in input */ prompt_tokens?: number /** * Total number of tokens in output */ completion_tokens?: number /** * Total number of input and output tokens */ total_tokens?: number } /** * An array of tool calls requests made during the response generation */ tool_calls?: { /** * The arguments passed to be passed to the tool call request */ arguments?: object /** * The name of the tool to be called */ name?: string }[] } declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output } type Ai_Cf_Qwen_Qwq_32B_Input = | Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages interface Ai_Cf_Qwen_Qwq_32B_Prompt { /** * The input text prompt for the model to generate a response. */ prompt: string /** * JSON schema that should be fulfilled for the response. */ guided_json?: object /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } interface Ai_Cf_Qwen_Qwq_32B_Messages { /** * An array of message objects representing the conversation history. */ messages: { /** * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ role?: string /** * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 */ tool_call_id?: string content?: | string | { /** * Type of the content provided */ type?: string text?: string image_url?: { /** * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ url?: string } }[] | { /** * Type of the content provided */ type?: string text?: string image_url?: { /** * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ url?: string } } }[] functions?: { name: string code: string }[] /** * A list of tools available for the assistant to use. */ tools?: ( | { /** * The name of the tool. More descriptive the better. */ name: string /** * A brief description of what the tool does. */ description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } | { /** * Specifies the type of tool (e.g., 'function'). */ type: string /** * Details of the function tool. */ function: { /** * The name of the function. */ name: string /** * A brief description of what the function does. */ description: string /** * Schema defining the parameters accepted by the function. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } } )[] /** * JSON schema that should be fufilled for the response. */ guided_json?: object /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } type Ai_Cf_Qwen_Qwq_32B_Output = { /** * The generated text response from the model */ response: string /** * Usage statistics for the inference request */ usage?: { /** * Total number of tokens in input */ prompt_tokens?: number /** * Total number of tokens in output */ completion_tokens?: number /** * Total number of input and output tokens */ total_tokens?: number } /** * An array of tool calls requests made during the response generation */ tool_calls?: { /** * The arguments passed to be passed to the tool call request */ arguments?: object /** * The name of the tool to be called */ name?: string }[] } declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { inputs: Ai_Cf_Qwen_Qwq_32B_Input postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output } type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ prompt: string /** * JSON schema that should be fulfilled for the response. */ guided_json?: object /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { /** * An array of message objects representing the conversation history. */ messages: { /** * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ role?: string /** * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 */ tool_call_id?: string content?: | string | { /** * Type of the content provided */ type?: string text?: string image_url?: { /** * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ url?: string } }[] | { /** * Type of the content provided */ type?: string text?: string image_url?: { /** * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ url?: string } } }[] functions?: { name: string code: string }[] /** * A list of tools available for the assistant to use. */ tools?: ( | { /** * The name of the tool. More descriptive the better. */ name: string /** * A brief description of what the tool does. */ description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } | { /** * Specifies the type of tool (e.g., 'function'). */ type: string /** * Details of the function tool. */ function: { /** * The name of the function. */ name: string /** * A brief description of what the function does. */ description: string /** * Schema defining the parameters accepted by the function. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } } )[] /** * JSON schema that should be fufilled for the response. */ guided_json?: object /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { /** * The generated text response from the model */ response: string /** * Usage statistics for the inference request */ usage?: { /** * Total number of tokens in input */ prompt_tokens?: number /** * Total number of tokens in output */ completion_tokens?: number /** * Total number of input and output tokens */ total_tokens?: number } /** * An array of tool calls requests made during the response generation */ tool_calls?: { /** * The arguments passed to be passed to the tool call request */ arguments?: object /** * The name of the tool to be called */ name?: string }[] } declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output } type Ai_Cf_Google_Gemma_3_12B_It_Input = | Ai_Cf_Google_Gemma_3_12B_It_Prompt | Ai_Cf_Google_Gemma_3_12B_It_Messages interface Ai_Cf_Google_Gemma_3_12B_It_Prompt { /** * The input text prompt for the model to generate a response. */ prompt: string /** * JSON schema that should be fufilled for the response. */ guided_json?: object /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } interface Ai_Cf_Google_Gemma_3_12B_It_Messages { /** * An array of message objects representing the conversation history. */ messages: { /** * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ role?: string content?: | string | { /** * Type of the content provided */ type?: string text?: string image_url?: { /** * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ url?: string } }[] }[] functions?: { name: string code: string }[] /** * A list of tools available for the assistant to use. */ tools?: ( | { /** * The name of the tool. More descriptive the better. */ name: string /** * A brief description of what the tool does. */ description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } | { /** * Specifies the type of tool (e.g., 'function'). */ type: string /** * Details of the function tool. */ function: { /** * The name of the function. */ name: string /** * A brief description of what the function does. */ description: string /** * Schema defining the parameters accepted by the function. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } } )[] /** * JSON schema that should be fufilled for the response. */ guided_json?: object /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } type Ai_Cf_Google_Gemma_3_12B_It_Output = { /** * The generated text response from the model */ response: string /** * Usage statistics for the inference request */ usage?: { /** * Total number of tokens in input */ prompt_tokens?: number /** * Total number of tokens in output */ completion_tokens?: number /** * Total number of input and output tokens */ total_tokens?: number } /** * An array of tool calls requests made during the response generation */ tool_calls?: { /** * The arguments passed to be passed to the tool call request */ arguments?: object /** * The name of the tool to be called */ name?: string }[] } declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { inputs: Ai_Cf_Google_Gemma_3_12B_It_Input postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output } type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ prompt: string /** * JSON schema that should be fulfilled for the response. */ guided_json?: object response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode { type?: 'json_object' | 'json_schema' json_schema?: unknown } interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages { /** * An array of message objects representing the conversation history. */ messages: { /** * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ role?: string /** * The tool call id. If you don't know what to put here you can fall back to 000000001 */ tool_call_id?: string content?: | string | { /** * Type of the content provided */ type?: string text?: string image_url?: { /** * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ url?: string } }[] | { /** * Type of the content provided */ type?: string text?: string image_url?: { /** * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ url?: string } } }[] functions?: { name: string code: string }[] /** * A list of tools available for the assistant to use. */ tools?: ( | { /** * The name of the tool. More descriptive the better. */ name: string /** * A brief description of what the tool does. */ description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } | { /** * Specifies the type of tool (e.g., 'function'). */ type: string /** * Details of the function tool. */ function: { /** * The name of the function. */ name: string /** * A brief description of what the function does. */ description: string /** * Schema defining the parameters accepted by the function. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } } )[] response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode /** * JSON schema that should be fufilled for the response. */ guided_json?: object /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch { requests: ( | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner )[] } interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { /** * The input text prompt for the model to generate a response. */ prompt: string /** * JSON schema that should be fulfilled for the response. */ guided_json?: object response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { /** * An array of message objects representing the conversation history. */ messages: { /** * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ role?: string /** * The tool call id. If you don't know what to put here you can fall back to 000000001 */ tool_call_id?: string content?: | string | { /** * Type of the content provided */ type?: string text?: string image_url?: { /** * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ url?: string } }[] | { /** * Type of the content provided */ type?: string text?: string image_url?: { /** * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ url?: string } } }[] functions?: { name: string code: string }[] /** * A list of tools available for the assistant to use. */ tools?: ( | { /** * The name of the tool. More descriptive the better. */ name: string /** * A brief description of what the tool does. */ description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } | { /** * Specifies the type of tool (e.g., 'function'). */ type: string /** * Details of the function tool. */ function: { /** * The name of the function. */ name: string /** * A brief description of what the function does. */ description: string /** * Schema defining the parameters accepted by the function. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } } )[] response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode /** * JSON schema that should be fufilled for the response. */ guided_json?: object /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = { /** * The generated text response from the model */ response: string /** * Usage statistics for the inference request */ usage?: { /** * Total number of tokens in input */ prompt_tokens?: number /** * Total number of tokens in output */ completion_tokens?: number /** * Total number of input and output tokens */ total_tokens?: number } /** * An array of tool calls requests made during the response generation */ tool_calls?: { /** * The tool call id. */ id?: string /** * Specifies the type of tool (e.g., 'function'). */ type?: string /** * Details of the function tool. */ function?: { /** * The name of the tool to be called */ name?: string /** * The arguments passed to be passed to the tool call request */ arguments?: object } }[] } declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output } type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt { /** * The input text prompt for the model to generate a response. */ prompt: string /** * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ lora?: string response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { type?: 'json_object' | 'json_schema' json_schema?: unknown } interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages { /** * An array of message objects representing the conversation history. */ messages: { /** * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ role: string /** * The content of the message as a string. */ content: string }[] functions?: { name: string code: string }[] /** * A list of tools available for the assistant to use. */ tools?: ( | { /** * The name of the tool. More descriptive the better. */ name: string /** * A brief description of what the tool does. */ description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } | { /** * Specifies the type of tool (e.g., 'function'). */ type: string /** * Details of the function tool. */ function: { /** * The name of the function. */ name: string /** * A brief description of what the function does. */ description: string /** * Schema defining the parameters accepted by the function. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } } )[] response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { type?: 'json_object' | 'json_schema' json_schema?: unknown } interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch { requests: ( | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 )[] } interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 { /** * The input text prompt for the model to generate a response. */ prompt: string /** * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ lora?: string response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { type?: 'json_object' | 'json_schema' json_schema?: unknown } interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 { /** * An array of message objects representing the conversation history. */ messages: { /** * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ role: string /** * The content of the message as a string. */ content: string }[] functions?: { name: string code: string }[] /** * A list of tools available for the assistant to use. */ tools?: ( | { /** * The name of the tool. More descriptive the better. */ name: string /** * A brief description of what the tool does. */ description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } | { /** * Specifies the type of tool (e.g., 'function'). */ type: string /** * Details of the function tool. */ function: { /** * The name of the function. */ name: string /** * A brief description of what the function does. */ description: string /** * Schema defining the parameters accepted by the function. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } } )[] response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 { type?: 'json_object' | 'json_schema' json_schema?: unknown } type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response | string | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response { /** * Unique identifier for the completion */ id?: string /** * Object type identifier */ object?: 'chat.completion' /** * Unix timestamp of when the completion was created */ created?: number /** * Model used for the completion */ model?: string /** * List of completion choices */ choices?: { /** * Index of the choice in the list */ index?: number /** * The message generated by the model */ message?: { /** * Role of the message author */ role: string /** * The content of the message */ content: string /** * Internal reasoning content (if available) */ reasoning_content?: string /** * Tool calls made by the assistant */ tool_calls?: { /** * Unique identifier for the tool call */ id: string /** * Type of tool call */ type: 'function' function: { /** * Name of the function to call */ name: string /** * JSON string of arguments for the function */ arguments: string } }[] } /** * Reason why the model stopped generating */ finish_reason?: string /** * Stop reason (may be null) */ stop_reason?: string | null /** * Log probabilities (if requested) */ logprobs?: {} | null }[] /** * Usage statistics for the inference request */ usage?: { /** * Total number of tokens in input */ prompt_tokens?: number /** * Total number of tokens in output */ completion_tokens?: number /** * Total number of input and output tokens */ total_tokens?: number } /** * Log probabilities for the prompt (if requested) */ prompt_logprobs?: {} | null } interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response { /** * Unique identifier for the completion */ id?: string /** * Object type identifier */ object?: 'text_completion' /** * Unix timestamp of when the completion was created */ created?: number /** * Model used for the completion */ model?: string /** * List of completion choices */ choices?: { /** * Index of the choice in the list */ index: number /** * The generated text completion */ text: string /** * Reason why the model stopped generating */ finish_reason: string /** * Stop reason (may be null) */ stop_reason?: string | null /** * Log probabilities (if requested) */ logprobs?: {} | null /** * Log probabilities for the prompt (if requested) */ prompt_logprobs?: {} | null }[] /** * Usage statistics for the inference request */ usage?: { /** * Total number of tokens in input */ prompt_tokens?: number /** * Total number of tokens in output */ completion_tokens?: number /** * Total number of input and output tokens */ total_tokens?: number } } interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse { /** * The async request id that can be used to obtain the results. */ request_id?: string } declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 { inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output } interface Ai_Cf_Deepgram_Nova_3_Input { audio: { body: object contentType: string } /** * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param. */ custom_topic_mode?: 'extended' | 'strict' /** * Custom topics you want the model to detect within your input audio or text if present Submit up to 100 */ custom_topic?: string /** * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param */ custom_intent_mode?: 'extended' | 'strict' /** * Custom intents you want the model to detect within your input audio if present */ custom_intent?: string /** * Identifies and extracts key entities from content in submitted audio */ detect_entities?: boolean /** * Identifies the dominant language spoken in submitted audio */ detect_language?: boolean /** * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0 */ diarize?: boolean /** * Identify and extract key entities from content in submitted audio */ dictation?: boolean /** * Specify the expected encoding of your submitted audio */ encoding?: | 'linear16' | 'flac' | 'mulaw' | 'amr-nb' | 'amr-wb' | 'opus' | 'speex' | 'g729' /** * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing */ extra?: string /** * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um' */ filler_words?: boolean /** * Key term prompting can boost or suppress specialized terminology and brands. */ keyterm?: string /** * Keywords can boost or suppress specialized terminology and brands. */ keywords?: string /** * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available. */ language?: string /** * Spoken measurements will be converted to their corresponding abbreviations. */ measurements?: boolean /** * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip. */ mip_opt_out?: boolean /** * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio */ mode?: 'general' | 'medical' | 'finance' /** * Transcribe each audio channel independently. */ multichannel?: boolean /** * Numerals converts numbers from written format to numerical format. */ numerals?: boolean /** * Splits audio into paragraphs to improve transcript readability. */ paragraphs?: boolean /** * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely. */ profanity_filter?: boolean /** * Add punctuation and capitalization to the transcript. */ punctuate?: boolean /** * Redaction removes sensitive information from your transcripts. */ redact?: string /** * Search for terms or phrases in submitted audio and replaces them. */ replace?: string /** * Search for terms or phrases in submitted audio. */ search?: string /** * Recognizes the sentiment throughout a transcript or text. */ sentiment?: boolean /** * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability. */ smart_format?: boolean /** * Detect topics throughout a transcript or text. */ topics?: boolean /** * Segments speech into meaningful semantic units. */ utterances?: boolean /** * Seconds to wait before detecting a pause between words in submitted audio. */ utt_split?: number /** * The number of channels in the submitted audio */ channels?: number /** * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets. */ interim_results?: boolean /** * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing */ endpointing?: string /** * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets. */ vad_events?: boolean /** * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets. */ utterance_end_ms?: boolean } interface Ai_Cf_Deepgram_Nova_3_Output { results?: { channels?: { alternatives?: { confidence?: number transcript?: string words?: { confidence?: number end?: number start?: number word?: string }[] }[] }[] summary?: { result?: string short?: string } sentiments?: { segments?: { text?: string start_word?: number end_word?: number sentiment?: string sentiment_score?: number }[] average?: { sentiment?: string sentiment_score?: number } } } } declare abstract class Base_Ai_Cf_Deepgram_Nova_3 { inputs: Ai_Cf_Deepgram_Nova_3_Input postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output } interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input { queries?: string | string[] /** * Optional instruction for the task */ instruction?: string documents?: string | string[] text?: string | string[] } interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output { data?: number[][] shape?: number[] } declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B { inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output } type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = | { /** * readable stream with audio data and content-type specified for that data */ audio: { body: object contentType: string } /** * type of data PCM data that's sent to the inference server as raw array */ dtype?: 'uint8' | 'float32' | 'float64' } | { /** * base64 encoded audio data */ audio: string /** * type of data PCM data that's sent to the inference server as raw array */ dtype?: 'uint8' | 'float32' | 'float64' } interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output { /** * if true, end-of-turn was detected */ is_complete?: boolean /** * probability of the end-of-turn detection */ probability?: number } declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 { inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output } declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { inputs: ResponsesInput postProcessedOutputs: ResponsesOutput } declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { inputs: ResponsesInput postProcessedOutputs: ResponsesOutput } interface Ai_Cf_Leonardo_Phoenix_1_0_Input { /** * A text description of the image you want to generate. */ prompt: string /** * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt */ guidance?: number /** * Random seed for reproducibility of the image generation */ seed?: number /** * The height of the generated image in pixels */ height?: number /** * The width of the generated image in pixels */ width?: number /** * The number of diffusion steps; higher values can improve quality but take longer */ num_steps?: number /** * Specify what to exclude from the generated images */ negative_prompt?: string } /** * The generated image in JPEG format */ type Ai_Cf_Leonardo_Phoenix_1_0_Output = string declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 { inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output } interface Ai_Cf_Leonardo_Lucid_Origin_Input { /** * A text description of the image you want to generate. */ prompt: string /** * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt */ guidance?: number /** * Random seed for reproducibility of the image generation */ seed?: number /** * The height of the generated image in pixels */ height?: number /** * The width of the generated image in pixels */ width?: number /** * The number of diffusion steps; higher values can improve quality but take longer */ num_steps?: number /** * The number of diffusion steps; higher values can improve quality but take longer */ steps?: number } interface Ai_Cf_Leonardo_Lucid_Origin_Output { /** * The generated image in Base64 format. */ image?: string } declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin { inputs: Ai_Cf_Leonardo_Lucid_Origin_Input postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output } interface Ai_Cf_Deepgram_Aura_1_Input { /** * Speaker used to produce the audio. */ speaker?: | 'angus' | 'asteria' | 'arcas' | 'orion' | 'orpheus' | 'athena' | 'luna' | 'zeus' | 'perseus' | 'helios' | 'hera' | 'stella' /** * Encoding of the output audio. */ encoding?: 'linear16' | 'flac' | 'mulaw' | 'alaw' | 'mp3' | 'opus' | 'aac' /** * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. */ container?: 'none' | 'wav' | 'ogg' /** * The text content to be converted to speech */ text: string /** * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable */ sample_rate?: number /** * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. */ bit_rate?: number } /** * The generated audio in MP3 format */ type Ai_Cf_Deepgram_Aura_1_Output = string declare abstract class Base_Ai_Cf_Deepgram_Aura_1 { inputs: Ai_Cf_Deepgram_Aura_1_Input postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output } interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input { /** * Input text to translate. Can be a single string or a list of strings. */ text: string | string[] /** * Target langauge to translate to */ target_language: | 'asm_Beng' | 'awa_Deva' | 'ben_Beng' | 'bho_Deva' | 'brx_Deva' | 'doi_Deva' | 'eng_Latn' | 'gom_Deva' | 'gon_Deva' | 'guj_Gujr' | 'hin_Deva' | 'hne_Deva' | 'kan_Knda' | 'kas_Arab' | 'kas_Deva' | 'kha_Latn' | 'lus_Latn' | 'mag_Deva' | 'mai_Deva' | 'mal_Mlym' | 'mar_Deva' | 'mni_Beng' | 'mni_Mtei' | 'npi_Deva' | 'ory_Orya' | 'pan_Guru' | 'san_Deva' | 'sat_Olck' | 'snd_Arab' | 'snd_Deva' | 'tam_Taml' | 'tel_Telu' | 'urd_Arab' | 'unr_Deva' } interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output { /** * Translated texts */ translations: string[] } declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B { inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output } type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt { /** * The input text prompt for the model to generate a response. */ prompt: string /** * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ lora?: string response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode { type?: 'json_object' | 'json_schema' json_schema?: unknown } interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages { /** * An array of message objects representing the conversation history. */ messages: { /** * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ role: string /** * The content of the message as a string. */ content: string }[] functions?: { name: string code: string }[] /** * A list of tools available for the assistant to use. */ tools?: ( | { /** * The name of the tool. More descriptive the better. */ name: string /** * A brief description of what the tool does. */ description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } | { /** * Specifies the type of tool (e.g., 'function'). */ type: string /** * Details of the function tool. */ function: { /** * The name of the function. */ name: string /** * A brief description of what the function does. */ description: string /** * Schema defining the parameters accepted by the function. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } } )[] response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 { type?: 'json_object' | 'json_schema' json_schema?: unknown } interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch { requests: ( | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 )[] } interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 { /** * The input text prompt for the model to generate a response. */ prompt: string /** * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ lora?: string response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 { type?: 'json_object' | 'json_schema' json_schema?: unknown } interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 { /** * An array of message objects representing the conversation history. */ messages: { /** * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ role: string /** * The content of the message as a string. */ content: string }[] functions?: { name: string code: string }[] /** * A list of tools available for the assistant to use. */ tools?: ( | { /** * The name of the tool. More descriptive the better. */ name: string /** * A brief description of what the tool does. */ description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } | { /** * Specifies the type of tool (e.g., 'function'). */ type: string /** * Details of the function tool. */ function: { /** * The name of the function. */ name: string /** * A brief description of what the function does. */ description: string /** * Schema defining the parameters accepted by the function. */ parameters: { /** * The type of the parameters object (usually 'object'). */ type: string /** * List of required parameter names. */ required?: string[] /** * Definitions of each parameter. */ properties: { [k: string]: { /** * The data type of the parameter. */ type: string /** * A description of the expected parameter. */ description: string } } } } } )[] response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ raw?: boolean /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ stream?: boolean /** * The maximum number of tokens to generate in the response. */ max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ top_p?: number /** * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ top_k?: number /** * Random seed for reproducibility of the generation. */ seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number } interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 { type?: 'json_object' | 'json_schema' json_schema?: unknown } type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response | string | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response { /** * Unique identifier for the completion */ id?: string /** * Object type identifier */ object?: 'chat.completion' /** * Unix timestamp of when the completion was created */ created?: number /** * Model used for the completion */ model?: string /** * List of completion choices */ choices?: { /** * Index of the choice in the list */ index?: number /** * The message generated by the model */ message?: { /** * Role of the message author */ role: string /** * The content of the message */ content: string /** * Internal reasoning content (if available) */ reasoning_content?: string /** * Tool calls made by the assistant */ tool_calls?: { /** * Unique identifier for the tool call */ id: string /** * Type of tool call */ type: 'function' function: { /** * Name of the function to call */ name: string /** * JSON string of arguments for the function */ arguments: string } }[] } /** * Reason why the model stopped generating */ finish_reason?: string /** * Stop reason (may be null) */ stop_reason?: string | null /** * Log probabilities (if requested) */ logprobs?: {} | null }[] /** * Usage statistics for the inference request */ usage?: { /** * Total number of tokens in input */ prompt_tokens?: number /** * Total number of tokens in output */ completion_tokens?: number /** * Total number of input and output tokens */ total_tokens?: number } /** * Log probabilities for the prompt (if requested) */ prompt_logprobs?: {} | null } interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response { /** * Unique identifier for the completion */ id?: string /** * Object type identifier */ object?: 'text_completion' /** * Unix timestamp of when the completion was created */ created?: number /** * Model used for the completion */ model?: string /** * List of completion choices */ choices?: { /** * Index of the choice in the list */ index: number /** * The generated text completion */ text: string /** * Reason why the model stopped generating */ finish_reason: string /** * Stop reason (may be null) */ stop_reason?: string | null /** * Log probabilities (if requested) */ logprobs?: {} | null /** * Log probabilities for the prompt (if requested) */ prompt_logprobs?: {} | null }[] /** * Usage statistics for the inference request */ usage?: { /** * Total number of tokens in input */ prompt_tokens?: number /** * Total number of tokens in output */ completion_tokens?: number /** * Total number of input and output tokens */ total_tokens?: number } } interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse { /** * The async request id that can be used to obtain the results. */ request_id?: string } declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It { inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output } interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input { /** * Input text to embed. Can be a single string or a list of strings. */ text: string | string[] } interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output { /** * Embedding vectors, where each vector is a list of floats. */ data: number[][] /** * Shape of the embedding data as [number_of_embeddings, embedding_dimension]. * * @minItems 2 * @maxItems 2 */ shape: [number, number] } declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B { inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output } interface Ai_Cf_Deepgram_Flux_Input { /** * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM. */ encoding: 'linear16' /** * Sample rate of the audio stream in Hz. */ sample_rate: string /** * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9. */ eager_eot_threshold?: string /** * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9. */ eot_threshold?: string /** * A turn will be finished when this much time has passed after speech, regardless of EOT confidence. */ eot_timeout_ms?: string /** * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms. */ keyterm?: string /** * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip */ mip_opt_out?: 'true' | 'false' /** * Label your requests for the purpose of identification during usage reporting */ tag?: string } /** * Output will be returned as websocket messages. */ interface Ai_Cf_Deepgram_Flux_Output { /** * The unique identifier of the request (uuid) */ request_id?: string /** * Starts at 0 and increments for each message the server sends to the client. */ sequence_id?: number /** * The type of event being reported. */ event?: | 'Update' | 'StartOfTurn' | 'EagerEndOfTurn' | 'TurnResumed' | 'EndOfTurn' /** * The index of the current turn */ turn_index?: number /** * Start time in seconds of the audio range that was transcribed */ audio_window_start?: number /** * End time in seconds of the audio range that was transcribed */ audio_window_end?: number /** * Text that was said over the course of the current turn */ transcript?: string /** * The words in the transcript */ words?: { /** * The individual punctuated, properly-cased word from the transcript */ word: string /** * Confidence that this word was transcribed correctly */ confidence: number }[] /** * Confidence that no more speech is coming in this turn */ end_of_turn_confidence?: number } declare abstract class Base_Ai_Cf_Deepgram_Flux { inputs: Ai_Cf_Deepgram_Flux_Input postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output } interface Ai_Cf_Deepgram_Aura_2_En_Input { /** * Speaker used to produce the audio. */ speaker?: | 'amalthea' | 'andromeda' | 'apollo' | 'arcas' | 'aries' | 'asteria' | 'athena' | 'atlas' | 'aurora' | 'callista' | 'cora' | 'cordelia' | 'delia' | 'draco' | 'electra' | 'harmonia' | 'helena' | 'hera' | 'hermes' | 'hyperion' | 'iris' | 'janus' | 'juno' | 'jupiter' | 'luna' | 'mars' | 'minerva' | 'neptune' | 'odysseus' | 'ophelia' | 'orion' | 'orpheus' | 'pandora' | 'phoebe' | 'pluto' | 'saturn' | 'thalia' | 'theia' | 'vesta' | 'zeus' /** * Encoding of the output audio. */ encoding?: 'linear16' | 'flac' | 'mulaw' | 'alaw' | 'mp3' | 'opus' | 'aac' /** * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. */ container?: 'none' | 'wav' | 'ogg' /** * The text content to be converted to speech */ text: string /** * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable */ sample_rate?: number /** * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. */ bit_rate?: number } /** * The generated audio in MP3 format */ type Ai_Cf_Deepgram_Aura_2_En_Output = string declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En { inputs: Ai_Cf_Deepgram_Aura_2_En_Input postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output } interface Ai_Cf_Deepgram_Aura_2_Es_Input { /** * Speaker used to produce the audio. */ speaker?: | 'sirio' | 'nestor' | 'carina' | 'celeste' | 'alvaro' | 'diana' | 'aquila' | 'selena' | 'estrella' | 'javier' /** * Encoding of the output audio. */ encoding?: 'linear16' | 'flac' | 'mulaw' | 'alaw' | 'mp3' | 'opus' | 'aac' /** * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. */ container?: 'none' | 'wav' | 'ogg' /** * The text content to be converted to speech */ text: string /** * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable */ sample_rate?: number /** * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. */ bit_rate?: number } /** * The generated audio in MP3 format */ type Ai_Cf_Deepgram_Aura_2_Es_Output = string declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es { inputs: Ai_Cf_Deepgram_Aura_2_Es_Input postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output } interface AiModels { '@cf/huggingface/distilbert-sst-2-int8': BaseAiTextClassification '@cf/stabilityai/stable-diffusion-xl-base-1.0': BaseAiTextToImage '@cf/runwayml/stable-diffusion-v1-5-inpainting': BaseAiTextToImage '@cf/runwayml/stable-diffusion-v1-5-img2img': BaseAiTextToImage '@cf/lykon/dreamshaper-8-lcm': BaseAiTextToImage '@cf/bytedance/stable-diffusion-xl-lightning': BaseAiTextToImage '@cf/myshell-ai/melotts': BaseAiTextToSpeech '@cf/google/embeddinggemma-300m': BaseAiTextEmbeddings '@cf/microsoft/resnet-50': BaseAiImageClassification '@cf/meta/llama-2-7b-chat-int8': BaseAiTextGeneration '@cf/mistral/mistral-7b-instruct-v0.1': BaseAiTextGeneration '@cf/meta/llama-2-7b-chat-fp16': BaseAiTextGeneration '@hf/thebloke/llama-2-13b-chat-awq': BaseAiTextGeneration '@hf/thebloke/mistral-7b-instruct-v0.1-awq': BaseAiTextGeneration '@hf/thebloke/zephyr-7b-beta-awq': BaseAiTextGeneration '@hf/thebloke/openhermes-2.5-mistral-7b-awq': BaseAiTextGeneration '@hf/thebloke/neural-chat-7b-v3-1-awq': BaseAiTextGeneration '@hf/thebloke/llamaguard-7b-awq': BaseAiTextGeneration '@hf/thebloke/deepseek-coder-6.7b-base-awq': BaseAiTextGeneration '@hf/thebloke/deepseek-coder-6.7b-instruct-awq': BaseAiTextGeneration '@cf/deepseek-ai/deepseek-math-7b-instruct': BaseAiTextGeneration '@cf/defog/sqlcoder-7b-2': BaseAiTextGeneration '@cf/openchat/openchat-3.5-0106': BaseAiTextGeneration '@cf/tiiuae/falcon-7b-instruct': BaseAiTextGeneration '@cf/thebloke/discolm-german-7b-v1-awq': BaseAiTextGeneration '@cf/qwen/qwen1.5-0.5b-chat': BaseAiTextGeneration '@cf/qwen/qwen1.5-7b-chat-awq': BaseAiTextGeneration '@cf/qwen/qwen1.5-14b-chat-awq': BaseAiTextGeneration '@cf/tinyllama/tinyllama-1.1b-chat-v1.0': BaseAiTextGeneration '@cf/microsoft/phi-2': BaseAiTextGeneration '@cf/qwen/qwen1.5-1.8b-chat': BaseAiTextGeneration '@cf/mistral/mistral-7b-instruct-v0.2-lora': BaseAiTextGeneration '@hf/nousresearch/hermes-2-pro-mistral-7b': BaseAiTextGeneration '@hf/nexusflow/starling-lm-7b-beta': BaseAiTextGeneration '@hf/google/gemma-7b-it': BaseAiTextGeneration '@cf/meta-llama/llama-2-7b-chat-hf-lora': BaseAiTextGeneration '@cf/google/gemma-2b-it-lora': BaseAiTextGeneration '@cf/google/gemma-7b-it-lora': BaseAiTextGeneration '@hf/mistral/mistral-7b-instruct-v0.2': BaseAiTextGeneration '@cf/meta/llama-3-8b-instruct': BaseAiTextGeneration '@cf/fblgit/una-cybertron-7b-v2-bf16': BaseAiTextGeneration '@cf/meta/llama-3-8b-instruct-awq': BaseAiTextGeneration '@cf/meta/llama-3.1-8b-instruct-fp8': BaseAiTextGeneration '@cf/meta/llama-3.1-8b-instruct-awq': BaseAiTextGeneration '@cf/meta/llama-3.2-3b-instruct': BaseAiTextGeneration '@cf/meta/llama-3.2-1b-instruct': BaseAiTextGeneration '@cf/deepseek-ai/deepseek-r1-distill-qwen-32b': BaseAiTextGeneration '@cf/ibm-granite/granite-4.0-h-micro': BaseAiTextGeneration '@cf/facebook/bart-large-cnn': BaseAiSummarization '@cf/llava-hf/llava-1.5-7b-hf': BaseAiImageToText '@cf/baai/bge-base-en-v1.5': Base_Ai_Cf_Baai_Bge_Base_En_V1_5 '@cf/openai/whisper': Base_Ai_Cf_Openai_Whisper '@cf/meta/m2m100-1.2b': Base_Ai_Cf_Meta_M2M100_1_2B '@cf/baai/bge-small-en-v1.5': Base_Ai_Cf_Baai_Bge_Small_En_V1_5 '@cf/baai/bge-large-en-v1.5': Base_Ai_Cf_Baai_Bge_Large_En_V1_5 '@cf/unum/uform-gen2-qwen-500m': Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M '@cf/openai/whisper-tiny-en': Base_Ai_Cf_Openai_Whisper_Tiny_En '@cf/openai/whisper-large-v3-turbo': Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo '@cf/baai/bge-m3': Base_Ai_Cf_Baai_Bge_M3 '@cf/black-forest-labs/flux-1-schnell': Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell '@cf/meta/llama-3.2-11b-vision-instruct': Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct '@cf/meta/llama-3.3-70b-instruct-fp8-fast': Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast '@cf/meta/llama-guard-3-8b': Base_Ai_Cf_Meta_Llama_Guard_3_8B '@cf/baai/bge-reranker-base': Base_Ai_Cf_Baai_Bge_Reranker_Base '@cf/qwen/qwen2.5-coder-32b-instruct': Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct '@cf/qwen/qwq-32b': Base_Ai_Cf_Qwen_Qwq_32B '@cf/mistralai/mistral-small-3.1-24b-instruct': Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct '@cf/google/gemma-3-12b-it': Base_Ai_Cf_Google_Gemma_3_12B_It '@cf/meta/llama-4-scout-17b-16e-instruct': Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct '@cf/qwen/qwen3-30b-a3b-fp8': Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 '@cf/deepgram/nova-3': Base_Ai_Cf_Deepgram_Nova_3 '@cf/qwen/qwen3-embedding-0.6b': Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B '@cf/pipecat-ai/smart-turn-v2': Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 '@cf/openai/gpt-oss-120b': Base_Ai_Cf_Openai_Gpt_Oss_120B '@cf/openai/gpt-oss-20b': Base_Ai_Cf_Openai_Gpt_Oss_20B '@cf/leonardo/phoenix-1.0': Base_Ai_Cf_Leonardo_Phoenix_1_0 '@cf/leonardo/lucid-origin': Base_Ai_Cf_Leonardo_Lucid_Origin '@cf/deepgram/aura-1': Base_Ai_Cf_Deepgram_Aura_1 '@cf/ai4bharat/indictrans2-en-indic-1B': Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B '@cf/aisingapore/gemma-sea-lion-v4-27b-it': Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It '@cf/pfnet/plamo-embedding-1b': Base_Ai_Cf_Pfnet_Plamo_Embedding_1B '@cf/deepgram/flux': Base_Ai_Cf_Deepgram_Flux '@cf/deepgram/aura-2-en': Base_Ai_Cf_Deepgram_Aura_2_En '@cf/deepgram/aura-2-es': Base_Ai_Cf_Deepgram_Aura_2_Es } type AiOptions = { /** * Send requests as an asynchronous batch job, only works for supported models * https://developers.cloudflare.com/workers-ai/features/batch-api */ queueRequest?: boolean /** * Establish websocket connections, only works for supported models */ websocket?: boolean /** * Tag your requests to group and view them in Cloudflare dashboard. * * Rules: * Tags must only contain letters, numbers, and the symbols: : - . / @ * Each tag can have maximum 50 characters. * Maximum 5 tags are allowed each request. * Duplicate tags will removed. */ tags?: string[] gateway?: GatewayOptions returnRawResponse?: boolean prefix?: string extraHeaders?: object } type AiModelsSearchParams = { author?: string hide_experimental?: boolean page?: number per_page?: number search?: string source?: number task?: string } type AiModelsSearchObject = { id: string source: number name: string description: string task: { id: string name: string description: string } tags: string[] properties: { property_id: string value: string }[] } interface InferenceUpstreamError extends Error {} interface AiInternalError extends Error {} type AiModelListType = Record declare abstract class Ai { aiGatewayLogId: string | null gateway(gatewayId: string): AiGateway autorag(autoragId: string): AutoRAG run< Name extends keyof AiModelList, Options extends AiOptions, InputOptions extends AiModelList[Name]['inputs'], >( model: Name, inputs: InputOptions, options?: Options, ): Promise< Options extends | { returnRawResponse: true } | { websocket: true } ? Response : InputOptions extends { stream: true } ? ReadableStream : AiModelList[Name]['postProcessedOutputs'] > models(params?: AiModelsSearchParams): Promise toMarkdown(): ToMarkdownService toMarkdown( files: MarkdownDocument[], options?: ConversionRequestOptions, ): Promise toMarkdown( files: MarkdownDocument, options?: ConversionRequestOptions, ): Promise } type GatewayRetries = { maxAttempts?: 1 | 2 | 3 | 4 | 5 retryDelayMs?: number backoff?: 'constant' | 'linear' | 'exponential' } type GatewayOptions = { id: string cacheKey?: string cacheTtl?: number skipCache?: boolean metadata?: Record collectLog?: boolean eventId?: string requestTimeoutMs?: number retries?: GatewayRetries } type UniversalGatewayOptions = Exclude & { /** ** @deprecated */ id?: string } type AiGatewayPatchLog = { score?: number | null feedback?: -1 | 1 | null metadata?: Record | null } type AiGatewayLog = { id: string provider: string model: string model_type?: string path: string duration: number request_type?: string request_content_type?: string status_code: number response_content_type?: string success: boolean cached: boolean tokens_in?: number tokens_out?: number metadata?: Record step?: number cost?: number custom_cost?: boolean request_size: number request_head?: string request_head_complete: boolean response_size: number response_head?: string response_head_complete: boolean created_at: Date } type AIGatewayProviders = | 'workers-ai' | 'anthropic' | 'aws-bedrock' | 'azure-openai' | 'google-vertex-ai' | 'huggingface' | 'openai' | 'perplexity-ai' | 'replicate' | 'groq' | 'cohere' | 'google-ai-studio' | 'mistral' | 'grok' | 'openrouter' | 'deepseek' | 'cerebras' | 'cartesia' | 'elevenlabs' | 'adobe-firefly' type AIGatewayHeaders = { 'cf-aig-metadata': | Record | string 'cf-aig-custom-cost': | { per_token_in?: number per_token_out?: number } | { total_cost?: number } | string 'cf-aig-cache-ttl': number | string 'cf-aig-skip-cache': boolean | string 'cf-aig-cache-key': string 'cf-aig-event-id': string 'cf-aig-request-timeout': number | string 'cf-aig-max-attempts': number | string 'cf-aig-retry-delay': number | string 'cf-aig-backoff': string 'cf-aig-collect-log': boolean | string Authorization: string 'Content-Type': string [key: string]: string | number | boolean | object } type AIGatewayUniversalRequest = { provider: AIGatewayProviders | string // eslint-disable-line endpoint: string headers: Partial query: unknown } interface AiGatewayInternalError extends Error {} interface AiGatewayLogNotFound extends Error {} declare abstract class AiGateway { patchLog(logId: string, data: AiGatewayPatchLog): Promise getLog(logId: string): Promise run( data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: { gateway?: UniversalGatewayOptions extraHeaders?: object }, ): Promise getUrl(provider?: AIGatewayProviders | string): Promise // eslint-disable-line } interface AutoRAGInternalError extends Error {} interface AutoRAGNotFoundError extends Error {} interface AutoRAGUnauthorizedError extends Error {} interface AutoRAGNameNotSetError extends Error {} type ComparisonFilter = { key: string type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte' value: string | number | boolean } type CompoundFilter = { type: 'and' | 'or' filters: ComparisonFilter[] } type AutoRagSearchRequest = { query: string filters?: CompoundFilter | ComparisonFilter max_num_results?: number ranking_options?: { ranker?: string score_threshold?: number } reranking?: { enabled?: boolean model?: string } rewrite_query?: boolean } type AutoRagAiSearchRequest = AutoRagSearchRequest & { stream?: boolean system_prompt?: string } type AutoRagAiSearchRequestStreaming = Omit< AutoRagAiSearchRequest, 'stream' > & { stream: true } type AutoRagSearchResponse = { object: 'vector_store.search_results.page' search_query: string data: { file_id: string filename: string score: number attributes: Record content: { type: 'text' text: string }[] }[] has_more: boolean next_page: string | null } type AutoRagListResponse = { id: string enable: boolean type: string source: string vectorize_name: string paused: boolean status: string }[] type AutoRagAiSearchResponse = AutoRagSearchResponse & { response: string } declare abstract class AutoRAG { list(): Promise search(params: AutoRagSearchRequest): Promise aiSearch(params: AutoRagAiSearchRequestStreaming): Promise aiSearch(params: AutoRagAiSearchRequest): Promise aiSearch( params: AutoRagAiSearchRequest, ): Promise } interface BasicImageTransformations { /** * Maximum width in image pixels. The value must be an integer. */ width?: number /** * Maximum height in image pixels. The value must be an integer. */ height?: number /** * Resizing mode as a string. It affects interpretation of width and height * options: * - scale-down: Similar to contain, but the image is never enlarged. If * the image is larger than given width or height, it will be resized. * Otherwise its original size will be kept. * - contain: Resizes to maximum size that fits within the given width and * height. If only a single dimension is given (e.g. only width), the * image will be shrunk or enlarged to exactly match that dimension. * Aspect ratio is always preserved. * - cover: Resizes (shrinks or enlarges) to fill the entire area of width * and height. If the image has an aspect ratio different from the ratio * of width and height, it will be cropped to fit. * - crop: The image will be shrunk and cropped to fit within the area * specified by width and height. The image will not be enlarged. For images * smaller than the given dimensions it's the same as scale-down. For * images larger than the given dimensions, it's the same as cover. * See also trim. * - pad: Resizes to the maximum size that fits within the given width and * height, and then fills the remaining area with a background color * (white by default). Use of this mode is not recommended, as the same * effect can be more efficiently achieved with the contain mode and the * CSS object-fit: contain property. * - squeeze: Stretches and deforms to the width and height given, even if it * breaks aspect ratio */ fit?: 'scale-down' | 'contain' | 'cover' | 'crop' | 'pad' | 'squeeze' /** * Image segmentation using artificial intelligence models. Sets pixels not * within selected segment area to transparent e.g "foreground" sets every * background pixel as transparent. */ segment?: 'foreground' /** * When cropping with fit: "cover", this defines the side or point that should * be left uncropped. The value is either a string * "left", "right", "top", "bottom", "auto", or "center" (the default), * or an object {x, y} containing focal point coordinates in the original * image expressed as fractions ranging from 0.0 (top or left) to 1.0 * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will * crop bottom or left and right sides as necessary, but won’t crop anything * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to * preserve as much as possible around a point at 20% of the height of the * source image. */ gravity?: | 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates /** * Background color to add underneath the image. Applies only to images with * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), * hsl(…), etc.) */ background?: string /** * Number of degrees (90, 180, 270) to rotate the image by. width and height * options refer to axes after rotation. */ rotate?: 0 | 90 | 180 | 270 | 360 } interface BasicImageTransformationsGravityCoordinates { x?: number y?: number mode?: 'remainder' | 'box-center' } /** * In addition to the properties you can set in the RequestInit dict * that you pass as an argument to the Request constructor, you can * set certain properties of a `cf` object to control how Cloudflare * features are applied to that new Request. * * Note: Currently, these properties cannot be tested in the * playground. */ interface RequestInitCfProperties extends Record { cacheEverything?: boolean /** * A request's cache key is what determines if two requests are * "the same" for caching purposes. If a request has the same cache key * as some previous request, then we can serve the same cached response for * both. (e.g. 'some-key') * * Only available for Enterprise customers. */ cacheKey?: string /** * This allows you to append additional Cache-Tag response headers * to the origin response without modifications to the origin server. * This will allow for greater control over the Purge by Cache Tag feature * utilizing changes only in the Workers process. * * Only available for Enterprise customers. */ cacheTags?: string[] /** * Force response to be cached for a given number of seconds. (e.g. 300) */ cacheTtl?: number /** * Force response to be cached for a given number of seconds based on the Origin status code. * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) */ cacheTtlByStatus?: Record scrapeShield?: boolean apps?: boolean image?: RequestInitCfPropertiesImage minify?: RequestInitCfPropertiesImageMinify mirage?: boolean polish?: 'lossy' | 'lossless' | 'off' r2?: RequestInitCfPropertiesR2 /** * Redirects the request to an alternate origin server. You can use this, * for example, to implement load balancing across several origins. * (e.g.us-east.example.com) * * Note - For security reasons, the hostname set in resolveOverride must * be proxied on the same Cloudflare zone of the incoming request. * Otherwise, the setting is ignored. CNAME hosts are allowed, so to * resolve to a host under a different domain or a DNS only domain first * declare a CNAME record within your own zone’s DNS mapping to the * external hostname, set proxy on Cloudflare, then set resolveOverride * to point to that CNAME record. */ resolveOverride?: string } interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations { /** * Absolute URL of the image file to use for the drawing. It can be any of * the supported file formats. For drawing of watermarks or non-rectangular * overlays we recommend using PNG or WebP images. */ url: string /** * Floating-point number between 0 (transparent) and 1 (opaque). * For example, opacity: 0.5 makes overlay semitransparent. */ opacity?: number /** * - If set to true, the overlay image will be tiled to cover the entire * area. This is useful for stock-photo-like watermarks. * - If set to "x", the overlay image will be tiled horizontally only * (form a line). * - If set to "y", the overlay image will be tiled vertically only * (form a line). */ repeat?: true | 'x' | 'y' /** * Position of the overlay image relative to a given edge. Each property is * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 * positions left side of the overlay 10 pixels from the left edge of the * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom * of the background image. * * Setting both left & right, or both top & bottom is an error. * * If no position is specified, the image will be centered. */ top?: number left?: number bottom?: number right?: number } interface RequestInitCfPropertiesImage extends BasicImageTransformations { /** * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it * easier to specify higher-DPI sizes in . */ dpr?: number /** * Allows you to trim your image. Takes dpr into account and is performed before * resizing or rotation. * * It can be used as: * - left, top, right, bottom - it will specify the number of pixels to cut * off each side * - width, height - the width/height you'd like to end up with - can be used * in combination with the properties above * - border - this will automatically trim the surroundings of an image based on * it's color. It consists of three properties: * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit) * - tolerance: difference from color to treat as color * - keep: the number of pixels of border to keep */ trim?: | 'border' | { top?: number bottom?: number left?: number right?: number width?: number height?: number border?: | boolean | { color?: string tolerance?: number keep?: number } } /** * Quality setting from 1-100 (useful values are in 60-90 range). Lower values * make images look worse, but load faster. The default is 85. It applies only * to JPEG and WebP images. It doesn’t have any effect on PNG. */ quality?: number | 'low' | 'medium-low' | 'medium-high' | 'high' /** * Output format to generate. It can be: * - avif: generate images in AVIF format. * - webp: generate images in Google WebP format. Set quality to 100 to get * the WebP-lossless format. * - json: instead of generating an image, outputs information about the * image, in JSON format. The JSON object will contain image size * (before and after resizing), source image’s MIME type, file size, etc. * - jpeg: generate images in JPEG format. * - png: generate images in PNG format. */ format?: | 'avif' | 'webp' | 'json' | 'jpeg' | 'png' | 'baseline-jpeg' | 'png-force' | 'svg' /** * Whether to preserve animation frames from input files. Default is true. * Setting it to false reduces animations to still images. This setting is * recommended when enlarging images or processing arbitrary user content, * because large GIF animations can weigh tens or even hundreds of megabytes. * It is also useful to set anim:false when using format:"json" to get the * response quicker without the number of frames. */ anim?: boolean /** * What EXIF data should be preserved in the output image. Note that EXIF * rotation and embedded color profiles are always applied ("baked in" into * the image), and aren't affected by this option. Note that if the Polish * feature is enabled, all metadata may have been removed already and this * option may have no effect. * - keep: Preserve most of EXIF metadata, including GPS location if there's * any. * - copyright: Only keep the copyright tag, and discard everything else. * This is the default behavior for JPEG files. * - none: Discard all invisible EXIF metadata. Currently WebP and PNG * output formats always discard metadata. */ metadata?: 'keep' | 'copyright' | 'none' /** * Strength of sharpening filter to apply to the image. Floating-point * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a * recommended value for downscaled images. */ sharpen?: number /** * Radius of a blur filter (approximate gaussian). Maximum supported radius * is 250. */ blur?: number /** * Overlays are drawn in the order they appear in the array (last array * entry is the topmost layer). */ draw?: RequestInitCfPropertiesImageDraw[] /** * Fetching image from authenticated origin. Setting this property will * pass authentication headers (Authorization, Cookie, etc.) through to * the origin. */ 'origin-auth'?: 'share-publicly' /** * Adds a border around the image. The border is added after resizing. Border * width takes dpr into account, and can be specified either using a single * width property, or individually for each side. */ border?: | { color: string width: number } | { color: string top: number right: number bottom: number left: number } /** * Increase brightness by a factor. A value of 1.0 equals no change, a value * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. * 0 is ignored. */ brightness?: number /** * Increase contrast by a factor. A value of 1.0 equals no change, a value of * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is * ignored. */ contrast?: number /** * Increase exposure by a factor. A value of 1.0 equals no change, a value of * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. */ gamma?: number /** * Increase contrast by a factor. A value of 1.0 equals no change, a value of * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is * ignored. */ saturation?: number /** * Flips the images horizontally, vertically, or both. Flipping is applied before * rotation, so if you apply flip=h,rotate=90 then the image will be flipped * horizontally, then rotated by 90 degrees. */ flip?: 'h' | 'v' | 'hv' /** * Slightly reduces latency on a cache miss by selecting a * quickest-to-compress file format, at a cost of increased file size and * lower image quality. It will usually override the format option and choose * JPEG over WebP or AVIF. We do not recommend using this option, except in * unusual circumstances like resizing uncacheable dynamically-generated * images. */ compression?: 'fast' } interface RequestInitCfPropertiesImageMinify { javascript?: boolean css?: boolean html?: boolean } interface RequestInitCfPropertiesR2 { /** * Colo id of bucket that an object is stored in */ bucketColoId?: number } /** * Request metadata provided by Cloudflare's edge. */ type IncomingRequestCfProperties = IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & IncomingRequestCfPropertiesGeographicInformation & IncomingRequestCfPropertiesCloudflareAccessOrApiShield interface IncomingRequestCfPropertiesBase extends Record { /** * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. * * @example 395747 */ asn?: number /** * The organization which owns the ASN of the incoming request. * * @example "Google Cloud" */ asOrganization?: string /** * The original value of the `Accept-Encoding` header if Cloudflare modified it. * * @example "gzip, deflate, br" */ clientAcceptEncoding?: string /** * The number of milliseconds it took for the request to reach your worker. * * @example 22 */ clientTcpRtt?: number /** * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) * airport code of the data center that the request hit. * * @example "DFW" */ colo: string /** * Represents the upstream's response to a * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) * from cloudflare. * * For workers with no upstream, this will always be `1`. * * @example 3 */ edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus /** * The HTTP Protocol the request used. * * @example "HTTP/2" */ httpProtocol: string /** * The browser-requested prioritization information in the request object. * * If no information was set, defaults to the empty string `""` * * @example "weight=192;exclusive=0;group=3;group-weight=127" * @default "" */ requestPriority: string /** * The TLS version of the connection to Cloudflare. * In requests served over plaintext (without TLS), this property is the empty string `""`. * * @example "TLSv1.3" */ tlsVersion: string /** * The cipher for the connection to Cloudflare. * In requests served over plaintext (without TLS), this property is the empty string `""`. * * @example "AEAD-AES128-GCM-SHA256" */ tlsCipher: string /** * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. * * If the incoming request was served over plaintext (without TLS) this field is undefined. */ tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata } interface IncomingRequestCfPropertiesBotManagementBase { /** * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). * * @example 54 */ score: number /** * A boolean value that is true if the request comes from a good bot, like Google or Bing. * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). */ verifiedBot: boolean /** * A boolean value that is true if the request originates from a * Cloudflare-verified proxy service. */ corporateProxy: boolean /** * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. */ staticResource: boolean /** * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). */ detectionIds: number[] } interface IncomingRequestCfPropertiesBotManagement { /** * Results of Cloudflare's Bot Management analysis */ botManagement: IncomingRequestCfPropertiesBotManagementBase /** * Duplicate of `botManagement.score`. * * @deprecated */ clientTrustScore: number } interface IncomingRequestCfPropertiesBotManagementEnterprise extends IncomingRequestCfPropertiesBotManagement { /** * Results of Cloudflare's Bot Management analysis */ botManagement: IncomingRequestCfPropertiesBotManagementBase & { /** * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients * across different destination IPs, Ports, and X509 certificates. */ ja3Hash: string } } interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise { /** * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). * * This field is only present if you have Cloudflare for SaaS enabled on your account * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). */ hostMetadata?: HostMetadata } interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { /** * Information about the client certificate presented to Cloudflare. * * This is populated when the incoming request is served over TLS using * either Cloudflare Access or API Shield (mTLS) * and the presented SSL certificate has a valid * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) * (i.e., not `null` or `""`). * * Otherwise, a set of placeholder values are used. * * The property `certPresented` will be set to `"1"` when * the object is populated (i.e. the above conditions were met). */ tlsClientAuth: | IncomingRequestCfPropertiesTLSClientAuth | IncomingRequestCfPropertiesTLSClientAuthPlaceholder } /** * Metadata about the request's TLS handshake */ interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { /** * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal * * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" */ clientHandshake: string /** * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal * * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" */ serverHandshake: string /** * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal * * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" */ clientFinished: string /** * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal * * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" */ serverFinished: string } /** * Geographic data about the request's origin. */ interface IncomingRequestCfPropertiesGeographicInformation { /** * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. * * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. * * If Cloudflare is unable to determine where the request originated this property is omitted. * * The country code `"T1"` is used for requests originating on TOR. * * @example "GB" */ country?: Iso3166Alpha2Code | 'T1' /** * If present, this property indicates that the request originated in the EU * * @example "1" */ isEUCountry?: '1' /** * A two-letter code indicating the continent the request originated from. * * @example "AN" */ continent?: ContinentCode /** * The city the request originated from * * @example "Austin" */ city?: string /** * Postal code of the incoming request * * @example "78701" */ postalCode?: string /** * Latitude of the incoming request * * @example "30.27130" */ latitude?: string /** * Longitude of the incoming request * * @example "-97.74260" */ longitude?: string /** * Timezone of the incoming request * * @example "America/Chicago" */ timezone?: string /** * If known, the ISO 3166-2 name for the first level region associated with * the IP address of the incoming request * * @example "Texas" */ region?: string /** * If known, the ISO 3166-2 code for the first-level region associated with * the IP address of the incoming request * * @example "TX" */ regionCode?: string /** * Metro code (DMA) of the incoming request * * @example "635" */ metroCode?: string } /** Data about the incoming request's TLS certificate */ interface IncomingRequestCfPropertiesTLSClientAuth { /** Always `"1"`, indicating that the certificate was presented */ certPresented: '1' /** * Result of certificate verification. * * @example "FAILED:self signed certificate" */ certVerified: Exclude /** The presented certificate's revokation status. * * - A value of `"1"` indicates the certificate has been revoked * - A value of `"0"` indicates the certificate has not been revoked */ certRevoked: '1' | '0' /** * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) * * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" */ certIssuerDN: string /** * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) * * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" */ certSubjectDN: string /** * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) * * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" */ certIssuerDNRFC2253: string /** * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) * * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" */ certSubjectDNRFC2253: string /** The certificate issuer's distinguished name (legacy policies) */ certIssuerDNLegacy: string /** The certificate subject's distinguished name (legacy policies) */ certSubjectDNLegacy: string /** * The certificate's serial number * * @example "00936EACBE07F201DF" */ certSerial: string /** * The certificate issuer's serial number * * @example "2489002934BDFEA34" */ certIssuerSerial: string /** * The certificate's Subject Key Identifier * * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" */ certSKI: string /** * The certificate issuer's Subject Key Identifier * * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" */ certIssuerSKI: string /** * The certificate's SHA-1 fingerprint * * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" */ certFingerprintSHA1: string /** * The certificate's SHA-256 fingerprint * * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" */ certFingerprintSHA256: string /** * The effective starting date of the certificate * * @example "Dec 22 19:39:00 2018 GMT" */ certNotBefore: string /** * The effective expiration date of the certificate * * @example "Dec 22 19:39:00 2018 GMT" */ certNotAfter: string } /** Placeholder values for TLS Client Authorization */ interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { certPresented: '0' certVerified: 'NONE' certRevoked: '0' certIssuerDN: '' certSubjectDN: '' certIssuerDNRFC2253: '' certSubjectDNRFC2253: '' certIssuerDNLegacy: '' certSubjectDNLegacy: '' certSerial: '' certIssuerSerial: '' certSKI: '' certIssuerSKI: '' certFingerprintSHA1: '' certFingerprintSHA256: '' certNotBefore: '' certNotAfter: '' } /** Possible outcomes of TLS verification */ declare type CertVerificationStatus = /** Authentication succeeded */ | 'SUCCESS' /** No certificate was presented */ | 'NONE' /** Failed because the certificate was self-signed */ | 'FAILED:self signed certificate' /** Failed because the certificate failed a trust chain check */ | 'FAILED:unable to verify the first certificate' /** Failed because the certificate not yet valid */ | 'FAILED:certificate is not yet valid' /** Failed because the certificate is expired */ | 'FAILED:certificate has expired' /** Failed for another unspecified reason */ | 'FAILED' /** * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. */ declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = | 0 /** Unknown */ | 1 /** no keepalives (not found) */ | 2 /** no connection re-use, opening keepalive connection failed */ | 3 /** no connection re-use, keepalive accepted and saved */ | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ | 5 /** connection re-use, accepted by the origin server */ /** ISO 3166-1 Alpha-2 codes */ declare type Iso3166Alpha2Code = | 'AD' | 'AE' | 'AF' | 'AG' | 'AI' | 'AL' | 'AM' | 'AO' | 'AQ' | 'AR' | 'AS' | 'AT' | 'AU' | 'AW' | 'AX' | 'AZ' | 'BA' | 'BB' | 'BD' | 'BE' | 'BF' | 'BG' | 'BH' | 'BI' | 'BJ' | 'BL' | 'BM' | 'BN' | 'BO' | 'BQ' | 'BR' | 'BS' | 'BT' | 'BV' | 'BW' | 'BY' | 'BZ' | 'CA' | 'CC' | 'CD' | 'CF' | 'CG' | 'CH' | 'CI' | 'CK' | 'CL' | 'CM' | 'CN' | 'CO' | 'CR' | 'CU' | 'CV' | 'CW' | 'CX' | 'CY' | 'CZ' | 'DE' | 'DJ' | 'DK' | 'DM' | 'DO' | 'DZ' | 'EC' | 'EE' | 'EG' | 'EH' | 'ER' | 'ES' | 'ET' | 'FI' | 'FJ' | 'FK' | 'FM' | 'FO' | 'FR' | 'GA' | 'GB' | 'GD' | 'GE' | 'GF' | 'GG' | 'GH' | 'GI' | 'GL' | 'GM' | 'GN' | 'GP' | 'GQ' | 'GR' | 'GS' | 'GT' | 'GU' | 'GW' | 'GY' | 'HK' | 'HM' | 'HN' | 'HR' | 'HT' | 'HU' | 'ID' | 'IE' | 'IL' | 'IM' | 'IN' | 'IO' | 'IQ' | 'IR' | 'IS' | 'IT' | 'JE' | 'JM' | 'JO' | 'JP' | 'KE' | 'KG' | 'KH' | 'KI' | 'KM' | 'KN' | 'KP' | 'KR' | 'KW' | 'KY' | 'KZ' | 'LA' | 'LB' | 'LC' | 'LI' | 'LK' | 'LR' | 'LS' | 'LT' | 'LU' | 'LV' | 'LY' | 'MA' | 'MC' | 'MD' | 'ME' | 'MF' | 'MG' | 'MH' | 'MK' | 'ML' | 'MM' | 'MN' | 'MO' | 'MP' | 'MQ' | 'MR' | 'MS' | 'MT' | 'MU' | 'MV' | 'MW' | 'MX' | 'MY' | 'MZ' | 'NA' | 'NC' | 'NE' | 'NF' | 'NG' | 'NI' | 'NL' | 'NO' | 'NP' | 'NR' | 'NU' | 'NZ' | 'OM' | 'PA' | 'PE' | 'PF' | 'PG' | 'PH' | 'PK' | 'PL' | 'PM' | 'PN' | 'PR' | 'PS' | 'PT' | 'PW' | 'PY' | 'QA' | 'RE' | 'RO' | 'RS' | 'RU' | 'RW' | 'SA' | 'SB' | 'SC' | 'SD' | 'SE' | 'SG' | 'SH' | 'SI' | 'SJ' | 'SK' | 'SL' | 'SM' | 'SN' | 'SO' | 'SR' | 'SS' | 'ST' | 'SV' | 'SX' | 'SY' | 'SZ' | 'TC' | 'TD' | 'TF' | 'TG' | 'TH' | 'TJ' | 'TK' | 'TL' | 'TM' | 'TN' | 'TO' | 'TR' | 'TT' | 'TV' | 'TW' | 'TZ' | 'UA' | 'UG' | 'UM' | 'US' | 'UY' | 'UZ' | 'VA' | 'VC' | 'VE' | 'VG' | 'VI' | 'VN' | 'VU' | 'WF' | 'WS' | 'YE' | 'YT' | 'ZA' | 'ZM' | 'ZW' /** The 2-letter continent codes Cloudflare uses */ declare type ContinentCode = 'AF' | 'AN' | 'AS' | 'EU' | 'NA' | 'OC' | 'SA' type CfProperties = | IncomingRequestCfProperties | RequestInitCfProperties interface D1Meta { duration: number size_after: number rows_read: number rows_written: number last_row_id: number changed_db: boolean changes: number /** * The region of the database instance that executed the query. */ served_by_region?: string /** * True if-and-only-if the database instance that executed the query was the primary. */ served_by_primary?: boolean timings?: { /** * The duration of the SQL query execution by the database instance. It doesn't include any network time. */ sql_duration_ms: number } /** * Number of total attempts to execute the query, due to automatic retries. * Note: All other fields in the response like `timings` only apply to the last attempt. */ total_attempts?: number } interface D1Response { success: true meta: D1Meta & Record error?: never } type D1Result = D1Response & { results: T[] } interface D1ExecResult { count: number duration: number } type D1SessionConstraint = // Indicates that the first query should go to the primary, and the rest queries // using the same D1DatabaseSession will go to any replica that is consistent with // the bookmark maintained by the session (returned by the first query). | 'first-primary' // Indicates that the first query can go anywhere (primary or replica), and the rest queries // using the same D1DatabaseSession will go to any replica that is consistent with // the bookmark maintained by the session (returned by the first query). | 'first-unconstrained' type D1SessionBookmark = string declare abstract class D1Database { prepare(query: string): D1PreparedStatement batch(statements: D1PreparedStatement[]): Promise[]> exec(query: string): Promise /** * Creates a new D1 Session anchored at the given constraint or the bookmark. * All queries executed using the created session will have sequential consistency, * meaning that all writes done through the session will be visible in subsequent reads. * * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session. */ withSession( constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint, ): D1DatabaseSession /** * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases. */ dump(): Promise } declare abstract class D1DatabaseSession { prepare(query: string): D1PreparedStatement batch(statements: D1PreparedStatement[]): Promise[]> /** * @returns The latest session bookmark across all executed queries on the session. * If no query has been executed yet, `null` is returned. */ getBookmark(): D1SessionBookmark | null } declare abstract class D1PreparedStatement { bind(...values: unknown[]): D1PreparedStatement first(colName: string): Promise first>(): Promise run>(): Promise> all>(): Promise> raw(options: { columnNames: true }): Promise<[string[], ...T[]]> raw(options?: { columnNames?: false }): Promise } // `Disposable` was added to TypeScript's standard lib types in version 5.2. // To support older TypeScript versions, define an empty `Disposable` interface. // Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, // but this will ensure type checking on older versions still passes. // TypeScript's interface merging will ensure our empty interface is effectively // ignored when `Disposable` is included in the standard lib. type Disposable = {} /** * An email message that can be sent from a Worker. */ interface EmailMessage { /** * Envelope From attribute of the email message. */ readonly from: string /** * Envelope To attribute of the email message. */ readonly to: string } /** * An email message that is sent to a consumer Worker and can be rejected/forwarded. */ interface ForwardableEmailMessage extends EmailMessage { /** * Stream of the email message content. */ readonly raw: ReadableStream /** * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). */ readonly headers: Headers /** * Size of the email message content. */ readonly rawSize: number /** * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. * @param reason The reject reason. * @returns void */ setReject(reason: string): void /** * Forward this email message to a verified destination address of the account. * @param rcptTo Verified destination address. * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). * @returns A promise that resolves when the email message is forwarded. */ forward(rcptTo: string, headers?: Headers): Promise /** * Reply to the sender of this email message with a new EmailMessage object. * @param message The reply message. * @returns A promise that resolves when the email message is replied. */ reply(message: EmailMessage): Promise } /** * A binding that allows a Worker to send email messages. */ interface SendEmail { send(message: EmailMessage): Promise } declare abstract class EmailEvent extends ExtendableEvent { readonly message: ForwardableEmailMessage } declare type EmailExportedHandler = ( message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext, ) => void | Promise declare module 'cloudflare:email' { let _EmailMessage: { prototype: EmailMessage new (from: string, to: string, raw: ReadableStream | string): EmailMessage } export { _EmailMessage as EmailMessage } } /** * Hello World binding to serve as an explanatory example. DO NOT USE */ interface HelloWorldBinding { /** * Retrieve the current stored value */ get(): Promise<{ value: string ms?: number }> /** * Set a new stored value */ set(value: string): Promise } interface Hyperdrive { /** * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. * * Calling this method returns an idential socket to if you call * `connect("host:port")` using the `host` and `port` fields from this object. * Pick whichever approach works better with your preferred DB client library. * * Note that this socket is not yet authenticated -- it's expected that your * code (or preferably, the client library of your choice) will authenticate * using the information in this class's readonly fields. */ connect(): Socket /** * A valid DB connection string that can be passed straight into the typical * client library/driver/ORM. This will typically be the easiest way to use * Hyperdrive. */ readonly connectionString: string /* * A randomly generated hostname that is only valid within the context of the * currently running Worker which, when passed into `connect()` function from * the "cloudflare:sockets" module, will connect to the Hyperdrive instance * for your database. */ readonly host: string /* * The port that must be paired the the host field when connecting. */ readonly port: number /* * The username to use when authenticating to your database via Hyperdrive. * Unlike the host and password, this will be the same every time */ readonly user: string /* * The randomly generated password to use when authenticating to your * database via Hyperdrive. Like the host field, this password is only valid * within the context of the currently running Worker instance from which * it's read. */ readonly password: string /* * The name of the database to connect to. */ readonly database: string } // Copyright (c) 2024 Cloudflare, Inc. // Licensed under the Apache 2.0 license found in the LICENSE file or at: // https://opensource.org/licenses/Apache-2.0 type ImageInfoResponse = | { format: 'image/svg+xml' } | { format: string fileSize: number width: number height: number } type ImageTransform = { width?: number height?: number background?: string blur?: number border?: | { color?: string width?: number } | { top?: number bottom?: number left?: number right?: number } brightness?: number contrast?: number fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop' flip?: 'h' | 'v' | 'hv' gamma?: number segment?: 'foreground' gravity?: | 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | { x?: number y?: number mode: 'remainder' | 'box-center' } rotate?: 0 | 90 | 180 | 270 saturation?: number sharpen?: number trim?: | 'border' | { top?: number bottom?: number left?: number right?: number width?: number height?: number border?: | boolean | { color?: string tolerance?: number keep?: number } } } type ImageDrawOptions = { opacity?: number repeat?: boolean | string top?: number left?: number bottom?: number right?: number } type ImageInputOptions = { encoding?: 'base64' } type ImageOutputOptions = { format: | 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba' quality?: number background?: string anim?: boolean } interface ImagesBinding { /** * Get image metadata (type, width and height) * @throws {@link ImagesError} with code 9412 if input is not an image * @param stream The image bytes */ info( stream: ReadableStream, options?: ImageInputOptions, ): Promise /** * Begin applying a series of transformations to an image * @param stream The image bytes * @returns A transform handle */ input( stream: ReadableStream, options?: ImageInputOptions, ): ImageTransformer } interface ImageTransformer { /** * Apply transform next, returning a transform handle. * You can then apply more transformations, draw, or retrieve the output. * @param transform */ transform(transform: ImageTransform): ImageTransformer /** * Draw an image on this transformer, returning a transform handle. * You can then apply more transformations, draw, or retrieve the output. * @param image The image (or transformer that will give the image) to draw * @param options The options configuring how to draw the image */ draw( image: ReadableStream | ImageTransformer, options?: ImageDrawOptions, ): ImageTransformer /** * Retrieve the image that results from applying the transforms to the * provided input * @param options Options that apply to the output e.g. output format */ output(options: ImageOutputOptions): Promise } type ImageTransformationOutputOptions = { encoding?: 'base64' } interface ImageTransformationResult { /** * The image as a response, ready to store in cache or return to users */ response(): Response /** * The content type of the returned image */ contentType(): string /** * The bytes of the response */ image(options?: ImageTransformationOutputOptions): ReadableStream } interface ImagesError extends Error { readonly code: number readonly message: string readonly stack?: string } /** * Media binding for transforming media streams. * Provides the entry point for media transformation operations. */ interface MediaBinding { /** * Creates a media transformer from an input stream. * @param media - The input media bytes * @returns A MediaTransformer instance for applying transformations */ input(media: ReadableStream): MediaTransformer } /** * Media transformer for applying transformation operations to media content. * Handles sizing, fitting, and other input transformation parameters. */ interface MediaTransformer { /** * Applies transformation options to the media content. * @param transform - Configuration for how the media should be transformed * @returns A generator for producing the transformed media output */ transform( transform: MediaTransformationInputOptions, ): MediaTransformationGenerator } /** * Generator for producing media transformation results. * Configures the output format and parameters for the transformed media. */ interface MediaTransformationGenerator { /** * Generates the final media output with specified options. * @param output - Configuration for the output format and parameters * @returns The final transformation result containing the transformed media */ output(output: MediaTransformationOutputOptions): MediaTransformationResult } /** * Result of a media transformation operation. * Provides multiple ways to access the transformed media content. */ interface MediaTransformationResult { /** * Returns the transformed media as a readable stream of bytes. * @returns A stream containing the transformed media data */ media(): ReadableStream /** * Returns the transformed media as an HTTP response object. * @returns The transformed media as a Response, ready to store in cache or return to users */ response(): Response /** * Returns the MIME type of the transformed media. * @returns The content type string (e.g., 'image/jpeg', 'video/mp4') */ contentType(): string } /** * Configuration options for transforming media input. * Controls how the media should be resized and fitted. */ type MediaTransformationInputOptions = { /** How the media should be resized to fit the specified dimensions */ fit?: 'contain' | 'cover' | 'scale-down' /** Target width in pixels */ width?: number /** Target height in pixels */ height?: number } /** * Configuration options for Media Transformations output. * Controls the format, timing, and type of the generated output. */ type MediaTransformationOutputOptions = { /** * Output mode determining the type of media to generate */ mode?: 'video' | 'spritesheet' | 'frame' | 'audio' /** Whether to include audio in the output */ audio?: boolean /** * Starting timestamp for frame extraction or start time for clips. (e.g. '2s'). */ time?: string /** * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s'). */ duration?: string /** * Number of frames in the spritesheet. */ imageCount?: number /** * Output format for the generated media. */ format?: 'jpg' | 'png' | 'm4a' } /** * Error object for media transformation operations. * Extends the standard Error interface with additional media-specific information. */ interface MediaError extends Error { readonly code: number readonly message: string readonly stack?: string } declare module 'cloudflare:node' { interface NodeStyleServer { listen(...args: unknown[]): this address(): { port?: number | null | undefined } } export function httpServerHandler(port: number): ExportedHandler export function httpServerHandler(options: { port: number }): ExportedHandler export function httpServerHandler(server: NodeStyleServer): ExportedHandler } type Params

= Record type EventContext = { request: Request> functionPath: string waitUntil: (promise: Promise) => void passThroughOnException: () => void next: (input?: Request | string, init?: RequestInit) => Promise env: Env & { ASSETS: { fetch: typeof fetch } } params: Params

data: Data } type PagesFunction< Env = unknown, Params extends string = any, Data extends Record = Record, > = (context: EventContext) => Response | Promise type EventPluginContext = { request: Request> functionPath: string waitUntil: (promise: Promise) => void passThroughOnException: () => void next: (input?: Request | string, init?: RequestInit) => Promise env: Env & { ASSETS: { fetch: typeof fetch } } params: Params

data: Data pluginArgs: PluginArgs } type PagesPluginFunction< Env = unknown, Params extends string = any, Data extends Record = Record, PluginArgs = unknown, > = ( context: EventPluginContext, ) => Response | Promise declare module 'assets:*' { export const onRequest: PagesFunction } // Copyright (c) 2022-2023 Cloudflare, Inc. // Licensed under the Apache 2.0 license found in the LICENSE file or at: // https://opensource.org/licenses/Apache-2.0 declare module 'cloudflare:pipelines' { export abstract class PipelineTransformationEntrypoint< Env = unknown, I extends PipelineRecord = PipelineRecord, O extends PipelineRecord = PipelineRecord, > { protected env: Env protected ctx: ExecutionContext constructor(ctx: ExecutionContext, env: Env) /** * run recieves an array of PipelineRecord which can be * transformed and returned to the pipeline * @param records Incoming records from the pipeline to be transformed * @param metadata Information about the specific pipeline calling the transformation entrypoint * @returns A promise containing the transformed PipelineRecord array */ public run(records: I[], metadata: PipelineBatchMetadata): Promise } export type PipelineRecord = Record export type PipelineBatchMetadata = { pipelineId: string pipelineName: string } export interface Pipeline { /** * The Pipeline interface represents the type of a binding to a Pipeline * * @param records The records to send to the pipeline */ send(records: T[]): Promise } } // PubSubMessage represents an incoming PubSub message. // The message includes metadata about the broker, the client, and the payload // itself. // https://developers.cloudflare.com/pub-sub/ interface PubSubMessage { // Message ID readonly mid: number // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT readonly broker: string // The MQTT topic the message was sent on. readonly topic: string // The client ID of the client that published this message. readonly clientId: string // The unique identifier (JWT ID) used by the client to authenticate, if token // auth was used. readonly jti?: string // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker // received the message from the client. readonly receivedAt: number // An (optional) string with the MIME type of the payload, if set by the // client. readonly contentType: string // Set to 1 when the payload is a UTF-8 string // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 readonly payloadFormatIndicator: number // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. // You can use payloadFormatIndicator to inspect this before decoding. payload: string | Uint8Array } // JsonWebKey extended by kid parameter interface JsonWebKeyWithKid extends JsonWebKey { // Key Identifier of the JWK readonly kid: string } interface RateLimitOptions { key: string } interface RateLimitOutcome { success: boolean } interface RateLimit { /** * Rate limit a request based on the provided options. * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/ * @returns A promise that resolves with the outcome of the rate limit. */ limit(options: RateLimitOptions): Promise } // Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need // to referenced by `Fetcher`. This is included in the "importable" version of the types which // strips all `module` blocks. declare namespace Rpc { // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND' export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND' export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND' export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND' export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND' export interface RpcTargetBranded { [__RPC_TARGET_BRAND]: never } export interface WorkerEntrypointBranded { [__WORKER_ENTRYPOINT_BRAND]: never } export interface DurableObjectBranded { [__DURABLE_OBJECT_BRAND]: never } export interface WorkflowEntrypointBranded { [__WORKFLOW_ENTRYPOINT_BRAND]: never } export type EntrypointBranded = | WorkerEntrypointBranded | DurableObjectBranded | WorkflowEntrypointBranded // Types that can be used through `Stub`s export type Stubable = RpcTargetBranded | ((...args: any[]) => any) // Types that can be passed over RPC // The reason for using a generic type here is to build a serializable subset of structured // cloneable composite types. This allows types defined with the "interface" keyword to pass the // serializable check as well. Otherwise, only types defined with the "type" keyword would pass. type Serializable = // Structured cloneables | BaseType // Structured cloneable composites | Map< T extends Map ? Serializable : never, T extends Map ? Serializable : never > | Set ? Serializable : never> | ReadonlyArray ? Serializable : never> | { [K in keyof T]: K extends number | string ? Serializable : never } // Special types | Stub // Serialized as stubs, see `Stubify` | Stubable // Base type for all RPC stubs, including common memory management methods. // `T` is used as a marker type for unwrapping `Stub`s later. interface StubBase extends Disposable { [__RPC_STUB_BRAND]: T dup(): this } export type Stub = Provider & StubBase // This represents all the types that can be sent as-is over an RPC boundary type BaseType = | void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | ReadableStream | WritableStream | Request | Response | Headers // Recursively rewrite all `Stubable` types with `Stub`s // prettier-ignore type Stubify = T extends Stubable ? Stub : T extends Map ? Map, Stubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { [key: string | number]: any } ? { [K in keyof T]: Stubify } : T // Recursively rewrite all `Stub`s with the corresponding `T`s. // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. // prettier-ignore type Unstubify = T extends StubBase ? V : T extends Map ? Map, Unstubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { [key: string | number]: unknown } ? { [K in keyof T]: Unstubify } : T type UnstubifyAll = { [I in keyof A]: Unstubify } // Utility type for adding `Provider`/`Disposable`s to `object` types only. // Note `unknown & T` is equivalent to `T`. type MaybeProvider = T extends object ? Provider : unknown type MaybeDisposable = T extends object ? Disposable : unknown // Type for method return or property on an RPC interface. // - Stubable types are replaced by stubs. // - Serializable types are passed by value, with stubable types replaced by stubs // and a top-level `Disposer`. // Everything else can't be passed over PRC. // Technically, we use custom thenables here, but they quack like `Promise`s. // Intersecting with `(Maybe)Provider` allows pipelining. // prettier-ignore type Result = R extends Stubable ? Promise> & Provider : R extends Serializable ? Promise & MaybeDisposable> & MaybeProvider : never // Type for method or property on an RPC interface. // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. // Unwrapping `Stub`s allows calling with `Stubable` arguments. // For properties, rewrite types to be `Result`s. // In each case, unwrap `Promise`s. type MethodOrProperty = V extends (...args: infer P) => infer R ? (...args: UnstubifyAll

) => Result> : Result> // Type for the callable part of an `Provider` if `T` is callable. // This is intersected with methods/properties. type MaybeCallableProvider = T extends (...args: any[]) => any ? MethodOrProperty : unknown // Base type for all other types providing RPC-like interfaces. // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. export type Provider< T extends object, Reserved extends string = never, > = MaybeCallableProvider & Pick< { [K in keyof T]: MethodOrProperty }, Exclude> > } declare namespace Cloudflare { // Type of `env`. // // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript // will merge all declarations. // // You can use `wrangler types` to generate the `Env` type automatically. type Env = {} // Project-specific parameters used to inform types. // // This interface is, again, intended to be declared in project-specific files, and then that // declaration will be merged with this one. // // A project should have a declaration like this: // // interface GlobalProps { // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type // // of `ctx.exports`. // mainModule: typeof import("my-main-module"); // // // Declares which of the main module's exports are configured with durable storage, and // // thus should behave as Durable Object namsepace bindings. // durableNamespaces: "MyDurableObject" | "AnotherDurableObject"; // } // // You can use `wrangler types` to generate `GlobalProps` automatically. type GlobalProps = {} // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not // present. type GlobalProp = K extends keyof GlobalProps ? GlobalProps[K] : Default // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the // `mainModule` property. type MainModule = GlobalProp<'mainModule', {}> // The type of ctx.exports, which contains loopback bindings for all top-level exports. type Exports = { [K in keyof MainModule]: LoopbackForExport & // If the export is listed in `durableNamespaces`, then it is also a // DurableObjectNamespace. (K extends GlobalProp<'durableNamespaces', never> ? MainModule[K] extends new ( ...args: any[] ) => infer DoInstance ? DoInstance extends Rpc.DurableObjectBranded ? DurableObjectNamespace : DurableObjectNamespace : DurableObjectNamespace : {}) } } declare namespace CloudflareWorkersModule { export type RpcStub = Rpc.Stub export const RpcStub: { new (value: T): Rpc.Stub } export abstract class RpcTarget implements Rpc.RpcTargetBranded { [Rpc.__RPC_TARGET_BRAND]: never } // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC export abstract class WorkerEntrypoint implements Rpc.WorkerEntrypointBranded { [Rpc.__WORKER_ENTRYPOINT_BRAND]: never protected ctx: ExecutionContext protected env: Env constructor(ctx: ExecutionContext, env: Env) email?(message: ForwardableEmailMessage): void | Promise fetch?(request: Request): Response | Promise queue?(batch: MessageBatch): void | Promise scheduled?(controller: ScheduledController): void | Promise tail?(events: TraceItem[]): void | Promise tailStream?( event: TailStream.TailEvent, ): | TailStream.TailEventHandlerType | Promise test?(controller: TestController): void | Promise trace?(traces: TraceItem[]): void | Promise } export abstract class DurableObject implements Rpc.DurableObjectBranded { [Rpc.__DURABLE_OBJECT_BRAND]: never protected ctx: DurableObjectState protected env: Env constructor(ctx: DurableObjectState, env: Env) alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise fetch?(request: Request): Response | Promise webSocketMessage?( ws: WebSocket, message: string | ArrayBuffer, ): void | Promise webSocketClose?( ws: WebSocket, code: number, reason: string, wasClean: boolean, ): void | Promise webSocketError?(ws: WebSocket, error: unknown): void | Promise } export type WorkflowDurationLabel = | 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year' export type WorkflowSleepDuration = | `${number} ${WorkflowDurationLabel}${'s' | ''}` | number export type WorkflowDelayDuration = WorkflowSleepDuration export type WorkflowTimeoutDuration = WorkflowSleepDuration export type WorkflowRetentionDuration = WorkflowSleepDuration export type WorkflowBackoff = 'constant' | 'linear' | 'exponential' export type WorkflowStepConfig = { retries?: { limit: number delay: WorkflowDelayDuration | number backoff?: WorkflowBackoff } timeout?: WorkflowTimeoutDuration | number } export type WorkflowEvent = { payload: Readonly timestamp: Date instanceId: string } export type WorkflowStepEvent = { payload: Readonly timestamp: Date type: string } export abstract class WorkflowStep { do>( name: string, callback: () => Promise, ): Promise do>( name: string, config: WorkflowStepConfig, callback: () => Promise, ): Promise sleep: (name: string, duration: WorkflowSleepDuration) => Promise sleepUntil: (name: string, timestamp: Date | number) => Promise waitForEvent>( name: string, options: { type: string timeout?: WorkflowTimeoutDuration | number }, ): Promise> } export abstract class WorkflowEntrypoint< Env = unknown, T extends Rpc.Serializable | unknown = unknown, > implements Rpc.WorkflowEntrypointBranded { [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never protected ctx: ExecutionContext protected env: Env constructor(ctx: ExecutionContext, env: Env) run(event: Readonly>, step: WorkflowStep): Promise } export function waitUntil(promise: Promise): void export function withEnv(newEnv: unknown, fn: () => unknown): unknown export function withExports(newExports: unknown, fn: () => unknown): unknown export function withEnvAndExports( newEnv: unknown, newExports: unknown, fn: () => unknown, ): unknown export const env: Cloudflare.Env export const exports: Cloudflare.Exports } declare module 'cloudflare:workers' { export = CloudflareWorkersModule } interface SecretsStoreSecret { /** * Get a secret from the Secrets Store, returning a string of the secret value * if it exists, or throws an error if it does not exist */ get(): Promise } declare module 'cloudflare:sockets' { function _connect( address: string | SocketAddress, options?: SocketOptions, ): Socket export { _connect as connect } } type MarkdownDocument = { name: string blob: Blob } type ConversionResponse = | { name: string mimeType: string format: 'markdown' tokens: number data: string } | { name: string mimeType: string format: 'error' error: string } type ImageConversionOptions = { descriptionLanguage?: 'en' | 'es' | 'fr' | 'it' | 'pt' | 'de' } type EmbeddedImageConversionOptions = ImageConversionOptions & { convert?: boolean maxConvertedImages?: number } type ConversionOptions = { html?: { images?: EmbeddedImageConversionOptions & { convertOGImage?: boolean } } docx?: { images?: EmbeddedImageConversionOptions } image?: ImageConversionOptions pdf?: { images?: EmbeddedImageConversionOptions metadata?: boolean } } type ConversionRequestOptions = { gateway?: GatewayOptions extraHeaders?: object conversionOptions?: ConversionOptions } type SupportedFileFormat = { mimeType: string extension: string } declare abstract class ToMarkdownService { transform( files: MarkdownDocument[], options?: ConversionRequestOptions, ): Promise transform( files: MarkdownDocument, options?: ConversionRequestOptions, ): Promise supported(): Promise } declare namespace TailStream { interface Header { readonly name: string readonly value: string } interface FetchEventInfo { readonly type: 'fetch' readonly method: string readonly url: string readonly cfJson?: object readonly headers: Header[] } interface JsRpcEventInfo { readonly type: 'jsrpc' } interface ScheduledEventInfo { readonly type: 'scheduled' readonly scheduledTime: Date readonly cron: string } interface AlarmEventInfo { readonly type: 'alarm' readonly scheduledTime: Date } interface QueueEventInfo { readonly type: 'queue' readonly queueName: string readonly batchSize: number } interface EmailEventInfo { readonly type: 'email' readonly mailFrom: string readonly rcptTo: string readonly rawSize: number } interface TraceEventInfo { readonly type: 'trace' readonly traces: (string | null)[] } interface HibernatableWebSocketEventInfoMessage { readonly type: 'message' } interface HibernatableWebSocketEventInfoError { readonly type: 'error' } interface HibernatableWebSocketEventInfoClose { readonly type: 'close' readonly code: number readonly wasClean: boolean } interface HibernatableWebSocketEventInfo { readonly type: 'hibernatableWebSocket' readonly info: | HibernatableWebSocketEventInfoClose | HibernatableWebSocketEventInfoError | HibernatableWebSocketEventInfoMessage } interface CustomEventInfo { readonly type: 'custom' } interface FetchResponseInfo { readonly type: 'fetch' readonly statusCode: number } type EventOutcome = | 'ok' | 'canceled' | 'exception' | 'unknown' | 'killSwitch' | 'daemonDown' | 'exceededCpu' | 'exceededMemory' | 'loadShed' | 'responseStreamDisconnected' | 'scriptNotFound' interface ScriptVersion { readonly id: string readonly tag?: string readonly message?: string } interface Onset { readonly type: 'onset' readonly attributes: Attribute[] // id for the span being opened by this Onset event. readonly spanId: string readonly dispatchNamespace?: string readonly entrypoint?: string readonly executionModel: string readonly scriptName?: string readonly scriptTags?: string[] readonly scriptVersion?: ScriptVersion readonly info: | FetchEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | CustomEventInfo } interface Outcome { readonly type: 'outcome' readonly outcome: EventOutcome readonly cpuTime: number readonly wallTime: number } interface SpanOpen { readonly type: 'spanOpen' readonly name: string // id for the span being opened by this SpanOpen event. readonly spanId: string readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes } interface SpanClose { readonly type: 'spanClose' readonly outcome: EventOutcome } interface DiagnosticChannelEvent { readonly type: 'diagnosticChannel' readonly channel: string readonly message: any } interface Exception { readonly type: 'exception' readonly name: string readonly message: string readonly stack?: string } interface Log { readonly type: 'log' readonly level: 'debug' | 'error' | 'info' | 'log' | 'warn' readonly message: object } // This marks the worker handler return information. // This is separate from Outcome because the worker invocation can live for a long time after // returning. For example - Websockets that return an http upgrade response but then continue // streaming information or SSE http connections. interface Return { readonly type: 'return' readonly info?: FetchResponseInfo } interface Attribute { readonly name: string readonly value: | string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[] } interface Attributes { readonly type: 'attributes' readonly info: Attribute[] } type EventType = | Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | Return | Attributes // Context in which this trace event lives. interface SpanContext { // Single id for the entire top-level invocation // This should be a new traceId for the first worker stage invoked in the eyeball request and then // same-account service-bindings should reuse the same traceId but cross-account service-bindings // should use a new traceId. readonly traceId: string // spanId in which this event is handled // for Onset and SpanOpen events this would be the parent span id // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events // For Hibernate and Mark this would be the span under which they were emitted. // spanId is not set ONLY if: // 1. This is an Onset event // 2. We are not inherting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) readonly spanId?: string } interface TailEvent { // invocation id of the currently invoked worker stage. // invocation id will always be unique to every Onset event and will be the same until the Outcome event. readonly invocationId: string // Inherited spanContext for this event. readonly spanContext: SpanContext readonly timestamp: Date readonly sequence: number readonly event: Event } type TailEventHandler = ( event: TailEvent, ) => void | Promise type TailEventHandlerObject = { outcome?: TailEventHandler spanOpen?: TailEventHandler spanClose?: TailEventHandler diagnosticChannel?: TailEventHandler exception?: TailEventHandler log?: TailEventHandler return?: TailEventHandler attributes?: TailEventHandler } type TailEventHandlerType = TailEventHandler | TailEventHandlerObject } // Copyright (c) 2022-2023 Cloudflare, Inc. // Licensed under the Apache 2.0 license found in the LICENSE file or at: // https://opensource.org/licenses/Apache-2.0 /** * Data types supported for holding vector metadata. */ type VectorizeVectorMetadataValue = string | number | boolean | string[] /** * Additional information to associate with a vector. */ type VectorizeVectorMetadata = | VectorizeVectorMetadataValue | Record type VectorFloatArray = Float32Array | Float64Array interface VectorizeError { code?: number error: string } /** * Comparison logic/operation to use for metadata filtering. * * This list is expected to grow as support for more operations are released. */ type VectorizeVectorMetadataFilterOp = | '$eq' | '$ne' | '$lt' | '$lte' | '$gt' | '$gte' type VectorizeVectorMetadataFilterCollectionOp = '$in' | '$nin' /** * Filter criteria for vector metadata used to limit the retrieved query result set. */ type VectorizeVectorMetadataFilter = { [field: string]: | Exclude | null | { [Op in VectorizeVectorMetadataFilterOp]?: Exclude< VectorizeVectorMetadataValue, string[] > | null } | { [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude< VectorizeVectorMetadataValue, string[] >[] } } /** * Supported distance metrics for an index. * Distance metrics determine how other "similar" vectors are determined. */ type VectorizeDistanceMetric = 'euclidean' | 'cosine' | 'dot-product' /** * Metadata return levels for a Vectorize query. * * Default to "none". * * @property all Full metadata for the vector return set, including all fields (including those un-indexed) without truncation. This is a more expensive retrieval, as it requires additional fetching & reading of un-indexed data. * @property indexed Return all metadata fields configured for indexing in the vector return set. This level of retrieval is "free" in that no additional overhead is incurred returning this data. However, note that indexed metadata is subject to truncation (especially for larger strings). * @property none No indexed metadata will be returned. */ type VectorizeMetadataRetrievalLevel = 'all' | 'indexed' | 'none' interface VectorizeQueryOptions { topK?: number namespace?: string returnValues?: boolean returnMetadata?: boolean | VectorizeMetadataRetrievalLevel filter?: VectorizeVectorMetadataFilter } /** * Information about the configuration of an index. */ type VectorizeIndexConfig = | { dimensions: number metric: VectorizeDistanceMetric } | { preset: string // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity } /** * Metadata about an existing index. * * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. * See {@link VectorizeIndexInfo} for its post-beta equivalent. */ interface VectorizeIndexDetails { /** The unique ID of the index */ readonly id: string /** The name of the index. */ name: string /** (optional) A human readable description for the index. */ description?: string /** The index configuration, including the dimension size and distance metric. */ config: VectorizeIndexConfig /** The number of records containing vectors within the index. */ vectorsCount: number } /** * Metadata about an existing index. */ interface VectorizeIndexInfo { /** The number of records containing vectors within the index. */ vectorCount: number /** Number of dimensions the index has been configured for. */ dimensions: number /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */ processedUpToDatetime: number /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */ processedUpToMutation: number } /** * Represents a single vector value set along with its associated metadata. */ interface VectorizeVector { /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ id: string /** The vector values */ values: VectorFloatArray | number[] /** The namespace this vector belongs to. */ namespace?: string /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */ metadata?: Record } /** * Represents a matched vector for a query along with its score and (if specified) the matching vector information. */ type VectorizeMatch = Pick, 'values'> & Omit & { /** The score or rank for similarity, when returned as a result */ score: number } /** * A set of matching {@link VectorizeMatch} for a particular query. */ interface VectorizeMatches { matches: VectorizeMatch[] count: number } /** * Results of an operation that performed a mutation on a set of vectors. * Here, `ids` is a list of vectors that were successfully processed. * * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. * See {@link VectorizeAsyncMutation} for its post-beta equivalent. */ interface VectorizeVectorMutation { /* List of ids of vectors that were successfully processed. */ ids: string[] /* Total count of the number of processed vectors. */ count: number } /** * Result type indicating a mutation on the Vectorize Index. * Actual mutations are processed async where the `mutationId` is the unique identifier for the operation. */ interface VectorizeAsyncMutation { /** The unique identifier for the async mutation operation containing the changeset. */ mutationId: string } /** * A Vectorize Vector Search Index for querying vectors/embeddings. * * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. * See {@link Vectorize} for its new implementation. */ declare abstract class VectorizeIndex { /** * Get information about the currently bound index. * @returns A promise that resolves with information about the current index. */ public describe(): Promise /** * Use the provided vector to perform a similarity search across the index. * @param vector Input vector that will be used to drive the similarity search. * @param options Configuration options to massage the returned data. * @returns A promise that resolves with matched and scored vectors. */ public query( vector: VectorFloatArray | number[], options?: VectorizeQueryOptions, ): Promise /** * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. * @param vectors List of vectors that will be inserted. * @returns A promise that resolves with the ids & count of records that were successfully processed. */ public insert(vectors: VectorizeVector[]): Promise /** * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. * @param vectors List of vectors that will be upserted. * @returns A promise that resolves with the ids & count of records that were successfully processed. */ public upsert(vectors: VectorizeVector[]): Promise /** * Delete a list of vectors with a matching id. * @param ids List of vector ids that should be deleted. * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). */ public deleteByIds(ids: string[]): Promise /** * Get a list of vectors with a matching id. * @param ids List of vector ids that should be returned. * @returns A promise that resolves with the raw unscored vectors matching the id set. */ public getByIds(ids: string[]): Promise } /** * A Vectorize Vector Search Index for querying vectors/embeddings. * * Mutations in this version are async, returning a mutation id. */ declare abstract class Vectorize { /** * Get information about the currently bound index. * @returns A promise that resolves with information about the current index. */ public describe(): Promise /** * Use the provided vector to perform a similarity search across the index. * @param vector Input vector that will be used to drive the similarity search. * @param options Configuration options to massage the returned data. * @returns A promise that resolves with matched and scored vectors. */ public query( vector: VectorFloatArray | number[], options?: VectorizeQueryOptions, ): Promise /** * Use the provided vector-id to perform a similarity search across the index. * @param vectorId Id for a vector in the index against which the index should be queried. * @param options Configuration options to massage the returned data. * @returns A promise that resolves with matched and scored vectors. */ public queryById( vectorId: string, options?: VectorizeQueryOptions, ): Promise /** * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. * @param vectors List of vectors that will be inserted. * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset. */ public insert(vectors: VectorizeVector[]): Promise /** * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. * @param vectors List of vectors that will be upserted. * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset. */ public upsert(vectors: VectorizeVector[]): Promise /** * Delete a list of vectors with a matching id. * @param ids List of vector ids that should be deleted. * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset. */ public deleteByIds(ids: string[]): Promise /** * Get a list of vectors with a matching id. * @param ids List of vector ids that should be returned. * @returns A promise that resolves with the raw unscored vectors matching the id set. */ public getByIds(ids: string[]): Promise } /** * The interface for "version_metadata" binding * providing metadata about the Worker Version using this binding. */ type WorkerVersionMetadata = { /** The ID of the Worker Version using this binding */ id: string /** The tag of the Worker Version using this binding */ tag: string /** The timestamp of when the Worker Version was uploaded */ timestamp: string } interface DynamicDispatchLimits { /** * Limit CPU time in milliseconds. */ cpuMs?: number /** * Limit number of subrequests. */ subRequests?: number } interface DynamicDispatchOptions { /** * Limit resources of invoked Worker script. */ limits?: DynamicDispatchLimits /** * Arguments for outbound Worker script, if configured. */ outbound?: { [key: string]: any } } interface DispatchNamespace { /** * @param name Name of the Worker script. * @param args Arguments to Worker script. * @param options Options for Dynamic Dispatch invocation. * @returns A Fetcher object that allows you to send requests to the Worker script. * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. */ get( name: string, args?: { [key: string]: any }, options?: DynamicDispatchOptions, ): Fetcher } declare module 'cloudflare:workflows' { /** * NonRetryableError allows for a user to throw a fatal error * that makes a Workflow instance fail immediately without triggering a retry */ export class NonRetryableError extends Error { public constructor(message: string, name?: string) } } declare abstract class Workflow { /** * Get a handle to an existing instance of the Workflow. * @param id Id for the instance of this Workflow * @returns A promise that resolves with a handle for the Instance */ public get(id: string): Promise /** * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown. * @param options Options when creating an instance including id and params * @returns A promise that resolves with a handle for the Instance */ public create( options?: WorkflowInstanceCreateOptions, ): Promise /** * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown. * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached. * @param batch List of Options when creating an instance including name and params * @returns A promise that resolves with a list of handles for the created instances. */ public createBatch( batch: WorkflowInstanceCreateOptions[], ): Promise } type WorkflowDurationLabel = | 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year' type WorkflowSleepDuration = | `${number} ${WorkflowDurationLabel}${'s' | ''}` | number type WorkflowRetentionDuration = WorkflowSleepDuration interface WorkflowInstanceCreateOptions { /** * An id for your Workflow instance. Must be unique within the Workflow. */ id?: string /** * The event payload the Workflow instance is triggered with */ params?: PARAMS /** * The retention policy for Workflow instance. * Defaults to the maximum retention period available for the owner's account. */ retention?: { successRetention?: WorkflowRetentionDuration errorRetention?: WorkflowRetentionDuration } } type InstanceStatus = { status: | 'queued' // means that instance is waiting to be started (see concurrency limits) | 'running' | 'paused' | 'errored' | 'terminated' // user terminated the instance while it was running | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish | 'waitingForPause' // instance is finishing the current work to pause | 'unknown' error?: { name: string message: string } output?: unknown } interface WorkflowError { code?: number message: string } declare abstract class WorkflowInstance { public id: string /** * Pause the instance. */ public pause(): Promise /** * Resume the instance. If it is already running, an error will be thrown. */ public resume(): Promise /** * Terminate the instance. If it is errored, terminated or complete, an error will be thrown. */ public terminate(): Promise /** * Restart the instance. */ public restart(): Promise /** * Returns the current status of the instance. */ public status(): Promise /** * Send an event to this instance. */ public sendEvent({ type, payload, }: { type: string payload: unknown }): Promise } ================================================ FILE: playgrounds/tanstack-start/wrangler.jsonc ================================================ { "$schema": "node_modules/wrangler/config-schema.json", "name": "tanstack-start-app", "compatibility_date": "2025-12-10", "compatibility_flags": ["nodejs_compat"], "main": "@tanstack/react-start/server-entry" } ================================================ FILE: playgrounds/vite-core/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: playgrounds/vite-core/index.html ================================================ Vite Core

================================================ FILE: playgrounds/vite-core/package.json ================================================ { "name": "vite-core", "private": true, "type": "module", "scripts": { "dev": "vite", "build": "tsc && vite build", "preview": "vite preview" }, "dependencies": { "@wagmi/connectors": "workspace:*", "@wagmi/core": "workspace:*", "react": "catalog:", "react-dom": "catalog:", "viem": "2.*" }, "devDependencies": { "@types/react": "catalog:", "@types/react-dom": "catalog:", "@vitejs/plugin-react": "catalog:", "buffer": "catalog:", "vite": "catalog:" } } ================================================ FILE: playgrounds/vite-core/src/App.tsx ================================================ import { connect, disconnect, type GetBalanceReturnType, type GetBlockNumberReturnType, getBalance, getBlockNumber, getConnection, reconnect, switchConnection, watchBlockNumber, watchConnection, } from '@wagmi/core' import { useEffect, useReducer, useState } from 'react' import { formatEther } from 'viem' import { config } from './wagmi' function App() { useEffect(() => { reconnect(config) }, []) return ( <> ) } function Connection() { const [connection, setConnection] = useState(getConnection(config)) useEffect(() => { return watchConnection(config, { onChange(data) { setConnection(data) }, }) }, []) return (

Connection

address: {connection.address}
chainId: {connection.chainId}
status: {connection.status}
{connection.status === 'connected' && ( )}
) } function Connect() { const [, rerender] = useReducer((count) => count + 1, 0) useEffect(() => { return config.subscribe(({ connections }) => connections, rerender) }, []) return (

Connect

{config.connectors.map((connector) => ( ))}
) } function SwitchConnection() { const [, rerender] = useReducer((count) => count + 1, 0) useEffect(() => { return config.subscribe( ({ connections, current }) => ({ connections, current }), rerender, ) }, []) return (

Switch Connection

{config.connectors .filter((connector) => config.state.connections.has(connector.uid)) .map((connector) => ( ))}
) } function Balance() { const [connection, setConnection] = useState(getConnection(config)) useEffect(() => { return watchConnection(config, { onChange(data) { setConnection(data) }, }) }, []) ///////////////////////////////////////////////////////// const [balance, setBalance] = useState() useEffect(() => { if (!connection.address) return return watchBlockNumber(config, { async onBlockNumber() { try { const balance = await getBalance(config, { address: connection.address!, }) setBalance(balance) } catch (error) { // biome-ignore lint/suspicious/noConsole: logging console.error('Error fetching balance', error) } }, }) }, [connection.address]) return (

Balance

Balance: {!!balance?.value && formatEther(balance.value)}
) } function BlockNumber() { const [blockNumber, setBlockNumber] = useState< GetBlockNumberReturnType | undefined >() useEffect(() => { ;(async () => { setBlockNumber(await getBlockNumber(config)) watchBlockNumber(config, { onBlockNumber: setBlockNumber }) })() }, []) return (

Block Number

Block Number (Default Chain): {blockNumber?.toString()}
) } export default App ================================================ FILE: playgrounds/vite-core/src/index.css ================================================ :root { background-color: #181818; color: rgba(255, 255, 255, 0.87); color-scheme: light dark; font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; font-synthesis: none; font-weight: 400; line-height: 1.5; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-text-size-adjust: 100%; } @media (prefers-color-scheme: light) { :root { background-color: #f8f8f8; color: #181818; } } ================================================ FILE: playgrounds/vite-core/src/main.tsx ================================================ import React from 'react' import ReactDOM from 'react-dom/client' import './index.css' import { Buffer } from 'buffer' // `@coinbase-wallet/sdk` uses `Buffer` globalThis.Buffer = Buffer import App from './App.tsx' ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render( , ) ================================================ FILE: playgrounds/vite-core/src/vite-env.d.ts ================================================ /// ================================================ FILE: playgrounds/vite-core/src/wagmi.ts ================================================ import { baseAccount, metaMask, walletConnect } from '@wagmi/connectors' import { createConfig, createStorage, http } from '@wagmi/core' import { mainnet, optimism, sepolia } from '@wagmi/core/chains' export const config = createConfig({ chains: [mainnet, sepolia, optimism], connectors: [ walletConnect({ projectId: import.meta.env.VITE_WC_PROJECT_ID }), baseAccount(), metaMask(), ], storage: createStorage({ storage: localStorage, key: 'vite-core' }), transports: { [mainnet.id]: http( 'https://eth-mainnet.g.alchemy.com/v2/StF61Ht3J9nXAojZX-b21LVt9l0qDL38', ), [sepolia.id]: http( 'https://eth-sepolia.g.alchemy.com/v2/roJyEHxkj7XWg1T9wmYnxvktDodQrFAS', ), [optimism.id]: http(), }, }) ================================================ FILE: playgrounds/vite-core/tsconfig.json ================================================ { "compilerOptions": { "target": "ESNext", "lib": ["DOM", "DOM.Iterable", "ESNext"], "module": "ESNext", "skipLibCheck": true, "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "paths": { "@wagmi/connectors": ["../../packages/connectors/src/exports"], "@wagmi/core": ["../../packages/core/src/exports"], "@wagmi/core/*": ["../../packages/core/src/exports/*"] } }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] } ================================================ FILE: playgrounds/vite-core/tsconfig.node.json ================================================ { "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true }, "include": ["vite.config.ts"] } ================================================ FILE: playgrounds/vite-core/vite.config.ts ================================================ import react from '@vitejs/plugin-react' import { defineConfig } from 'vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], }) ================================================ FILE: playgrounds/vite-react/.gitignore ================================================ src/generated.ts # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: playgrounds/vite-react/index.html ================================================ Vite React
================================================ FILE: playgrounds/vite-react/package.json ================================================ { "name": "vite-react", "private": true, "type": "module", "scripts": { "dev": "vite", "build": "tsc && vite build", "preview": "vite preview" }, "dependencies": { "@tanstack/query-sync-storage-persister": "^5.90.12", "@tanstack/react-query": "catalog:", "@tanstack/react-query-persist-client": "^5.90.12", "cuer": "^0.0.3", "idb-keyval": "^6.2.1", "react": "catalog:", "react-dom": "catalog:", "viem": "2.*", "wagmi": "workspace:*" }, "devDependencies": { "@tanstack/react-query-devtools": "^5.91.2", "@types/react": "catalog:", "@types/react-dom": "catalog:", "@vitejs/plugin-react": "catalog:", "@wagmi/cli": "workspace:*", "buffer": "catalog:", "vite": "catalog:" } } ================================================ FILE: playgrounds/vite-react/public/manifest.json ================================================ { "name": "vite-react", "description": "vite-react playground", "iconPath": "favicon.ico" } ================================================ FILE: playgrounds/vite-react/src/App.tsx ================================================ import { Cuer } from 'cuer' import { type FormEvent, useState } from 'react' import { formatEther, type Hex, parseAbi, parseEther, stringify } from 'viem' import { type BaseError, useBalance, useBlockNumber, useChainId, useChains, useConnect, useConnection, useConnectionEffect, useConnections, useConnectorClient, useConnectors, useDisconnect, useEnsName, useReadContract, useReadContracts, useSendTransaction, useSignMessage, useSwitchChain, useSwitchConnection, useWaitForTransactionReceipt, useWriteContract, } from 'wagmi' import { optimism } from 'wagmi/chains' import { wagmiContractConfig } from './contracts' function App() { useConnectionEffect({ onConnect(_data) { // console.log('onConnect', data) }, onDisconnect() { // console.log('onDisconnect') }, }) return ( <> ) } function Connection() { const connection = useConnection() const { disconnect } = useDisconnect() const { data: ensName } = useEnsName({ address: connection.address, }) return (

Connection

account: {connection.address} {ensName}
chainId: {connection.chainId}
status: {connection.status}
{connection.status !== 'disconnected' && ( )}
) } function Connect() { const chainId = useChainId() const connectors = useConnectors() const [qrUri, setQrUri] = useState() const connect = useConnect({ mutation: { onMutate(variables) { const connector = variables.connector if (connector && typeof connector !== 'function') { if (connector.id === 'walletConnect') connector.emitter.on('message', (message) => { if (message.type !== 'display_uri') return if (typeof message.data !== 'string') return setQrUri(message.data) }) if (connector.id === 'metaMaskSDK') connector.emitter.on('message', (message) => { if (message.type !== 'display_uri') return if (typeof message.data !== 'string') return setQrUri(message.data) }) } }, onSettled() { setQrUri(undefined) }, }, }) return (

Connect

{connectors.map((connector) => ( ))}
{connect.status}
{connect.error?.message}
{qrUri && (
)}
) } function SwitchConnection() { const connection = useConnection() const { switchConnection } = useSwitchConnection() const connections = useConnections() return (

Switch Connection

{connections.map(({ connector }) => ( ))}
) } function SwitchChain() { const chainId = useChainId() const { switchChain, error } = useSwitchChain() const chains = useChains() return (

Switch Chain

{chains.map((chain) => ( ))} {error?.message}
) } function SignMessage() { const signMessage = useSignMessage() return (

Sign Message

{ event.preventDefault() const formData = new FormData(event.target as HTMLFormElement) signMessage.mutate({ message: formData.get('message') as string }) }} >
{signMessage.data}
) } function Connections() { const connections = useConnections() return (

Connections

{connections.map((connection) => (
connector {connection.connector.name}
accounts: {stringify(connection.accounts)}
chainId: {connection.chainId}
))}
) } function Balance() { const { address } = useConnection() const { data: default_ } = useBalance({ address }) const { data: account_ } = useBalance({ address }) const { data: optimism_ } = useBalance({ address, chainId: optimism.id, }) return (

Balance

Balance (Default Chain):{' '} {!!default_?.value && formatEther(default_.value)}
Balance (Connection Chain):{' '} {!!account_?.value && formatEther(account_.value)}
Balance (Optimism Chain):{' '} {!!optimism_?.value && formatEther(optimism_.value)}
) } function BlockNumber() { const { data: default_ } = useBlockNumber({ watch: true }) const { data: account_ } = useBlockNumber({ watch: true, }) const { data: optimism_ } = useBlockNumber({ chainId: optimism.id, watch: true, }) return (

Block Number

Block Number (Default Chain): {default_?.toString()}
Block Number (Connection Chain): {account_?.toString()}
Block Number (Optimism): {optimism_?.toString()}
) } function ConnectorClient() { const { data, error } = useConnectorClient() return (

Connector Client

client {data?.account?.address} {data?.chain?.id} {error?.message}
) } function SendTransaction() { const { data: hash, error, isPending, sendTransaction } = useSendTransaction() async function submit(e: FormEvent) { e.preventDefault() const formData = new FormData(e.target as HTMLFormElement) const to = formData.get('address') as Hex const value = formData.get('value') as string sendTransaction({ to, value: parseEther(value) }) } const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({ hash, }) return (

Send Transaction

{hash &&
Transaction Hash: {hash}
} {isConfirming && 'Waiting for confirmation...'} {isConfirmed && 'Transaction confirmed.'} {error && (
Error: {(error as BaseError).shortMessage || error.message}
)}
) } function ReadContract() { const { data: balance } = useReadContract({ ...wagmiContractConfig, functionName: 'balanceOf', args: ['0x03A71968491d55603FFe1b11A9e23eF013f75bCF'], }) return (

Read Contract

Balance: {balance?.toString()}
) } function ReadContracts() { const { data } = useReadContracts({ allowFailure: false, contracts: [ { ...wagmiContractConfig, functionName: 'balanceOf', args: ['0x03A71968491d55603FFe1b11A9e23eF013f75bCF'], }, { ...wagmiContractConfig, functionName: 'ownerOf', args: [69n], }, { ...wagmiContractConfig, functionName: 'totalSupply', }, ], }) const [balance, ownerOf, totalSupply] = data || [] return (

Read Contract

Balance: {balance?.toString()}
Owner of Token 69: {ownerOf?.toString()}
Total Supply: {totalSupply?.toString()}
) } function WriteContract() { const { data: hash, error, isPending, writeContract } = useWriteContract() async function submit(e: FormEvent) { e.preventDefault() const formData = new FormData(e.target as HTMLFormElement) const tokenId = formData.get('tokenId') as string writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: parseAbi(['function mint(uint256 tokenId)']), functionName: 'mint', args: [BigInt(tokenId)], }) } const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({ hash, }) return (

Write Contract

{hash &&
Transaction Hash: {hash}
} {isConfirming && 'Waiting for confirmation...'} {isConfirmed && 'Transaction confirmed.'} {error && (
Error: {(error as BaseError).shortMessage || error.message}
)}
) } export default App ================================================ FILE: playgrounds/vite-react/src/contracts.ts ================================================ export const wagmiContractConfig = { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: [ { inputs: [], stateMutability: 'nonpayable', type: 'constructor' }, { anonymous: false, inputs: [ { indexed: true, name: 'owner', type: 'address', }, { indexed: true, name: 'approved', type: 'address', }, { indexed: true, name: 'tokenId', type: 'uint256', }, ], name: 'Approval', type: 'event', }, { anonymous: false, inputs: [ { indexed: true, name: 'owner', type: 'address', }, { indexed: true, name: 'operator', type: 'address', }, { indexed: false, name: 'approved', type: 'bool', }, ], name: 'ApprovalForAll', type: 'event', }, { anonymous: false, inputs: [ { indexed: true, name: 'from', type: 'address', }, { indexed: true, name: 'to', type: 'address' }, { indexed: true, name: 'tokenId', type: 'uint256', }, ], name: 'Transfer', type: 'event', }, { inputs: [ { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, ], name: 'approve', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ name: 'owner', type: 'address' }], name: 'balanceOf', outputs: [{ name: '', type: 'uint256' }], stateMutability: 'view', type: 'function', }, { inputs: [{ name: 'tokenId', type: 'uint256' }], name: 'getApproved', outputs: [{ name: '', type: 'address' }], stateMutability: 'view', type: 'function', }, { inputs: [ { name: 'owner', type: 'address' }, { name: 'operator', type: 'address' }, ], name: 'isApprovedForAll', outputs: [{ name: '', type: 'bool' }], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'mint', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ internalType: 'uint256', name: 'tokenId', type: 'uint256' }], name: 'mint', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [], name: 'name', outputs: [{ name: '', type: 'string' }], stateMutability: 'view', type: 'function', }, { inputs: [{ name: 'tokenId', type: 'uint256' }], name: 'ownerOf', outputs: [{ name: '', type: 'address' }], stateMutability: 'view', type: 'function', }, { inputs: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, ], name: 'safeTransferFrom', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, { name: '_data', type: 'bytes' }, ], name: 'safeTransferFrom', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { name: 'operator', type: 'address' }, { name: 'approved', type: 'bool' }, ], name: 'setApprovalForAll', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ name: 'interfaceId', type: 'bytes4' }], name: 'supportsInterface', outputs: [{ name: '', type: 'bool' }], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'symbol', outputs: [{ name: '', type: 'string' }], stateMutability: 'view', type: 'function', }, { inputs: [{ name: 'tokenId', type: 'uint256' }], name: 'tokenURI', outputs: [{ name: '', type: 'string' }], stateMutability: 'pure', type: 'function', }, { inputs: [], name: 'totalSupply', outputs: [{ name: '', type: 'uint256' }], stateMutability: 'view', type: 'function', }, { inputs: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, ], name: 'transferFrom', outputs: [], stateMutability: 'nonpayable', type: 'function', }, ], } as const ================================================ FILE: playgrounds/vite-react/src/index.css ================================================ :root { background-color: #181818; color: rgba(255, 255, 255, 0.87); color-scheme: light dark; font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; font-synthesis: none; font-weight: 400; line-height: 1.5; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-text-size-adjust: 100%; } @media (prefers-color-scheme: light) { :root { background-color: #f8f8f8; color: #181818; } } ================================================ FILE: playgrounds/vite-react/src/main.tsx ================================================ import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister' import { QueryClient } from '@tanstack/react-query' import { ReactQueryDevtools } from '@tanstack/react-query-devtools' import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client' import { Buffer } from 'buffer' import React from 'react' import ReactDOM from 'react-dom/client' import { deserialize, serialize, WagmiProvider } from 'wagmi' import './index.css' // `@coinbase-wallet/sdk` uses `Buffer` globalThis.Buffer = Buffer import App from './App.tsx' import { config } from './wagmi.ts' const queryClient = new QueryClient({ defaultOptions: { queries: { gcTime: 1_000 * 60 * 60 * 24, // 24 hours networkMode: 'offlineFirst', refetchOnWindowFocus: false, retry: 0, }, mutations: { networkMode: 'offlineFirst' }, }, }) const persister = createSyncStoragePersister({ key: 'vite-react.cache', serialize, storage: window.localStorage, deserialize, }) ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render( , ) ================================================ FILE: playgrounds/vite-react/src/vite-env.d.ts ================================================ /// ================================================ FILE: playgrounds/vite-react/src/wagmi.ts ================================================ import { del, get, set } from 'idb-keyval' import { createConfig, http } from 'wagmi' import { celo, mainnet, optimism, sepolia } from 'wagmi/chains' import { baseAccount, metaMask, porto, walletConnect } from 'wagmi/connectors' // biome-ignore lint/correctness/noUnusedVariables: allowed const indexedDBStorage = { async getItem(name: string) { return get(name) }, async setItem(name: string, value: string) { await set(name, value) }, async removeItem(name: string) { await del(name) }, } export const config = createConfig({ chains: [mainnet, sepolia, optimism, celo], connectors: [ walletConnect({ projectId: import.meta.env.VITE_WC_PROJECT_ID, }), porto(), baseAccount(), metaMask({ ui: { headless: true } }), ], transports: { [mainnet.id]: http(), [sepolia.id]: http(), [optimism.id]: http(), [celo.id]: http(), }, }) declare module 'wagmi' { interface Register { config: typeof config } } ================================================ FILE: playgrounds/vite-react/tsconfig.json ================================================ { "compilerOptions": { "target": "ESNext", "lib": ["DOM", "DOM.Iterable", "ESNext"], "module": "ESNext", "skipLibCheck": true, "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "paths": { "@wagmi/connectors": ["../../packages/connectors/src/exports"], "@wagmi/core": ["../../packages/core/src/exports"], "@wagmi/core/*": ["../../packages/core/src/exports/*"], "wagmi": ["../../packages/react/src/exports"], "wagmi/*": ["../../packages/react/src/exports/*"] } }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] } ================================================ FILE: playgrounds/vite-react/tsconfig.node.json ================================================ { "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true }, "include": ["vite.config.ts"] } ================================================ FILE: playgrounds/vite-react/vite.config.ts ================================================ import react from '@vitejs/plugin-react' import { defineConfig } from 'vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], }) ================================================ FILE: playgrounds/vite-react/wagmi.config.ts ================================================ import { defineConfig } from '@wagmi/cli' import { foundry, hardhat } from '@wagmi/cli/plugins' export default defineConfig({ out: 'src/generated.ts', contracts: [], plugins: [ foundry({ namePrefix: 'foundry', project: '../../packages/cli/src/plugins/__fixtures__/foundry', }), hardhat({ namePrefix: 'hardhat', project: '../../packages/cli/src/plugins/__fixtures__/hardhat', }), ], }) ================================================ FILE: playgrounds/vite-solid/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: playgrounds/vite-solid/index.html ================================================ Vite Solid
================================================ FILE: playgrounds/vite-solid/package.json ================================================ { "name": "vite-solid", "private": true, "type": "module", "scripts": { "dev": "vite", "build": "tsc && vite build", "preview": "vite preview" }, "dependencies": { "@tanstack/solid-query": "catalog:", "@wagmi/solid": "workspace:*", "solid-js": "catalog:", "viem": "2.*" }, "devDependencies": { "buffer": "catalog:", "vite": "catalog:", "vite-plugin-solid": "catalog:" } } ================================================ FILE: playgrounds/vite-solid/src/App.tsx ================================================ import { useBalance, useBlockNumber, useChainId, useChains, useConnect, useConnection, useConnections, useConnectorClient, useConnectors, useDisconnect, useSwitchChain, useSwitchConnection, } from '@wagmi/solid' import { optimism } from '@wagmi/solid/chains' import { For, Show } from 'solid-js' import { formatEther, stringify } from 'viem' export function App() { return ( <> {/* */} {/* */} {/* */} {/* */} {/* */} ) } function Connection() { const connection = useConnection() const disconnect = useDisconnect() return (

Connection

account: {connection().address}
chainId: {connection().chainId}
status: {connection().status}
) } function Connect() { const chainId = useChainId() const connect = useConnect() const connectors = useConnectors() return (

Connect

{(connector) => ( )}
{connect.status}
{connect.error?.message}
) } function SwitchConnection() { const connection = useConnection() const { mutate: switchConnection } = useSwitchConnection() const connections = useConnections() return (

Switch Connection

{(conn) => ( )}
) } function SwitchChain() { const chainId = useChainId() const switchChain = useSwitchChain() const chains = useChains() return (

Switch Chain

{(chain) => ( )} {switchChain.error?.message}
) } function Connections() { const connections = useConnections() return (

Connections

{(connection) => (
connector {connection.connector.name}
accounts: {stringify(connection.accounts)}
chainId: {connection.chainId}
)}
) } function BlockNumber() { const default_ = useBlockNumber(() => ({ watch: true })) const account_ = useBlockNumber(() => ({ watch: true })) const optimism_ = useBlockNumber(() => ({ chainId: optimism.id, watch: true, })) return (

Block Number

Block Number (Default Chain): {default_.data?.toString()}
Block Number (Connection Chain): {account_.data?.toString()}
Block Number (Optimism): {optimism_.data?.toString()}
) } function Balance() { const connection = useConnection() const default_ = useBalance(() => ({ address: connection().address, })) const account_ = useBalance(() => ({ address: connection().address, })) const optimism_ = useBalance(() => ({ address: connection().address, chainId: optimism.id, })) return (

Balance

Balance (Default Chain):{' '} {!!default_?.data?.value && formatEther(default_.data.value)}
Balance (Connection Chain):{' '} {!!account_?.data?.value && formatEther(account_.data.value)}
Balance (Optimism Chain):{' '} {!!optimism_?.data?.value && formatEther(optimism_.data.value)}
) } function ConnectorClient() { const connectorClient = useConnectorClient() return (

Connector Client

client {connectorClient.data?.account?.address}{' '} {connectorClient.data?.chain?.id} {connectorClient.error?.message}
) } ================================================ FILE: playgrounds/vite-solid/src/contracts.ts ================================================ export const wagmiContractConfig = { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: [ { inputs: [], stateMutability: 'nonpayable', type: 'constructor' }, { anonymous: false, inputs: [ { indexed: true, name: 'owner', type: 'address', }, { indexed: true, name: 'approved', type: 'address', }, { indexed: true, name: 'tokenId', type: 'uint256', }, ], name: 'Approval', type: 'event', }, { anonymous: false, inputs: [ { indexed: true, name: 'owner', type: 'address', }, { indexed: true, name: 'operator', type: 'address', }, { indexed: false, name: 'approved', type: 'bool', }, ], name: 'ApprovalForAll', type: 'event', }, { anonymous: false, inputs: [ { indexed: true, name: 'from', type: 'address', }, { indexed: true, name: 'to', type: 'address' }, { indexed: true, name: 'tokenId', type: 'uint256', }, ], name: 'Transfer', type: 'event', }, { inputs: [ { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, ], name: 'approve', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ name: 'owner', type: 'address' }], name: 'balanceOf', outputs: [{ name: '', type: 'uint256' }], stateMutability: 'view', type: 'function', }, { inputs: [{ name: 'tokenId', type: 'uint256' }], name: 'getApproved', outputs: [{ name: '', type: 'address' }], stateMutability: 'view', type: 'function', }, { inputs: [ { name: 'owner', type: 'address' }, { name: 'operator', type: 'address' }, ], name: 'isApprovedForAll', outputs: [{ name: '', type: 'bool' }], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'mint', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ internalType: 'uint256', name: 'tokenId', type: 'uint256' }], name: 'mint', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [], name: 'name', outputs: [{ name: '', type: 'string' }], stateMutability: 'view', type: 'function', }, { inputs: [{ name: 'tokenId', type: 'uint256' }], name: 'ownerOf', outputs: [{ name: '', type: 'address' }], stateMutability: 'view', type: 'function', }, { inputs: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, ], name: 'safeTransferFrom', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, { name: '_data', type: 'bytes' }, ], name: 'safeTransferFrom', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { name: 'operator', type: 'address' }, { name: 'approved', type: 'bool' }, ], name: 'setApprovalForAll', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ name: 'interfaceId', type: 'bytes4' }], name: 'supportsInterface', outputs: [{ name: '', type: 'bool' }], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'symbol', outputs: [{ name: '', type: 'string' }], stateMutability: 'view', type: 'function', }, { inputs: [{ name: 'tokenId', type: 'uint256' }], name: 'tokenURI', outputs: [{ name: '', type: 'string' }], stateMutability: 'pure', type: 'function', }, { inputs: [], name: 'totalSupply', outputs: [{ name: '', type: 'uint256' }], stateMutability: 'view', type: 'function', }, { inputs: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, ], name: 'transferFrom', outputs: [], stateMutability: 'nonpayable', type: 'function', }, ], } as const ================================================ FILE: playgrounds/vite-solid/src/index.css ================================================ :root { background-color: #181818; color: rgba(255, 255, 255, 0.87); color-scheme: light dark; font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; font-synthesis: none; font-weight: 400; line-height: 1.5; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-text-size-adjust: 100%; } @media (prefers-color-scheme: light) { :root { background-color: #f8f8f8; color: #181818; } } ================================================ FILE: playgrounds/vite-solid/src/index.tsx ================================================ /* @refresh reload */ import { QueryClient, QueryClientProvider } from '@tanstack/solid-query' import { WagmiProvider } from '@wagmi/solid' import { Buffer } from 'buffer' import { render } from 'solid-js/web' import './index.css' // `@coinbase-wallet/sdk` uses `Buffer` globalThis.Buffer = Buffer import { App } from './App.tsx' import { config } from './wagmi.ts' const queryClient = new QueryClient() const root = document.getElementById('root') render( () => ( ), root!, ) ================================================ FILE: playgrounds/vite-solid/src/vite-env.d.ts ================================================ /// ================================================ FILE: playgrounds/vite-solid/src/wagmi.ts ================================================ import { createConfig, http } from '@wagmi/solid' import { celo, mainnet, optimism, sepolia } from '@wagmi/solid/chains' import { baseAccount, metaMask, porto, walletConnect, } from '@wagmi/solid/connectors' export const config = createConfig({ chains: [mainnet, sepolia, optimism, celo], connectors: [ walletConnect({ projectId: import.meta.env.VITE_WC_PROJECT_ID, }), porto(), baseAccount(), metaMask(), ], transports: { [mainnet.id]: http(), [sepolia.id]: http(), [optimism.id]: http(), [celo.id]: http(), }, }) declare module '@wagmi/solid' { interface Register { config: typeof config } } ================================================ FILE: playgrounds/vite-solid/tsconfig.json ================================================ { "compilerOptions": { "target": "ESNext", "lib": ["DOM", "DOM.Iterable", "ESNext"], "module": "ESNext", "skipLibCheck": true, "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "preserve", "jsxImportSource": "solid-js", "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "paths": { "@wagmi/connectors": ["../../packages/connectors/src/exports"], "@wagmi/core": ["../../packages/core/src/exports"], "@wagmi/core/*": ["../../packages/core/src/exports/*"], "@wagmi/solid": ["../../packages/solid/src/exports"], "@wagmi/solid/*": ["../../packages/solid/src/exports/*"] } }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] } ================================================ FILE: playgrounds/vite-solid/tsconfig.node.json ================================================ { "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true }, "include": ["vite.config.ts"] } ================================================ FILE: playgrounds/vite-solid/vite.config.ts ================================================ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' export default defineConfig({ plugins: [solid()], }) ================================================ FILE: playgrounds/vite-vue/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: playgrounds/vite-vue/index.html ================================================ Vite Vue
================================================ FILE: playgrounds/vite-vue/package.json ================================================ { "name": "vite-vue", "private": true, "type": "module", "scripts": { "dev": "vite", "build": "vue-tsc && vite build", "preview": "vite preview" }, "dependencies": { "@tanstack/vue-query": "catalog:", "@wagmi/vue": "workspace:*", "viem": "2.*", "vue": "catalog:" }, "devDependencies": { "@vitejs/plugin-vue": "catalog:", "buffer": "catalog:", "vite": "catalog:", "vue-tsc": "3.1.3" } } ================================================ FILE: playgrounds/vite-vue/src/App.vue ================================================ ================================================ FILE: playgrounds/vite-vue/src/components/Balance.vue ================================================ ================================================ FILE: playgrounds/vite-vue/src/components/BlockNumber.vue ================================================ ================================================ FILE: playgrounds/vite-vue/src/components/Client.vue ================================================ ================================================ FILE: playgrounds/vite-vue/src/components/Connect.vue ================================================ ================================================ FILE: playgrounds/vite-vue/src/components/Connection.vue ================================================ ================================================ FILE: playgrounds/vite-vue/src/components/Connections.vue ================================================ ================================================ FILE: playgrounds/vite-vue/src/components/ConnectorClient.vue ================================================ ================================================ FILE: playgrounds/vite-vue/src/components/ReadContract.vue ================================================ ================================================ FILE: playgrounds/vite-vue/src/components/SendTransaction.vue ================================================ ================================================ FILE: playgrounds/vite-vue/src/components/SwitchChain.vue ================================================ ================================================ FILE: playgrounds/vite-vue/src/components/SwitchConnection.vue ================================================ ================================================ FILE: playgrounds/vite-vue/src/components/WriteContract.vue ================================================ ================================================ FILE: playgrounds/vite-vue/src/contracts.ts ================================================ export const wagmiContractConfig = { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: [ { inputs: [], stateMutability: 'nonpayable', type: 'constructor' }, { anonymous: false, inputs: [ { indexed: true, name: 'owner', type: 'address', }, { indexed: true, name: 'approved', type: 'address', }, { indexed: true, name: 'tokenId', type: 'uint256', }, ], name: 'Approval', type: 'event', }, { anonymous: false, inputs: [ { indexed: true, name: 'owner', type: 'address', }, { indexed: true, name: 'operator', type: 'address', }, { indexed: false, name: 'approved', type: 'bool', }, ], name: 'ApprovalForAll', type: 'event', }, { anonymous: false, inputs: [ { indexed: true, name: 'from', type: 'address', }, { indexed: true, name: 'to', type: 'address' }, { indexed: true, name: 'tokenId', type: 'uint256', }, ], name: 'Transfer', type: 'event', }, { inputs: [ { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, ], name: 'approve', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ name: 'owner', type: 'address' }], name: 'balanceOf', outputs: [{ name: '', type: 'uint256' }], stateMutability: 'view', type: 'function', }, { inputs: [{ name: 'tokenId', type: 'uint256' }], name: 'getApproved', outputs: [{ name: '', type: 'address' }], stateMutability: 'view', type: 'function', }, { inputs: [ { name: 'owner', type: 'address' }, { name: 'operator', type: 'address' }, ], name: 'isApprovedForAll', outputs: [{ name: '', type: 'bool' }], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'mint', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ internalType: 'uint256', name: 'tokenId', type: 'uint256' }], name: 'mint', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [], name: 'name', outputs: [{ name: '', type: 'string' }], stateMutability: 'view', type: 'function', }, { inputs: [{ name: 'tokenId', type: 'uint256' }], name: 'ownerOf', outputs: [{ name: '', type: 'address' }], stateMutability: 'view', type: 'function', }, { inputs: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, ], name: 'safeTransferFrom', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, { name: '_data', type: 'bytes' }, ], name: 'safeTransferFrom', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [ { name: 'operator', type: 'address' }, { name: 'approved', type: 'bool' }, ], name: 'setApprovalForAll', outputs: [], stateMutability: 'nonpayable', type: 'function', }, { inputs: [{ name: 'interfaceId', type: 'bytes4' }], name: 'supportsInterface', outputs: [{ name: '', type: 'bool' }], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'symbol', outputs: [{ name: '', type: 'string' }], stateMutability: 'view', type: 'function', }, { inputs: [{ name: 'tokenId', type: 'uint256' }], name: 'tokenURI', outputs: [{ name: '', type: 'string' }], stateMutability: 'pure', type: 'function', }, { inputs: [], name: 'totalSupply', outputs: [{ name: '', type: 'uint256' }], stateMutability: 'view', type: 'function', }, { inputs: [ { name: 'from', type: 'address' }, { name: 'to', type: 'address' }, { name: 'tokenId', type: 'uint256' }, ], name: 'transferFrom', outputs: [], stateMutability: 'nonpayable', type: 'function', }, ], } as const ================================================ FILE: playgrounds/vite-vue/src/main.ts ================================================ import { VueQueryPlugin } from '@tanstack/vue-query' import { WagmiPlugin } from '@wagmi/vue' import { Buffer } from 'buffer' import { createApp } from 'vue' // `@coinbase-wallet/sdk` uses `Buffer` globalThis.Buffer = Buffer import App from './App.vue' import './style.css' import { config } from './wagmi' const app = createApp(App) app.use(WagmiPlugin, { config }).use(VueQueryPlugin, {}) app.mount('#app') ================================================ FILE: playgrounds/vite-vue/src/style.css ================================================ :root { background-color: #181818; color: rgba(255, 255, 255, 0.87); color-scheme: light dark; font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; font-synthesis: none; font-weight: 400; line-height: 1.5; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-text-size-adjust: 100%; } @media (prefers-color-scheme: light) { :root { background-color: #f8f8f8; color: #181818; } } ================================================ FILE: playgrounds/vite-vue/src/vite-env.d.ts ================================================ /// ================================================ FILE: playgrounds/vite-vue/src/wagmi.ts ================================================ import { createConfig, createStorage, http } from '@wagmi/vue' import { mainnet, optimism, sepolia } from '@wagmi/vue/chains' import { baseAccount, metaMask, walletConnect } from '@wagmi/vue/connectors' export const config = createConfig({ chains: [mainnet, sepolia, optimism], connectors: [ walletConnect({ projectId: import.meta.env.VITE_WC_PROJECT_ID, }), baseAccount({ appName: 'Vite Vue Playground' }), metaMask(), ], storage: createStorage({ storage: localStorage, key: 'vite-vue' }), transports: { [mainnet.id]: http(), [sepolia.id]: http(), [optimism.id]: http(), }, }) declare module '@wagmi/vue' { interface Register { config: typeof config } } ================================================ FILE: playgrounds/vite-vue/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "module": "ESNext", "lib": ["ES2020", "DOM", "DOM.Iterable"], "skipLibCheck": true, "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "preserve", "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true }, "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"], "references": [{ "path": "./tsconfig.node.json" }] } ================================================ FILE: playgrounds/vite-vue/tsconfig.node.json ================================================ { "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true, "strict": true }, "include": ["vite.config.ts"] } ================================================ FILE: playgrounds/vite-vue/vite.config.ts ================================================ import vue from '@vitejs/plugin-vue' import { defineConfig } from 'vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [vue()], }) ================================================ FILE: pnpm-workspace.yaml ================================================ packages: - packages/* - '!packages/register-tests' - packages/cli/src/plugins/__fixtures__/hardhat - packages/register-tests/* - playgrounds/* - site auditConfig: ignoreGhsas: - GHSA-g3ch-rx76-35fx - GHSA-ffrw-9mx8-89p8 - GHSA-qpm2-6cq5-7pq5 - GHSA-93m4-6634-74q7 - GHSA-29xp-372q-xqph - GHSA-mh29-5h37-fv8m - GHSA-5j98-mcp5-4vw2 - GHSA-92fh-27vv-894w - GHSA-677m-j7p3-52f9 autoInstallPeers: false catalog: '@base-org/account': 2.4.0 '@coinbase/wallet-sdk': 4.3.6 '@metamask/connect-evm': 0.9.0 '@nuxt/schema': 4.2.1 '@safe-global/safe-apps-provider': 0.18.6 '@safe-global/safe-apps-sdk': 9.1.0 '@tanstack/query-core': 5.49.1 '@tanstack/react-query': 5.49.2 '@tanstack/solid-query': 5.49.1 '@tanstack/vue-query': 5.49.1 '@types/react': ^19.2.0 '@types/react-dom': ^19.2.0 '@vitejs/plugin-react': ^4.3.3 '@vitejs/plugin-vue': 6.0.1 '@walletconnect/ethereum-provider': 2.21.1 buffer: 6.0.3 nuxt: 4.2.1 ox: 0.11.1 porto: 0.2.37 react: 19.2.0 react-dom: 19.2.0 solid-js: 1.9.10 vite: 7.2.2 vite-plugin-solid: 2.11.10 vue: 3.5.25 linkWorkspacePackages: deep minimumReleaseAge: 1440 minimumReleaseAgeExclude: - '@metamask/connect-evm' - '@metamask/connect-multichain' - '@wagmi/cli' - '@wagmi/connectors' - '@wagmi/core' - '@wagmi/test' - '@wagmi/solid' - '@wagmi/vue' - abitype - ox - porto - prool - wagmi - viem overrides: '@isaacs/brace-expansion@<=5.0.0': 5.0.1 axios@<=1.13.4: 1.13.5 cookie@<0.7.0: 0.7.0 bn.js@>=5.0.0 <5.2.3: 5.2.3 devalue@<5.6.4: 5.6.4 diff@<8.0.3: 8.0.3 elliptic@<=6.6.0: '>=6.6.1' esbuild@<=0.24.2: 0.25.0 glob@>=10.2.0 <10.5.0: 10.5.0 h3@<1.15.6: 1.15.6 happy-dom@<20.0.2: '>=20.0.2' minimatch@<3.1.4: 3.1.4 minimatch@>=5.0.0 <5.1.8: 5.1.8 minimatch@>=9.0.0 <9.0.7: 9.0.7 minimatch@>=10.0.0 <10.2.3: 10.2.3 hono@<4.12.7: 4.12.7 lodash@>=4.0.0 <=4.17.22: '>=4.17.23' markdown-it@>=13.0.0 <14.1.1: 14.1.1 mdast-util-to-hast@<13.2.1: '>=13.2.1' nanoid@<3.3.8: 3.3.8 node-forge@<1.3.2: '>=1.3.2' rollup@>=4.0.0 <4.59.0: 4.59.0 semver@<5.7.2: '>=5.7.2' serialize-javascript@<=7.0.2: 7.0.3 simple-git@>=3.15.0 <3.32.3: 3.32.3 seroval@<1.4.1: '>=1.4.1' svgo@=4.0.0: 4.0.1 tar@<=7.5.10: 7.5.11 tmp@<=0.2.3: 0.2.4 unhead@<=2.1.10: 2.1.11 undici@<6.24.0: 6.24.0 undici@>=7.0.0 <7.24.0: 7.24.0 vite@>=7.1.0 <=7.1.10: '>=7.1.11' wrangler@>=4.0.0 <4.59.1: '>=4.59.1' ws@>=8.0.0 <8.17.1: 8.17.1 peerDependencyRules: ignoreMissing: - '@algolia/client-search' - react - react-native - search-insights trustPolicy: no-downgrade trustPolicyExclude: - '@coinbase/cdp-sdk@1.38.4' - '@noble/curves@1.8.0' - '@noble/hashes@1.7.0' - chokidar@4.0.3 - semver@6.3.1 - undici@6.22.0 - serialize-javascript@7.0.3 - simple-git@3.32.3 - vite@5.4.21 || 6.4.1 ================================================ FILE: scripts/formatPackageJson.ts ================================================ import fs from 'node:fs/promises' import path from 'node:path' // Generates package.json files to be published to NPM with only the necessary fields. console.log('Formatting package.json files.') // Get all package.json files const packagePaths = fs.glob('packages/**/package.json', { exclude: ['**/dist/**', '**/node_modules/**'], }) let count = 0 for await (const packagePath of packagePaths) { type Package = Record & { name?: string | undefined private?: boolean | undefined } const packageJson = JSON.parse( await fs.readFile(packagePath, 'utf-8'), ) as Package // Skip private packages if (packageJson.private) continue if (!packageJson.name) continue count += 1 console.log(`${packageJson.name} — ${path.dirname(packagePath)}`) await fs.writeFile( `${packagePath}.tmp`, `${JSON.stringify(packageJson, undefined, 2)}\n`, 'utf-8', ) const { devDependencies: _dD, scripts: _s, ...rest } = packageJson await fs.writeFile( packagePath, `${JSON.stringify(rest, undefined, 2)}\n`, 'utf-8', ) } console.log(`Done. Formatted ${count} ${count === 1 ? 'file' : 'files'}.`) ================================================ FILE: scripts/generateProxyPackages.ts ================================================ import fs from 'node:fs/promises' import path from 'node:path' // Generates proxy packages for package.json#exports. console.log('Generating proxy packages.') // Get all package.json files const packagePaths = fs.glob('packages/**/package.json', { exclude: ['**/dist/**', '**/node_modules/**'], }) let count = 0 for await (const packagePath of packagePaths) { type Package = Record & { name?: string | undefined private?: boolean | undefined exports?: | Record | undefined } const packageJson = JSON.parse( await fs.readFile(packagePath, 'utf-8'), ) as Package // Skip private packages if (packageJson.private) continue if (!packageJson.exports) continue count += 1 console.log(`${packageJson.name} — ${path.dirname(packagePath)}`) const dir = path.resolve(path.dirname(packagePath)) for (const [key, exports] of Object.entries(packageJson.exports)) { // Skip `package.json` export if (/package\.json$/.test(key)) continue if (key === '.') continue if (typeof exports === 'string') continue if (!exports.default) continue const proxyDir = path.resolve(dir, key) await fs.mkdir(proxyDir, { recursive: true }) const types = path.relative(key, exports.types) const main = path.relative(key, exports.default) await fs.writeFile( `${proxyDir}/package.json`, `${JSON.stringify({ type: 'module', types, main }, undefined, 2)}\n`, 'utf-8', ) } } console.log( `Done. Generated proxy packages for ${count} ${ count === 1 ? 'package' : 'packages' }.`, ) ================================================ FILE: scripts/preconstruct.ts ================================================ import fs from 'node:fs/promises' import path from 'node:path' // Symlinks package sources to dist for local development console.log('Setting up packages for development.') // Get all package.json files const packagePaths = fs.glob('**/package.json', { exclude: ['**/dist/**', '**/node_modules/**'], }) let count = 0 for await (const packagePath of packagePaths) { type Package = { bin?: Record | undefined exports?: | Record | undefined name?: string | undefined private?: boolean | undefined } const packageJson = JSON.parse( await fs.readFile(packagePath, 'utf-8'), ) as Package // Skip private packages if (packageJson.private && packageJson.name !== '@wagmi/test') continue if (!packageJson.exports) continue if (packageJson.bin) continue count += 1 console.log(`${packageJson.name} — ${path.dirname(packagePath)}`) const dir = path.resolve(path.dirname(packagePath)) // Empty dist directory const dist = path.resolve(dir, 'dist') let files: string[] = [] try { files = await fs.readdir(dist) } catch { await fs.mkdir(dist) } const promises = [] for (const file of files) { promises.push( fs.rm(path.join(dist, file), { recursive: true, force: true }), ) } await Promise.all(promises) // Link exports to dist locations for (const [key, exports] of Object.entries(packageJson.exports)) { // Skip `package.json` exports if (/package\.json$/.test(key)) continue if (typeof exports === 'string') continue // Link exports to dist locations for (const [type, value] of Object.entries(exports) as [ type: 'types' | 'default', value: string, ][]) { const srcDir = path.resolve( dir, path .dirname(value) .replace(`dist/${type === 'default' ? 'esm' : type}`, 'src'), ) let srcFileName: string if (key === '.') srcFileName = 'index.ts' else srcFileName = path.basename(`${key}.ts`) const srcFilePath = path.resolve(srcDir, srcFileName) const distDir = path.resolve(dir, path.dirname(value)) const distFileName = path.basename(value) const distFilePath = path.resolve(distDir, distFileName) await fs.mkdir(distDir, { recursive: true }) // Symlink src to dist file await fs.symlink(srcFilePath, distFilePath, 'file') } } } console.log(`Done. Set up ${count} ${count === 1 ? 'package' : 'packages'}.`) ================================================ FILE: scripts/restorePackageJson.ts ================================================ import fs from 'node:fs/promises' import path from 'node:path' // Restores package.json files from package.json.tmp files. console.log('Restoring package.json files.') // Get all package.json files const packagePaths = fs.glob('packages/**/package.json.tmp', { exclude: ['**/dist/**', '**/node_modules/**'], }) let count = 0 for await (const packagePath of packagePaths) { type Package = { name?: string | undefined } & Record const packageJson = JSON.parse( await fs.readFile(packagePath, 'utf-8'), ) as Package count += 1 console.log(`${packageJson.name} — ${path.dirname(packagePath)}`) await fs.writeFile( packagePath.replace('.tmp', ''), `${JSON.stringify(packageJson, undefined, 2)}\n`, 'utf-8', ) await fs.rm(packagePath) } console.log(`Done. Restored ${count} ${count === 1 ? 'file' : 'files'}.`) ================================================ FILE: scripts/updateBlockExplorerPluginChains.ts ================================================ import fs from 'node:fs/promises' // Fetches supported chains for Etherscan and Sourcify console.log('Updating block explorer plugins chains.') let count = 0 { console.log('etherscan - https://api.etherscan.io/v2/chainlist') const res = (await fetch('https://api.etherscan.io/v2/chainlist').then( (res) => res.json(), )) as { totalcount: number result: { chainname: string chainid: number blockexplorer: string apiurl: string status: 0 | 1 }[] } let content = 'type ChainId =\n' for (const chain of res.result) content += ` | ${chain.chainid} // ${chain.chainname}\n` await writeContent('./packages/cli/src/plugins/etherscan.ts', content) count += 1 } { console.log('sourcify - https://sourcify.dev/server/chains') const res = (await fetch('https://sourcify.dev/server/chains').then((res) => res.json(), )) as { name: string chainId: number }[] let content = 'type ChainId =\n' for (const chain of res) content += ` | ${chain.chainId} // ${chain.name}\n` await writeContent('./packages/cli/src/plugins/sourcify.ts', content) count += 1 } console.log(`Done. Updated chains for ${count} plugins.`) async function writeContent(pluginPath: string, content: string) { const text = await fs .readFile(pluginPath, 'utf8') .then((text) => text.replace(/type ChainId =[\s\S]*$/, content)) await fs.writeFile(pluginPath, text, 'utf8') } ================================================ FILE: scripts/updateVersion.ts ================================================ import child_process from 'node:child_process' import fs from 'node:fs/promises' import path from 'node:path' // Updates package version.ts files (so you can use the version in code without importing package.json). console.log('Updating version files.') // Get all package.json files const packagePaths = fs.glob('packages/**/package.json', { exclude: ['**/dist/**', '**/node_modules/**'], }) let count = 0 for await (const packagePath of packagePaths) { type Package = { name?: string | undefined private?: boolean | undefined version?: string | undefined } const packageJson = JSON.parse( await fs.readFile(packagePath, 'utf-8'), ) as Package // Skip private packages if (packageJson.private) continue const version = (() => { if (process.env.PKG_PR_NEW) { const gitHash = child_process .execSync('git rev-parse --short HEAD') .toString() .trim() const branch = ( process.env.GITHUB_HEAD_REF || child_process.execSync('git branch --show-current').toString().trim() ).replace(/[^a-zA-Z0-9]/g, '-') return `0.0.0-${branch}.${gitHash}` } return packageJson.version })() count += 1 console.log(`${packageJson.name} — ${version}`) const versionFilePath = path.resolve( path.dirname(packagePath), 'src', 'version.ts', ) await fs.writeFile( versionFilePath, `export const version = '${version}'\n`, 'utf-8', ) if (process.env.PKG_PR_NEW) { packageJson.version = version await fs.writeFile( packagePath, `${JSON.stringify(packageJson, null, 2)}\n`, 'utf-8', ) } } console.log( `Done. Updated version file for ${count} ${ count === 1 ? 'package' : 'packages' }.`, ) ================================================ FILE: scripts/updateViemVersion.ts ================================================ import fs from 'node:fs/promises' // Updates viem version in Vitest snapshots, etc. console.log('Updating Viem version.') const packageJson = JSON.parse(await fs.readFile('package.json', 'utf-8')) const viemVersion = packageJson.devDependencies.viem // Update Vitest snapshots // Get all *.test.ts files const testPaths = fs.glob('packages/**/*.test.ts') let count = 0 for await (const testPath of testPaths) { const testFile = await fs.readFile(testPath, 'utf-8') // Skip files that don't contain viem version if (!testFile.includes('Version: viem@')) continue // Skip files that contain current version if (testFile.includes(`Version: viem@${viemVersion}`)) continue const updatedTestFile = testFile.replace( /Version: viem@[A-Za-z0-9\-.]+/g, `Version: viem@${viemVersion}`, ) await fs.writeFile(testPath, updatedTestFile, 'utf-8') count += 1 } // // Update package.json#pnpm.overrides.viem // if (packageJson.pnpm?.overrides?.viem !== viemVersion) { // const path = 'package.json' // console.log(path) // packageJson.pnpm.overrides.viem = viemVersion // await fs.writeFile(path, `${JSON.stringify(packageJson, undefined, 2)}\n`, 'utf-8') // count += 1 // } console.log(`Done. Updated ${count} ${count === 1 ? 'file' : 'files'}.`) ================================================ FILE: site/.gitignore ================================================ .vercel .env*.local ================================================ FILE: site/.vitepress/config.ts ================================================ import { createTwoslashWithInlineCache } from '@shikijs/vitepress-twoslash/cache-inline' import unocss from 'unocss/vite' import { defineConfig } from 'vitepress' import { groupIconMdPlugin, groupIconVitePlugin, } from 'vitepress-plugin-group-icons' import llmstxt, { copyOrDownloadAsMarkdownButtons } from 'vitepress-plugin-llms' import { getSidebar } from './sidebar' const withTwoslashInlineCache = createTwoslashWithInlineCache() // https://vitepress.dev/reference/site-config export default withTwoslashInlineCache( defineConfig({ cleanUrls: true, description: 'Reactivity for Ethereum apps', head: [ [ 'meta', { name: 'keywords', content: 'react, ethereum, typescript, react, react hooks, open source', }, ], ['link', { rel: 'icon', href: '/favicon.svg' }], ['meta', { name: 'theme-color', content: '#646cff' }], // Open Graph ['meta', { property: 'og:type', content: 'website' }], ['meta', { property: 'og:image', content: 'https://wagmi.sh/og.png' }], ['meta', { property: 'og:url', content: 'https://wagmi.sh' }], // Twitter ['meta', { name: 'twitter:card', content: 'summary_large_image' }], ['meta', { name: 'twitter:creator', content: '@wevm_dev' }], ['meta', { name: 'twitter:image', content: 'https://wagmi.sh/og.png' }], ['meta', { name: 'twitter:site', content: 'wagmi.sh' }], // Fathom [ 'script', { src: 'https://cdn.usefathom.com/script.js', 'data-site': 'QWAXSUPT', defer: '', }, ], ], ignoreDeadLinks: false, lang: 'en-US', lastUpdated: true, markdown: { config(md) { md.use(copyOrDownloadAsMarkdownButtons).use(groupIconMdPlugin) }, languages: ['js', 'jsx', 'ts', 'tsx'], theme: { light: 'vitesse-light', dark: 'vitesse-dark', }, }, themeConfig: { editLink: { pattern: 'https://github.com/wevm/wagmi/edit/main/site/:path', text: 'Suggest changes to this page', }, footer: { message: 'Released under the
MIT License.', copyright: 'Copyright © 2022-present Weth, LLC', }, logo: { light: '/logo-light.svg', dark: '/logo-dark.svg', alt: 'wagmi logo', }, nav: [ { text: 'React', link: '/react/getting-started' }, { text: 'Core', link: '/core/getting-started' }, { text: 'Tempo', link: '/tempo/getting-started' }, { text: 'CLI', link: '/cli/getting-started' }, { text: 'Frameworks', items: [ { text: 'React', link: '/react/getting-started' }, { text: 'Solid', link: '/solid/getting-started' }, { text: 'Vue', link: '/vue/getting-started' }, ], }, // { text: 'Examples', link: '/examples/connect-wallet' }, { text: 'More', items: [ { text: 'Discussions ', link: 'https://github.com/wevm/wagmi/discussions', }, { text: 'Release Notes ', link: 'https://github.com/wevm/wagmi/releases', }, { text: 'Contributing ', link: '/dev/contributing', }, ], }, ], outline: [2, 3], search: { provider: 'local', options: { _render(src, env, md) { const html = md.render(src, env) if (env.frontmatter?.search === false) return '' if (env.relativePath.startsWith('shared')) return '' return html }, }, }, sidebar: getSidebar(), siteTitle: false, socialLinks: [ { icon: 'github', link: 'https://github.com/wevm/wagmi' }, { icon: 'x', link: 'https://twitter.com/wevm_dev' }, { icon: 'bluesky', link: 'https://bsky.app/profile/wevm.dev' }, { icon: 'discord', link: 'https://discord.gg/9zHPXuBpqy' }, ], }, title: 'Wagmi', vite: { plugins: [ llmstxt({ ignoreFiles: ['shared/'] }), groupIconVitePlugin(), unocss(), ], }, }), ) ================================================ FILE: site/.vitepress/sidebar.ts ================================================ import type { DefaultTheme } from 'vitepress' export function getSidebar() { return { '/react': [ { text: 'Introduction', items: [ { text: 'Why Wagmi', link: '/react/why' }, { text: 'Installation', link: '/react/installation' }, { text: 'Getting Started', link: '/react/getting-started' }, { text: 'TypeScript', link: '/react/typescript' }, { text: 'Comparisons', link: '/react/comparisons' }, ], }, { text: 'Guides', items: [ { text: 'TanStack Query', link: '/react/guides/tanstack-query', }, { text: 'Viem', link: '/react/guides/viem', }, { text: 'Error Handling', link: '/react/guides/error-handling', }, { text: 'Ethers.js Adapters', link: '/react/guides/ethers', }, // { // text: 'Testing', // link: '/react/guides/testing', // }, { text: 'Chain Properties', link: '/react/guides/chain-properties', }, { text: 'SSR', link: '/react/guides/ssr', }, { text: 'Connect Wallet', link: '/react/guides/connect-wallet', }, { text: 'Send Transaction', link: '/react/guides/send-transaction', }, { text: 'Read from Contract', link: '/react/guides/read-from-contract', }, { text: 'Write to Contract', link: '/react/guides/write-to-contract', }, { text: 'FAQ / Troubleshooting', link: '/react/guides/faq', }, { text: 'Migrate from v2 to v3', link: '/react/guides/migrate-from-v2-to-v3', }, { text: 'Migrate from v1 to v2', link: '/react/guides/migrate-from-v1-to-v2', }, ], }, { text: 'Configuration', items: [ { text: 'createConfig', link: '/react/api/createConfig' }, { text: 'createStorage', link: '/react/api/createStorage' }, { text: 'Chains', link: '/react/api/chains' }, { text: 'Connectors', collapsed: true, link: '/react/api/connectors', items: [ { text: 'baseAccount', link: '/react/api/connectors/baseAccount', }, { text: 'injected', link: '/react/api/connectors/injected' }, { text: 'metaMask', link: '/react/api/connectors/metaMask', }, { text: 'mock', link: '/react/api/connectors/mock', }, { text: 'porto', link: '/react/api/connectors/porto', }, { text: 'safe', link: '/react/api/connectors/safe', }, { text: 'walletConnect', link: '/react/api/connectors/walletConnect', }, ], }, { text: 'Transports', collapsed: true, link: '/react/api/transports', items: [ { text: 'custom (EIP-1193)', link: '/react/api/transports/custom', }, { text: 'fallback', link: '/react/api/transports/fallback', }, { text: 'http', link: '/react/api/transports/http', }, { text: 'unstable_connector', link: '/react/api/transports/unstable_connector', }, { text: 'webSocket', link: '/react/api/transports/webSocket', }, ], }, { text: 'WagmiProvider', link: '/react/api/WagmiProvider' }, ], }, { text: 'Hooks', link: '/react/api/hooks', items: [ { text: 'useBalance', link: '/react/api/hooks/useBalance' }, { text: 'useBlobBaseFee', link: '/react/api/hooks/useBlobBaseFee', }, { text: 'useBlockNumber', link: '/react/api/hooks/useBlockNumber', }, { text: 'useBlock', link: '/react/api/hooks/useBlock', }, { text: 'useBlockTransactionCount', link: '/react/api/hooks/useBlockTransactionCount', }, { text: 'useBytecode', link: '/react/api/hooks/useBytecode', }, { text: 'useCall', link: '/react/api/hooks/useCall' }, { text: 'useCallsStatus', link: '/react/api/hooks/useCallsStatus', }, { text: 'useCapabilities', link: '/react/api/hooks/useCapabilities', }, { text: 'useChainId', link: '/react/api/hooks/useChainId' }, { text: 'useChains', link: '/react/api/hooks/useChains' }, { text: 'useClient', link: '/react/api/hooks/useClient' }, { text: 'useConfig', link: '/react/api/hooks/useConfig' }, { text: 'useConnect', link: '/react/api/hooks/useConnect' }, { text: 'useConnection', link: '/react/api/hooks/useConnection' }, { text: 'useConnectionEffect', link: '/react/api/hooks/useConnectionEffect', }, { text: 'useConnections', link: '/react/api/hooks/useConnections', }, { text: 'useConnectorClient', link: '/react/api/hooks/useConnectorClient', }, { text: 'useConnectors', link: '/react/api/hooks/useConnectors', }, { text: 'useContractEvents', link: '/react/api/hooks/useContractEvents', }, { text: 'useDeployContract', link: '/react/api/hooks/useDeployContract', }, { text: 'useDisconnect', link: '/react/api/hooks/useDisconnect' }, { text: 'useEnsAddress', link: '/react/api/hooks/useEnsAddress' }, { text: 'useEnsAvatar', link: '/react/api/hooks/useEnsAvatar' }, { text: 'useEnsName', link: '/react/api/hooks/useEnsName' }, { text: 'useEnsResolver', link: '/react/api/hooks/useEnsResolver', }, { text: 'useEnsText', link: '/react/api/hooks/useEnsText', }, { text: 'useFeeHistory', link: '/react/api/hooks/useFeeHistory', }, { text: 'useProof', link: '/react/api/hooks/useProof', }, { text: 'usePublicClient', link: '/react/api/hooks/usePublicClient', }, { text: 'useEstimateFeesPerGas', link: '/react/api/hooks/useEstimateFeesPerGas', }, { text: 'useEstimateGas', link: '/react/api/hooks/useEstimateGas', }, { text: 'useEstimateMaxPriorityFeePerGas', link: '/react/api/hooks/useEstimateMaxPriorityFeePerGas', }, { text: 'useGasPrice', link: '/react/api/hooks/useGasPrice', }, { text: 'useInfiniteReadContracts', link: '/react/api/hooks/useInfiniteReadContracts', }, { text: 'usePrepareTransactionRequest', link: '/react/api/hooks/usePrepareTransactionRequest', }, { text: 'useReadContract', link: '/react/api/hooks/useReadContract', }, { text: 'useReadContracts', link: '/react/api/hooks/useReadContracts', }, { text: 'useReconnect', link: '/react/api/hooks/useReconnect' }, { text: 'useSendCalls', link: '/react/api/hooks/useSendCalls', }, { text: 'useSendTransaction', link: '/react/api/hooks/useSendTransaction', }, { text: 'useShowCallsStatus', link: '/react/api/hooks/useShowCallsStatus', }, { text: 'useSignMessage', link: '/react/api/hooks/useSignMessage', }, { text: 'useSignTransaction', link: '/react/api/hooks/useSignTransaction', }, { text: 'useSignTypedData', link: '/react/api/hooks/useSignTypedData', }, { text: 'useSimulateContract', link: '/react/api/hooks/useSimulateContract', }, { text: 'useStorageAt', link: '/react/api/hooks/useStorageAt', }, { text: 'useSwitchChain', link: '/react/api/hooks/useSwitchChain', }, { text: 'useSwitchConnection', link: '/react/api/hooks/useSwitchConnection', }, { text: 'useTransaction', link: '/react/api/hooks/useTransaction', }, { text: 'useTransactionConfirmations', link: '/react/api/hooks/useTransactionConfirmations', }, { text: 'useTransactionCount', link: '/react/api/hooks/useTransactionCount', }, { text: 'useTransactionReceipt', link: '/react/api/hooks/useTransactionReceipt', }, { text: 'useWaitForCallsStatus', link: '/react/api/hooks/useWaitForCallsStatus', }, { text: 'useWaitForTransactionReceipt', link: '/react/api/hooks/useWaitForTransactionReceipt', }, { text: 'useVerifyMessage', link: '/react/api/hooks/useVerifyMessage', }, { text: 'useVerifyTypedData', link: '/react/api/hooks/useVerifyTypedData', }, { text: 'useWalletClient', link: '/react/api/hooks/useWalletClient', }, { text: 'useWatchAsset', link: '/react/api/hooks/useWatchAsset', }, { text: 'useWatchBlocks', link: '/react/api/hooks/useWatchBlocks', }, { text: 'useWatchBlockNumber', link: '/react/api/hooks/useWatchBlockNumber', }, { text: 'useWatchContractEvent', link: '/react/api/hooks/useWatchContractEvent', }, { text: 'useWatchPendingTransactions', link: '/react/api/hooks/useWatchPendingTransactions', }, { text: 'useWriteContract', link: '/react/api/hooks/useWriteContract', }, ], }, { text: 'Miscellaneous', items: [ { text: 'Actions', link: '/react/api/actions' }, { text: 'Errors', link: '/react/api/errors' }, { text: 'Utilities', collapsed: true, items: [ { text: 'cookieToInitialState', link: '/react/api/utilities/cookieToInitialState', }, { text: 'deserialize', link: '/react/api/utilities/deserialize' }, { text: 'serialize', link: '/react/api/utilities/serialize' }, ], }, ], }, ], '/vue': [ { text: 'Introduction', items: [ { text: 'Why Wagmi', link: '/vue/why' }, { text: 'Installation', link: '/vue/installation' }, { text: 'Getting Started', link: '/vue/getting-started' }, { text: 'TypeScript', link: '/vue/typescript' }, ], }, { text: 'Guides', items: [ { text: 'TanStack Query', link: '/vue/guides/tanstack-query', }, { text: 'Viem', link: '/vue/guides/viem', }, { text: 'Error Handling', link: '/vue/guides/error-handling', }, { text: 'Chain Properties', link: '/vue/guides/chain-properties', }, { text: 'SSR', link: '/vue/guides/ssr', }, { text: 'Connect Wallet', link: '/vue/guides/connect-wallet', }, { text: 'Send Transaction', link: '/vue/guides/send-transaction', }, { text: 'Read from Contract', link: '/vue/guides/read-from-contract', }, { text: 'Write to Contract', link: '/vue/guides/write-to-contract', }, { text: 'FAQ / Troubleshooting', link: '/vue/guides/faq', }, ], }, { text: 'Configuration', items: [ { text: 'createConfig', link: '/vue/api/createConfig' }, { text: 'createStorage', link: '/vue/api/createStorage' }, { text: 'Chains', link: '/vue/api/chains' }, { text: 'Connectors', collapsed: true, link: '/vue/api/connectors', items: [ { text: 'baseAccount', link: '/vue/api/connectors/baseAccount', }, { text: 'injected', link: '/vue/api/connectors/injected' }, { text: 'metaMask', link: '/vue/api/connectors/metaMask', }, { text: 'mock', link: '/vue/api/connectors/mock', }, { text: 'porto', link: '/vue/api/connectors/porto', }, { text: 'safe', link: '/vue/api/connectors/safe', }, { text: 'walletConnect', link: '/vue/api/connectors/walletConnect', }, ], }, { text: 'Transports', collapsed: true, link: '/vue/api/transports', items: [ { text: 'custom (EIP-1193)', link: '/vue/api/transports/custom', }, { text: 'fallback', link: '/vue/api/transports/fallback', }, { text: 'http', link: '/vue/api/transports/http', }, { text: 'unstable_connector', link: '/vue/api/transports/unstable_connector', }, { text: 'webSocket', link: '/vue/api/transports/webSocket', }, ], }, { text: 'WagmiPlugin', link: '/vue/api/WagmiPlugin' }, { text: 'Nuxt', link: '/vue/api/Nuxt' }, ], }, { text: 'Composables', link: '/vue/api/composables', items: [ { text: 'useBalance', link: '/vue/api/composables/useBalance', }, { text: 'useBlockNumber', link: '/vue/api/composables/useBlockNumber', }, { text: 'useBytecode', link: '/vue/api/composables/useBytecode', }, { text: 'useChainId', link: '/vue/api/composables/useChainId' }, { text: 'useChains', link: '/vue/api/composables/useChains' }, { text: 'useClient', link: '/vue/api/composables/useClient' }, { text: 'useConfig', link: '/vue/api/composables/useConfig' }, { text: 'useConnect', link: '/vue/api/composables/useConnect' }, { text: 'useConnection', link: '/vue/api/composables/useConnection' }, { text: 'useConnectionEffect', link: '/vue/api/composables/useConnectionEffect', }, { text: 'useConnections', link: '/vue/api/composables/useConnections', }, { text: 'useConnectorClient', link: '/vue/api/composables/useConnectorClient', }, { text: 'useConnectors', link: '/vue/api/composables/useConnectors', }, { text: 'useDisconnect', link: '/vue/api/composables/useDisconnect', }, { text: 'useEnsAddress', link: '/vue/api/composables/useEnsAddress', }, { text: 'useEnsAvatar', link: '/vue/api/composables/useEnsAvatar', }, { text: 'useEstimateGas', link: '/vue/api/composables/useEstimateGas', }, { text: 'useReadContract', link: '/vue/api/composables/useReadContract', }, { text: 'useReconnect', link: '/vue/api/composables/useReconnect', }, { text: 'useSendTransaction', link: '/vue/api/composables/useSendTransaction', }, { text: 'useSignMessage', link: '/vue/api/composables/useSignMessage', }, { text: 'useSignTransaction', link: '/vue/api/composables/useSignTransaction', }, { text: 'useSignTypedData', link: '/vue/api/composables/useSignTypedData', }, { text: 'useSimulateContract', link: '/vue/api/composables/useSimulateContract', }, { text: 'useSwitchChain', link: '/vue/api/composables/useSwitchChain', }, { text: 'useSwitchConnection', link: '/vue/api/composables/useSwitchConnection', }, { text: 'useTransaction', link: '/vue/api/composables/useTransaction', }, { text: 'useTransactionReceipt', link: '/vue/api/composables/useTransactionReceipt', }, { text: 'useWaitForTransactionReceipt', link: '/vue/api/composables/useWaitForTransactionReceipt', }, { text: 'useWatchBlockNumber', link: '/vue/api/composables/useWatchBlockNumber', }, { text: 'useWatchContractEvent', link: '/vue/api/composables/useWatchContractEvent', }, { text: 'useWriteContract', link: '/vue/api/composables/useWriteContract', }, ], }, { text: 'Miscellaneous', items: [ { text: 'Actions', link: '/vue/api/actions' }, { text: 'Errors', link: '/vue/api/errors' }, { text: 'Utilities', collapsed: true, items: [ { text: 'deserialize', link: '/vue/api/utilities/deserialize', }, { text: 'serialize', link: '/vue/api/utilities/serialize' }, ], }, ], }, ], '/core': [ { text: 'Introduction', items: [ { text: 'Why Wagmi', link: '/core/why' }, { text: 'Installation', link: '/core/installation' }, { text: 'Getting Started', link: '/core/getting-started' }, { text: 'TypeScript', link: '/core/typescript' }, ], }, { text: 'Guides', items: [ { text: 'Viem', link: '/core/guides/viem', }, { text: 'Framework Adapters', link: '/core/guides/framework-adapters', }, { text: 'Error Handling', link: '/core/guides/error-handling', }, { text: 'Ethers.js Adapters', link: '/core/guides/ethers', }, // { // text: 'Testing', // link: '/core/guides/testing', // }, { text: 'Chain Properties', link: '/core/guides/chain-properties', }, { text: 'FAQ / Troubleshooting', link: '/core/guides/faq', }, { text: 'Migrate from v2 to v3', link: '/core/guides/migrate-from-v2-to-v3', }, { text: 'Migrate from v1 to v2', link: '/core/guides/migrate-from-v1-to-v2', }, ], }, { text: 'Configuration', items: [ { text: 'createConfig', link: '/core/api/createConfig' }, { text: 'createConnector', link: '/core/api/createConnector' }, { text: 'createStorage', link: '/core/api/createStorage' }, { text: 'Chains', link: '/core/api/chains' }, { text: 'Connectors', collapsed: true, link: '/core/api/connectors', items: [ { text: 'baseAccount', link: '/core/api/connectors/baseAccount', }, { text: 'injected', link: '/core/api/connectors/injected' }, { text: 'metaMask', link: '/core/api/connectors/metaMask', }, { text: 'mock', link: '/core/api/connectors/mock', }, { text: 'porto', link: '/core/api/connectors/porto', }, { text: 'safe', link: '/core/api/connectors/safe', }, { text: 'walletConnect', link: '/core/api/connectors/walletConnect', }, ], }, { text: 'Transports', collapsed: true, link: '/core/api/transports', items: [ { text: 'custom (EIP-1193)', link: '/core/api/transports/custom', }, { text: 'fallback', link: '/core/api/transports/fallback', }, { text: 'http', link: '/core/api/transports/http', }, { text: 'unstable_connector', link: '/core/api/transports/unstable_connector', }, { text: 'webSocket', link: '/core/api/transports/webSocket', }, ], }, ], }, { text: 'Actions', link: '/core/api/actions', items: [ { text: 'call', link: '/core/api/actions/call', }, { text: 'connect', link: '/core/api/actions/connect' }, { text: 'deployContract', link: '/core/api/actions/deployContract' }, { text: 'disconnect', link: '/core/api/actions/disconnect' }, { text: 'estimateFeesPerGas', link: '/core/api/actions/estimateFeesPerGas', }, { text: 'estimateGas', link: '/core/api/actions/estimateGas' }, { text: 'estimateMaxPriorityFeePerGas', link: '/core/api/actions/estimateMaxPriorityFeePerGas', }, { text: 'getBalance', link: '/core/api/actions/getBalance' }, { text: 'getBlobBaseFee', link: '/core/api/actions/getBlobBaseFee', }, { text: 'getBlock', link: '/core/api/actions/getBlock', }, { text: 'getBlockNumber', link: '/core/api/actions/getBlockNumber', }, { text: 'getBlockTransactionCount', link: '/core/api/actions/getBlockTransactionCount', }, { text: 'getBytecode', link: '/core/api/actions/getBytecode', }, { text: 'getCallsStatus', link: '/core/api/actions/getCallsStatus', }, { text: 'getCapabilities', link: '/core/api/actions/getCapabilities', }, { text: 'getChainId', link: '/core/api/actions/getChainId' }, { text: 'getChains', link: '/core/api/actions/getChains' }, { text: 'getClient', link: '/core/api/actions/getClient', }, { text: 'getConnection', link: '/core/api/actions/getConnection' }, { text: 'getConnections', link: '/core/api/actions/getConnections', }, { text: 'getConnectorClient', link: '/core/api/actions/getConnectorClient', }, { text: 'getConnectors', link: '/core/api/actions/getConnectors', }, { text: 'getContractEvents', link: '/core/api/actions/getContractEvents', }, { text: 'getEnsAddress', link: '/core/api/actions/getEnsAddress', }, { text: 'getEnsAvatar', link: '/core/api/actions/getEnsAvatar' }, { text: 'getEnsName', link: '/core/api/actions/getEnsName' }, { text: 'getEnsResolver', link: '/core/api/actions/getEnsResolver', }, { text: 'getEnsText', link: '/core/api/actions/getEnsText', }, { text: 'getFeeHistory', link: '/core/api/actions/getFeeHistory', }, { text: 'getGasPrice', link: '/core/api/actions/getGasPrice', }, { text: 'getProof', link: '/core/api/actions/getProof', }, { text: 'getPublicClient', link: '/core/api/actions/getPublicClient', }, { text: 'getStorageAt', link: '/core/api/actions/getStorageAt', }, { text: 'getTransaction', link: '/core/api/actions/getTransaction', }, { text: 'getTransactionConfirmations', link: '/core/api/actions/getTransactionConfirmations', }, { text: 'getTransactionCount', link: '/core/api/actions/getTransactionCount', }, { text: 'getTransactionReceipt', link: '/core/api/actions/getTransactionReceipt', }, { text: 'getWalletClient', link: '/core/api/actions/getWalletClient', }, { text: 'multicall', link: '/core/api/actions/multicall', }, { text: 'prepareTransactionRequest', link: '/core/api/actions/prepareTransactionRequest', }, { text: 'reconnect', link: '/core/api/actions/reconnect' }, { text: 'readContract', link: '/core/api/actions/readContract', }, { text: 'readContracts', link: '/core/api/actions/readContracts', }, { text: 'sendCalls', link: '/core/api/actions/sendCalls', }, { text: 'sendTransaction', link: '/core/api/actions/sendTransaction', }, { text: 'showCallsStatus', link: '/core/api/actions/showCallsStatus', }, { text: 'signMessage', link: '/core/api/actions/signMessage', }, { text: 'signTypedData', link: '/core/api/actions/signTypedData', }, { text: 'simulateContract', link: '/core/api/actions/simulateContract', }, { text: 'switchChain', link: '/core/api/actions/switchChain', }, { text: 'switchConnection', link: '/core/api/actions/switchConnection', }, { text: 'verifyMessage', link: '/core/api/actions/verifyMessage', }, { text: 'verifyTypedData', link: '/core/api/actions/verifyTypedData', }, { text: 'waitForCallsStatus', link: '/core/api/actions/waitForCallsStatus', }, { text: 'waitForTransactionReceipt', link: '/core/api/actions/waitForTransactionReceipt', }, { text: 'watchAsset', link: '/core/api/actions/watchAsset', }, { text: 'watchBlocks', link: '/core/api/actions/watchBlocks', }, { text: 'watchBlockNumber', link: '/core/api/actions/watchBlockNumber', }, { text: 'watchChainId', link: '/core/api/actions/watchChainId', }, { text: 'watchClient', link: '/core/api/actions/watchClient', }, { text: 'watchConnection', link: '/core/api/actions/watchConnection', }, { text: 'watchConnections', link: '/core/api/actions/watchConnections', }, { text: 'watchConnectors', link: '/core/api/actions/watchConnectors', }, { text: 'watchContractEvent', link: '/core/api/actions/watchContractEvent', }, { text: 'watchPendingTransactions', link: '/core/api/actions/watchPendingTransactions', }, { text: 'watchPublicClient', link: '/core/api/actions/watchPublicClient', }, { text: 'writeContract', link: '/core/api/actions/writeContract', }, ], }, { text: 'Miscellaneous', items: [ { text: 'Errors', link: '/core/api/errors' }, { text: 'Utilities', collapsed: true, items: [ { text: 'cookieToInitialState', link: '/core/api/utilities/cookieToInitialState', }, { text: 'deserialize', link: '/core/api/utilities/deserialize' }, { text: 'serialize', link: '/core/api/utilities/serialize' }, ], }, ], }, ], '/cli': [ { text: 'Introduction', items: [ { text: 'Why Wagmi CLI', link: '/cli/why' }, { text: 'Installation', link: '/cli/installation' }, { text: 'Getting Started', link: '/cli/getting-started' }, ], }, { text: 'Guides', items: [ { text: 'Migrate from v1 to v2', link: '/cli/guides/migrate-from-v1-to-v2', }, ], }, { text: 'Config File', items: [ { text: 'Configuring CLI', link: '/cli/config/configuring-cli', }, { text: 'Config Options', link: '/cli/config/options' }, ], }, { text: 'Commands', link: '/cli/api/commands', items: [ { text: 'generate', link: '/cli/api/commands/generate', }, { text: 'init', link: '/cli/api/commands/init', }, ], }, { text: 'Plugins', link: '/cli/api/plugins', items: [ { text: 'actions', link: '/cli/api/plugins/actions' }, { text: 'blockExplorer', link: '/cli/api/plugins/blockExplorer' }, { text: 'etherscan', link: '/cli/api/plugins/etherscan' }, { text: 'fetch', link: '/cli/api/plugins/fetch' }, { text: 'foundry', link: '/cli/api/plugins/foundry' }, { text: 'hardhat', link: '/cli/api/plugins/hardhat' }, { text: 'react', link: '/cli/api/plugins/react' }, { text: 'sourcify', link: '/cli/api/plugins/sourcify' }, ], }, { text: 'create-wagmi', link: '/cli/create-wagmi', }, ], '/solid': [ { text: 'Introduction', items: [ { text: 'Why Wagmi', link: '/solid/why' }, { text: 'Installation', link: '/solid/installation' }, { text: 'Getting Started', link: '/solid/getting-started' }, { text: 'TypeScript', link: '/solid/typescript' }, ], }, { text: 'Guides', items: [ { text: 'TanStack Query', link: '/solid/guides/tanstack-query', }, { text: 'Viem', link: '/solid/guides/viem', }, { text: 'Error Handling', link: '/solid/guides/error-handling', }, { text: 'Connect Wallet', link: '/solid/guides/connect-wallet', }, ], }, { text: 'Configuration', items: [ { text: 'createConfig', link: '/solid/api/createConfig' }, { text: 'createStorage', link: '/solid/api/createStorage' }, { text: 'Chains', link: '/solid/api/chains' }, { text: 'Connectors', collapsed: true, link: '/solid/api/connectors', items: [ { text: 'baseAccount', link: '/solid/api/connectors/baseAccount', }, { text: 'injected', link: '/solid/api/connectors/injected' }, { text: 'metaMask', link: '/solid/api/connectors/metaMask', }, { text: 'mock', link: '/solid/api/connectors/mock', }, { text: 'porto', link: '/solid/api/connectors/porto', }, { text: 'safe', link: '/solid/api/connectors/safe', }, { text: 'walletConnect', link: '/solid/api/connectors/walletConnect', }, ], }, { text: 'Transports', collapsed: true, link: '/solid/api/transports', items: [ { text: 'custom (EIP-1193)', link: '/solid/api/transports/custom', }, { text: 'fallback', link: '/solid/api/transports/fallback', }, { text: 'http', link: '/solid/api/transports/http', }, { text: 'webSocket', link: '/solid/api/transports/webSocket', }, ], }, { text: 'WagmiProvider', link: '/solid/api/WagmiProvider' }, ], }, { text: 'Primitives', link: '/solid/api/primitives', items: [ { text: 'useBalance', link: '/solid/api/primitives/useBalance' }, { text: 'useBlockNumber', link: '/solid/api/primitives/useBlockNumber', }, { text: 'useChainId', link: '/solid/api/primitives/useChainId' }, { text: 'useChains', link: '/solid/api/primitives/useChains' }, { text: 'useClient', link: '/solid/api/primitives/useClient' }, { text: 'useConfig', link: '/solid/api/primitives/useConfig' }, { text: 'useConnect', link: '/solid/api/primitives/useConnect' }, { text: 'useConnection', link: '/solid/api/primitives/useConnection', }, { text: 'useConnectionEffect', link: '/solid/api/primitives/useConnectionEffect', }, { text: 'useConnections', link: '/solid/api/primitives/useConnections', }, { text: 'useConnectorClient', link: '/solid/api/primitives/useConnectorClient', }, { text: 'useConnectors', link: '/solid/api/primitives/useConnectors', }, { text: 'useDisconnect', link: '/solid/api/primitives/useDisconnect', }, { text: 'useReconnect', link: '/solid/api/primitives/useReconnect' }, { text: 'useSwitchChain', link: '/solid/api/primitives/useSwitchChain', }, { text: 'useSwitchConnection', link: '/solid/api/primitives/useSwitchConnection', }, { text: 'useWatchBlockNumber', link: '/solid/api/primitives/useWatchBlockNumber', }, ], }, { text: 'Miscellaneous', items: [ { text: 'Actions', link: '/solid/api/actions' }, { text: 'Errors', link: '/solid/api/errors' }, ], }, ], '/dev': [ { text: 'Dev', items: [ { text: 'Contributing', link: '/dev/contributing' }, { text: 'Creating Connectors', link: '/dev/creating-connectors' }, ], }, ], '/examples': [ { text: 'React', items: [ { text: 'Connect Wallet', link: '/examples/connect-wallet' }, { text: 'Send Transaction', link: '/examples/send-transaction' }, { text: 'Write Contract', link: '/examples/contract-write' }, { text: 'Write Contract (Dynamic Args)', link: '/examples/contract-write-dynamic', }, { text: 'Sign Message', link: '/examples/sign-message' }, { text: 'Sign In With Ethereum', link: '/examples/sign-in-with-ethereum', }, ], }, ], '/tempo': [ { text: 'Tempo', items: [ { text: 'Getting Started', link: '/tempo/getting-started' }, { text: 'Chains', link: '/tempo/chains' }, { text: 'Tempo Docs & Guides', link: 'https://docs.tempo.xyz' }, ], }, { text: 'Hooks', link: '/tempo/hooks/', items: [ { text: 'AMM', collapsed: true, items: [ { text: 'useBurn', link: '/tempo/hooks/amm.useBurn' }, { text: 'useLiquidityBalance', link: '/tempo/hooks/amm.useLiquidityBalance', }, { text: 'useMint', link: '/tempo/hooks/amm.useMint' }, { text: 'usePool', link: '/tempo/hooks/amm.usePool' }, { text: 'useRebalanceSwap', link: '/tempo/hooks/amm.useRebalanceSwap', }, { text: 'useWatchBurn', link: '/tempo/hooks/amm.useWatchBurn' }, { text: 'useWatchFeeSwap', link: '/tempo/hooks/amm.useWatchFeeSwap', }, { text: 'useWatchMint', link: '/tempo/hooks/amm.useWatchMint' }, { text: 'useWatchRebalanceSwap', link: '/tempo/hooks/amm.useWatchRebalanceSwap', }, ], }, { text: 'DEX', collapsed: true, items: [ { text: 'useBalance', link: '/tempo/hooks/dex.useBalance' }, { text: 'useBuy', link: '/tempo/hooks/dex.useBuy' }, { text: 'useBuyQuote', link: '/tempo/hooks/dex.useBuyQuote' }, { text: 'useCancel', link: '/tempo/hooks/dex.useCancel' }, { text: 'useCreatePair', link: '/tempo/hooks/dex.useCreatePair' }, { text: 'useOrder', link: '/tempo/hooks/dex.useOrder' }, { text: 'usePlace', link: '/tempo/hooks/dex.usePlace' }, { text: 'usePlaceFlip', link: '/tempo/hooks/dex.usePlaceFlip' }, { text: 'useSell', link: '/tempo/hooks/dex.useSell' }, { text: 'useSellQuote', link: '/tempo/hooks/dex.useSellQuote' }, { text: 'useTickLevel', link: '/tempo/hooks/dex.useTickLevel' }, { text: 'useWatchFlipOrderPlaced', link: '/tempo/hooks/dex.useWatchFlipOrderPlaced', }, { text: 'useWatchOrderCancelled', link: '/tempo/hooks/dex.useWatchOrderCancelled', }, { text: 'useWatchOrderFilled', link: '/tempo/hooks/dex.useWatchOrderFilled', }, { text: 'useWatchOrderPlaced', link: '/tempo/hooks/dex.useWatchOrderPlaced', }, { text: 'useWithdraw', link: '/tempo/hooks/dex.useWithdraw' }, ], }, { text: 'Faucet', collapsed: true, items: [{ text: 'useFund', link: '/tempo/hooks/faucet.useFund' }], }, { text: 'Fee', collapsed: true, items: [ { text: 'useSetUserToken', link: '/tempo/hooks/fee.useSetUserToken', }, { text: 'useUserToken', link: '/tempo/hooks/fee.useUserToken' }, { text: 'useWatchSetUserToken', link: '/tempo/hooks/fee.useWatchSetUserToken', }, ], }, { text: 'Nonce', collapsed: true, items: [ { text: 'useNonce', link: '/tempo/hooks/nonce.useNonce' }, { text: 'useNonceKeyCount', link: '/tempo/hooks/nonce.useNonceKeyCount', }, { text: 'useWatchActiveKeyCountChanged', link: '/tempo/hooks/nonce.useWatchActiveKeyCountChanged', }, { text: 'useWatchNonceIncremented', link: '/tempo/hooks/nonce.useWatchNonceIncremented', }, ], }, { text: 'Policy', collapsed: true, items: [ { text: 'useCreate', link: '/tempo/hooks/policy.useCreate' }, { text: 'useData', link: '/tempo/hooks/policy.useData' }, { text: 'useIsAuthorized', link: '/tempo/hooks/policy.useIsAuthorized', }, { text: 'useModifyBlacklist', link: '/tempo/hooks/policy.useModifyBlacklist', }, { text: 'useModifyWhitelist', link: '/tempo/hooks/policy.useModifyWhitelist', }, { text: 'useSetAdmin', link: '/tempo/hooks/policy.useSetAdmin' }, { text: 'useWatchAdminUpdated', link: '/tempo/hooks/policy.useWatchAdminUpdated', }, { text: 'useWatchBlacklistUpdated', link: '/tempo/hooks/policy.useWatchBlacklistUpdated', }, { text: 'useWatchCreate', link: '/tempo/hooks/policy.useWatchCreate', }, { text: 'useWatchWhitelistUpdated', link: '/tempo/hooks/policy.useWatchWhitelistUpdated', }, ], }, { text: 'Reward', collapsed: true, items: [ { text: 'useClaim', link: '/tempo/hooks/reward.useClaim' }, { text: 'useSetRecipient', link: '/tempo/hooks/reward.useSetRecipient', }, { text: 'useStart', link: '/tempo/hooks/reward.useStart' }, { text: 'useUserRewardInfo', link: '/tempo/hooks/reward.useUserRewardInfo', }, { text: 'useWatchRewardRecipientSet', link: '/tempo/hooks/reward.useWatchRewardRecipientSet', }, { text: 'useWatchRewardScheduled', link: '/tempo/hooks/reward.useWatchRewardScheduled', }, ], }, { text: 'Token', collapsed: true, items: [ { text: 'useApprove', link: '/tempo/hooks/token.useApprove' }, { text: 'useBurn', link: '/tempo/hooks/token.useBurn' }, { text: 'useBurnBlocked', link: '/tempo/hooks/token.useBurnBlocked', }, { text: 'useChangeTransferPolicy', link: '/tempo/hooks/token.useChangeTransferPolicy', }, { text: 'useCreate', link: '/tempo/hooks/token.useCreate' }, { text: 'useGetAllowance', link: '/tempo/hooks/token.useGetAllowance', }, { text: 'useGetBalance', link: '/tempo/hooks/token.useGetBalance', }, { text: 'useGetMetadata', link: '/tempo/hooks/token.useGetMetadata', }, { text: 'useGrantRoles', link: '/tempo/hooks/token.useGrantRoles', }, { text: 'useHasRole', link: '/tempo/hooks/token.useHasRole' }, { text: 'useMint', link: '/tempo/hooks/token.useMint' }, { text: 'usePause', link: '/tempo/hooks/token.usePause' }, { text: 'useRenounceRoles', link: '/tempo/hooks/token.useRenounceRoles', }, { text: 'useRevokeRoles', link: '/tempo/hooks/token.useRevokeRoles', }, { text: 'useSetRoleAdmin', link: '/tempo/hooks/token.useSetRoleAdmin', }, { text: 'useSetSupplyCap', link: '/tempo/hooks/token.useSetSupplyCap', }, { text: 'useTransfer', link: '/tempo/hooks/token.useTransfer' }, { text: 'useUnpause', link: '/tempo/hooks/token.useUnpause' }, { text: 'useWatchAdminRole', link: '/tempo/hooks/token.useWatchAdminRole', }, { text: 'useWatchApprove', link: '/tempo/hooks/token.useWatchApprove', }, { text: 'useWatchBurn', link: '/tempo/hooks/token.useWatchBurn' }, { text: 'useWatchCreate', link: '/tempo/hooks/token.useWatchCreate', }, { text: 'useWatchMint', link: '/tempo/hooks/token.useWatchMint' }, { text: 'useWatchRole', link: '/tempo/hooks/token.useWatchRole' }, { text: 'useWatchTransfer', link: '/tempo/hooks/token.useWatchTransfer', }, ], }, ], }, { text: 'Actions', link: '/tempo/actions/', items: [ { text: 'AMM', collapsed: true, items: [ { text: 'burn', link: '/tempo/actions/amm.burn' }, { text: 'getLiquidityBalance', link: '/tempo/actions/amm.getLiquidityBalance', }, { text: 'getPool', link: '/tempo/actions/amm.getPool' }, { text: 'mint', link: '/tempo/actions/amm.mint' }, { text: 'rebalanceSwap', link: '/tempo/actions/amm.rebalanceSwap', }, { text: 'watchBurn', link: '/tempo/actions/amm.watchBurn' }, { text: 'watchFeeSwap', link: '/tempo/actions/amm.watchFeeSwap' }, { text: 'watchMint', link: '/tempo/actions/amm.watchMint' }, { text: 'watchRebalanceSwap', link: '/tempo/actions/amm.watchRebalanceSwap', }, ], }, { text: 'DEX', collapsed: true, items: [ { text: 'buy', link: '/tempo/actions/dex.buy' }, { text: 'cancel', link: '/tempo/actions/dex.cancel' }, { text: 'createPair', link: '/tempo/actions/dex.createPair' }, { text: 'getBalance', link: '/tempo/actions/dex.getBalance' }, { text: 'getBuyQuote', link: '/tempo/actions/dex.getBuyQuote' }, { text: 'getOrder', link: '/tempo/actions/dex.getOrder' }, { text: 'getSellQuote', link: '/tempo/actions/dex.getSellQuote' }, { text: 'getTickLevel', link: '/tempo/actions/dex.getTickLevel' }, { text: 'place', link: '/tempo/actions/dex.place' }, { text: 'placeFlip', link: '/tempo/actions/dex.placeFlip' }, { text: 'sell', link: '/tempo/actions/dex.sell' }, { text: 'watchFlipOrderPlaced', link: '/tempo/actions/dex.watchFlipOrderPlaced', }, { text: 'watchOrderCancelled', link: '/tempo/actions/dex.watchOrderCancelled', }, { text: 'watchOrderFilled', link: '/tempo/actions/dex.watchOrderFilled', }, { text: 'watchOrderPlaced', link: '/tempo/actions/dex.watchOrderPlaced', }, { text: 'withdraw', link: '/tempo/actions/dex.withdraw' }, ], }, { text: 'Faucet', collapsed: true, items: [{ text: 'fund', link: '/tempo/actions/faucet.fund' }], }, { text: 'Fee', collapsed: true, items: [ { text: 'getUserToken', link: '/tempo/actions/fee.getUserToken' }, { text: 'setUserToken', link: '/tempo/actions/fee.setUserToken' }, { text: 'watchSetUserToken', link: '/tempo/actions/fee.watchSetUserToken', }, ], }, { text: 'Nonce', collapsed: true, items: [ { text: 'getNonce', link: '/tempo/actions/nonce.getNonce' }, { text: 'getNonceKeyCount', link: '/tempo/actions/nonce.getNonceKeyCount', }, { text: 'watchActiveKeyCountChanged', link: '/tempo/actions/nonce.watchActiveKeyCountChanged', }, { text: 'watchNonceIncremented', link: '/tempo/actions/nonce.watchNonceIncremented', }, ], }, { text: 'Policy', collapsed: true, items: [ { text: 'create', link: '/tempo/actions/policy.create' }, { text: 'getData', link: '/tempo/actions/policy.getData' }, { text: 'isAuthorized', link: '/tempo/actions/policy.isAuthorized', }, { text: 'modifyBlacklist', link: '/tempo/actions/policy.modifyBlacklist', }, { text: 'modifyWhitelist', link: '/tempo/actions/policy.modifyWhitelist', }, { text: 'setAdmin', link: '/tempo/actions/policy.setAdmin' }, { text: 'watchAdminUpdated', link: '/tempo/actions/policy.watchAdminUpdated', }, { text: 'watchBlacklistUpdated', link: '/tempo/actions/policy.watchBlacklistUpdated', }, { text: 'watchCreate', link: '/tempo/actions/policy.watchCreate', }, { text: 'watchWhitelistUpdated', link: '/tempo/actions/policy.watchWhitelistUpdated', }, ], }, { text: 'Reward', collapsed: true, items: [ { text: 'claim', link: '/tempo/actions/reward.claim' }, { text: 'getUserRewardInfo', link: '/tempo/actions/reward.getUserRewardInfo', }, { text: 'setRecipient', link: '/tempo/actions/reward.setRecipient', }, { text: 'start', link: '/tempo/actions/reward.start' }, { text: 'watchRewardRecipientSet', link: '/tempo/actions/reward.watchRewardRecipientSet', }, { text: 'watchRewardScheduled', link: '/tempo/actions/reward.watchRewardScheduled', }, ], }, { text: 'Token', collapsed: true, items: [ { text: 'approve', link: '/tempo/actions/token.approve' }, { text: 'burn', link: '/tempo/actions/token.burn' }, { text: 'burnBlocked', link: '/tempo/actions/token.burnBlocked' }, { text: 'changeTransferPolicy', link: '/tempo/actions/token.changeTransferPolicy', }, { text: 'create', link: '/tempo/actions/token.create' }, { text: 'getAllowance', link: '/tempo/actions/token.getAllowance', }, { text: 'getBalance', link: '/tempo/actions/token.getBalance' }, { text: 'getMetadata', link: '/tempo/actions/token.getMetadata' }, { text: 'grantRoles', link: '/tempo/actions/token.grantRoles' }, { text: 'hasRole', link: '/tempo/actions/token.hasRole' }, { text: 'mint', link: '/tempo/actions/token.mint' }, { text: 'pause', link: '/tempo/actions/token.pause' }, { text: 'renounceRoles', link: '/tempo/actions/token.renounceRoles', }, { text: 'revokeRoles', link: '/tempo/actions/token.revokeRoles' }, { text: 'setRoleAdmin', link: '/tempo/actions/token.setRoleAdmin', }, { text: 'setSupplyCap', link: '/tempo/actions/token.setSupplyCap', }, { text: 'transfer', link: '/tempo/actions/token.transfer' }, { text: 'unpause', link: '/tempo/actions/token.unpause' }, { text: 'watchAdminRole', link: '/tempo/actions/token.watchAdminRole', }, { text: 'watchApprove', link: '/tempo/actions/token.watchApprove', }, { text: 'watchBurn', link: '/tempo/actions/token.watchBurn' }, { text: 'watchCreate', link: '/tempo/actions/token.watchCreate' }, { text: 'watchMint', link: '/tempo/actions/token.watchMint' }, { text: 'watchRole', link: '/tempo/actions/token.watchRole' }, { text: 'watchTransfer', link: '/tempo/actions/token.watchTransfer', }, ], }, ], }, { text: 'Connectors', link: '/tempo/connectors/', items: [ { text: 'dangerous_secp256k1', link: '/tempo/connectors/dangerous_secp256k1', }, { text: 'webAuthn', link: '/tempo/connectors/webAuthn' }, ], }, { text: 'Key Managers', link: '/tempo/keyManagers/', items: [ { text: 'http', link: '/tempo/keyManagers/http' }, { text: 'localStorage', link: '/tempo/keyManagers/localStorage' }, ], }, ], } satisfies DefaultTheme.Sidebar } ================================================ FILE: site/.vitepress/theme/components/AsideSponsors.vue ================================================ ================================================ FILE: site/.vitepress/theme/components/Banner.vue ================================================ // TODO: Dismissable, a11y, etc. // https://github.com/faker-js/faker/pull/1487 ================================================ FILE: site/.vitepress/theme/components/HomeBanner.vue ================================================ ================================================ FILE: site/.vitepress/theme/components/HomePage.vue ================================================ ================================================ FILE: site/.vitepress/theme/composables/useSponsors.ts ================================================ import { onMounted, ref } from 'vue' type Sponsor = { name: string img: string url: string } type Data = { size: 'big' | 'medium' | 'small' items: Sponsor[] tier: string type: 'platinum' | 'gold' | 'silver' }[] // shared data across instances so we load only once. const data = ref() // TODO: Data powered // const dataHost = 'https://sponsors.vuejs.org' // const dataUrl = `${dataHost}/vite.json` export function useSponsors() { onMounted(async () => { if (data.value) return // const result = await fetch(dataUrl) // const json = await result.json() // console.log(json) const sponsors = { platinum: [ { name: 'Paradigm', url: 'https://paradigm.xyz', img: 'paradigm-light.svg', }, { name: 'Tempo', url: 'https://tempo.xyz', img: 'tempo-light.svg', }, ], gold: [ { name: 'Stripe', url: 'https://www.stripe.com', img: 'stripe-light.svg', }, ], silver: [ { name: 'Family', url: 'https://twitter.com/family', img: 'family-light.svg', }, { name: 'Context', url: 'https://twitter.com/context', img: 'context-light.svg', }, { name: 'SushiSwap', url: 'https://www.sushi.com', img: 'sushi-light.svg', }, { name: 'Dynamic', url: 'https://www.dynamic.xyz', img: 'dynamic-light.svg', }, { name: 'Privy', url: 'https://privy.io', img: 'privy-light.svg', }, { name: 'PancakeSwap', url: 'https://pancakeswap.finance', img: 'pancake-light.svg', }, { name: 'Pimlico', url: 'https://pimlico.io', img: 'pimlico-light.svg', }, { name: 'Zora', url: 'https://zora.co', img: 'zora-light.svg', }, { name: 'Syndicate', url: 'https://syndicate.io', img: 'syndicate-light.svg', }, { name: 'Relay', url: 'https://relay.link', img: 'relay-light.svg', }, { name: 'Polymarket', url: 'https://polymarket.com', img: 'polymarket-light.svg', }, { name: 'Sequence', url: 'https://sequence.xyz', img: 'sequence-light.svg', }, { name: 'Web3Auth', url: 'https://web3auth.io', img: 'web3auth-light.svg', }, ], } data.value = mapSponsors(sponsors) }) return { data } } function mapSponsors(sponsors: { platinum: Sponsor[] gold: Sponsor[] silver: Sponsor[] }) { return [ { size: 'big', items: mapImgPath(sponsors.platinum), tier: 'Collaborators', type: 'platinum', }, { size: 'medium', items: mapImgPath(sponsors.gold), tier: 'Large Enterprises', type: 'gold', }, { size: 'small', items: mapImgPath(sponsors.silver), tier: 'Small Enterprises', type: 'silver', }, ] satisfies Data } function mapImgPath(sponsors: Sponsor[]) { return sponsors.map((sponsor) => ({ ...sponsor, img: `https://raw.githubusercontent.com/wevm/.github/main/content/sponsors/${sponsor.img}`, })) } ================================================ FILE: site/.vitepress/theme/index.ts ================================================ import TwoslashFloatingVue from '@shikijs/vitepress-twoslash/client' import type { EnhanceAppContext, Theme } from 'vitepress' import DefaultTheme from 'vitepress/theme' // https://vitepress.dev/guide/custom-theme import { h } from 'vue' import 'virtual:uno.css' import 'virtual:group-icons.css' import '@shikijs/vitepress-twoslash/style.css' import './style.css' import AsideSponsors from './components/AsideSponsors.vue' // import Banner from './components/Banner.vue' import HomeBanner from './components/HomeBanner.vue' import HomePage from './components/HomePage.vue' export default { extends: DefaultTheme, Layout() { // https://vitepress.dev/guide/extending-default-theme#layout-slots return h(DefaultTheme.Layout, null, { 'aside-ads-before': () => h(AsideSponsors), // 'doc-before': () => h(Banner), 'home-features-after': () => h(HomePage), 'home-hero-before': () => h(HomeBanner), }) }, enhanceApp({ app }: EnhanceAppContext) { app.use(TwoslashFloatingVue) }, } satisfies Theme ================================================ FILE: site/.vitepress/theme/style.css ================================================ /** * Customize default theme styling by overriding CSS variables: * https://github.com/vuejs/vitepress/blob/main/src/client/theme-default/styles/vars.css */ /** * Colors * * Each colors have exact same color scale system with 3 levels of solid * colors with different brightness, and 1 soft color. * * - `XXX-1`: The most solid color used mainly for colored text. It must * satisfy the contrast ratio against when used on top of `XXX-soft`. * * - `XXX-2`: The color used mainly for hover state of the button. * * - `XXX-3`: The color for solid background, such as bg color of the button. * It must satisfy the contrast ratio with pure white (#ffffff) text on * top of it. * * - `XXX-soft`: The color used for subtle background such as custom container * or badges. It must satisfy the contrast ratio when putting `XXX-1` colors * on top of it. * * The soft color must be semi transparent alpha channel. This is crucial * because it allows adding multiple "soft" colors on top of each other * to create a accent, such as when having inline code block inside * custom containers. * * - `default`: The color used purely for subtle indication without any * special meanings attached to it such as bg color for menu hover state. * * - `brand`: Used for primary brand colors, such as link text, button with * brand theme, etc. * * - `tip`: Used to indicate useful information. The default theme uses the * brand color for this by default. * * - `warning`: Used to indicate warning to the users. Used in custom * container, badges, etc. * * - `danger`: Used to show error, or dangerous message to the users. Used * in custom container, badges, etc. * -------------------------------------------------------------------------- */ :root { --vp-c-default-1: var(--vp-c-gray-1); --vp-c-default-2: var(--vp-c-gray-2); --vp-c-default-3: var(--vp-c-gray-3); --vp-c-default-soft: var(--vp-c-gray-soft); --vp-c-brand-1: var(--vp-c-indigo-1); --vp-c-brand-2: var(--vp-c-indigo-2); --vp-c-brand-3: var(--vp-c-indigo-3); --vp-c-brand-soft: var(--vp-c-indigo-soft); --vp-c-tip-1: var(--vp-c-brand-1); --vp-c-tip-2: var(--vp-c-brand-2); --vp-c-tip-3: var(--vp-c-brand-3); --vp-c-tip-soft: var(--vp-c-brand-soft); --vp-c-warning-1: var(--vp-c-yellow-1); --vp-c-warning-2: var(--vp-c-yellow-2); --vp-c-warning-3: var(--vp-c-yellow-3); --vp-c-warning-soft: var(--vp-c-yellow-soft); --vp-c-danger-1: var(--vp-c-red-1); --vp-c-danger-2: var(--vp-c-red-2); --vp-c-danger-3: var(--vp-c-red-3); --vp-c-danger-soft: var(--vp-c-red-soft); } /** * Component: Button * -------------------------------------------------------------------------- */ :root { --vp-button-brand-border: transparent; --vp-button-brand-text: var(--vp-c-white); --vp-button-brand-bg: var(--vp-c-brand-3); --vp-button-brand-hover-border: transparent; --vp-button-brand-hover-text: var(--vp-c-white); --vp-button-brand-hover-bg: var(--vp-c-brand-2); --vp-button-brand-active-border: transparent; --vp-button-brand-active-text: var(--vp-c-white); --vp-button-brand-active-bg: var(--vp-c-brand-1); } /** * Component: Home * -------------------------------------------------------------------------- */ :root { --vp-home-hero-name-color: transparent; --vp-home-hero-name-background: -webkit-linear-gradient( 120deg, var(--vp-c-brand-1) 30%, var(--vp-c-brand-3) ); --vp-home-hero-image-background-image: linear-gradient( -45deg, var(--vp-c-brand-1) 50%, var(--vp-c-brand-3) 50% ); --vp-home-hero-image-filter: blur(44px); } @media (min-width: 640px) { :root { --vp-home-hero-image-filter: blur(56px); } } @media (min-width: 960px) { :root { --vp-home-hero-image-filter: blur(68px); } } /** * Component: Custom Block * -------------------------------------------------------------------------- */ :root { --vp-custom-block-tip-border: transparent; --vp-custom-block-tip-text: var(--vp-c-text-1); --vp-custom-block-tip-bg: var(--vp-c-brand-soft); --vp-custom-block-tip-code-bg: var(--vp-c-brand-soft); } /** * Component: Algolia * -------------------------------------------------------------------------- */ .DocSearch { --docsearch-primary-color: var(--vp-c-brand-1) !important; } .vp-doc [class*="language-"] .has-focused-lines .line:not(.has-focus) { filter: unset; opacity: 0.3; } /** * twoslash * -------------------------------------------------------------------------- */ .twoslash-error-line { max-width: min-content; white-space: wrap; } html.dark .shiki, html.dark .shiki span { color: var(--shiki-dark) !important; background-color: var(--shiki-dark-bg) !important; /* Optional, if you also want font styles */ font-style: var(--shiki-dark-font-style) !important; font-weight: var(--shiki-dark-font-weight) !important; text-decoration: var(--shiki-dark-text-decoration) !important; } ================================================ FILE: site/AGENTS.md ================================================ # Agent Guidelines Agent guidance for the Wagmi documentation site. > **Communication Style**: Be brief, concise. Maximize information density, minimize tokens. Incomplete sentences acceptable when clear. Remove filler words. Prioritize clarity over grammar. ## Tempo - All Tempo documentation must be added under the `/tempo` sidebar item. ## Wagmi Actions - **All documentation must be based on their corresponding Wagmi actions** from `@wagmi/core/tempo` (`packages/core/src/tempo/`) - Make sure you update `site/tempo/actions/index.md` for new actions ### Query Actions ````md # `namespace.action` description ## Usage ::: code-group ```ts twoslash [example.ts] // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' import { tempoTestnet } from 'wagmi/chains' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const result = await Actions.amm.action(config, { foo: '0x...', bar: 123n, }) console.log('Result:', result) // @log: Result: 10500000000000000000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `bigint` description ## Parameters ### foo - **Type:** `Address` description ### bar - **Type:** `bigint` description ### baz (optional) - **Type:** `Hex` description ## Viem - [`namespace.action`](https://viem.sh/tempo/actions/namespace.action) ```` ### Mutation Actions ````md # `namespace.action` description ## Usage ::: code-group ```ts twoslash [example.ts] // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' import { tempoTestnet } from 'wagmi/chains' export const config = {} as Config // ---cut--- // @filename: example.ts import { Actions } from 'wagmi/tempo' import { config } from './config' const result = await Actions.namespace.actionSync(config, { foo: '0x...', bar: 123n, }) console.log('Foo:', result.foo) // @log: Foo: 5250000000000000000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `namespace.action` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.namespace.action(config, { foo: '0x...', bar: 123n, }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args: { baz } } = viem_Actions.namespace.action.extractEvent(receipt.logs) ``` ## Return Type description ```ts type ReturnType = { /** description */ baz: bigint } ``` ## Parameters ### foo - **Type:** `Address` description ### bar - **Type:** `bigint` description ## Viem - [`namespace.action`](https://viem.sh/tempo/actions/namespace.action) ```` ### Watch Actions ````md # `namespace.watchAction` description ## Usage ::: code-group ```ts twoslash [example.ts] // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' import { tempoTestnet } from 'wagmi/chains' export const config = {} as Config // ---cut--- // @filename: example.ts import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.namespace.watchAction(config, { onAction(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `() => void` Returns a function to unsubscribe from the event. ## Parameters ### onAction - **Type:** `function` ```ts declare function onBurn(args: Args, log: Log): void type Args = { /** description */ foo: bigint /** description */ barBaz: bigint } ``` Callback to invoke when action occurs. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `function` ```ts declare function onError(error: Error): void ``` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Enable polling mode. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`namespace.action`](https://viem.sh/tempo/actions/namespace.action) ```` ## Wagmi Hooks - **All documentation must be based on their corresponding Wagmi hooks** from `wagmi/tempo` (`packages/react/src/tempo/`) - Make sure you update `site/tempo/hooks/index.md` for new actions ### Query Hooks An example of a generated hook set can be found in `hooks/amm.useLiquidityBalance.ts`. Template example: ````md # `namespace.useHook` description ## Usage ::: code-group ```ts twoslash [example.ts] import { Hooks } from 'wagmi/tempo' const { data: result } = Hooks.namespace.useHook({ foo: '0x...', bar: 123n, }) console.log('Result:', resut) // @log: Result: ... ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type See [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook return types. ### data See [Wagmi Action `namespace.action` Return Type](/tempo/actions/namespace.action#return-type) ## Parameters See [Wagmi Action `namespace.action` Parameters](/tempo/actions/namespace.action#parameters) ### query See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook parameters. ## Action - [`namespace.action`](/tempo/actions/namespace.action) ```` ### Mutation Hooks ````md # `namespace.useHook` description ## Usage ::: code-group ```ts twoslash [example.ts] import { Hooks } from 'wagmi/tempo' const actionNameSync = Hooks.namespace.useHookSync() // Call `mutate` in response to user action (e.g. button click, form submission) actionNameSync.mutate({ foo: '0x...', bar: 123n, }) console.log('Received baz:', actionNameSync.data?.baz) // @log: Received baz: ... ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `amm.burn` action and wait for inclusion manually: ```ts import { Actions } from 'viem/tempo' import { Hooks } from 'wagmi/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const actionName = Hooks.namespace.useHook() const { data: receipt } = useWaitForTransactionReceipt({ hash: actionName.data }) // Call `mutate` in response to user action (e.g. button click, form submission) actionName.mutate({ foo: '0x...', bar: 123n, }) if (receipt) { const { args: { baz } } = Actions.namespace.action.extractEvent(receipt.logs) } ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `namespace.action` Return Type](/tempo/actions/namespace.action#return-type) ### mutate/mutateAsync See [Wagmi Action `namespace.action` Parameters](/tempo/actions/namespace.action#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`namespace.action`](/tempo/actions/namespace.action) ```` ### Watch Hooks ````md # `namespace.useWatchHook` description ## Usage ::: code-group ```ts twoslash [example.ts] import { Hooks } from 'wagmi/tempo' Hooks.amm.useWatchHook({ onAction(args, log) { console.log('args:', args) }, }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `namespace.watchAction` Parameters](/tempo/actions/namespace.watchAction#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`namespace.action`](/tempo/actions/namespace.action) - [`namespace.watchAction`](/tempo/actions/namespace.watchAction) ```` ================================================ FILE: site/cli/api/commands/generate.md ================================================ # generate Generates code based on configuration, using `contracts` and `plugins`. ## Usage ```bash wagmi generate ``` ## Options ### -c, --config \ `string` Path to config file. ```bash wagmi generate --config wagmi.config.ts ``` ### -r, --root \ `string` Root path to resolve config from. ```bash wagmi generate --root path/to/root ``` ### -w, --watch `boolean` Watch for changes (for plugins that support watch mode). ```bash wagmi generate --watch ``` ### -h, --help Displays help message. ```bash wagmi generate --help ``` ================================================ FILE: site/cli/api/commands/init.md ================================================ # init Creates configuration file. If TypeScript is detected, the config file will use TypeScript and be named `wagmi.config.ts`. Otherwise, the config file will use JavaScript and be named `wagmi.config.js`. ## Usage ```bash wagmi init ``` ## Options ### -c, --config \ `string` Path to config file. ```bash wagmi init --config wagmi.config.ts ``` ### -r, --root \ `string` Root path to resolve config from. ```bash wagmi init --root path/to/root ``` ### -h, --help Displays help message. ```bash wagmi init --help ``` ================================================ FILE: site/cli/api/commands.md ================================================ # Commands ## Available Commands - [`init`](/cli/api/commands/init) Creates configuration file. - [`generate`](/cli/api/commands/generate) Generates code based on configuration, using `contracts` and `plugins`. ## Display Info ### `-h`, `--help` Show help message when `-h`, `--help` flags appear. ::: code-group ```bash [pnpm] pnpm wagmi --help ``` ```bash [npm] npx wagmi --help ``` ```bash [yarn] yarn wagmi --help ``` ```bash [bun] bun wagmi --help ``` ::: ### `-v`, `--version` Show version number when `-v`, `--version` flags appear. ::: code-group ```bash [pnpm] pnpm wagmi --version ``` ```bash [npm] npx wagmi --version ``` ```bash [yarn] yarn wagmi --version ``` ```bash [bun] bun wagmi --version ``` ::: ================================================ FILE: site/cli/api/plugins/actions.md ================================================ # actions Plugin for type-safe VanillaJS actions. ## Import ```ts import { actions } from '@wagmi/cli/plugins' ``` ## Usage ```ts{2,6} import { defineConfig } from '@wagmi/cli' import { actions } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ actions(), ], }) ``` ## Configuration ```ts import { type ActionsConfig } from '@wagmi/cli/plugins' ``` ### getActionName `` 'legacy' | ((options: { contractName: string; type: 'read' | 'simulate' | 'watch' | 'write' }) => `use${string}`) `` - Function for setting custom hook names. - Defaults to `` `${type}${contractName}` ``. For example, `readErc20`, `simulateErc20`, `watchErc20Event`, `writeErc20`. - When `'legacy'` (deprecated), hook names are set to `@wagmi/cli@1` format. ```ts import { defineConfig } from '@wagmi/cli' import { actions } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ actions({ getActionName({ contractName, type }) { // [!code focus] return `${contractName}__${type}` // [!code focus] }, // [!code focus] }), ], }) ``` ### overridePackageName `'@wagmi/core' | 'wagmi'` - Override detected import source. - Defaults to `'wagmi'` or `'@wagmi/core'` depending on which package is installed. ```ts import { defineConfig } from '@wagmi/cli' import { actions } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ actions({ overridePackageName: 'wagmi', // [!code focus] }), ], }) ``` ================================================ FILE: site/cli/api/plugins/blockExplorer.md ================================================ # blockExplorer Plugin for fetching ABIs from block explorers that supports the `?module=contract&action=getabi` API format. ## Import ```ts import { blockExplorer } from '@wagmi/cli/plugins' ``` ## Usage ```ts{2,6-14} import { defineConfig } from '@wagmi/cli' import { blockExplorer } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ blockExplorer({ baseUrl: 'https://api.etherscan.io/v2/api', contracts: [ { name: 'Wagmigotchi', address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', }, ], }), ], }) ``` ## Configuration ```ts import { type BlockExplorerConfig } from '@wagmi/cli/plugins' ``` ### apiKey `string | undefined` API key for block explorer. Appended to the request URL as query param `&apikey=${apiKey}`. ```ts import { defineConfig } from '@wagmi/cli' import { blockExplorer } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ blockExplorer({ apiKey: process.env.ETHERSCAN_API_KEY, // [!code focus] baseUrl: 'https://api.etherscan.io/v2/api', contracts: [ { name: 'Wagmigotchi', address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', }, ], }), ], }) ``` ### baseUrl `string` Base URL for block explorer. ```ts import { defineConfig } from '@wagmi/cli' import { blockExplorer } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ blockExplorer({ baseUrl: 'https://api.etherscan.io/v2/api', // [!code focus] contracts: [ { name: 'Wagmigotchi', address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', }, ], }), ], }) ``` ### cacheDuration `number | undefined` Duration in milliseconds to cache ABIs. Defaults to `1_800_000` (30 minutes). ```ts import { defineConfig } from '@wagmi/cli' import { blockExplorer } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ blockExplorer({ baseUrl: 'https://api.etherscan.io/v2/api', cacheDuration: 300_000, // [!code focus] contracts: [ { name: 'Wagmigotchi', address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', }, ], }), ], }) ``` ### chainId `number | undefined` Chain ID for block explorer. Appended to the request URL as query param `&chainId=${chainId}`. ```ts import { defineConfig } from '@wagmi/cli' import { blockExplorer } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ blockExplorer({ apiKey: process.env.ETHERSCAN_API_KEY, baseUrl: 'https://api.etherscan.io/v2/api', chainId: 1, // [!code focus] contracts: [ { name: 'Wagmigotchi', address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', }, ], }), ], }) ``` ### contracts `{ name: string; address?: Address | Record | undefined }[]` Contracts to fetch ABIs for. ```ts import { defineConfig } from '@wagmi/cli' import { blockExplorer } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ blockExplorer({ baseUrl: 'https://api.etherscan.io/v2/api', contracts: [ // [!code focus] { // [!code focus] name: 'Wagmigotchi', // [!code focus] address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', // [!code focus] }, // [!code focus] ], // [!code focus] }), ], }) ``` ### getAddress `((config: { address: Address | Record }) => Address) | undefined` - Function to get address from contract config. - Defaults to `({ address }) => typeof address === 'string' ? address : Object.values(address)[0]`. ```ts import { defineConfig } from '@wagmi/cli' import { blockExplorer } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ blockExplorer({ baseUrl: 'https://api.etherscan.io/v2/api', contracts: [ { name: 'Wagmigotchi', address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', }, ], getAddress({ address }) { // [!code focus] if (typeof address === 'string') return address // [!code focus] return Object.values(address)[0] // [!code focus] }, // [!code focus] }), ], }) ``` ### name `string` - Name of source. - Defaults to `'Block Explorer'`. ```ts import { defineConfig } from '@wagmi/cli' import { blockExplorer } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ blockExplorer({ baseUrl: 'https://api.etherscan.io/v2/api', contracts: [ { name: 'Wagmigotchi', address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', }, ], name: 'Etherscan', // [!code focus] }), ], }) ``` ================================================ FILE: site/cli/api/plugins/etherscan.md ================================================ # etherscan Plugin for fetching ABIs from [Etherscan](https://etherscan.io) and adding into `contracts` config. ## Import ```ts import { etherscan } from '@wagmi/cli/plugins' ``` ## Usage ```ts{2,6-14} import { defineConfig } from '@wagmi/cli' import { etherscan } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ etherscan({ apiKey: process.env.ETHERSCAN_API_KEY, chainId: 1, contracts: [ { name: 'Wagmigotchi', address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', }, ], }), ], }) ``` ## Configuration ```ts import { type EtherscanConfig } from '@wagmi/cli/plugins' ``` ### apiKey `string` Etherscan API key. Etherscan API keys are specific per network and include testnets (e.g. Ethereum Mainnet and Sepolia share same API key). ```ts import { defineConfig } from '@wagmi/cli' import { etherscan } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ etherscan({ apiKey: process.env.ETHERSCAN_API_KEY, // [!code focus] chainId: 1, contracts: [ { name: 'Wagmigotchi', address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', }, ], }), ], }) ``` ### cacheDuration `number | undefined` - Duration in milliseconds to cache ABIs. - Defaults to `1_800_000` (30 minutes). ```ts import { defineConfig } from '@wagmi/cli' import { etherscan } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ etherscan({ apiKey: process.env.ETHERSCAN_API_KEY, cacheDuration: 300_000, // [!code focus] chainId: 1, contracts: [ { name: 'Wagmigotchi', address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', }, ], }), ], }) ``` ### chainId `number` Chain ID to use for fetching ABI. If [`address`](/cli/config/options#address) is an object, `chainId` is used to select the address. View supported chains on the [Etherscan docs](https://docs.etherscan.io/etherscan-v2/getting-started/supported-chains). ```ts import { defineConfig } from '@wagmi/cli' import { etherscan } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ etherscan({ apiKey: process.env.ETHERSCAN_API_KEY, chainId: 1, // [!code focus] contracts: [ { name: 'Wagmigotchi', address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', }, { name: 'EnsRegistry', address: { 1: '0x314159265dd8dbb310642f98f50c066173c1259b', 5: '0x112234455c3a32fd11230c42e7bccd4a84e02010', }, }, ], }), ], }) ``` ### contracts `{ name: string; address?: Address | Record | undefined }[]` Contracts to fetch ABIs for. ```ts import { defineConfig } from '@wagmi/cli' import { etherscan } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ etherscan({ apiKey: process.env.ETHERSCAN_API_KEY, chainId: 1, contracts: [ // [!code focus] { // [!code focus] name: 'Wagmigotchi', // [!code focus] address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', // [!code focus] }, // [!code focus] ], // [!code focus] }), ], }) ``` ### tryFetchProxyImplementation `boolean | undefined` - Whether to try fetching proxy implementation address of the contract. - Defaults to `false`. ```ts import { defineConfig } from '@wagmi/cli' import { etherscan } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ etherscan({ apiKey: process.env.ETHERSCAN_API_KEY, chainId: 1, contracts: [ { name: 'FiatToken', address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', }, ], tryFetchProxyImplementation: true, // [!code focus] }), ], }) ``` ================================================ FILE: site/cli/api/plugins/fetch.md ================================================ # fetch Plugin for fetching and parsing ABIs from network resource with `fetch`. ## Import ```ts import { fetch } from '@wagmi/cli/plugins' ``` ## Usage ```ts{2,6-23} import { defineConfig } from '@wagmi/cli' import { fetch } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ fetch({ contracts: [ { name: 'Wagmigotchi', address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', }, ], request(contract) { if (!contract.address) throw new Error('address is required') const address = typeof contract.address === 'string' ? contract.address : Object.values(contract.address)[0] return { url: `https://api.etherscan.io/api?module=contract&action=getabi&address=${address}`, } }, }), ], }) ``` ## Configuration ```ts import { type FetchConfig } from '@wagmi/cli/plugins' ``` ### cacheDuration `number | undefined` - Duration in milliseconds to cache ABIs. - Defaults to `1_800_000` (30 minutes). ```ts import { defineConfig } from '@wagmi/cli' import { fetch } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ fetch({ cacheDuration: 300_000, // [!code focus] contracts: [ { name: 'Wagmigotchi', address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', }, ], request(contract) { if (!contract.address) throw new Error('address is required') const address = typeof contract.address === 'string' ? contract.address : Object.values(contract.address)[0] return { url: `https://api.etherscan.io/api?module=contract&action=getabi&address=${address}`, } }, }), ], }) ``` ### contracts `{ name: string; address?: Address | Record | undefined }[]` Contracts to fetch ABIs for. ```ts import { defineConfig } from '@wagmi/cli' import { fetch } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ fetch({ contracts: [ // [!code focus] { // [!code focus] name: 'Wagmigotchi', // [!code focus] address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', // [!code focus] }, // [!code focus] ], // [!code focus] request(contract) { if (!contract.address) throw new Error('address is required') const address = typeof contract.address === 'string' ? contract.address : Object.values(contract.address)[0] return { url: `https://api.etherscan.io/api?module=contract&action=getabi&address=${address}`, } }, }), ], }) ``` ### getCacheKey `((config: { contract: { address: Address | Record | undefined; name: string } }) => string) | undefined` - Function for creating a cache key for contract. Contract data is cached at `~/.wagmi-cli/plugins/fetch/cache/`. - Defaults to `({ contract }) => JSON.stringify(contract)`. ```ts import { defineConfig } from '@wagmi/cli' import { fetch } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ fetch({ contracts: [ { name: 'wagmigotchi', address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', }, ], getCacheKey({ contract }) { // [!code focus] if (typeof contract.address === 'string') // [!code focus] return `${name}:${contract.address}` // [!code focus] return `${name}:${JSON.stringify(contract.address)}` // [!code focus] }, // [!code focus] request(contract) { if (!contract.address) throw new Error('address is required') const address = typeof contract.address === 'string' ? contract.address : Object.values(contract.address)[0] return { url: `https://api.etherscan.io/api?module=contract&action=getabi&address=${address}`, } }, }), ], }) ``` ### name `string` - Name of source. - Defaults to `'Fetch'`. ```ts import { defineConfig } from '@wagmi/cli' import { fetch } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ fetch({ contracts: [ { name: 'Wagmigotchi', address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', }, ], name: 'Etherscan', // [!code focus] request(contract) { if (!contract.address) throw new Error('address is required') const address = typeof contract.address === 'string' ? contract.address : Object.values(contract.address)[0] return { url: `https://api.etherscan.io/api?module=contract&action=getabi&address=${address}`, } }, }), ], }) ``` ### parse `((config: { response: Response }) => Abi | Promise) | undefined` - Function for parsing ABI from fetch response. - Defaults to `({ response }) => response.json()` ```ts import { defineConfig } from '@wagmi/cli' import { fetch } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ fetch({ contracts: [ { name: 'Wagmigotchi', address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', }, ], async parse({ response }) { // [!code focus] const json = await response.json() // [!code focus] if (json.status === '0') throw new Error(json.message) // [!code focus] return json.result // [!code focus] }, // [!code focus] request(contract) { if (!contract.address) throw new Error('address is required') const address = typeof contract.address === 'string' ? contract.address : Object.values(contract.address)[0] return { url: `https://api.etherscan.io/api?module=contract&action=getabi&address=${address}`, } }, }), ], }) ``` ### request `(config: { address?: Address | Record | undefined }) => { url: RequestInfo; init?: RequestInit | undefined } | Promise<{ url: RequestInfo; init?: RequestInit | undefined }>` Function for returning a request to fetch ABI from. ```ts import { defineConfig } from '@wagmi/cli' import { fetch } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ fetch({ contracts: [ { name: 'Wagmigotchi', address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', }, ], request(contract) { // [!code focus] if (!contract.address) throw new Error('address is required') // [!code focus] const address = // [!code focus] typeof contract.address === 'string' // [!code focus] ? contract.address // [!code focus] : Object.values(contract.address)[0] // [!code focus] return { // [!code focus] url: `https://api.etherscan.io/api?module=contract&action=getabi&address=${address}`, // [!code focus] } // [!code focus] }, // [!code focus] }), ], }) ``` ================================================ FILE: site/cli/api/plugins/foundry.md ================================================ # foundry Plugin for resolving ABIs from [Foundry](https://github.com/foundry-rs/foundry) projects. Supports [`watch`](/cli/api/commands/generate#w-watch) mode. ## Import ```ts import { foundry } from '@wagmi/cli/plugins' ``` ## Usage ```ts{2,6-8} import { defineConfig } from '@wagmi/cli' import { foundry } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ foundry({ project: '../hello_foundry', }), ], }) ``` ## Configuration ```ts import { type FoundryConfig } from '@wagmi/cli/plugins' ``` ### artifacts `string | undefined` - Project's artifacts directory. Same as your `foundry.toml`/`forge`s `--out` (`-o`) option. - Defaults to `'out/'`. ```ts import { defineConfig } from '@wagmi/cli' import { foundry } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ foundry({ artifacts: 'out/', // [!code focus] }), ], }) ``` ### includeBroadcasts `boolean | undefined` Automatically detect contract deployments from Foundry's `run-latest.json` files in the `broadcast/` directory. - The `deployments` mapping can be used to override broadcast deployments for the same contract. - Broadcasts are read once when `wagmi generate` runs. To pick up new broadcast deployments after running deploy scripts, rerun the generate command. - Defaults to `false`. ```ts import { defineConfig } from '@wagmi/cli' import { foundry } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ foundry({ includeBroadcasts: true, // [!code focus] }), ], }) ``` ### deployments `{ [key: string]: address?: Address | Record | undefined } | undefined` Mapping of addresses to attach to artifacts. ```ts import { defineConfig } from '@wagmi/cli' import { foundry } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ foundry({ deployments: { // [!code focus] Counter: { // [!code focus] 1: '0x314159265dd8dbb310642f98f50c066173c1259b', // [!code focus] 5: '0x112234455c3a32fd11230c42e7bccd4a84e02010', // [!code focus] }, // [!code focus] }, // [!code focus] }), ], }) ``` ### exclude `string[] | undefined` Artifact files to exclude relative to `artifacts`. Supports glob patterns. ```ts import { defineConfig } from '@wagmi/cli' import { foundry } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ foundry({ exclude: [ // [!code focus] // the following patterns are excluded by default // [!code focus] 'Common.sol/**', // [!code focus] 'Components.sol/**', // [!code focus] 'Script.sol/**', // [!code focus] 'StdAssertions.sol/**', // [!code focus] 'StdInvariant.sol/**', // [!code focus] 'StdError.sol/**', // [!code focus] 'StdCheats.sol/**', // [!code focus] 'StdMath.sol/**', // [!code focus] 'StdJson.sol/**', // [!code focus] 'StdStorage.sol/**', // [!code focus] 'StdUtils.sol/**', // [!code focus] 'Vm.sol/**', // [!code focus] 'console.sol/**', // [!code focus] 'console2.sol/**', // [!code focus] 'test.sol/**', // [!code focus] '**.s.sol/*.json', // [!code focus] '**.t.sol/*.json', // [!code focus] ], // [!code focus] }), ], }) ``` ### forge `{ clean?: boolean | undefined; build?: boolean | undefined; path?: string | undefined; rebuild?: boolean | undefined } | undefined` Options for `forge`. ```ts import { defineConfig } from '@wagmi/cli' import { foundry } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ foundry({ forge: { // [!code focus] clean: true, // [!code focus] build: true, // [!code focus] path: 'path/to/forge', // [!code focus] rebuild: true, // [!code focus] }, // [!code focus] }), ], }) ``` #### clean - Remove build artifacts and cache directories on start up. - Defaults to `false`. #### build - Build Foundry project before fetching artifacts. - Defaults to `true`. #### path - Path to `forge` executable command. - Defaults to `forge`. #### rebuild - Rebuild every time a watched file or directory is changed. Used for setting up [`watch`](/cli/api/commands/generate#w-watch) mode. - Defaults to `true`. ### include `string[] | undefined` Artifact files to include relative to `artifacts`. Supports glob patterns. ```ts import { defineConfig } from '@wagmi/cli' import { foundry } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ foundry({ include: [ // [!code focus] // the following patterns are included by default // [!code focus] '*.json', // [!code focus] ], // [!code focus] }), ], }) ``` ### namePrefix `string | undefined` Prefix to prepend to artifact names. Useful for preventing name collisions between contracts from other sources. ```ts import { defineConfig } from '@wagmi/cli' import { foundry } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ foundry({ // [!code focus] namePrefix: 'HelloFoundry', // [!code focus] }), // [!code focus] ], }) ``` ### project `string | undefined` - Path to Foundry project. - Defaults to Foundry configuration using `forge config --json` command. ```ts import { defineConfig } from '@wagmi/cli' import { foundry } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ foundry({ // [!code focus] project: '../hello_foundry', // [!code focus] }), // [!code focus] ], }) ``` ================================================ FILE: site/cli/api/plugins/hardhat.md ================================================ # hardhat Plugin for resolving ABIs from [Hardhat](https://hardhat.org) projects. Supports [`watch`](/cli/api/commands/generate#w-watch) mode. ```ts import { hardhat } from '@wagmi/cli/plugins' ``` ## Usage ```ts{2,6-8} import { defineConfig } from '@wagmi/cli' import { hardhat } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ hardhat({ project: '../hello_hardhat', }), ], }) ``` ## Configuration ```ts import { type HardhatConfig } from '@wagmi/cli/plugins' ``` ### artifacts `string | undefined` - Project's artifacts directory. Same as your project's `artifacts` [path configuration](https://hardhat.org/hardhat-runner/docs/config#path-configuration) option. - Defaults to `'artifacts/'`. ```ts import { defineConfig } from '@wagmi/cli' import { hardhat } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ hardhat({ artifacts: 'out/', // [!code focus] project: '../hello_hardhat', }), ], }) ``` ### deployments `{ [key: string]: address?: Address | Record | undefined } | undefined` Mapping of addresses to attach to artifacts. ```ts import { defineConfig } from '@wagmi/cli' import { hardhat } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ hardhat({ project: '../hello_hardhat', deployments: { // [!code focus] Counter: { // [!code focus] 1: '0x314159265dd8dbb310642f98f50c066173c1259b', // [!code focus] 5: '0x112234455c3a32fd11230c42e7bccd4a84e02010', // [!code focus] }, // [!code focus] }, // [!code focus] }), ], }) ``` ### exclude `string[] | undefined` Artifact files to exclude relative to `artifacts`. Supports glob patterns. ```ts import { defineConfig } from '@wagmi/cli' import { hardhat } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ hardhat({ exclude: [ // [!code focus] // the following patterns are excluded by default // [!code focus] 'build-info/**', // [!code focus] '*.dbg.json', // [!code focus] ], // [!code focus] project: '../hello_hardhat', }), ], }) ``` ### commands `{ clean?: string | boolean | undefined; build?: string | boolean | undefined; rebuild?: string | boolean | undefined } | undefined` Hardhat command options. ```ts import { defineConfig } from '@wagmi/cli' import { hardhat } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ hardhat({ commands: { // [!code focus] clean: 'pnpm hardhat clean', // [!code focus] build: 'pnpm hardhat compile', // [!code focus] rebuild: 'pnpm hardhat compile', // [!code focus] }, // [!code focus] project: '../hello_hardhat', }), ], }) ``` #### clean - Remove build artifacts and cache directories on start up. - Defaults to `'${packageManger} hardhat clean'`. #### build - Build Foundry project before fetching artifacts. - Defaults to `'${packageManger} hardhat compile'`. #### rebuild - Command to run when watched file or directory is changed. Used for setting up [`watch`](/cli/api/commands/generate#w-watch) mode. - Defaults to `'${packageManger} hardhat compile'`. ### include `string[] | undefined` Artifact files to include relative to `artifacts`. Supports glob patterns. ```ts import { defineConfig } from '@wagmi/cli' import { hardhat } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ hardhat({ include: [ // [!code focus] // the following patterns are included by default // [!code focus] '*.json', // [!code focus] ], // [!code focus] project: '../hello_hardhat', }), ], }) ``` ### namePrefix `string | undefined` Prefix to prepend to artifact names. Useful for preventing name collisions between contracts from other sources. ```ts import { defineConfig } from '@wagmi/cli' import { hardhat } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ hardhat({ namePrefix: 'HelloHardhat', // [!code focus] project: '../hello_hardhat', }), ], }) ``` ### project `string` Path to Hardhat project. ```ts import { defineConfig } from '@wagmi/cli' import { hardhat } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ hardhat({ project: '../hello_hardhat', // [!code focus] }), ], }) ``` ================================================ FILE: site/cli/api/plugins/react.md ================================================ # react Plugin for generating type-safe [Wagmi Hooks](/react/api/hooks). ## Import ```ts import { react } from '@wagmi/cli/plugins' ``` ## Usage ```ts{2,6} import { defineConfig } from '@wagmi/cli' import { react } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ react(), ], }) ``` ## Configuration ```ts import { type ReactConfig } from '@wagmi/cli/plugins' ``` ### abiItemHooks - Boolean flag to generate abi item hooks (e.g. hooks for each abi function and events). - Defaults to `true`. ```ts plugins: [ react({ abiItemHooks: false }), // [!code focus] ], ``` ### getHookName `` 'legacy' | ((options: { contractName: string; type: 'read' | 'simulate' | 'watch' | 'write' }) => `use${string}`) `` - Function for setting custom hook names. - Defaults to `` `use${type}${contractName}` ``. For example, `useReadErc20`, `useSimulateErc20`, `useWatchErc20Event`, `useWriteErc20`. - When `'legacy'` (deprecated), hook names are set to `@wagmi/cli@1` format. ```ts import { defineConfig } from '@wagmi/cli' import { react } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ react({ getHookName({ contractName, type }) { // [!code focus] return `use${contractName}__${type}` // [!code focus] }, // [!code focus] }), ], }) ``` ================================================ FILE: site/cli/api/plugins/sourcify.md ================================================ # sourcify Plugin for fetching ABIs from [Sourcify](https://sourcify.dev/). Sourcify is a decentralized, open-source, smart contract verification and metadata repository. ## Import ```ts import { sourcify } from '@wagmi/cli/plugins' ``` ## Usage ```ts{2,6-13} import { defineConfig } from '@wagmi/cli' import { sourcify } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ sourcify({ contracts: [ { name: 'deposit', address: '0x00000000219ab540356cbb839cbe05303d7705fa', }, ], }), ], }) ``` ## Configuration ```ts import { type SourcifyConfig } from '@wagmi/cli/plugins' ``` ### cacheDuration `number | undefined` - Duration in milliseconds to cache ABIs. - Defaults to `1_800_000` (30 minutes). ```ts import { defineConfig } from '@wagmi/cli' import { sourcify } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ sourcify({ cacheDuration: 300_000, // [!code focus] chainId: 100, contracts: [ { name: 'Deposit', address: '0x00000000219ab540356cbb839cbe05303d7705fa', }, ], }), ], }) ``` ### chainId `number` Chain ID to use for fetching ABI. If `address` is an object, `chainId` is used to select the address. See [Sourcify docs](https://docs.sourcify.dev/docs/chains) for supported chains. ```ts import { defineConfig } from '@wagmi/cli' import { sourcify } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ sourcify({ chainId: 100, // [!code focus] contracts: [ { name: 'Community', address: { 100: '0xC4c622862a8F548997699bE24EA4bc504e5cA865', 137: '0xC4c622862a8F548997699bE24EA4bc504e5cA865', }, }, ], }), ], }) ``` ### contracts `{ name: string; address?: Address | Record | undefined }[]` Contracts to fetch ABIs for. ```ts import { defineConfig } from '@wagmi/cli' import { sourcify } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ sourcify({ chainId: 100, contracts: [ // [!code focus] { // [!code focus] name: 'Deposit', // [!code focus] address: '0x00000000219ab540356cbb839cbe05303d7705fa', // [!code focus] }, // [!code focus] ], // [!code focus] }), ], }) ``` ================================================ FILE: site/cli/api/plugins.md ================================================ # Plugins Plugins for managing ABIs, generating code, and more. ## Import Import via the `'@wagmi/cli/plugins'` entrypoint. ```ts import { etherscan } from '@wagmi/cli/plugins' ``` ## Available Plugins - [`actions`](/cli/api/plugins/actions) Generate type-safe VanillaJS actions from configuration `contracts`. - [`blockExplorer`](/cli/api/plugins/blockExplorer) Fetch ABIs from Block Explorers that support `?module=contract&action=getabi`. - [`etherscan`](/cli/api/plugins/etherscan) Fetch ABIs from Etherscan and add into configuration. - [`fetch`](/cli/api/plugins/fetch) Fetch and parse ABIs from network resource with `fetch`. - [`foundry`](/cli/api/plugins/foundry) Generate ABIs and watch for Foundry project changes. - [`hardhat`](/cli/api/plugins/hardhat) Generate ABIs and watch for Hardhat projects changes. - [`react`](/cli/api/plugins/react) Generate type-safe React Hooks from configuration `contracts`. - [`sourcify`](/cli/api/plugins/sourcify) Fetch ABIs from Sourcify from configuration `contracts`. ## Create Plugin Creating plugins to hook into the CLI is quite simple. Plugins most commonly inject contracts into `contracts` config, e.g. [`etherscan`](/cli/api/plugins/etherscan), and/or generate code using the `run` option, e.g. [`react`](/cli/api/plugins/react). All you need to do is write a function that returns the `Plugin` type. ```ts{3-8} import { type Plugin, defineConfig } from '@wagmi/cli' function myPlugin(): Plugin { // `name` is the only required property. name: 'MyPlugin', // You likely want to at least include `contracts` or `run`. // ... } export default defineConfig({ out: 'src/generated.ts', plugins: [myPlugin()], }) ``` ================================================ FILE: site/cli/config/configuring-cli.md ================================================ # Configuring CLI When running `wagmi` from the command line, `@wagmi/cli` will automatically try to resolve a config file named `wagmi.config.js` or `wagmi.config.ts` inside the project root. The most basic config file looks like this: ::: code-group ```js [wagmi.config.js] export default { // config options } ``` ::: Note `@wagmi/cli` supports using ES modules syntax in the config file even if the project is not using native Node ESM, e.g. `"type": "module"` in package.json. In this case, the config file is auto pre-processed before load. You can also explicitly specify a config file to use with the `--config`/`-c` CLI option (resolved relative to the current directory): ```bash wagmi --config my-config.js ``` To scaffold a config file quickly, check out the [`init`](/cli/api/commands/init) command. ## Config Intellisense Since Wagmi CLI ships with TypeScript typings, you can use your editor's intellisense with [JSDoc](https://jsdoc.app) type hints: ::: code-group ```js [wagmi.config.js] /** @type {import('@wagmi/cli').Config} */ export default { // ... } ``` ::: Alternatively, you can use the `defineConfig` utility which should provide intellisense without the need for JSDoc annotations: ::: code-group ```js [wagmi.config.js] import { defineConfig } from '@wagmi/cli' export default defineConfig({ // ... }) ``` ::: Wagmi CLI also directly supports TypeScript config files. You can use `wagmi.config.ts` with the `defineConfig` helper as well. ## Conditional Config If the config needs to conditionally determine options based on the environment, it can export a function instead: ::: code-group ```js [wagmi.config.js] export default defineConfig(() => { if (process.env.NODE_ENV === 'dev') { return { // dev specific config } } else { return { // production specific config } } }) ``` ::: ## Async Config If the config needs to call async function, it can export a async function instead: ::: code-group ```js [wagmi.config.js] export default defineConfig(async () => { const data = await asyncFunction() return { // ... } }) ``` ::: This can be useful for resolving external resources from the network or filesystem that are required for configuration ahead of running a command. ## Array Config The config can also be represented either as a pre-defined array or returned as an array from a function: ::: code-group ```js [wagmi.config.js] export default defineConfig([ { // config 1 }, { // config 2 }, ]) ``` ::: ## Environment Variables Environmental Variables can be obtained from `process.env` as usual. Note that Wagmi CLI doesn't load `.env` files by default as the files to load can only be determined after evaluating the config. However, you can use the exported `loadEnv` utility to load the specific `.env` files if needed. ::: code-group ```js [wagmi.config.js] import { defineConfig, loadEnv } from '@wagmi/cli' export default defineConfig(() => { const env = loadEnv({ mode: process.env.NODE_ENV, envDir: process.cwd(), }) return { // ... } }) ``` ::: ================================================ FILE: site/cli/config/options.md ================================================ # Config Options Configuration options for Wagmi CLI. ## contracts `ContractConfig[] | undefined` Array of contracts to use when running [commands](/cli/api/commands). `abi` and `name` are required, all other properties are optional. ### address `Address | Record | undefined` Contract address or addresses. Accepts an object `{ [chainId]: address }` for targeting specific chains. ::: code-group ```ts {6,11-14} [wagmi.config.ts] export default { out: 'src/generated.ts', contracts: [ { abi: […], address: '0x…', name: 'MyCoolContract', }, { abi: […], address: { 1: '0xfoo…', 5: '0xbar…', }, name: 'MyCoolMultichainContract' } ], } ``` ::: ### abi `Abi` ABI for contract. Used by [plugins](/cli/api/plugins) to generate code base on properties. ::: code-group ```ts {5} [wagmi.config.ts] export default { out: 'src/generated.ts', contracts: [ { abi: […], name: 'MyCoolContract' }, ], } ``` ::: ### name `string` Name of contract. Must be unique. Used by [plugins](/cli/api/plugins) to name generated code. ::: code-group ```ts {6} [wagmi.config.ts] export default { out: 'src/generated.ts', contracts: [ { abi: […], name: 'MyCoolContract' }, ], } ``` ::: ## out `string` Path to output generated code. Must be unique per config. Use an [Array Config](/cli/config/configuring-cli#array-config) for multiple outputs. ::: code-group ```ts {2} [wagmi.config.ts] export default { out: 'src/generated.ts', contracts: [ { abi: […], name: 'MyCoolContract' }, ], } ``` ::: ## plugins `Plugin[] | undefined` Plugins to use and their configuration. Wagmi CLI has multiple [built-in plugins](/cli/api/plugins) that are used to manage ABIs, generate code, etc. ::: code-group ```ts {1,5-20} [wagmi.config.ts] import { etherscan, react } from '@wagmi/cli/plugins' export default { out: 'src/generated.js', plugins: [ etherscan({ apiKey: process.env.ETHERSCAN_API_KEY, chainId: 5, contracts: [ { name: 'EnsRegistry', address: { 1: '0x314159265dd8dbb310642f98f50c066173c1259b', 5: '0x112234455c3a32fd11230c42e7bccd4a84e02010', }, }, ], }), react(), ], } ``` ::: ================================================ FILE: site/cli/create-wagmi.md ================================================ # create-wagmi ## Overview create-wagmi is a command line interface (CLI) for scaffolding new Wagmi projects. ## Usage ::: code-group ```bash [pnpm] pnpm create wagmi ``` ```bash [npm] npm create wagmi@latest ``` ```bash [yarn] yarn create wagmi ``` ```bash [bun] bun create wagmi ``` ::: ## Options ### `-t`, `--template` You can specify a custom [template](#templates) by passing the `--template`/`-t` flag: ::: code-group ```bash [pnpm] pnpm create wagmi --template next ``` ```bash [npm] npm create wagmi@latest --template next ``` ```bash [yarn] yarn create wagmi --template next ``` ```bash [bun] bun create wagmi --template next ``` ::: ### `--bun`/`--npm`/`--pnpm`/`--yarn` Use a specific package manager to install dependencies. By default, `create-wagmi` will use the package manager you used to run the command. ### `-h`, `--help` Prints the help message. ### `-v`, `--version` Prints the CLI version. ## Templates `create-wagmi` currently comes with the following templates: - `next`: A Next.js Wagmi project. - `nuxt`: A Nuxt Wagmi project. - `vite-react`: A Vite (React) Wagmi project. - `vite-vanilla`: A Vite Wagmi Core project. - `vite-vue`: A Vite (Vue) Wagmi project. If you do not specify the template on the command line, you will be prompted to select a framework and variant. - **React** : A React project. - **Vite** : A React + Vite Wagmi project (`vite-react`). - **Next** : A React + Next Wagmi project (`next`). - **Vue**: A Vue project. - **Vite**: A Vue + Vite Wagmi project (`vite-vue`). - **Nuxt**: A Vue + Nuxt Wagmi project (`nuxt`). - **Vanilla**: A Vite Wagmi project without React (`vite-vanilla`). ================================================ FILE: site/cli/getting-started.md ================================================ # Getting Started ## Overview Wagmi CLI is a command line interface for managing ABIs (from Etherscan/block explorers, Foundry/Hardhat projects, etc.), generating code (e.g. React Hooks), and much more. It makes working with Ethereum easier by automating manual work so you can build faster. You can learn more about the rationale behind the project in the [Why Wagmi CLI](/cli/why) section. ## Manual Installation To manually add Wagmi CLI to your project, install the required packages. ::: code-group ```bash [pnpm] pnpm add -D @wagmi/cli ``` ```bash [npm] npm install --save-dev @wagmi/cli ``` ```bash [yarn] yarn add -D @wagmi/cli ``` ```bash [bun] bun add -D @wagmi/cli ``` ::: ## Create Config File Run the `init` command to generate a configuration file: either `wagmi.config.ts` if TypeScript is detected, otherwise `wagmi.config.js`. You can also create the configuration file manually. See [Configuring CLI](/cli/config/configuring-cli) for more info. ::: code-group ```bash [pnpm] pnpm wagmi init ``` ```bash [npm] npx wagmi init ``` ```bash [yarn] yarn wagmi init ``` ```bash [bun] bun wagmi init ``` ::: The generated configuration file will look something like this: ::: code-group ```ts [wagmi.config.ts] import { defineConfig } from '@wagmi/cli' export default defineConfig({ out: 'src/generated.ts', contracts: [], plugins: [], }) ``` ::: ## Add Contracts And Plugins Once the configuration file is set up, you can add contracts and plugins to it. These contracts and plugins are used to manage ABIs (fetch from block explorers, resolve from the file system, etc.), generate code (React hooks, etc.), and much more! For example, we can add the ERC-20 contract from Viem, and the [`etherscan`](/cli/api/plugins/etherscan) and [`react`](/cli/api/plugins/react) plugins. ::: code-group ```ts{2,3,9-12,15-27,28} [wagmi.config.ts] import { defineConfig } from '@wagmi/cli' import { etherscan, react } from '@wagmi/cli/plugins' import { erc20Abi } from 'viem' import { mainnet, sepolia } from 'wagmi/chains' export default defineConfig({ out: 'src/generated.ts', contracts: [ { name: 'erc20', abi: erc20Abi, }, ], plugins: [ etherscan({ apiKey: process.env.ETHERSCAN_API_KEY!, chainId: mainnet.id, contracts: [ { name: 'EnsRegistry', address: { [mainnet.id]: '0x314159265dd8dbb310642f98f50c066173c1259b', [sepolia.id]: '0x112234455c3a32fd11230c42e7bccd4a84e02010', }, }, ], }), react(), ], }) ``` ::: ## Run Code Generation Now that we added a few contracts and plugins to the configuration file, we can run the [`generate`](/cli/api/commands/generate) command to resolve ABIs and generate code to the `out` file. ::: code-group ```bash [pnpm] pnpm wagmi generate ``` ```bash [npm] npx wagmi generate ``` ```bash [yarn] yarn wagmi generate ``` ```bash [bun] bun wagmi generate ``` ::: In this example, the `generate` command will do the following: - Validate the `etherscan` and `react` plugins - Fetch and cache the ENS Registry ABI from the Mainnet Etherscan API - Pull in the `erc20Abi` using the name `'ERC20'` - Generate React Hooks for both ABIs - Save ABIs, ENS Registry deployment addresses, and React Hooks to the `out` file ## Use Generated Code Once `out` is created, you can start using the generated code in your project. ```ts import { useReadErc20, useReadErc20BalanceOf } from './generated' // Use the generated ERC-20 read hook const { data } = useReadErc20({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', functionName: 'balanceOf', args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'], }) // Use the generated ERC-20 "balanceOf" hook const { data } = useReadErc20BalanceOf({ address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'], }) ``` ::: tip Instead of committing the `out` file, you likely want to add `out` to your `.gitignore` and run `generate` during the build process or before you start your dev server in a `"predev"` script. ::: ## Next Steps For more information on what to do next, check out the following topics. - [**Configuring CLI**](/cli/config/configuring-cli) Learn how to configure the CLI to work best for your project. - [**Commands**](/cli/api/commands) Learn more about the CLI commands and how to use them. - [**Plugins**](/cli/api/plugins) Browse the collection of plugins and set them up with your config. ================================================ FILE: site/cli/guides/migrate-from-v1-to-v2.md ================================================ --- title: Migrate from v1 to v2 titleTemplate: Wagmi CLI description: Guide for migrating from Wagmi CLI v1 to v2. --- # Migrate from v1 to v2 To get started, install the latest version of the Wagmi CLI. ::: code-group ```bash-vue [pnpm] pnpm add @wagmi/cli ``` ```bash-vue [npm] npm install @wagmi/cli ``` ```bash-vue [yarn] yarn add @wagmi/cli ``` ```bash-vue [bun] bun add @wagmi/cli ``` ::: ::: info Not ready to migrate yet? The Wagmi CLI v1 docs are still available at [1.x.wagmi.sh/cli](https://1.x.wagmi.sh/cli). ::: ## Changed generated action and hook names Generated action and hook names now align with [Wagmi v2 naming conventions](/react/guides/migrate-from-v1-to-v2#renamed-hooks). If you want hooks to still follow Wagmi v1 naming conventions, set [`getActionName`](/cli/api/plugins/actions#getactionname) and [`getHookName`](/cli/api/plugins/react#gethookname) to `'legacy'`. ```ts import { defineConfig } from '@wagmi/cli' import { actions, react } from '@wagmi/cli/plugins' export default defineConfig({ plugins: [ actions({ getActionName: 'legacy', // [!code focus] }), react({ getHookName: 'legacy', // [!code focus] }), ], }) ``` ================================================ FILE: site/cli/installation.md ================================================ # Installation Install Wagmi CLI via your package manager. ## Package Manager Install the required package. ::: code-group ```bash [pnpm] pnpm add @wagmi/cli ``` ```bash [npm] npm install @wagmi/cli ``` ```bash [yarn] yarn add @wagmi/cli ``` ```bash [bun] bun add @wagmi/cli ``` ::: ## Using Unreleased Commits If you can't wait for a new release to test the latest features, you can either install from the `canary` tag (tracks the [`main`](https://github.com/wevm/wagmi/tree/main) branch). ::: code-group ```bash [pnpm] pnpm add @wagmi/cli@canary ``` ```bash [npm] npm install @wagmi/cli@canary ``` ```bash [yarn] yarn add @wagmi/cli@canary ``` ```bash [bun] bun add @wagmi/cli@canary ``` ::: Or clone the [Wagmi repo](https://github.com/wevm/wagmi) to your local machine, build, and link it yourself. ```bash git clone https://github.com/wevm/wagmi.git cd wagmi pnpm install pnpm build cd packages/cli pnpm link --global ``` Then go to the project where you are using the Wagmi CLI and run `pnpm link --global @wagmi/cli` (or the package manager that you used to link Wagmi CLI globally). Finally, pull requests are continuously released via [pkg.pr.new](https://pkg.pr.new) and can be installed using the pull request number or short commit ID. ::: code-group ```bash [pnpm] pnpm add https://pkg.pr.new/@wagmi/cli@123 ``` ```bash [npm] npm install https://pkg.pr.new/@wagmi/cli@123 ``` ```bash [yarn] yarn add https://pkg.pr.new/@wagmi/cli@123 ``` ```bash [bun] bun add https://pkg.pr.new/@wagmi/cli@123 ``` ::: ================================================ FILE: site/cli/why.md ================================================ # Why Wagmi CLI ## The Problem The most common way to interact with smart contracts is through [Application Binary Interfaces](https://docs.soliditylang.org/en/latest/abi-spec.html). ABIs describe smart contracts' public functionality (e.g. functions, events, errors) as well as how to encode and decode related data (e.g. arguments and results). While ABIs are extremely powerful, there isn't a uniform way developers manage them in their apps. Developers do a bunch of different things, like: - Publish packages on npm containing ABIs - Write custom scripts to fetch ABIs from external sources - Compile contracts into application project - Copy and paste ABIs from local projects or block explorers All these approaches take time that you could spend doing more important things, like interacting with your smart contracts! ## The Solution The Wagmi CLI is an attempt to automate manual work so you can build faster. In short, the CLI manages ABIs and generates code. It takes ABIs as inputs and outputs ABIs and generated code. For example, the [Etherscan plugin](/cli/api/plugins/etherscan) allows you to fetch ABIs across multiple chains and deployments and immediately start importing them into your project. Code generation is another big advantage of the CLI. Using the [React plugin](/cli/api/plugins/react), you can generate [Wagmi Hooks](/react/api/hooks) for ABIs. When you combine this with the CLI's different ABI sources, like Etherscan, Foundry/Hardhat, and more, you reduce a lot of boilerplate code. ::: code-group ```ts [Diff] import { useReadContract, useWriteContract } from 'wagmi' // [!code --] import { froggyFriendsAbi, froggyFriendsAddress } from './generated' // [!code --] import { useReadFroggyFriends, useWriteFroggyFriends } from './generated' // [!code ++] function App() { const { data } = useReadContract({ // [!code --] const { data } = useReadFroggyFriends({ // [!code ++] abi: froggyFriendsAbi, // [!code --] address: froggyFriendsAddress, // [!code --] functionName: 'tokenURI', args: [123n], }) const { write } = useWriteContract() // [!code --] const { write } = useWriteFroggyFriends() // [!code ++] const onClick = React.useCallback(() => { write({ abi: froggyFriendsAbi, // [!code --] address: froggyFriendsAddress, // [!code --] functionName: 'mint', args: ['foo', 123n], }) }, [write]) } ``` ```ts [Before] import { useReadContract, useWriteContract } from 'wagmi' import { froggyFriendsAbi, froggyFriendsAddress } from './generated' function App() { const { data } = useReadContract({ abi: froggyFriendsAbi, address: froggyFriendsAddress, functionName: 'tokenURI', args: [123n], }) const { write } = useWriteContract() const onClick = React.useCallback(() => { write({ abi: froggyFriendsAbi, address: froggyFriendsAddress, functionName: 'mint', args: ['foo', 123n], }) }, [write]) } ``` ```ts [After] import { useReadFroggyFriends, useWriteFroggyFriends } from './generated' function App() { const { data } = useReadFroggyFriends({ functionName: 'tokenURI', args: [123n], }) const { write } = useWriteFroggyFriends() const onClick = React.useCallback(() => { write({ functionName: 'mint', args: ['foo', 123n], }) }, [write]) } ``` ::: Finally, the Wagmi CLI supports popular smart contract development tools, [Foundry](/cli/api/plugins/foundry) and [Hardhat](/cli/api/plugins/hardhat). You can run the CLI in [watch mode](/cli/api/commands/generate#w-watch), make changes to your contracts, and the CLI will automatically pick up ABI changes and run plugins over those changes. A major boon to working a monorepo and shortening the feedback loop across your stack. ================================================ FILE: site/components/Browsers.vue ================================================ ================================================ FILE: site/components/PackageMetadata.vue ================================================ ================================================ FILE: site/components/SearchChains.vue ================================================ ================================================ FILE: site/core/api/actions/call.md ================================================ # call Action for executing a new message call immediately without submitting a transaction to the network. ## Import ```ts import { call } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { call } from '@wagmi/core' import { config } from './config' await call(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts twoslash // @twoslash-cache: {"v":1,"hash":"f9d98dd791931821ca041f2ffa5df1409ff16b6299b7878935aa5d977af43747","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAJMcvAMJtWABWalmAWxg1ScADwBjCGABm7AOa86NMFDjC1mnQF5jG7QD5eFka3GSZcskYBkw/M3ZgAklASUrLyKiY2ADpg7NJYEKRowqJBLvIIVHBokgyIAIwALFSsMGBaaPhIBVRZpFpyeA5Owa4KlCAcYLiIAAxUyt5SyvKV+QC+ALp90F0gMXEJvMD82DBJjikhbryjvOqkENK8AOQAAgDuzFrS7AD0qqQwR20hzEigeiVw7Gp4aAijoyAA"} import { type CallParameters } from '@wagmi/core' ``` ### account `Account | Address | undefined` The Account to call from. ::: code-group ```ts [index.ts] import { call } from '@wagmi/core' import { config } from './config' await call(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus] data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### data `` `0x${string}` | undefined `` A contract hashed method call with encoded args. ::: code-group ```ts [index.ts] import { call } from '@wagmi/core' import { config } from './config' await call(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### to `Address | undefined` The contract address or recipient. ::: code-group ```ts [index.ts] import { call } from '@wagmi/core' import { config } from './config' await call(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### accessList `AccessList | undefined` The access list. ::: code-group ```ts [index.ts] import { call } from '@wagmi/core' import { config } from './config' await call(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', accessList: [ // [!code focus:6] { address: '0x1', storageKeys: ['0x1'], }, ], data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### gas `bigint | undefined` The gas provided for transaction execution. ::: code-group ```ts [index.ts] import { call } from '@wagmi/core' import { config } from './config' await call(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', gas: 1_000_000n, // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### gasPrice `bigint | undefined` The price (in wei) to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction). ::: code-group ```ts [index.ts] import { call } from '@wagmi/core' import { parseGwei } from 'viem' import { config } from './config' await call(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', gasPrice: parseGwei('20'), // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### maxFeePerGas `bigint | undefined` Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```ts [index.ts] import { call } from '@wagmi/core' import { parseGwei } from 'viem' import { config } from './config' await call(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', maxFeePerGas: parseGwei('20'), // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### maxPriorityFeePerGas `bigint | undefined` Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```ts [index.ts] import { call } from '@wagmi/core' import { parseGwei } from 'viem' import { config } from './config' await call(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### nonce `number | undefined` Unique number identifying this transaction. ::: code-group ```ts [index.ts] import { call } from '@wagmi/core' import { config } from './config' await call(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', nonce: 420, // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### value `bigint | undefined` Value (in wei) sent with this transaction. ::: code-group ```ts [index.ts] import { call } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' await call(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockNumber `number | undefined` The block number to perform the call against. ::: code-group ```ts [index.ts] import { call } from '@wagmi/core' import { config } from './config' await call(config, { blockNumber: 15121123n, // [!code focus] account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` The block tag to perform the call against. ::: code-group ```ts [index.ts] import { call } from '@wagmi/core' import { config } from './config' await call(config, { blockTag: 'safe', // [!code focus] account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` The block tag to perform the call against. ::: code-group ```ts [index.ts] import { call } from '@wagmi/core' import { config } from './config' import { mainnet } from '@wagmi/core/chains' await call(config, { chainId: mainnet.id, // [!code focus] account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts twoslash // @twoslash-cache: {"v":1,"hash":"21d9f77d5084c8206ac7e44980e375eda94c1b843ad4d776e3c3ed3a076f7de7","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAJMcvAMJtWAJRhoArqTAAVbDF4BeXsAA6YXtt5RmaZol4AJOrwA+vKWFgAzdmBhQA3JoC+m9gFssEUmmFRCWlZBRxKEDgDfyQARgAWKlYYMABzNHw4xOpmUlTJPBFWcUkZeUUIjkckAAYqAGN8XOZ6mnJEBLcAXQboXEQQb19/NX5FQOLgsrClN15bUggvXgByAAEAd2ZUr3YAenq/GBWIr0lmJFA6GjA4dggwPDQENzcgA==="} import { type CallReturnType } from '@wagmi/core' ``` `{ data: 0x${string} }` The call data. ## Error ```ts twoslash // @twoslash-cache: {"v":1,"hash":"b8acbdeab78439603d8a045b8f32426b8530ecc55b9057e0cccd65e1da03193a","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAJMcvAMJtWAUVKkIpACrYYvALy8A8gFt2aADwjW42jADGAVzTsIYCVNnyKvADohDzY3BiOAfLwBkvYPbBeIN5nVxhEXgAFZlI3AEFDQwhjMDQraTlBAB9eAEkwIjZ2KDioKFJ4OHSbbN4EpJS0AGU0ZhohCwAzDkM0yQz5Xhz8mgBzMhVTFU6AJWYwcerMhRym9gAvGDFaQxgYKDhosvYFtc2lwZyL2pa2mDi4OHZRsDUYVI6wbvZe65W8gpFKAAIQwNDgABl3qM0Pg/kNeAA6ZG8ABsAEZeGppApkYiEQBxGBoABy0C2/VIM2JxlIYGWAG4AgBfALsNRYaRoYSiP6UEBwVqkBiIdEAFiorGhsKQ6IAzFQheMRSBdOJKct+RwwLhEAAGKiGfAxZi9MiysXMgC6hvJeHZnOFfn4gzV8OZvE6UjUvAA5AABADuzFGGgA9EkKr7+W9WkhQHQaGAnhY8GgEMzmUA=="} import { type CallErrorType } from '@wagmi/core' ``` ## Viem - [`call`](https://viem.sh/docs/actions/public/call) ================================================ FILE: site/core/api/actions/connect.md ================================================ # connect Action for connecting accounts with [connectors](/core/api/connectors). ## Import ```ts import { connect } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { connect } from '@wagmi/core' import { injected } from '@wagmi/connectors' import { config } from './config' const result = await connect(config, { connector: injected() }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type ConnectParameters } from '@wagmi/core' ``` ### chainId `number | undefined` Chain ID to connect to. Not all connectors support connecting directly to a `chainId` (e.g. they don't support programmatic chain switching). In those cases, the connector will connect to whatever chain the connector's provider is connected to. ::: code-group ```ts [index.ts] import { connect } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { injected } from '@wagmi/connectors' import { config } from './config' const result = await connect(config, { chainId: mainnet.id, // [!code focus] connector: injected(), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### connector `CreateConnectorFn | Connector` [Connector](/core/api/connectors) to connect with. ::: code-group ```ts [index.ts] import { connect } from '@wagmi/core' import { injected } from '@wagmi/connectors' // [!code focus] import { config } from './config' const result = await connect(config, { connector: injected(), // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### withCapabilities `boolean | undefined` - Exposes [capabilities](https://eips.ethereum.org/EIPS/eip-7846#capabilities) on return type. - Defaults to `false`. ::: code-group ```ts [index.ts] import { connect } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { injected } from '@wagmi/connectors' import { config } from './config' const result = await connect(config, { connector: injected(), withCapabilities: true, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type ConnectReturnType } from '@wagmi/core' ``` ::: tip When [`withCapabilities: false | undefined`](#withcapabilities): ```ts type ConnectReturnType = { accounts: readonly Address[] // ... } ``` When [`withCapabilities: true`](#withcapabilities): ```ts type ConnectReturnType = { accounts: readonly { address: Address; capabilities: Record }[] // ... } ``` ::: ### accounts `readonly [Address, ...Address[]]` Connected accounts from connector. ### chainId `number` Connected chain ID from connector. ## Error ```ts import { type ConnectErrorType } from '@wagmi/core' ``` ================================================ FILE: site/core/api/actions/deployContract.md ================================================ # deployContract Action for deploying a contract to the network, given bytecode, and constructor arguments. ## Import ```ts import { deployContract } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { deployContract } from '@wagmi/core' import { wagmiAbi } from './abi' import { config } from './config' const result = await deployContract(config, { abi: wagmiAbi, bytecode: '0x608060405260405161083e38038061083e833981016040819052610...', }) ``` ```ts [abi.ts] export const wagmiAbi = [ ... { inputs: [], stateMutability: "nonpayable", type: "constructor", }, ... ] as const ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Deploying with Constructor Args ::: code-group ```ts [index.ts] import { deployContract } from '@wagmi/core' import { wagmiAbi } from './abi' import { config } from './config' const result = await deployContract(config, { abi: wagmiAbi, args: [69420], bytecode: '0x608060405260405161083e38038061083e833981016040819052610...', }) ``` ```ts [abi.ts] export const wagmiAbi = [ ... { inputs: [{ name: "x", type: "uint32" }], stateMutability: "nonpayable", type: "constructor", }, ... ] as const; ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type DeployContractParameters } from '@wagmi/core' ``` ### abi `Abi` The contract's ABI. ::: code-group ```ts [index.ts] import { deployContract } from '@wagmi/core' import { wagmiAbi } from './abi' import { config } from './config' const result = await deployContract(config, { abi: wagmiAbi, // [!code focus] args: [69420], bytecode: '0x608060405260405161083e38038061083e833981016040819052610...', }) ``` ```ts [abi.ts] export const wagmiAbi = [ ... { inputs: [{ name: "x", type: "uint32" }], stateMutability: "nonpayable", type: "constructor", }, ... ] as const; ``` <<< @/snippets/core/config.ts[config.ts] ::: ### account `Address | Account | undefined` Account to use when deploying a contract. Throws if account is not found on [`connector`](#connector). ::: code-group ```ts [index.ts] import { deployContract } from '@wagmi/core' import { wagmiAbi } from './abi' import { config } from './config' const result = await deployContract(config, { abi: wagmiAbi, account: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] args: [69420], bytecode: '0x608060405260405161083e38038061083e833981016040819052610...', }) ``` ```ts [abi.ts] export const wagmiAbi = [ ... { inputs: [{ name: "x", type: "uint32" }], stateMutability: "nonpayable", type: "constructor", }, ... ] as const; ``` <<< @/snippets/core/config.ts[config.ts] ::: ### args `readonly unknown[] | undefined` - Arguments to pass when deploying the contract. - Inferred from [`abi`](#abi). ::: code-group ```ts [index.ts] import { deployContract } from '@wagmi/core' import { wagmiAbi } from './abi' import { config } from './config' const result = await deployContract(config, { abi: wagmiAbi, args: [69420], // [!code focus] bytecode: '0x608060405260405161083e38038061083e833981016040819052610...', }) ``` ```ts [abi.ts] export const wagmiAbi = [ ... { inputs: [{ name: "x", type: "uint32" }], stateMutability: "nonpayable", type: "constructor", }, ... ] as const; ``` <<< @/snippets/core/config.ts[config.ts] ::: ### bytecode `Hex` The contract's bytecode. ::: code-group ```ts [index.ts] import { deployContract } from '@wagmi/core' import { wagmiAbi } from './abi' import { config } from './config' const result = await deployContract(config, { abi: wagmiAbi, args: [69420], bytecode: '0x608060405260405161083e38038061083e833981016040819052610...', // [!code focus] }) ``` ```ts [abi.ts] export const wagmiAbi = [ ... { inputs: [{ name: "x", type: "uint32" }], stateMutability: "nonpayable", type: "constructor", }, ... ] as const; ``` <<< @/snippets/core/config.ts[config.ts] ::: ### connector `Connector | undefined` - Connector to use when deploying a contract. - Defaults to current connector. ::: code-group ```ts [index.ts] import { getConnection, deployContract } from '@wagmi/core' import { wagmiAbi } from './abi' import { config } from './config' const { connector } = getConnection(config) const result = await deployContract(config, { abi: wagmiAbi, args: [69420], bytecode: '0x608060405260405161083e38038061083e833981016040819052610...', connector, // [!code focus] }) ``` ```ts [abi.ts] export const wagmiAbi = [ ... { inputs: [{ name: "x", type: "uint32" }], stateMutability: "nonpayable", type: "constructor", }, ... ] as const; ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type DeployContractReturnType } from '@wagmi/core' ``` [`Hash`](https://viem.sh/docs/glossary/types#hash) Transaction hash. ## Error ```ts import { type DeployContractErrorType } from '@wagmi/core' ``` ## Viem - [`deployContract`](https://viem.sh/docs/contract/deployContract) ================================================ FILE: site/core/api/actions/disconnect.md ================================================ # disconnect Action for disconnecting connections. ## Import ```ts import { disconnect } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { disconnect } from '@wagmi/core' import { config } from './config' await disconnect(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type DisconnectParameters } from '@wagmi/core' ``` ### connector `Connector | undefined` [Connector](/core/api/connectors) to disconnect with. ::: code-group ```ts [index.ts] import { disconnect, getConnection } from '@wagmi/core' import { config } from './config' const { connector } = getConnection(config) const result = await disconnect(config, { connector, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Error ```ts import { type DisconnectErrorType } from '@wagmi/core' ``` ================================================ FILE: site/core/api/actions/estimateFeesPerGas.md ================================================ # estimateFeesPerGas Returns an estimate for the fees per gas (in wei) for a transaction to be likely included in the next block. ## Import ```ts import { estimateFeesPerGas } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { estimateFeesPerGas } from '@wagmi/core' import { config } from './config' const result = await estimateFeesPerGas(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type EstimateFeesPerGasParameters } from '@wagmi/core' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { estimateFeesPerGas } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const result = await estimateFeesPerGas(config, { chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### type `'legacy' | 'eip1559'` - Fee value type. - Defaults to `'eip1559'` ::: code-group ```ts [index.ts] import { estimateFeesPerGas } from '@wagmi/core' import { config } from './config' const result = estimateFeesPerGas(config, { type: 'legacy', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type EstimateFeesPerGasReturnType } from '@wagmi/core' ``` [`FeeValues`](https://viem.sh/docs/glossary/types#feevalues) An estimate (in wei) for the fees per gas. ### gasPrice `bigint | undefined` - Gas price. - When [`type`](#type) is `'eip1559'`, value is `undefined`. ### maxFeePerGas `bigint | undefined` - Max fee per gas. - When [`type`](#type) is `'legacy'`, value is `undefined`. ### maxPriorityFeePerGas `bigint | undefined` - Max priority fee per gas. - When [`type`](#type) is `'legacy'`, value is `undefined`. ## Error ```ts import { type EstimateFeesPerGasErrorType } from '@wagmi/core' ``` ## Viem - [`estimateFeesPerGas`](https://viem.sh/docs/actions/public/estimateFeesPerGas) ================================================ FILE: site/core/api/actions/estimateGas.md ================================================ # estimateGas Action for estimating the gas necessary to complete a transaction without submitting it to the network. ## Import ```ts import { estimateGas } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { estimateGas } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await estimateGas(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type EstimateGasParameters } from '@wagmi/core' ``` ### accessList `AccessList | undefined` The access list. ::: code-group ```ts [index.ts] import { estimateGas } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await estimateGas(config, { accessList: [{ // [!code focus] address: '0x1', // [!code focus] storageKeys: ['0x1'], // [!code focus] }], // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### account `Address | Account | undefined` Account to use when estimating gas. ::: code-group ```ts [index.ts] import { estimateGas } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await estimateGas(config, { account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` Chain ID to target when estimating gas. ::: code-group ```ts [index.ts] import { estimateGas } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { parseEther } from 'viem' import { config } from './config' const result = await estimateGas(config, { chainId: mainnet.id, // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### connector `Connector | undefined` Connector to estimate with. If no [`account`](#account) is provided, will use default account from connector. ::: code-group ```ts [index.ts] import { getConnections, estimateGas } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const connections = getConnections(config) const result = await estimateGas(config, { connector: connections[0]?.connector, // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### data `` `0x${string}` | undefined `` A contract hashed method call with encoded args. ::: code-group ```ts [index.ts] import { estimateGas } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await estimateGas(config, { data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### gas `bigint | undefined` Gas provided for transaction execution. ::: code-group ```ts [index.ts] import { estimateGas } from '@wagmi/core' import { parseEther, parseGwei } from 'viem' import { config } from './config' const result = await estimateGas(config, { gas: parseGwei('20'), // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: --- ### gasPrice `bigint | undefined` The price in wei to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction). ::: code-group ```ts [index.ts] import { estimateGas } from '@wagmi/core' import { parseEther, parseGwei } from 'viem' import { config } from './config' const result = await estimateGas(config, { gasPrice: parseGwei('20'), // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### maxFeePerGas `bigint | undefined` Total fee per gas in wei, inclusive of [`maxPriorityFeePerGas`](#maxPriorityFeePerGas). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```ts [index.ts] import { estimateGas } from '@wagmi/core' import { parseEther, parseGwei } from 'viem' import { config } from './config' const result = await estimateGas(config, { maxFeePerGas: parseGwei('20'), // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### maxPriorityFeePerGas `bigint | undefined` Max priority fee per gas in wei. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```ts [index.ts] import { estimateGas } from '@wagmi/core' import { parseEther, parseGwei } from 'viem' import { config } from './config' const result = await estimateGas(config, { maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: --- ### nonce `number` Unique number identifying this transaction. ::: code-group ```ts [index.ts] import { estimateGas } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await estimateGas(config, { nonce: 123, // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### to `Address | undefined` The transaction recipient or contract address. ::: code-group ```ts [index.ts] import { estimateGas } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await estimateGas(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### type `'legacy' | 'eip1559' | 'eip2930' | undefined` Optional transaction request type to narrow parameters. ::: code-group ```ts [index.ts] import { estimateGas } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await estimateGas(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', type: 'eip1559', // [!code focus] value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### value `bigint | undefined` Value in wei sent with this transaction. ::: code-group ```ts [index.ts] import { estimateGas } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await estimateGas(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type EstimateGasReturnType } from '@wagmi/core' ``` `bigint` The gas estimate in wei. ## Error ```ts import { type EstimateGasErrorType } from '@wagmi/core' ``` ## Viem - [`estimateGas`](https://viem.sh/docs/actions/public/estimateGas) ================================================ FILE: site/core/api/actions/estimateMaxPriorityFeePerGas.md ================================================ # estimateMaxPriorityFeePerGas Returns an estimate for the max priority fee per gas (in wei) for a transaction to be likely included in the next block. ## Import ```ts import { estimateMaxPriorityFeePerGas } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { estimateMaxPriorityFeePerGas } from '@wagmi/core' import { config } from './config' const result = await estimateMaxPriorityFeePerGas(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type EstimateFeesPerGasParameters } from '@wagmi/core' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { estimateMaxPriorityFeePerGas } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const result = await estimateMaxPriorityFeePerGas(config, { chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type EstimateFeesPerGasReturnType } from '@wagmi/core' ``` `bigint` An estimate (in wei) for the max priority fee per gas. ## Error ```ts import { type EstimateFeesPerGasErrorType } from '@wagmi/core' ``` ## Viem - [`estimateMaxPriorityFeePerGas`](https://viem.sh/docs/actions/public/estimateMaxPriorityFeePerGas) ================================================ FILE: site/core/api/actions/getBalance.md ================================================ # getBalance Action for fetching native currency balance. ## Import ```ts import { getBalance } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getBalance } from '@wagmi/core' import { config } from './config' const balance = getBalance(config, { address: '0x4557B18E779944BFE9d78A672452331C186a9f48', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetBalanceParameters } from '@wagmi/core' ``` ### address `Address` Address to get balance for. ::: code-group ```ts [index.ts] import { getBalance } from '@wagmi/core' import { config } from './config' const balance = getBalance(config, { address: '0x4557B18E779944BFE9d78A672452331C186a9f48', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: --- ### blockNumber `bigint | undefined` Block number to get balance at. ::: code-group ```ts [index.ts] import { getBalance } from '@wagmi/core' import { config } from './config' const balance = getBalance(config, { address: '0x4557B18E779944BFE9d78A672452331C186a9f48', blockNumber: 17829139n, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get balance at. ::: code-group ```ts [index.ts] import { getBalance } from '@wagmi/core' import { config } from './config' const balance = getBalance(config, { address: '0x4557B18E779944BFE9d78A672452331C186a9f48', blockTag: 'latest', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { getBalance } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const balance = await getBalance(config, { address: '0x4557B18E779944BFE9d78A672452331C186a9f48', chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetBalanceReturnType } from '@wagmi/core' ``` ### decimals `number` Number of decimals for balance [`value`](#value). ### symbol `string` Symbol of native currency. ### value `bigint` Raw value of balance. ## Error ```ts import { type GetBalanceErrorType } from '@wagmi/core' ``` ## Viem - [`getBalance`](https://viem.sh/docs/actions/public/getBalance) for native currency balances - [`multicall`](https://viem.sh/docs/contract/multicall) for token balances ================================================ FILE: site/core/api/actions/getBlobBaseFee.md ================================================ # getBlobBaseFee Action for fetching the current blob base fee (in wei). ## Import ```ts import { getBlobBaseFee } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getBlobBaseFee } from '@wagmi/core' import { config } from './config' const blobBaseFee = await getBlobBaseFee(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetBlobBaseFeeParameters } from '@wagmi/core' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { getBlobBaseFee } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const blobBaseFee = await getBlobBaseFee(config, { chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetBlobBaseFeeReturnType } from '@wagmi/core' ``` `bigint` Current blob base fee (in wei). ## Error ```ts import { type GetBlobBaseFeeErrorType } from '@wagmi/core' ``` ## Viem - [`getBlobBaseFee`](https://viem.sh/docs/actions/public/getBlobBaseFee) ================================================ FILE: site/core/api/actions/getBlock.md ================================================ # getBlock Action for fetching information about a block at a block number, hash or tag. ## Import ```ts import { getBlock } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getBlock } from '@wagmi/core' import { config } from './config' const blockNumber = await getBlock(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetBlockParameters } from '@wagmi/core' ``` ### blockHash `` `0x${string}` `` Information at a given block hash. ::: code-group ```ts [index.ts] import { getBlock } from '@wagmi/core' import { config } from './config' const blockNumber = await getBlock(config, { blockHash: '0x89644bbd5c8d682a2e9611170e6c1f02573d866d286f006cbf517eec7254ec2d' // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockNumber `` bigint `` Information at a given block number. ::: code-group ```ts [index.ts] import { getBlock } from '@wagmi/core' import { config } from './config' const blockNumber = await getBlock(config, { blockNumber: 42069n // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockTag `` 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' `` Information at a given block tag. Defaults to `'latest'`. ::: code-group ```ts [index.ts] import { getBlock } from '@wagmi/core' import { config } from './config' const blockNumber = await getBlock(config, { blockTag: 'pending' // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { getBlock } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const blockNumber = await getBlock(config, { chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### includeTransactions `boolean` Whether or not to include transactions as objects. ::: code-group ```ts [index.ts] import { getBlock } from '@wagmi/core' import { config } from './config' const blockNumber = await getBlock(config, { includeTransactions: true // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetBlockReturnType } from '@wagmi/core' ``` [`Block`](https://viem.sh/docs/glossary/types#block) Information about the block. ## Error ```ts import { type GetBlockErrorType } from '@wagmi/core' ``` ## Viem - [`getBlock`](https://viem.sh/docs/actions/public/getBlock) ================================================ FILE: site/core/api/actions/getBlockNumber.md ================================================ # getBlockNumber Action for fetching the number of the most recent block seen. ## Import ```ts import { getBlockNumber } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getBlockNumber } from '@wagmi/core' import { config } from './config' const blockNumber = await getBlockNumber(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetBlockNumberParameters } from '@wagmi/core' ``` ### cacheTime `number | undefined` Time in milliseconds that cached block number will remain in memory. ::: code-group ```ts [index.ts] import { getBlockNumber } from '@wagmi/core' import { config } from './config' const blockNumber = await getBlockNumber(config, { cacheTime: 4_000, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { getBlockNumber } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const blockNumber = await getBlockNumber(config, { chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetBlockNumberReturnType } from '@wagmi/core' ``` `bigint` Most recent block number seen. ## Error ```ts import { type GetBlockNumberErrorType } from '@wagmi/core' ``` ## Viem - [`getBlockNumber`](https://viem.sh/docs/actions/public/getBlockNumber) - [`watchBlockNumber`](https://viem.sh/docs/actions/public/watchBlockNumber) ================================================ FILE: site/core/api/actions/getBlockTransactionCount.md ================================================ # getBlockTransactionCount Action for fetching the number of Transactions at a block number, hash or tag. ## Import ```ts import { getBlockTransactionCount } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getBlockTransactionCount } from '@wagmi/core' import { config } from './config' const blockTransactionCount = await getBlockTransactionCount(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetBlockTransactionCountParameters } from '@wagmi/core' ``` ### cacheTime `number | undefined` Time in milliseconds that cached block transaction count will remain in memory. ::: code-group ```ts [index.ts] import { getBlockTransactionCount } from '@wagmi/core' import { config } from './config' const blockTransactionCount = await getBlockTransactionCount(config, { cacheTime: 4_000, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { getBlockTransactionCount } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const blockTransactionCount = await getBlockTransactionCount(config, { chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetBlockTransactionCountReturnType } from '@wagmi/core' ``` `number` The number of Transactions at a block number ## Error ```ts import { type GetBlockTransactionCountErrorType } from '@wagmi/core' ``` ## Viem - [`getBlockTransactionCount`](https://viem.sh/docs/actions/public/getBlockTransactionCount) ================================================ FILE: site/core/api/actions/getBytecode.md ================================================ # getBytecode Action for retrieving the bytecode at an address. ## Import ```ts import { getBytecode } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getBytecode } from '@wagmi/core' import { config } from './config' await getBytecode(config, { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetBytecodeParameters } from '@wagmi/core' ``` ### address `Address` The contract address. ::: code-group ```ts [index.ts] import { getBytecode } from '@wagmi/core' import { config } from './config' await getBytecode(config, { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockNumber `bigint | undefined` The block number to check the bytecode at. ::: code-group ```ts [index.ts] import { getBytecode } from '@wagmi/core' import { config } from './config' await getBytecode(config, { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', blockNumber: 16280770n, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` The block tag to check the bytecode at. ::: code-group ```ts [index.ts] import { getBytecode } from '@wagmi/core' import { config } from './config' await getBytecode(config, { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', blockTag: 'safe', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` The chain ID to check the bytecode at. ::: code-group ```ts [index.ts] import { getBytecode } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' await getBytecode(config, { chainId: mainnet.id, // [!code focus] address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetBytecodeReturnType } from '@wagmi/core' ``` `Hex` The contract's bytecode. ## Error ```ts import { type GetBytecodeErrorType } from '@wagmi/core' ``` ## Viem - [`getCode`](https://viem.sh/docs/contract/getCode) ================================================ FILE: site/core/api/actions/getCallsStatus.md ================================================ # getCallsStatus Action to fetch the status and receipts of a call batch that was sent via [`sendCalls`](/core/api/actions/sendCalls). [Read more.](https://github.com/ethereum/EIPs/blob/1663ea2e7a683285f977eda51c32cec86553f585/EIPS/eip-5792.md#wallet_getcallsstatus) ## Import ```ts import { getCallsStatus } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getCallsStatus } from '@wagmi/core' import { config } from './config' const status = await getCallsStatus(config, { id: '0x1234567890abcdef', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetCallsStatusParameters } from '@wagmi/core' ``` ### connector `Connector | undefined` Connector to get call statuses with. ::: code-group ```ts [index.ts] import { getConnections, getCallsStatus } from '@wagmi/core' import { config } from './config' const connections = getConnections(config) const status = await getCallsStatus(config, { connector: connections[0]?.connector, // [!code focus] id: '0x1234567890abcdef', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### id `string` Identifier of the call batch. ::: code-group ```ts [index.ts] import { getCallsStatus } from '@wagmi/core' import { config } from './config' const status = await getCallsStatus(config, { id: '0x1234567890abcdef', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetCallsStatusReturnType } from '@wagmi/core' ``` `{ status: 'PENDING' | 'CONFIRMED', receipts: TransactionReceipt[] }` The status and receipts of the call batch. ## Error ```ts import { type GetCallsStatusErrorType } from '@wagmi/core' ``` ## Viem - [`getCallsStatus`](https://viem.sh/docs/actions/wallet/getCallsStatus) ================================================ FILE: site/core/api/actions/getCapabilities.md ================================================ # getCapabilities Action to extract capabilities (grouped by chain ID) that a connected wallet supports (e.g. paymasters, session keys, etc). [Read more.](https://github.com/ethereum/EIPs/blob/815028dc634463e1716fc5ce44c019a6040f0bef/EIPS/eip-5792.md#wallet_getcapabilities) ## Import ```ts import { getCapabilities } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getCapabilities } from '@wagmi/core' import { config } from './config' const capabilities = await getCapabilities(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetCapabilitiesParameters } from '@wagmi/core' ``` ### account `Account | Address | undefined` Fetch capabilities for the provided account. ::: code-group ```ts [index.ts] import { getCapabilities } from '@wagmi/core' import { config } from './config' const capabilities = await getCapabilities(config, { account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### connector `Connector | undefined` Connector to get capabilities from. ::: code-group ```ts [index.ts] import { getConnections, getCapabilities } from '@wagmi/core' import { config } from './config' const connections = getConnections(config) const capabilities = await getCapabilities(config, { connector: connections[0]?.connector, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetCapabilitiesReturnType } from '@wagmi/core' ``` `bigint` Most recent block number seen. ## Error ```ts import { type GetCapabilitiesErrorType } from '@wagmi/core' ``` ## Viem - [`getCapabilities`](https://viem.sh/docs/actions/wallet/getCapabilities) ================================================ FILE: site/core/api/actions/getChainId.md ================================================ # getChainId Action for getting current chain ID. ## Import ```ts import { getChainId } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getChainId } from '@wagmi/core' import { config } from './config' const chainId = getChainId(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetChainIdReturnType } from '@wagmi/core' ``` `number` Current chain ID from [`config.state.chainId`](/core/api/createConfig#chainid). ::: info Only returns chain IDs for chains configured via `createConfig`'s [`chains`](/core/api/createConfig#chains) parameter. If the active [connection](/core/api/createConfig#connection) [`chainId`](/core/api/createConfig#chainid-1) is not from a chain included in your Wagmi `Config`, `getChainId` will return the last configured chain ID. ::: ================================================ FILE: site/core/api/actions/getChains.md ================================================ # getChains Action for getting configured chains. ## Import ```ts import { getChains } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getChains } from '@wagmi/core' import { config } from './config' const chains = getChains(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetChainsReturnType } from '@wagmi/core' ``` `readonly [Chain, ...Chain[]]` Chains from [`config.chains`](/core/api/createConfig#chains). ================================================ FILE: site/core/api/actions/getClient.md ================================================ # getClient Action for getting Viem [`Client`](https://viem.sh/docs/clients/custom) instance. ## Import ```ts import { getClient } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getClient } from '@wagmi/core' import { config } from './config' const client = getClient(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetClientParameters } from '@wagmi/core' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when getting Viem Client. ::: code-group ```ts [index.ts] import { getClient } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const client = await getClient(config, { chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetClientReturnType } from '@wagmi/core' ``` `Client` Viem [`Client`](https://viem.sh/docs/clients/custom) instance. ================================================ FILE: site/core/api/actions/getConnection.md ================================================ # getConnection Action for getting current connection. ## Import ```ts import { getConnection } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getConnection } from '@wagmi/core' import { config } from './config' const connection = getConnection(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetConnectionReturnType } from '@wagmi/core' ``` ================================================ FILE: site/core/api/actions/getConnections.md ================================================ # getConnections Action for getting active connections. ## Import ```ts import { getConnections } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getConnections } from '@wagmi/core' import { config } from './config' const connections = getConnections(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetConnectionsReturnType } from '@wagmi/core' ``` [`Connection[]`](/core/api/createConfig#connection) Active connections. ================================================ FILE: site/core/api/actions/getConnectorClient.md ================================================ # getConnectorClient Action for getting a Viem [`Client`](https://viem.sh/docs/clients/custom) object for the current or provided connector. ## Import ```ts import { getConnectorClient } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getConnectorClient } from '@wagmi/core' import { config } from './config' const client = await getConnectorClient(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetConnectorClientParameters } from '@wagmi/core' ``` ### account `Address | Account | undefined` Account to use with client. Throws if account is not found on [`connector`](#connector). ::: code-group ```ts [index.ts] import { getConnectorClient } from '@wagmi/core' import { config } from './config' const client = await getConnectorClient(config, { account: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use with client. ::: code-group ```ts [index.ts] import { getConnectorClient } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const client = await getConnectorClient(config, { chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### connector `Connector | undefined` - Connector to get client for. - Defaults to current connector. ::: code-group ```ts [index.ts] import { getConnections, getConnectorClient } from '@wagmi/core' import { config } from './config' const connections = getConnections(config) const client = await getConnectorClient(config, { connector: connections[0]?.connector, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetChainIdReturnType } from '@wagmi/core' ``` `Client` Viem [`Client`](https://viem.sh/docs/clients/custom) object for the current or provided connector. ## Error ```ts import { type GetConnectorClientErrorType } from '@wagmi/core' ``` ================================================ FILE: site/core/api/actions/getConnectors.md ================================================ # getConnectors Action for getting configured connectors. ## Import ```ts import { getConnectors } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getConnectors } from '@wagmi/core' import { config } from './config' const connectors = getConnectors(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetConnectorsReturnType } from '@wagmi/core' ``` `readonly Connector[]` Connectors from [`config.connectors`](/core/api/createConfig#connectors-1). ================================================ FILE: site/core/api/actions/getContractEvents.md ================================================ # getContractEvents Action for fetching a list of contract event logs matching the provided parameters. ## Import ```ts import { getContractEvents } from '@wagmi/core' ``` ## Usage By default, `getContractEvents` returns all matched events on the ABI. In practice, you must use scoping to filter for specific events. ::: code-group ```ts [index.ts] import { getContractEvents } from '@wagmi/core' import { abi } from './abi' import { config } from './config' // Fetch event logs for every event on every ERC-20 contract. const logs = getContractEvents(config, { abi }) ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetContractEventsParameters } from '@wagmi/core' ``` ### abi `Abi` The contract's ABI. Check out the [TypeScript docs](/react/typescript#const-assert-abis-typed-data) for how to set up ABIs for maximum type inference and safety. ::: code-group ```ts [index.ts] import { getContractEvents } from '@wagmi/core' import { abi } from './abi' // [!code focus] import { config } from './config' const logs = getContractEvents(config, { abi, // [!code focus] }) ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### address `Address | undefined` The contract's address. ::: code-group ```ts [index.ts] import { getContractEvents } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const logs = getContractEvents(config, { address: '0x6b175474e89094c44da98b954eedeac495271d0f', // [!code focus] abi, }) ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### args `object | readonly unknown[] | undefined` - Logs can be scoped to given indexed arguments. - Inferred from [`abi`](#abi) and [`eventName`](#eventname). ::: code-group ```ts [index.ts] import { getContractEvents } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const logs = getContractEvents(config, { abi, eventName: 'Transfer', args: { // [!code focus] from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] }, // [!code focus] }) ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: Only indexed arguments in `event` are candidates for `args`. An argument can also be an array to indicate that other values can exist in the position: ::: code-group ```ts [index.ts] import { getContractEvents } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const logs = getContractEvents(config, { abi, eventName: 'Transfer', args: { from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', to: [ // [!code focus] '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac', // [!code focus] '0xa152f8bb749c55e9943a3a0a3111d18ee2b3f94e', // [!code focus] ], // [!code focus] }, }) ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### blockHash `` `0x${string}` | undefined `` - Block hash to include logs from. Mutually exclusive with `fromBlock`/`toBlock`. ::: code-group ```ts [index.ts] import { getContractEvents } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const logs = getContractEvents(config, { abi, blockHash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', // [!code focus] }) ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { getContractEvents } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { abi } from './abi' import { config } from './config' const logs = getContractEvents(config, { abi, chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### eventName `string | undefined` - Event to filter for the contract. - Inferred from [`abi`](#abi). ::: code-group ```ts [index.ts] import { getContractEvents } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const logs = getContractEvents(config, { abi, eventName: 'Approval', // [!code focus] }) ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### fromBlock `bigint | 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` - Block to start including logs from. Mutually exclusive with `blockHash`. ::: code-group ```ts [index.ts] import { getContractEvents } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const logs = getContractEvents(config, { abi, fromBlock: 69420n, // [!code focus] }) ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### strict `boolean | undefined` - Flag to only return logs that conform to the indexed & non-indexed arguments on the `event`, meaning that `args` will always be defined. Defaults to `false`. ::: code-group ```ts [index.ts] import { getContractEvents } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const logs = getContractEvents(config, { abi, strict: true, // [!code focus] }) ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### toBlock `bigint | 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` - Block to stop including logs from. Mutually exclusive with `blockHash`. ::: code-group ```ts [index.ts] import { getContractEvents } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const logs = getContractEvents(config, { abi, toBlock: 70120n, // [!code focus] }) ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetContractEventsReturnType } from '@wagmi/core' ``` A list of event logs. ## Type Inference With [`abi`](#abi) setup correctly, TypeScript will infer the correct types for [`eventName`](#eventname), [`args`](#args), and [`onLogs`](#onlogs) parameters. See the Wagmi [TypeScript docs](/core/typescript) for more information. ## Error ```ts import { type GetContractEventsError } from '@wagmi/core' ``` ## Viem - [`getContractEvents`](https://viem.sh/docs/contract/getContractEvents) ================================================ FILE: site/core/api/actions/getEnsAddress.md ================================================ # getEnsAddress Action for fetching ENS address for name. ## Import ```ts import { getEnsAddress } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getEnsAddress } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensAddress = getEnsAddress(config, { name: normalize('wevm.eth'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ::: warning Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAddress`. You can use Viem's built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this. ::: ## Parameters ```ts import { type GetEnsAddressParameters } from '@wagmi/core' ``` --- ### blockNumber `bigint | undefined` Block number to get ENS address at. ::: code-group ```ts [index.ts] import { getEnsAddress } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensAddress = getEnsAddress(config, { blockNumber: 17829139n, // [!code focus] name: normalize('wevm.eth'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get ENS address at. ::: code-group ```ts [index.ts] import { getEnsAddress } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensAddress = getEnsAddress(config, { blockTag: 'latest', // [!code focus] name: normalize('wevm.eth'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { getEnsAddress } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { normalize } from 'viem/ens' import { config } from './config' const ensAddress = await getEnsAddress(config, { chainId: mainnet.id, // [!code focus] name: normalize('wevm.eth'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### coinType `number | undefined` The [ENSIP-9](https://docs.ens.domains/ens-improvement-proposals/ensip-9-multichain-address-resolution) coin type to fetch the address for. ::: code-group ```ts [index.ts] import { getEnsAddress } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensAddress = await getEnsAddress(config, { coinType: 60, // [!code focus] name: normalize('wevm.eth'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### name `string` Name to get the address for. ::: code-group ```ts [index.ts] import { getEnsAddress } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensAddress = await getEnsAddress(config, { name: normalize('wevm.eth'), // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### universalResolverAddress `Address | undefined` - Address of ENS Universal Resolver Contract. - Defaults to current chain's Universal Resolver Contract address. ::: code-group ```ts [index.ts] import { getEnsAddress } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensAddress = await getEnsAddress(config, { name: normalize('wevm.eth'), universalResolverAddress: '0x74E20Bd2A1fE0cdbe45b9A1d89cb7e0a45b36376', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetEnsAddressReturnType } from '@wagmi/core' ``` `string` ENS address. ## Error ```ts import { type GetEnsAddressErrorType } from '@wagmi/core' ``` ## Viem - [`getEnsAddress`](https://viem.sh/docs/ens/actions/getEnsAddress) ================================================ FILE: site/core/api/actions/getEnsAvatar.md ================================================ # getEnsAvatar Action for fetching ENS address for avatar. ## Import ```ts import { getEnsAvatar } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getEnsAvatar } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensAvatar = await getEnsAvatar(config, { name: normalize('wevm.eth'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ::: warning Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsAvatar`. You can use Viem's built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this. ::: ## Parameters ```ts import { type GetEnsAvatarParameters } from '@wagmi/core' ``` --- ### assetGatewayUrls `{ ipfs?: string | undefined; arweave?: string | undefined } | undefined` Gateway urls to resolve IPFS and/or Arweave assets. ::: code-group ```ts [index.ts] import { getEnsAvatar } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensAvatar = await getEnsAvatar(config, { assetGatewayUrls: { // [!code focus] ipfs: 'https://cloudflare-ipfs.com', // [!code focus] }, // [!code focus] name: normalize('wevm.eth'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockNumber `bigint | undefined` Block number to get avatar at. ::: code-group ```ts [index.ts] import { getEnsAvatar } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensAvatar = await getEnsAvatar(config, { blockNumber: 17829139n, // [!code focus] name: normalize('wevm.eth'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get avatar at. ::: code-group ```ts [index.ts] import { getEnsAvatar } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensAvatar = await getEnsAvatar(config, { blockTag: 'latest', // [!code focus] name: normalize('wevm.eth'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { getEnsAvatar } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { normalize } from 'viem/ens' import { config } from './config' const ensAvatar = await getEnsAvatar(config, { chainId: mainnet.id, // [!code focus] name: normalize('wevm.eth'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### gatewayUrls `string[] | undefined` A set of Universal Resolver gateways, used for resolving CCIP-Read requests made through the ENS Universal Resolver Contract. ::: code-group ```ts [index.ts] import { getEnsAvatar } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensAvatar = await getEnsAvatar(config, { gatewayUrls: ['https://cloudflare-ipfs.com'] { // [!code focus] name: normalize('wevm.eth'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### name `string` Name to get the avatar for. ::: code-group ```ts [index.ts] import { getEnsAvatar } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensAvatar = await getEnsAvatar(config, { name: normalize('wevm.eth'), // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### universalResolverAddress `Address | undefined` - Address of ENS Universal Resolver Contract. - Defaults to current chain's Universal Resolver Contract address. ::: code-group ```ts [index.ts] import { getEnsAvatar } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensAvatar = await getEnsAvatar(config, { name: normalize('wevm.eth'), universalResolverAddress: '0x74E20Bd2A1fE0cdbe45b9A1d89cb7e0a45b36376', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetEnsAvatarReturnType } from '@wagmi/core' ``` `string | null` The avatar URI for ENS name. ## Error ```ts import { type getEnsAvatarError } from '@wagmi/core' ``` ## Viem - [`getEnsAvatar`](https://viem.sh/docs/ens/actions/getEnsAvatar) ================================================ FILE: site/core/api/actions/getEnsName.md ================================================ # getEnsName Action for fetching primary ENS name for address. ## Import ```ts import { getEnsName } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getEnsName } from '@wagmi/core' import { config } from './config' const ensName = getEnsName(config, { address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetEnsNameParameters } from '@wagmi/core' ``` ### address `Address` Address to get the name for. ::: code-group ```ts [index.ts] import { getEnsName } from '@wagmi/core' import { config } from './config' const ensName = await getEnsName(config, { address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: --- ### blockNumber `bigint | undefined` Block number to get name at. ::: code-group ```ts [index.ts] import { getEnsName } from '@wagmi/core' import { config } from './config' const ensName = getEnsName(config, { address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', blockNumber: 17829139n, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get name at. ::: code-group ```ts [index.ts] import { getEnsName } from '@wagmi/core' import { config } from './config' const ensName = getEnsName(config, { address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', blockTag: 'latest', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { getEnsName } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const ensName = await getEnsName(config, { address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### universalResolverAddress `Address | undefined` - Address of ENS Universal Resolver Contract. - Defaults to current chain's Universal Resolver Contract address. ::: code-group ```ts [index.ts] import { getEnsName } from '@wagmi/core' import { config } from './config' const ensName = await getEnsName(config, { address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', universalResolverName: '0x74E20Bd2A1fE0cdbe45b9A1d89cb7e0a45b36376', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetEnsNameReturnType } from '@wagmi/core' ``` `string | null` The primary ENS name for the address. Returns `null` if address does not have primary name assigned. ## Error ```ts import { type GetEnsNameErrorType } from '@wagmi/core' ``` ## Viem - [`getEnsName`](https://viem.sh/docs/ens/actions/getEnsName) ================================================ FILE: site/core/api/actions/getEnsResolver.md ================================================ # getEnsResolver Action for fetching ENS resolver for name. ## Import ```ts import { getEnsResolver } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getEnsResolver } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensResolver = getEnsResolver(config, { name: normalize('wevm.eth'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ::: warning Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsResolver`. You can use Viem's built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this. ::: ## Parameters ```ts import { type GetEnsResolverParameters } from '@wagmi/core' ``` --- ### blockNumber `bigint | undefined` Block number to get resolver at. ::: code-group ```ts [index.ts] import { getEnsResolver } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensResolver = getEnsResolver(config, { blockNumber: 17829139n, // [!code focus] name: normalize('wevm.eth'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get resolver at. ::: code-group ```ts [index.ts] import { getEnsResolver } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensResolver = getEnsResolver(config, { blockTag: 'latest', // [!code focus] name: normalize('wevm.eth'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { getEnsResolver } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { normalize } from 'viem/ens' import { config } from './config' const ensResolver = await getEnsResolver(config, { chainId: mainnet.id, // [!code focus] name: normalize('wevm.eth'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### name `string` Name to get the resolver for. ::: code-group ```ts [index.ts] import { getEnsResolver } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensResolver = await getEnsResolver(config, { name: normalize('wevm.eth'), // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### universalResolverAddress `Address | undefined` - Address of ENS Universal Resolver Contract. - Defaults to current chain's Universal Resolver Contract address. ::: code-group ```ts [index.ts] import { getEnsResolver } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensResolver = await getEnsResolver(config, { name: normalize('wevm.eth'), universalResolverAddress: '0x74E20Bd2A1fE0cdbe45b9A1d89cb7e0a45b36376', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetEnsResolverReturnType } from '@wagmi/core' ``` `Address` The address of the resolver. ## Error ```ts import { type getEnsResolverError } from '@wagmi/core' ``` ## Viem - [`getEnsResolver`](https://viem.sh/docs/ens/actions/getEnsResolver) ================================================ FILE: site/core/api/actions/getEnsText.md ================================================ # getEnsText Action for fetching a text record for a specified ENS name and key. ## Import ```ts import { getEnsText } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getEnsText } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensText = getEnsText(config, { name: normalize('wevm.eth'), key: 'com.twitter', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ::: warning Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `getEnsText`. You can use Viem's built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this. ::: ## Parameters ```ts import { type GetEnsTextParameters } from '@wagmi/core' ``` --- ### blockNumber `bigint | undefined` Block number to get the text at. ::: code-group ```ts [index.ts] import { getEnsText } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensText = getEnsText(config, { blockNumber: 17829139n, // [!code focus] name: normalize('wevm.eth'), key: 'com.twitter', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get the text at. ::: code-group ```ts [index.ts] import { getEnsText } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensText = getEnsText(config, { blockTag: 'latest', // [!code focus] name: normalize('wevm.eth'), key: 'com.twitter', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { getEnsText } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { normalize } from 'viem/ens' import { config } from './config' const ensText = await getEnsText(config, { chainId: mainnet.id, // [!code focus] name: normalize('wevm.eth'), key: 'com.twitter', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### key `string` ENS key to get Text for. ::: code-group ```ts [index.ts] import { getEnsText } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensText = await getEnsText(config, { name: normalize('wevm.eth'), key: 'com.twitter', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### name `string` Name to get the text for. ::: code-group ```ts [index.ts] import { getEnsText } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensText = await getEnsText(config, { name: normalize('wevm.eth'), // [!code focus] key: 'com.twitter', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### universalResolverAddress `Address | undefined` - Address of ENS Universal Resolver Contract. - Defaults to current chain's Universal Resolver Contract address. ::: code-group ```ts [index.ts] import { getEnsText } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' const ensText = await getEnsText(config, { name: normalize('wevm.eth'), key: 'com.twitter', universalResolverAddress: '0x74E20Bd2A1fE0cdbe45b9A1d89cb7e0a45b36376', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetEnsTextReturnType } from '@wagmi/core' ``` `string | null` The text record for ENS name. Returns `null` if name does not have text assigned. ## Error ```ts import { type getEnsTextError } from '@wagmi/core' ``` ## Viem - [`getEnsText`](https://viem.sh/docs/ens/actions/getEnsText) ================================================ FILE: site/core/api/actions/getFeeHistory.md ================================================ # getFeeHistory Action for fetching a collection of historical gas information. ## Import ```ts import { getFeeHistory } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getFeeHistory } from '@wagmi/core' import { config } from './config' const feeHistory = await getFeeHistory(config, { blockCount: 4, rewardPercentiles: [25, 75] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetFeeHistoryParameters } from '@wagmi/core' ``` ### blockCount `number` Number of blocks in the requested range. Between 1 and 1024 blocks can be requested in a single query. Less than requested may be returned if not all blocks are available. ::: code-group ```ts [index.ts] import { getFeeHistory } from '@wagmi/core' import { config } from './config' const feeHistory = await getFeeHistory(config, { blockCount: 4, // [!code focus] rewardPercentiles: [25, 75] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### rewardPercentiles `number[]` A monotonically increasing list of percentile values to sample from each block's effective priority fees per gas in ascending order, weighted by gas used. ::: code-group ```ts [index.ts] import { getFeeHistory } from '@wagmi/core' import { config } from './config' const feeHistory = await getFeeHistory(config, { blockCount: 4, rewardPercentiles: [25, 75] // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockNumber `bigint | undefined` Highest number block of the requested range. ::: code-group ```ts [index.ts] import { getFeeHistory } from '@wagmi/core' import { config } from './config' const feeHistory = await getFeeHistory(config, { blockCount: 4, blockNumber: 1551231n, // [!code focus] rewardPercentiles: [25, 75], }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag of the highest number block of the requested range. ::: code-group ```ts [index.ts] import { getFeeHistory } from '@wagmi/core' import { config } from './config' const feeHistory = await getFeeHistory(config, { blockCount: 4, blockTag: 'safe', // [!code focus] rewardPercentiles: [25, 75], }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { getFeeHistory } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const feeHistory = await getFeeHistory(config, { blockCount: 4, chainId: mainnet.id, // [!code focus] rewardPercentiles: [25, 75], }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetFeeHistoryReturnType } from '@wagmi/core' ``` [`FeeHistory`](https://viem.sh/docs/glossary/types#feehistory) The fee history. ## Error ```ts import { type GetFeeHistoryErrorType } from '@wagmi/core' ``` ## Viem - [`getFeeHistory`](https://viem.sh/docs/actions/public/getFeeHistory) ================================================ FILE: site/core/api/actions/getGasPrice.md ================================================ # getGasPrice Action for fetching the current price of gas (in wei). ## Import ```ts import { getGasPrice } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getGasPrice } from '@wagmi/core' import { config } from './config' const gasPrice = await getGasPrice(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetGasPriceParameters } from '@wagmi/core' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { getGasPrice } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const gasPrice = await getGasPrice(config, { chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetGasPriceReturnType } from '@wagmi/core' ``` `bigint` Current price of gas (in wei). ## Error ```ts import { type GetGasPriceErrorType } from '@wagmi/core' ``` ## Viem - [`getGasPrice`](https://viem.sh/docs/actions/public/getGasPrice) ================================================ FILE: site/core/api/actions/getProof.md ================================================ # getProof Action for return the account and storage values of the specified account including the Merkle-proof. ## Import ```ts import { getProof } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getProof } from '@wagmi/core' import { config } from './config' await getProof(config, { address: '0x4200000000000000000000000000000000000016', storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetProofParameters } from '@wagmi/core' ``` ### address `Address` The account address to get the proof for. ::: code-group ```ts [index.ts] import { getProof } from '@wagmi/core' import { config } from './config' await getProof(config, { address: '0x4200000000000000000000000000000000000016', // [!code focus] storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### storageKeys `` `0x${string}`[] `` Array of storage-keys that should be proofed and included. ::: code-group ```ts [index.ts] import { getProof } from '@wagmi/core' import { config } from './config' await getProof(config, { address: '0x4200000000000000000000000000000000000016', storageKeys: [ // [!code focus:3] '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockNumber `bigint | undefined` Proof at a given block number. ::: code-group ```ts [index.ts] import { getProof } from '@wagmi/core' import { config } from './config' await getProof(config, { address: '0x4200000000000000000000000000000000000016', blockNumber: 42069n, // [!code focus] storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Proof at a given block tag. ::: code-group ```ts [index.ts] import { getProof } from '@wagmi/core' import { config } from './config' await getProof(config, { address: '0x4200000000000000000000000000000000000016', blockTag: 'latest', // [!code focus] storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` The ID of chain to get the proof for. ::: code-group ```ts [index.ts] import { getProof } from '@wagmi/core' import { config } from './config' import { optimism } from '@wagmi/core/chains' await getProof(config, { chainId: optimism.id, // [!code focus] address: '0x4200000000000000000000000000000000000016', storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetProofReturnType } from '@wagmi/core' ``` `Proof` Proof data. ## Error ```ts import { type GetProofErrorType } from '@wagmi/core' ``` ## Viem - [`getProof`](https://viem.sh/docs/actions/public/getProof) ================================================ FILE: site/core/api/actions/getPublicClient.md ================================================ # getPublicClient Action for getting Viem [`PublicClient`](https://viem.sh/docs/clients/public) instance. ## Import ```ts import { getPublicClient } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getPublicClient } from '@wagmi/core' import { config } from './config' const client = getPublicClient(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: ::: warning If you want to optimize bundle size, you should use [`getClient`](/core/api/actions/getClient) along with Viem's [tree-shakable actions](https://viem.sh/docs/clients/custom#tree-shaking) instead. Since Public Client has all public actions attached directly to it. ::: ## Parameters ```ts import { type GetClientParameters } from '@wagmi/core' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when getting Viem Public Client. ::: code-group ```ts [index.ts] import { getPublicClient } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const client = getPublicClient(config, { chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetPublicClientReturnType } from '@wagmi/core' ``` `PublicClient | undefined` Viem [`PublicClient`](https://viem.sh/docs/clients/public) instance. ================================================ FILE: site/core/api/actions/getStorageAt.md ================================================ # getStorageAt Action for returning the value from a storage slot at a given address. ## Import ```ts import { getStorageAt } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getStorageAt } from '@wagmi/core' import { config } from './config' await getStorageAt(config, { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', slot: '0x0', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetStorageAtParameters } from '@wagmi/core' ``` ### address `Address` The contract address. ::: code-group ```ts [index.ts] import { getStorageAt } from '@wagmi/core' import { config } from './config' await getStorageAt(config, { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', // [!code focus] slot: '0x0', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### slot `Hex` The storage position (as a hex encoded value). ::: code-group ```ts [index.ts] import { getStorageAt } from '@wagmi/core' import { config } from './config' await getStorageAt(config, { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', slot: '0x0', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockNumber `bigint | undefined` The block number to check the storage at. ::: code-group ```ts [index.ts] import { getStorageAt } from '@wagmi/core' import { config } from './config' await getStorageAt(config, { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', blockNumber: 16280770n, // [!code focus] slot: '0x0', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` The block tag to check the storage at. ::: code-group ```ts [index.ts] import { getStorageAt } from '@wagmi/core' import { config } from './config' await getStorageAt(config, { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', blockTag: 'safe', // [!code focus] slot: '0x0', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` The chain ID to check the storage at. ::: code-group ```ts [index.ts] import { getStorageAt } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' await getStorageAt(config, { chainId: mainnet.id, // [!code focus] address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', slot: '0x0', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetStorageAtReturnType } from '@wagmi/core' ``` `Hex` The value of the storage slot. ## Error ```ts import { type GetStorageAtErrorType } from '@wagmi/core' ``` ## Viem - [`getStorageAt`](https://viem.sh/docs/contract/getStorageAt) ================================================ FILE: site/core/api/actions/getTransaction.md ================================================ # getTransaction Action for fetching transactions given hashes or block identifiers. ## Import ```ts import { getTransaction } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getTransaction } from '@wagmi/core' import { config } from './config' const transaction = getTransaction(config, { hash: '0x0fa64daeae54e207aa98613e308c2ba8abfe274f75507e741508cc4db82c8cb5', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetTransactionParameters } from '@wagmi/core' ``` --- ### blockHash `bigint | undefined` Block hash to get transaction at (with [`index`](#index)). ::: code-group ```ts [index.ts] import { getTransaction } from '@wagmi/core' import { config } from './config' const transaction = getTransaction(config, { blockHash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', // [!code focus] index: 0, }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockNumber `bigint | undefined` Block number to get transaction at (with [`index`](#index)). ::: code-group ```ts [index.ts] import { getTransaction } from '@wagmi/core' import { config } from './config' const transaction = getTransaction(config, { blockNumber: 17829139n, // [!code focus] index: 0, }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get transaction at (with [`index`](#index)). ::: code-group ```ts [index.ts] import { getTransaction } from '@wagmi/core' import { config } from './config' const transaction = getTransaction(config, { blockTag: 'safe', // [!code focus] index: 0, }) ``` <<< @/snippets/core/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { getTransaction } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const transaction = await getTransaction(config, { chainId: mainnet.id, // [!code focus] hash: '0x0fa64daeae54e207aa98613e308c2ba8abfe274f75507e741508cc4db82c8cb5', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### hash `` `0x${string}` | undefined `` Hash to get transaction. ::: code-group ```ts [index.ts] import { getTransaction } from '@wagmi/core' import { config } from './config' const transaction = getTransaction(config, { hash: '0x0fa64daeae54e207aa98613e308c2ba8abfe274f75507e741508cc4db82c8cb5', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### index `number | undefined` An index to be used with a block identifier ([hash](#blockhash), [number](#blocknumber), or [tag](#blocktag)). ::: code-group ```ts [index.ts] import { getTransaction } from '@wagmi/core' import { config } from './config' const transaction = getTransaction(config, { blockTag: 'safe', index: 0 // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetTransactionReturnType } from '@wagmi/core' ``` [`Transaction`](https://viem.sh/docs/glossary/types#transaction) ## Error ```ts import { type GetTransactionErrorType } from '@wagmi/core' ``` ## Viem - [`getTransaction`](https://viem.sh/docs/actions/public/getTransaction) ================================================ FILE: site/core/api/actions/getTransactionConfirmations.md ================================================ # getTransactionConfirmations Action for fetching the number of blocks passed (confirmations) since the transaction was processed on a block. If confirmations is 0, then the Transaction has not been confirmed & processed yet. ## Import ```ts import { getTransactionConfirmations } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getTransactionConfirmations } from '@wagmi/core' import { config } from './config' const transaction = getTransactionConfirmations(config, { hash: '0x0fa64daeae54e207aa98613e308c2ba8abfe274f75507e741508cc4db82c8cb5', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetTransactionConfirmationsParameters } from '@wagmi/core' ``` --- ### hash `` `0x${string}` | undefined `` The hash of the transaction. ::: code-group ```ts [index.ts] import { getTransactionConfirmations } from '@wagmi/core' import { config } from './config' const transaction = getTransactionConfirmations(config, { hash: '0x0fa64daeae54e207aa98613e308c2ba8abfe274f75507e741508cc4db82c8cb5', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### transactionReceipt `TransactionReceipt | undefined` The transaction receipt. ::: code-group ```ts [index.ts] import { getTransactionConfirmations } from '@wagmi/core' import { config } from './config' const transaction = getTransactionConfirmations(config, { transactionReceipt: { ... }, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { getTransactionConfirmations } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const transaction = await getTransactionConfirmations(config, { chainId: mainnet.id, // [!code focus] hash: '0x0fa64daeae54e207aa98613e308c2ba8abfe274f75507e741508cc4db82c8cb5', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetTransactionConfirmationsReturnType } from '@wagmi/core' ``` `bigint` The number of blocks passed since the transaction was processed. If confirmations is 0, then the Transaction has not been confirmed & processed yet. ## Error ```ts import { type GetTransactionConfirmationsErrorType } from '@wagmi/core' ``` ## Viem - [`getTransactionConfirmations`](https://viem.sh/docs/actions/public/getTransactionConfirmations) ================================================ FILE: site/core/api/actions/getTransactionCount.md ================================================ # getTransactionCount Action for fetching the number of transactions an Account has sent. ## Import ```ts import { getTransactionCount } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getTransactionCount } from '@wagmi/core' import { config } from './config' const transactionCount = getTransactionCount(config, { address: '0x4557B18E779944BFE9d78A672452331C186a9f48', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetTransactionCountParameters } from '@wagmi/core' ``` --- ### address `Address` The address of the account. ::: code-group ```ts [index.ts] import { getTransactionCount } from '@wagmi/core' import { config } from './config' const transactionCount = getTransactionCount(config, { address: '0x4557B18E779944BFE9d78A672452331C186a9f48', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: --- ### blockNumber `bigint | undefined` Get the count at a block number. ::: code-group ```ts [index.ts] import { getTransactionCount } from '@wagmi/core' import { config } from './config' const transactionCount = getTransactionCount(config, { address: '0x4557B18E779944BFE9d78A672452331C186a9f48', blockNumber: 17829139n, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Get the count at a block tag. ::: code-group ```ts [index.ts] import { getTransactionCount } from '@wagmi/core' import { config } from './config' const transactionCount = getTransactionCount(config, { address: '0x4557B18E779944BFE9d78A672452331C186a9f48', blockTag: 'latest', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { getTransactionCount } from '@wagmi/core' import { config } from './config' const transactionCount = getTransactionCount(config, { address: '0x4557B18E779944BFE9d78A672452331C186a9f48', chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetTransactionCountReturnType } from '@wagmi/core' ``` `number` The number of transactions an account has sent. ## Error ```ts import { type GetTransactionCountErrorType } from '@wagmi/core' ``` ## Viem - [`getTransactionCount`](https://viem.sh/docs/actions/public/getTransactionCount) ================================================ FILE: site/core/api/actions/getTransactionReceipt.md ================================================ # getTransactionReceipt Action for return the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. ## Import ```ts import { getTransactionReceipt } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getTransactionReceipt } from '@wagmi/core' import { config } from './config' await getTransactionReceipt(config, { hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type GetTransactionReceiptParameters } from '@wagmi/core' ``` ### hash `` `0x${string}` `` A transaction hash. ::: code-group ```ts [index.ts] import { getTransactionReceipt } from '@wagmi/core' import { config } from './config' await getTransactionReceipt(config, { hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` The ID of chain to return the transaction receipt from. ::: code-group ```ts [index.ts] import { getTransactionReceipt } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' await getTransactionReceipt(config, { chainId: mainnet.id, // [!code focus] hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetTransactionReceiptReturnType } from '@wagmi/core' ``` [`TransactionReceipt`](https://viem.sh/docs/glossary/types#transactionreceipt) The transaction receipt. ## Error ```ts import { type GetTransactionReceiptErrorType } from '@wagmi/core' ``` ## Viem - [`getTransactionReceipt`](https://viem.sh/docs/actions/public/getTransactionReceipt) ================================================ FILE: site/core/api/actions/getWalletClient.md ================================================ # getWalletClient Action for getting a Viem [`WalletClient`](https://viem.sh/docs/clients/wallet) object for the current or provided connector. ## Import ```ts import { getWalletClient } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getWalletClient } from '@wagmi/core' import { config } from './config' const client = getWalletClient(config) ``` <<< @/snippets/core/config.ts[config.ts] ::: ::: warning If you want to optimize bundle size, you should use [`getConnectorClient`](/core/api/actions/getConnectorClient) along with Viem's [tree-shakable actions](https://viem.sh/docs/clients/custom#tree-shaking) instead. Since Wallet Client has all wallet actions attached directly to it. ::: ## Parameters ```ts import { type GetWalletClientParameters } from '@wagmi/core' ``` ### account `Address | Account | undefined` Account to use with client. Throws if account is not found on [`connector`](#connector). ::: code-group ```ts [index.ts] import { getWalletClient } from '@wagmi/core' import { config } from './config' const client = getWalletClient(config, { account: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use with client. ::: code-group ```ts [index.ts] import { getWalletClient } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const client = getWalletClient(config, { chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### connector `Connector | undefined` - Connector to get client for. - Defaults to current connector. ::: code-group ```ts [index.ts] import { getConnections, getWalletClient } from '@wagmi/core' import { config } from './config' const connections = getConnections(config) const client = getWalletClient(config, { connector: connections[0]?.connector, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type GetChainIdReturnType } from '@wagmi/core' ``` `WalletClient` Viem [`WalletClient`](https://viem.sh/docs/clients/wallet) object for the current or provided connector. ## Error ```ts import { type GetWalletClientErrorType } from '@wagmi/core' ``` ================================================ FILE: site/core/api/actions/multicall.md ================================================ # multicall Action for batching up multiple functions on a contract in a single RPC call via the [Multicall3 contract](https://github.com/mds1/multicall). ## Import ```ts import { multicall } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { multicall } from '@wagmi/core' import { config } from './config' const wagmigotchiContract = { address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', abi: wagmigotchiABI, } as const const mlootContract = { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, } as const const result = await multicall(config, { contracts: [ { ...wagmigotchiContract, functionName: 'getAlive', }, { ...wagmigotchiContract, functionName: 'getBoredom', }, { ...mlootContract, functionName: 'getChest', args: [69], }, { ...mlootContract, functionName: 'getWaist', args: [69], }, ], }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type MulticallParameters } from '@wagmi/core' ``` ### contracts `readonly Contract[]` Set of contracts to call. #### abi `Abi | undefined` The contract's ABI. Check out the [TypeScript docs](/react/typescript#const-assert-abis-typed-data) for how to set up ABIs for maximum type inference and safety. ::: code-group ```tsx [index.tsx] import { multicall } from '@wagmi/core' import { config } from './config' const result = await multicall(config, { contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, // [!code hl] functionName: 'getChest', args: [69], }, // ... ], }) ``` <<< @/snippets/react/config.ts[config.ts] ::: #### address `Address | undefined` The contract's address. ::: code-group ```tsx [index.tsx] import { multicall } from '@wagmi/core' import { config } from './config' const result = await multicall(config, { contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', // [!code hl] abi: mlootABI, functionName: 'getChest', args: [69], }, // ... ], }) ``` <<< @/snippets/react/config.ts[config.ts] ::: #### args `readonly unknown[] | undefined` - Arguments to pass when calling the contract. - Inferred from [`abi`](#abi) and [`functionName`](#functionname). ::: code-group ```tsx [index.tsx] import { multicall } from '@wagmi/core' import { config } from './config' const result = await multicall(config, { contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69], // [!code hl] }, // ... ], }) ``` <<< @/snippets/react/config.ts[config.ts] ::: #### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { multicall } from '@wagmi/core' import { config } from './config' const result = await multicall(config, { contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69], chainId: 1, // [!code hl] }, // ... ], }) ``` <<< @/snippets/react/config.ts[config.ts] ::: #### functionName `string | undefined` - Function to call on the contract. - Inferred from [`abi`](#abi). ::: code-group ```tsx [index.tsx] import { multicall } from '@wagmi/core' import { config } from './config' const result = await multicall(config, { contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', // [!code hl] args: [69], }, // ... ], }) ``` <<< @/snippets/react/config.ts[config.ts] ::: ### allowFailure `boolean` Whether or not the Hook should throw if a call reverts. If set to `true` (default), and a call reverts, then `multicall` will fail silently and its error will be logged in the results array. Defaults to `true`. ::: code-group ```tsx [index.tsx] import { multicall } from '@wagmi/core' import { config } from './config' const result = await multicall(config, { allowFailure: false, // [!code hl] contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69], }, // ... ], }) ``` <<< @/snippets/react/config.ts[config.ts] ::: ### batchSize `number` The maximum size (in bytes) for each calldata chunk. Set to `0` to disable the size limit. Defaults to `1024`. > Note: Some RPC Providers limit the amount of calldata (`data`) that can be sent in a single `eth_call` request. It is best to check with your RPC Provider to see if there are any calldata size limits to `eth_call` requests. ::: code-group ```tsx [index.tsx] import { multicall } from '@wagmi/core' import { config } from './config' const result = await multicall(config, { batchSize: 1_024, // [!code hl] contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69], }, // ... ], }) ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockNumber `number` The block number to perform the read against. ::: code-group ```tsx [index.tsx] import { multicall } from '@wagmi/core' import { config } from './config' const result = await multicall(config, { blockNumber: 69420n, // [!code hl] contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69], }, // ... ], }) ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to read against. ::: code-group ```tsx [index.tsx] import { multicall } from '@wagmi/core' import { config } from './config' const result = await multicall(config, { blockTag: 'safe', // [!code hl] contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69], }, // ... ], }) ``` <<< @/snippets/react/config.ts[config.ts] ::: ### multicallAddress `Address` Address of multicall contract. ::: code-group ```tsx [index.tsx] import { multicall } from '@wagmi/core' import { config } from './config' const result = await multicall(config, { contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69], }, // ... ], multicallAddress: '0xca11bde05977b3631167028862be2a173976ca11', // [!code hl] }) ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type MulticallReturnType } from '@wagmi/core' ``` ## Type Inference With [`contracts[number]['abi']`](#abi) setup correctly, TypeScript will infer the correct types for [`functionName`](#functionname), [`args`](#args), and the return type. See the Wagmi [TypeScript docs](/core/typescript) for more information. ## Error ```ts import { type MulticallErrorType } from '@wagmi/core' ``` ## Viem - [`multicall`](https://viem.sh/docs/contract/multicall) ================================================ FILE: site/core/api/actions/prepareTransactionRequest.md ================================================ # prepareTransactionRequest Action for preparing a transaction request for signing by populating a nonce, gas limit, fee values, and a transaction type. ## Import ```ts import { prepareTransactionRequest } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { prepareTransactionRequest } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' await prepareTransactionRequest(config, { to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type PrepareTransactionRequestParameters } from '@wagmi/core' ``` ### account `Account | Address | undefined` The Account to send the transaction from. ::: code-group ```ts [index.ts] import { prepareTransactionRequest } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' await prepareTransactionRequest(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### to `` `0x${string}` | undefined `` The transaction recipient or contract address. ::: code-group ```ts [index.ts] import { prepareTransactionRequest } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' await prepareTransactionRequest(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', // [!code focus] value: parseEther('1'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### accessList `AccessList | undefined` The access list. ::: code-group ```ts [index.ts] import { prepareTransactionRequest } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' await prepareTransactionRequest(config, { accessList: [ // [!code focus:6] { address: '0x1', storageKeys: ['0x1'], }, ], account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` Chain ID to prepare the transaction request for. ::: code-group ```ts [index.ts] import { prepareTransactionRequest } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { parseEther } from 'viem' import { config } from './config' await prepareTransactionRequest(config, { chainId: mainnet.id, // [!code focus] account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### data `` `0x${string}` | undefined `` A contract hashed method call with encoded args. ::: code-group ```ts [index.ts] import { prepareTransactionRequest } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' await prepareTransactionRequest(config, { data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // [!code focus] account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### gasPrice `bigint | undefined` The price (in wei) to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction). ::: code-group ```ts [index.ts] import { prepareTransactionRequest } from '@wagmi/core' import { parseEther, parseGwei } from 'viem' import { config } from './config' await prepareTransactionRequest(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', gasPrice: parseGwei('20'), // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### maxFeePerGas `bigint | undefined` Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```ts [index.ts] import { prepareTransactionRequest } from '@wagmi/core' import { parseEther, parseGwei } from 'viem' import { config } from './config' await prepareTransactionRequest(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', maxFeePerGas: parseGwei('20'), // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### maxPriorityFeePerGas `bigint | undefined` Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```ts [index.ts] import { prepareTransactionRequest } from '@wagmi/core' import { parseEther, parseGwei } from 'viem' import { config } from './config' await prepareTransactionRequest(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### nonce `number | undefined` Unique number identifying this transaction. ::: code-group ```ts [index.ts] import { prepareTransactionRequest } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' await prepareTransactionRequest(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), nonce: 5, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### parameters `("fees" | "gas" | "nonce" | "type")[] | undefined` Parameters to prepare. For instance, if `["gas", "nonce"]` is provided, then only the `gas` and `nonce` parameters will be prepared. ::: code-group ```ts [index.ts] import { prepareTransactionRequest } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' await prepareTransactionRequest(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', parameters: ['gas', 'nonce'], // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### value `bigint | undefined` The transaction recipient or contract address. ::: code-group ```ts [index.ts] import { prepareTransactionRequest } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' await prepareTransactionRequest(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type PrepareTransactionRequestReturnType } from '@wagmi/core' ``` [`TransactionRequest`](https://viem.sh/docs/glossary/types#transactionrequest) The transaction request. ## Error ```ts import { type PrepareTransactionRequestErrorType } from '@wagmi/core' ``` ## Viem - [`prepareTransactionRequest`](https://viem.sh/docs/actions/wallet/prepareTransactionRequest) ================================================ FILE: site/core/api/actions/readContract.md ================================================ # readContract Action for calling a **read-only** function on a contract, and returning the response. A **read-only** function (constant function) on a Solidity contract is denoted by a pure or view keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas. ## Import ```ts import { readContract } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { readContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await readContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'totalSupply', }) ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type ReadContractParameters } from '@wagmi/core' ``` ### abi `Abi` The contract's ABI. Check out the [TypeScript docs](/react/typescript#const-assert-abis-typed-data) for how to set up ABIs for maximum type inference and safety. ::: code-group ```ts [index.ts] import { readContract } from '@wagmi/core' import { abi } from './abi' // [!code focus] import { config } from './config' const result = await readContract(config, { abi, // [!code focus] address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'totalSupply', }) ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### account `Account | undefined` Account to use when calling the contract (`msg.sender`). ::: code-group ```ts [index.ts] import { readContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await readContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'balanceOf', args: ['0xd2135CfB216b74109775236E36d4b433F1DF507B'], account: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] }) ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### address `Address` The contract's address. ::: code-group ```ts [index.ts] import { readContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await readContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', // [!code focus] functionName: 'totalSupply', }) ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### args `readonly unknown[] | undefined` - Arguments to pass when calling the contract. - Inferred from [`abi`](#abi) and [`functionName`](#functionname). ::: code-group ```ts [index.ts] import { readContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await readContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'balanceOf', args: ['0xd2135CfB216b74109775236E36d4b433F1DF507B'], // [!code focus] }) ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: --- ### blockNumber `bigint | undefined` Block number to call contract at. ::: code-group ```ts [index.ts] import { readContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await readContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'totalSupply', blockNumber: 17829139n, // [!code focus] }) ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to call contract at. ::: code-group ```ts [index.ts] import { readContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await readContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'totalSupply', blockTag: 'safe', // [!code focus] }) ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { readContract } from '@wagmi/core' import { mainnet } from 'wagmi/chains' // [!code focus] import { abi } from './abi' import { config } from './config' const result = await readContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'totalSupply', chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### functionName `string` - Function to call on the contract. - Inferred from [`abi`](#abi). ::: code-group ```ts [index.ts] import { readContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await readContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'balanceOf', // [!code focus] args: ['0xd2135CfB216b74109775236E36d4b433F1DF507B'], }) ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type ReadContractReturnType } from '@wagmi/core' ``` `unknown` - Result of contract read-only function. - Inferred from [`abi`](#abi), [`functionName`](#functionname), and [`args`](#args). ## Type Inference With [`abi`](#abi) setup correctly, TypeScript will infer the correct types for [`functionName`](#functionname), [`args`](#args), and the return type. See the Wagmi [TypeScript docs](/core/typescript) for more information. ## Error ```ts import { type ReadContractErrorType } from '@wagmi/core' ``` ## Viem - [`readContract`](https://viem.sh/docs/contract/readContract) ================================================ FILE: site/core/api/actions/readContracts.md ================================================ # readContracts Action for calling multiple read methods on a contract. ## Import ```ts import { readContracts } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { readContracts } from '@wagmi/core' import { config } from './config' const wagmigotchiContract = { address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', abi: wagmigotchiABI, } as const const mlootContract = { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, } as const const result = await readContracts(config, { contracts: [ { ...wagmigotchiContract, functionName: 'getAlive', }, { ...wagmigotchiContract, functionName: 'getBoredom', }, { ...mlootContract, functionName: 'getChest', args: [69], }, { ...mlootContract, functionName: 'getWaist', args: [69], }, ], }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type ReadContractsParameters } from '@wagmi/core' ``` ### contracts `readonly Contract[]` Set of contracts to call. #### abi `Abi | undefined` The contract's ABI. Check out the [TypeScript docs](/react/typescript#const-assert-abis-typed-data) for how to set up ABIs for maximum type inference and safety. ::: code-group ```tsx [index.tsx] import { readContracts } from '@wagmi/core' import { config } from './config' const result = await readContracts(config, { contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, // [!code hl] functionName: 'getChest', args: [69], }, // ... ], }) ``` <<< @/snippets/react/config.ts[config.ts] ::: #### address `Address | undefined` The contract's address. ::: code-group ```tsx [index.tsx] import { readContracts } from '@wagmi/core' import { config } from './config' const result = await readContracts(config, { contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', // [!code hl] abi: mlootABI, functionName: 'getChest', args: [69], }, // ... ], }) ``` <<< @/snippets/react/config.ts[config.ts] ::: #### args `readonly unknown[] | undefined` - Arguments to pass when calling the contract. - Inferred from [`abi`](#abi) and [`functionName`](#functionname). ::: code-group ```tsx [index.tsx] import { readContracts } from '@wagmi/core' import { config } from './config' const result = await readContracts(config, { contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69], // [!code hl] }, // ... ], }) ``` <<< @/snippets/react/config.ts[config.ts] ::: #### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { readContracts } from '@wagmi/core' import { config } from './config' const result = await readContracts(config, { contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69], chainId: 1, // [!code hl] }, // ... ], }) ``` <<< @/snippets/react/config.ts[config.ts] ::: #### functionName `string | undefined` - Function to call on the contract. - Inferred from [`abi`](#abi). ::: code-group ```tsx [index.tsx] import { readContracts } from '@wagmi/core' import { config } from './config' const result = await readContracts(config, { contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', // [!code hl] args: [69], }, // ... ], }) ``` <<< @/snippets/react/config.ts[config.ts] ::: ### allowFailure `boolean` Whether or not the Hook should throw if a call reverts. If set to `true` (default), and a call reverts, then `readContracts` will fail silently and its error will be logged in the results array. Defaults to `true`. ::: code-group ```tsx [index.tsx] import { readContracts } from '@wagmi/core' import { config } from './config' const result = await readContracts(config, { allowFailure: false, // [!code hl] contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69], }, // ... ], }) ``` <<< @/snippets/react/config.ts[config.ts] ::: ### batchSize `number` The maximum size (in bytes) for each calldata chunk. Set to `0` to disable the size limit. Defaults to `1024`. > Note: Some RPC Providers limit the amount of calldata (`data`) that can be sent in a single `eth_call` request. It is best to check with your RPC Provider to see if there are any calldata size limits to `eth_call` requests. ::: code-group ```tsx [index.tsx] import { readContracts } from '@wagmi/core' import { config } from './config' const result = await readContracts(config, { batchSize: 1_024, // [!code hl] contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69], }, // ... ], }) ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockNumber `number` The block number to perform the read against. ::: code-group ```tsx [index.tsx] import { readContracts } from '@wagmi/core' import { config } from './config' const result = await readContracts(config, { blockNumber: 69420n, // [!code hl] contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69], }, // ... ], }) ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to read against. ::: code-group ```tsx [index.tsx] import { readContracts } from '@wagmi/core' import { config } from './config' const result = await readContracts(config, { blockTag: 'safe', // [!code hl] contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69], }, // ... ], }) ``` <<< @/snippets/react/config.ts[config.ts] ::: ### multicallAddress `Address` Address of multicall contract. ::: code-group ```tsx [index.tsx] import { readContracts } from '@wagmi/core' import { config } from './config' const result = await readContracts(config, { contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69], }, // ... ], multicallAddress: '0xca11bde05977b3631167028862be2a173976ca11', // [!code hl] }) ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type ReadContractsReturnType } from '@wagmi/core' ``` ## Type Inference With [`contracts[number]['abi']`](#abi) setup correctly, TypeScript will infer the correct types for [`functionName`](#functionname), [`args`](#args), and the return type. See the Wagmi [TypeScript docs](/core/typescript) for more information. ## Error ```ts import { type ReadContractsErrorType } from '@wagmi/core' ``` ## Viem - [`multicall`](https://viem.sh/docs/contract/multicall) when supported by current chain. - [`readContract`](https://viem.sh/docs/contract/readContract) when multicall is not supported. ================================================ FILE: site/core/api/actions/reconnect.md ================================================ # reconnect Action for reconnecting [connectors](/core/api/connectors). ## Import ```ts import { reconnect } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { reconnect } from '@wagmi/core' import { injected } from '@wagmi/connectors' import { config } from './config' const result = await reconnect(config, { connectors: [injected()] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type ReconnectParameters } from '@wagmi/core' ``` ### connectors `(CreateConnectorFn | Connector)[] | undefined` - [Connectors](/core/api/connectors) to reconnect to. - Defaults to [`Config['connectors']`](/core/api/createConfig#connectors). ::: code-group ```ts [index.ts] import { reconnect } from '@wagmi/core' import { injected } from '@wagmi/connectors' import { config } from './config' const result = await reconnect(config, { connectors: [injected()], // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type ReconnectReturnType } from '@wagmi/core' ``` `Connection[]` [Connections](/core/api/createConfig#connection) that were successfully reconnected. ## Error ```ts import { type ReconnectErrorType } from '@wagmi/core' ``` ================================================ FILE: site/core/api/actions/sendCalls.md ================================================ # sendCalls Action that requests for the wallet to sign and broadcast a batch of calls (transactions) to the network. [Read more.](https://github.com/ethereum/EIPs/blob/815028dc634463e1716fc5ce44c019a6040f0bef/EIPS/eip-5792.md#wallet_sendcalls) ## Import ```ts import { sendCalls } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { parseEther } from 'viem' import { sendCalls } from '@wagmi/core' import { config } from './config' const id = await sendCalls(config, { calls: [ { to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }, { data: '0xdeadbeef', to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', }, ] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### Synchronous Usage If you want to wait for the calls to be included in a block before returning, you can use `sendCallsSync`: ::: code-group ```ts [index.ts] import { parseEther } from 'viem' import { sendCallsSync } from '@wagmi/core' import { config } from './config' const receipt = await sendCallsSync(config, { calls: [ { to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }, { data: '0xdeadbeef', to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', }, ] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type SendCallsParameters } from '@wagmi/core' ``` ### account `Account | Address | null | undefined` Account to execute the calls. If set to `null`, it is assumed that the wallet will handle filling the sender of the calls. ::: code-group ```ts [index.ts] import { parseEther } from 'viem' import { sendCalls } from '@wagmi/core' import { config } from './config' const id = await sendCalls(config, { account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus] calls: [ { to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }, { data: '0xdeadbeef', to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', }, ], }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### calls `{ to: Hex, data?: Hex, value?: bigint }[]` Calls to execute. ::: code-group ```ts [index.ts] import { parseEther } from 'viem' import { sendCalls } from '@wagmi/core' import { config } from './config' const id = await sendCalls(config, { calls: [ // [!code focus] { // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', // [!code focus] value: parseEther('1') // [!code focus] }, // [!code focus] { // [!code focus] data: '0xdeadbeef', // [!code focus] to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', // [!code focus] }, // [!code focus] ], // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### capabilities `WalletCapabilities | undefined` Capability metadata for the calls (e.g. specifying a paymaster). ::: code-group ```ts [index.ts] import { parseEther } from 'viem' import { sendCalls } from '@wagmi/core' import { config } from './config' const id = await sendCalls(config, { calls: [ { to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }, { data: '0xdeadbeef', to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', }, ], capabilities: { // [!code focus] paymasterService: { // [!code focus] url: 'https://...' // [!code focus] } // [!code focus] } // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `number | undefined` The target chain ID to broadcast the calls. ::: code-group ```ts [index.ts] import { parseEther } from 'viem' import { sendCalls } from '@wagmi/core' import { config } from './config' const id = await sendCalls(config, { calls: [ { to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }, { data: '0xdeadbeef', to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', }, ], chainId: 10, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### connector `Connector | undefined` Connector to get send the calls with. ::: code-group ```ts [index.ts] import { parseEther } from 'viem' import { getConnections } from '@wagmi/core' import { sendCalls } from '@wagmi/core' import { config } from './config' const connections = getConnections(config) const id = await sendCalls(config, { calls: [ { to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }, { data: '0xdeadbeef', to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', }, ], connector: connections[0]?.connector, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type SendCallsReturnType } from '@wagmi/core' ``` `{ id: string; capabilities?: WalletCapabilities | undefined }` Identifier of the call batch. ## Error ```ts import { type SendCallsErrorType } from '@wagmi/core' ``` ## Viem - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls) ================================================ FILE: site/core/api/actions/sendTransaction.md ================================================ # sendTransaction Action for creating, signing, and sending transactions to networks. ## Import ```ts import { sendTransaction } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { sendTransaction } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await sendTransaction(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### Synchronous Usage If you want to wait for the transaction to be included in a block before returning, you can use `sendTransactionSync`: ::: code-group ```ts [index.ts] import { sendTransactionSync } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const receipt = await sendTransactionSync(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type SendTransactionParameters } from '@wagmi/core' ``` ### accessList `AccessList | undefined` The access list. ::: code-group ```ts [index.ts] import { sendTransaction } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await sendTransaction(config, { accessList: [{ // [!code focus] address: '0x1', // [!code focus] storageKeys: ['0x1'], // [!code focus] }], // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### account `Address | Account | undefined` Account to use when sending transaction. Throws if account is not found on [`connector`](#connector). ::: code-group ```ts [index.ts] import { sendTransaction } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await sendTransaction(config, { account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` Chain ID to validate against before sending transaction. ::: code-group ```ts [index.ts] import { sendTransaction } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { parseEther } from 'viem' import { config } from './config' const result = await sendTransaction(config, { chainId: mainnet.id, // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### connector `Connector | undefined` - Connector to send transaction with. - Defaults to current connector. ::: code-group ```ts [index.ts] import { getConnections, sendTransaction } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const connections = getConnections(config) const result = await sendTransaction(config, { connector: connections[0]?.connector, // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### data `` `0x${string}` | undefined `` A contract hashed method call with encoded args. ::: code-group ```ts [index.ts] import { sendTransaction } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await sendTransaction(config, { data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### gas `bigint | undefined | null` Gas provided for transaction execution. ::: code-group ```ts [index.ts] import { sendTransaction } from '@wagmi/core' import { parseEther, parseGwei } from 'viem' import { config } from './config' const result = await sendTransaction(config, { gas: parseGwei('20'), // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: --- ### gasPrice `bigint | undefined` The price in wei to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction). ::: code-group ```ts [index.ts] import { sendTransaction } from '@wagmi/core' import { parseEther, parseGwei } from 'viem' import { config } from './config' const result = await sendTransaction(config, { gasPrice: parseGwei('20'), // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### maxFeePerGas `bigint | undefined` Total fee per gas in wei, inclusive of [`maxPriorityFeePerGas`](#maxPriorityFeePerGas). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```ts [index.ts] import { sendTransaction } from '@wagmi/core' import { parseEther, parseGwei } from 'viem' import { config } from './config' const result = await sendTransaction(config, { maxFeePerGas: parseGwei('20'), // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### maxPriorityFeePerGas `bigint | undefined` Max priority fee per gas in wei. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```ts [index.ts] import { sendTransaction } from '@wagmi/core' import { parseEther, parseGwei } from 'viem' import { config } from './config' const result = await sendTransaction(config, { maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: --- ### nonce `number` Unique number identifying this transaction. ::: code-group ```ts [index.ts] import { sendTransaction } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await sendTransaction(config, { nonce: 123, // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### to `Address` The transaction recipient or contract address. ::: code-group ```ts [index.ts] import { sendTransaction } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await sendTransaction(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### type `'legacy' | 'eip1559' | 'eip2930' | undefined` Optional transaction request type to narrow parameters. ::: code-group ```ts [index.ts] import { sendTransaction } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await sendTransaction(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', type: 'eip1559', // [!code focus] value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### value `bigint | undefined` Value in wei sent with this transaction. ::: code-group ```ts [index.ts] import { sendTransaction } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await sendTransaction(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type SendTransactionReturnType } from '@wagmi/core' ``` [`Hash`](https://viem.sh/docs/glossary/types#hash) Transaction hash. ## Error ```ts import { type SendTransactionErrorType } from '@wagmi/core' ``` ## Viem - [`sendTransaction`](https://viem.sh/docs/actions/wallet/sendTransaction) ================================================ FILE: site/core/api/actions/showCallsStatus.md ================================================ # showCallsStatus Action to request for the wallet to show information about a call batch that was sent via `sendCalls`. [Read more.](https://github.com/ethereum/EIPs/blob/1663ea2e7a683285f977eda51c32cec86553f585/EIPS/eip-5792.md#wallet_showcallsstatus) ## Import ```ts import { showCallsStatus } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { showCallsStatus } from '@wagmi/core' import { config } from './config' await showCallsStatus(config, { id: '0x1234567890abcdef', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type ShowCallsStatusParameters } from '@wagmi/core' ``` ### connector `Connector | undefined` Connector to show call statuses with. ::: code-group ```ts [index.ts] import { getConnections, showCallsStatus } from '@wagmi/core' import { config } from './config' const connections = getConnections(config) await showCallsStatus(config, { connector: connections[0]?.connector, // [!code focus] id: '0x1234567890abcdef', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### id `string` Identifier of the call batch. ::: code-group ```ts [index.ts] import { showCallsStatus } from '@wagmi/core' import { config } from './config' await showCallsStatus(config, { id: '0x1234567890abcdef', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type ShowCallsStatusReturnType } from '@wagmi/core' ``` `bigint` Most recent block number seen. ## Error ```ts import { type ShowCallsStatusErrorType } from '@wagmi/core' ``` ## Viem - [`showCallsStatus`](https://viem.sh/docs/actions/wallet/showCallsStatus) ================================================ FILE: site/core/api/actions/signMessage.md ================================================ # signMessage Action for signing messages. ## Import ```ts import { signMessage } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { signMessage } from '@wagmi/core' import { config } from './config' await signMessage(config, { message: 'hello world' }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type SignMessageParameters } from '@wagmi/core' ``` ### account `Address | Account | undefined` Account to use when signing message. Throws if account is not found on [`connector`](#connector). ::: code-group ```ts [index.ts] import { signMessage } from '@wagmi/core' import { config } from './config' const result = await signMessage(config, { account: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] message: 'hello world', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### connector `Connector | undefined` [Connector](/core/api/connectors) to sign message with. ::: code-group ```ts [index.ts] import { getConnection, signMessage } from '@wagmi/core' import { config } from './config' const { connector } = getConnection(config) const result = await signMessage(config, { connector, // [!code focus] message: 'hello world', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### message `string | { raw: Hex | ByteArray }` Message to sign. ::: code-group ```ts [index.ts] import { signMessage } from '@wagmi/core' import { config } from './config' const result = await signMessage(config, { message: 'hello world', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ::: tip By default, viem signs the UTF-8 representation of the message. To sign the data representation of the message, you can use the `raw` attribute. ```ts import { signMessage } from '@wagmi/core' import { config } from './config' const result = await signMessage(config, { message: { raw: '0x68656c6c6f20776f726c64' }, // [!code focus] }) ``` ::: ## Return Type ```ts import { type SignMessageReturnType } from '@wagmi/core' ``` [`Hex`](https://viem.sh/docs/glossary/types#hex) The signed message. ## Error ```ts import { type SignMessageErrorType } from '@wagmi/core' ``` ## Viem - [`signMessage`](https://viem.sh/docs/actions/wallet/signMessage) ================================================ FILE: site/core/api/actions/signTransaction.md ================================================ # signTransaction Action for creating and signing transactions to networks. ## Import ```ts import { signTransaction } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { signTransaction } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await signTransaction(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### Synchronous Usage If you want to wait for the transaction to be included in a block before returning, you can use `signTransactionSync`: ::: code-group ```ts [index.ts] import { signTransactionSync } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const receipt = await signTransactionSync(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type SignTransactionParameters } from '@wagmi/core' ``` ### accessList `AccessList | undefined` The access list. ::: code-group ```ts [index.ts] import { signTransaction } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await signTransaction(config, { accessList: [{ // [!code focus] address: '0x1', // [!code focus] storageKeys: ['0x1'], // [!code focus] }], // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### account `Address | Account | undefined` Account to use when signing transaction. Throws if account is not found on [`connector`](#connector). ::: code-group ```ts [index.ts] import { signTransaction } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await signTransaction(config, { account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` Chain ID to validate against before signing transaction. ::: code-group ```ts [index.ts] import { signTransaction } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { parseEther } from 'viem' import { config } from './config' const result = await signTransaction(config, { chainId: mainnet.id, // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### connector `Connector | undefined` - Connector to sign transaction with. - Defaults to current connector. ::: code-group ```ts [index.ts] import { getConnections, signTransaction } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const connections = getConnections(config) const result = await signTransaction(config, { connector: connections[0]?.connector, // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### data `` `0x${string}` | undefined `` A contract hashed method call with encoded args. ::: code-group ```ts [index.ts] import { signTransaction } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await signTransaction(config, { data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### gas `bigint | undefined | null` Gas provided for transaction execution. ::: code-group ```ts [index.ts] import { signTransaction } from '@wagmi/core' import { parseEther, parseGwei } from 'viem' import { config } from './config' const result = await signTransaction(config, { gas: parseGwei('20'), // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: --- ### gasPrice `bigint | undefined` The price in wei to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction). ::: code-group ```ts [index.ts] import { signTransaction } from '@wagmi/core' import { parseEther, parseGwei } from 'viem' import { config } from './config' const result = await signTransaction(config, { gasPrice: parseGwei('20'), // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### maxFeePerGas `bigint | undefined` Total fee per gas in wei, inclusive of [`maxPriorityFeePerGas`](#maxpriorityfeepergas). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```ts [index.ts] import { signTransaction } from '@wagmi/core' import { parseEther, parseGwei } from 'viem' import { config } from './config' const result = await signTransaction(config, { maxFeePerGas: parseGwei('20'), // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### maxPriorityFeePerGas `bigint | undefined` Max priority fee per gas in wei. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```ts [index.ts] import { signTransaction } from '@wagmi/core' import { parseEther, parseGwei } from 'viem' import { config } from './config' const result = await signTransaction(config, { maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: --- ### nonce `number` Unique number identifying this transaction. ::: code-group ```ts [index.ts] import { signTransaction } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await signTransaction(config, { nonce: 123, // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### to `Address` The transaction recipient or contract address. ::: code-group ```ts [index.ts] import { signTransaction } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await signTransaction(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### type `'legacy' | 'eip1559' | 'eip2930' | undefined` Optional transaction request type to narrow parameters. ::: code-group ```ts [index.ts] import { signTransaction } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await signTransaction(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', type: 'eip1559', // [!code focus] value: parseEther('0.01'), }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### value `bigint | undefined` Value in wei sent with this transaction. ::: code-group ```ts [index.ts] import { signTransaction } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' const result = await signTransaction(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type SignTransactionReturnType } from '@wagmi/core' ``` [`Hash`](https://viem.sh/docs/glossary/types#hash) Transaction hash. ## Error ```ts import { type SignTransactionErrorType } from '@wagmi/core' ``` ## Viem - [`signTransaction`](https://viem.sh/docs/actions/wallet/signTransaction) ================================================ FILE: site/core/api/actions/signTypedData.md ================================================ # signTypedData Action for signing typed data and calculating an Ethereum-specific [EIP-712](https://eips.ethereum.org/EIPS/eip-712) signature. ## Import ```ts import { signTypedData } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { signTypedData } from '@wagmi/core' import { config } from './config' const result = await signTypedData(config, { types: { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }, primaryType: 'Mail', message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type SignTypedDataParameters } from '@wagmi/core' ``` ### account `Address | Account | undefined` Account to use when signing data. Throws if account is not found on [`connector`](#connector). ::: code-group ```ts [index.ts] import { signTypedData } from '@wagmi/core' import { config } from './config' import { types } from './typedData' const result = await signTypedData(config, { account: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] types, primaryType: 'Mail', message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) ``` <<< @/snippets/typedData.ts[typedData.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### connector `Connector | undefined` [Connector](/core/api/connectors) to sign data with. ::: code-group ```ts [index.ts] import { getConnection, signTypedData } from '@wagmi/core' import { config } from './config' import { types } from './typedData' const { connector } = getConnection(config) const result = await signTypedData(config, { connector, // [!code focus] types, primaryType: 'Mail', message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) ``` <<< @/snippets/typedData.ts[typedData.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### domain `TypedDataDomain | undefined` - The typed data domain. - If `EIP712Domain` key exists in [`types`](#types), `domain` schema is inferred from it. ::: code-group ```ts [index.ts] import { signTypedData } from '@wagmi/core' import { config } from './config' import { types } from './typedData' const result = await signTypedData(config, { domain: { // [!code focus] name: 'Ether Mail', // [!code focus] chainId: 1, // [!code focus] verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', // [!code focus] version: '1', // [!code focus] }, // [!code focus] types, primaryType: 'Mail', message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) ``` <<< @/snippets/typedData.ts[typedData.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### message `Record` - Data to sign. - Type inferred from [`types`](#types) and [`primaryType`](#primarytype). ::: code-group ```ts [index.ts] import { signTypedData } from '@wagmi/core' import { config } from './config' import { types } from './typedData' const result = await signTypedData(config, { types, primaryType: 'Mail', message: { // [!code focus] from: { // [!code focus] name: 'Cow', // [!code focus] wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', // [!code focus] }, // [!code focus] to: { // [!code focus] name: 'Bob', // [!code focus] wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', // [!code focus] }, // [!code focus] contents: 'Hello, Bob!', // [!code focus] }, // [!code focus] }) ``` <<< @/snippets/typedData.ts[typedData.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### primaryType `string` - The primary type to extract from [`types`](#types) and use in [`message`](#message). - Type inferred from [`types`](#types). ::: code-group ```ts [index.ts] import { signTypedData } from '@wagmi/core' import { config } from './config' import { types } from './typedData' const result = await signTypedData(config, { types, primaryType: 'Mail', // [!code focus] message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) ``` <<< @/snippets/typedData.ts[typedData.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### types `TypedData` - The type definitions for the typed data. - By defining inline or adding a [const assertion](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions) to `types`, TypeScript will infer the correct types for [`message`](#message) and [`primaryType`](#primarytype). See the Wagmi [TypeScript docs](/core/typescript) for more information. ::: code-group ```ts [index.ts] import { signTypedData } from '@wagmi/core' import { config } from './config' const result = await signTypedData(config, { types: { // [!code focus] Person: [ // [!code focus] { name: 'name', type: 'string' }, // [!code focus] { name: 'wallet', type: 'address' }, // [!code focus] ], // [!code focus] Mail: [ // [!code focus] { name: 'from', type: 'Person' }, // [!code focus] { name: 'to', type: 'Person' }, // [!code focus] { name: 'contents', type: 'string' }, // [!code focus] ], // [!code focus] }, // [!code focus] primaryType: 'Mail', message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type SignTypedDataReturnType } from '@wagmi/core' ``` [`Hex`](https://viem.sh/docs/glossary/types#hex) The signed data. ## Type Inference With [`types`](#types) setup correctly, TypeScript will infer the correct types for [`domain`](#domain), [`message`](#message), and [`primaryType`](#primarytype). See the Wagmi [TypeScript docs](/core/typescript) for more information. ::: code-group ```ts twoslash [Inline] // @twoslash-cache: {"v":1,"hash":"44d90fe296d503e3675e18b904994e8969cc43a5fc5d95c28c6ca88739b0e3f3","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BjCMONAAlPgFcAbNROwAGABloASYG1IBLMAHMAvkMog2AQ1INEANiq8YCtPiR7qm+TG0gucPg31zciEVUb5N6xjXK7FFdGxnAmIyVRp6PAAKdV4ZdTgASnY4GXkwABUgqAARdTR1AB5gAB0wdgrOGHUoFl4MdgAFMjgWQS4auobUMsq+qs6wevYwdQBbGEES8HGYaYBuXv6KjtqhhswcKbU0WQUFpYr/dlLy5YG14dGJ7YB3WIM0A7Pl1a72Tcn2aZqoWzhnn1FABdRYvC7vACy6hkvHa1Uu3VO5wh6xGs22ADNSBAxoDzm80Z9ts1SK0wPijhQTod+oSrhjvtQIJS6Qj3sSmaTyazjsiCey0dcvtNmGAaOKASAwSj6RsgttpHJ5LzQWVjtNobDpgA+KJizFpQQAYRYhvk1KwngmPjggn5FU+dpp4L6cqaLTaqOGPVdAsGDJuTOFrNlguGnOmSv20tpQOpDpR3oawruDysof9iI+CqZv3+maOar9K3DDS1cOT7F9Scq7tTTOxuMLbID8q2XM9FNjJfYfLjWfeDemaBZPdrpbbOY7025LBb/d7brL6KDopYErQUplE/dkZ2exV4/OIJ3Rz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NzBaI0+WfQcnzFa/PJBC4mNLCgLx6eEDFxTh54uKGszoDNjyA01Y4vQ+V+tkNPLa+q51OHd19fkNZ2GfrptZteXgJdN7dJ3uaz2p90aAXtY1b54dFTBsGZG8qZQ1mMadPPQq2bmCovyrA0tvwl21X4vjbd3DyXeuMks+CB7w2cslZA8omddmG1fdHL9htZ3skqpLbxjrO6k2beuWjKb0roOHdzVairmPvIXZ4y+vH777tRf07DuLKhSsxNvAjO9H2zBfdk79551PfC05x/Tm7nW7vJAK/dFI2nrls1240u5X2ZcIEp2YYXy3x7uWgMECKHBbD2HYHXdg6h7gyBolhey6l1D6jPhaULgCUsehrYIZAA5gDJvYAAcmFD76knIfdIJ932Cgnvvc+9kwHvdvvCGh/8LScetJSUe79F7hsPv6Ex6DyAhP4f0+R9HDn3MPu89h4j5ntXJeOzB+0/npPBeqRLHw8x39vuKwB7KN3s4dWgs94HxSIfg/B99B6wOTPppbhd79INn3YhjQ5FNrjDGy83sI2yuZRfvrYbZUYErAAgilY0sNl7ZQtreHImIEY5ByAjR9M/4y0nBxPxkPuABCEAUqP/6HPsQKV38AD39gCUogDADQDwDwCIDACoCAC4CgCACf9m9wQ1dBAfc44YAhYIBqRP8UoABCH/RPMAOCVQG0ZiRAUAMKZ6BSMAK9BARQRQIAA"} import { createConfig, http, signTypedData } from '@wagmi/core' import { mainnet, sepolia } from '@wagmi/core/chains' const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) // ---cut--- const result = await signTypedData(config, { types: { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }, primaryType: 'Mail', // ^? message: { // ^? from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) ``` ```ts twoslash [Const-Asserted] // @twoslash-cache: {"v":1,"hash":"3253afdbde057c102c6b708011549c2795dd31d2584982f81ae20a403b5bdb54","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BjCMONAAkxzkXeAB0w7Ye1IwAhlBYAbDOwAKZOC15jJMuakEidoiVLCz2YcQFsYvfuDMwrAbm27hag0a4X2VtqQCWYAOb2jsIAvhR8wbouGsY2liAA7uLS0jBoQUJOeuqGcu7xklBicHAZOiEAug6ZzvoxALLiPtKqdbnsWjVRbUYm5vEAZqQQpmVZ0e35niCKpMpgY6HhAl06E71x02gQi905btgeVrPzu2ERqyLrcn1HIMxgNI+lINVZ2a55h/HefoGvkUq1RClBAbHEpAYiAAbFRUgE0PgkABWKhoCH+NJ4dwIOF+XCIAAMVEY+Ah4kYNHIMLC6EOeEIJHIaLoUJAAAosMMcJCMABKBRKFQfGKdNY9G6bKy3XbXTjfaa/AIZc4rcX7SX9aZJFJpWUS+U4ApQIrwF7Aiqg8GQpAARgAHHCYAikTC0RisYgZkKwKDpPi7SSyaQKVSkAAmWnUelexlkUE0eh4TncsiYAW3eIykBW9E2xAAZgALE6XUgS9QPWzbn6A4hw0HyZT4zSKHScAziPGWUmvSmIDz04a7kr/rmIVCi46QPD/Ijy+7SJi2e5a2ACQ37sHQy3w4So6vY13mdRWcmuQO0/zYlqrDrUukc1RrVCAOyb2fzxAVvPLvA1vF1yQAtGxDZtqWhA8YwIY8EzPPsL0Ha8pisQpihecd83tadP1dH8q2xelAIJECtybMN60jNtow7I8mTg3sOUQq8BUaZpWg1Do1SuA1M2mIYRn1TiUO9OYWBVZZIjlPirG2ITPmHeITnEgEwFVKTeKle4WCeNBzQ04SFS8NBfGVVTKkwqFbVtCtcIXSsl09EA2OkNcCVRMiwIoqj2wJGD6J7Nl+yQjMtIE0YnzBPMrPDHDnTnPDFz/L0AJnOtYU8ncIKg2j/O7U9GOCljFOmZSFkil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BGDj9jnf24eBwR+j+XUJp2kWmmDJy4UhupeJy2SmuuXrKYNwt4qZvpMO+AhOrHrvqw2A9+17Xg9ffUy2rdo37BLec7F7buuofCzJq+edcTDU8D3w93Jge2UE9ZyT8jRbfPTebFlzoNP1vuf28xvmIsjcsebh69sD3F2IXe+u1Xw3VOhoeFHPXRNzvOsXR6xDFquavfl/hpXinRU9pN65+LyfaascF6usX4mSu4/L4m6vlTlPFvS9RyE+u9b7rTWnD16XHvSbyfLJUEk0A/K5xxCzS2O8yAkQwAlmvAAA5LcGAeEFMGAaOGASHBQMAaAewGAffFASVGAdovAWEI4BUIgZkN/EAV0CAXxGAeFOgTAWVNgfgToCQZsGAdsBQQqGAVQQgUgaQdLkwSLLASEtQbgfgSEOwBPAzPCoIIILnB3EXP/uIEkD4FMh0kCq8uIFQowjPHRjiDQUtr4P1sdrVigS5FAWIQsJkOrnTkYeYcYRYVYV0Cbn/KQQwgkIYZcJbmAeXHQkvGuhmsmjxsmgWPaASr8u4cmomgSowKOgAIKYp0Kvg8YEqbpFhLwDD2hLxLz2jhjQhOHyLA4QCg7CCkEABCEAmKmRugLh5cmK+RFR+R1RmKVRlRtR9R9RDRlRTRFRbRVRFRJRSwUuMWzw4B36MAKQEA4QhRmKAAhCUTgWpHyKCOwosogKAKyM6ncr6F6HpCACECEEAA"} import { createConfig, http, signTypedData } from '@wagmi/core' import { mainnet, sepolia } from '@wagmi/core/chains' const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) // ---cut--- const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const const result = await signTypedData(config, { types, primaryType: 'Mail', // ^? message: { // ^? from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) ``` ::: ## Error ```ts import { type SignTypedDataErrorType } from '@wagmi/core' ``` ## Viem - [`signTypedData`](https://viem.sh/docs/actions/wallet/signTypedData) ================================================ FILE: site/core/api/actions/simulateContract.md ================================================ # simulateContract Action for simulating/validating a contract interaction. ## Import ```ts import { simulateContract } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { simulateContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type SimulateContractParameters } from '@wagmi/core' ``` ### abi `Abi` The contract's ABI. Check out the [TypeScript docs](/react/typescript#const-assert-abis-typed-data) for how to set up ABIs for maximum type inference and safety. ::: code-group ```ts [index.ts] import { simulateContract } from '@wagmi/core' import { abi } from './abi' // [!code focus] import { config } from './config' const result = await simulateContract(config, { abi, // [!code focus] address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### accessList `AccessList | undefined` The access list. ::: code-group ```ts [index.ts] import { simulateContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], accessList: [{ // [!code focus] address: '0x1', // [!code focus] storageKeys: ['0x1'], // [!code focus] }], // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### account `Address | Account | undefined` Account to use when signing data. Throws if account is not found on [`connector`](#connector). ::: code-group ```ts [index.ts] import { simulateContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], account: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### address `Address` The contract's address. ::: code-group ```ts [index.ts] import { simulateContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', // [!code focus] functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### args `readonly unknown[] | undefined` - Arguments to pass when calling the contract. - Inferred from [`abi`](#abi) and [`functionName`](#functionname). ::: code-group ```ts [index.ts] import { simulateContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ // [!code focus] '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', // [!code focus] 123n, // [!code focus] ], // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: --- ### blockNumber `bigint | undefined` Block number to simulate against. ::: code-group ```ts [index.ts] import { simulateContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], blockNumber: 17829139n, // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to simulate against. ::: code-group ```ts [index.ts] import { simulateContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], blockTag: 'safe', // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` Chain ID to validate against before sending transaction. ::: code-group ```ts [index.ts] import { simulateContract } from '@wagmi/core' import { mainnet } from 'wagmi/chains' // [!code focus] import { abi } from './abi' import { config } from './config' const result = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### connector `Connector | undefined` [Connector](/core/api/connectors) to simulate transaction with. ::: code-group ```ts [index.ts] import { getConnection, simulateContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const { connector } = getConnection(config) const result = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], connector, // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### dataSuffix `` `0x${string}` | undefined `` Data to append to the end of the calldata. Useful for adding a ["domain" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f). ::: code-group ```ts [index.ts] import { simulateContract } from '@wagmi/core' import { parseGwei } from 'viem' import { abi } from './abi' import { config } from './config' const result = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], dataSuffix: '0xdeadbeef', // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### functionName `string` - Function to call on the contract. - Inferred from [`abi`](#abi). ::: code-group ```ts [index.ts] import { simulateContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'approve', // [!code focus] args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### gas `bigint | undefined` Gas provided for transaction execution. ::: code-group ```ts [index.ts] import { simulateContract } from '@wagmi/core' import { parseGwei } from 'viem' import { abi } from './abi' import { config } from './config' const result = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], gas: parseGwei('20'), // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: --- ### gasPrice `bigint | undefined` The price in wei to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction). ::: code-group ```ts [index.ts] import { simulateContract } from '@wagmi/core' import { parseGwei } from 'viem' import { abi } from './abi' import { config } from './config' const result = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], gasPrice: parseGwei('20'), // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### maxFeePerGas `bigint | undefined` Total fee per gas in wei, inclusive of [`maxPriorityFeePerGas`](#maxPriorityFeePerGas). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```ts [index.ts] import { simulateContract } from '@wagmi/core' import { parseGwei } from 'viem' import { abi } from './abi' import { config } from './config' const result = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], maxFeePerGas: parseGwei('20'), // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### maxPriorityFeePerGas `bigint | undefined` Max priority fee per gas in wei. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```ts [index.ts] import { simulateContract } from '@wagmi/core' import { parseGwei } from 'viem' import { abi } from './abi' import { config } from './config' const result = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: --- ### nonce `number` Unique number identifying this transaction. ::: code-group ```ts [index.ts] import { simulateContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], nonce: 123, // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### type `'legacy' | 'eip1559' | 'eip2930' | undefined` Optional transaction request type to narrow parameters. ::: code-group ```ts [index.ts] import { simulateContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], type: 'eip1559', // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### value `bigint | undefined` Value in wei sent with this transaction. ::: code-group ```ts [index.ts] import { simulateContract } from '@wagmi/core' import { parseEther } from 'viem' import { abi } from './abi' import { config } from './config' const result = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], value: parseEther('0.01'), // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type SimulateContractReturnType } from '@wagmi/core' ``` The simulation result and write request. ### request Write request that includes [parameters](#parameters). ### response `unknown` - Result of contract simulation. - Inferred from [`abi`](#abi), [`functionName`](#functionname), and [`args`](#args). ## Type Inference With [`abi`](#abi) setup correctly, TypeScript will infer the correct types for [`functionName`](#functionname), [`args`](#args), and [`value`](#value). See the Wagmi [TypeScript docs](/core/typescript) for more information. ## Error ```ts import { type SimulateContractErrorType } from '@wagmi/core' ``` ## Viem - [`simulateContract`](https://viem.sh/docs/contract/simulateContract) ================================================ FILE: site/core/api/actions/switchChain.md ================================================ # switchChain Action for switching the target chain for a connector or the Wagmi [`Config`](/core/api/createConfig#config). ## Import ```ts import { switchChain } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { switchChain } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' await switchChain(config, { chainId: mainnet.id }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ::: tip When connected, `switchChain` will switch the target chain for the connector. When not connected, `switchChain` will switch the target chain for the Wagmi [`Config`](/core/api/createConfig#config). ::: ## Parameters ```ts import { type SwitchChainParameters } from '@wagmi/core' ``` ### addEthereumChainParameter `{ chainName: string; nativeCurrency?: { name: string; symbol: string; decimals: number } | undefined; rpcUrls: readonly string[]; blockExplorerUrls?: string[] | undefined; iconUrls?: string[] | undefined } | undefined` [EIP-3085 parameters](https://eips.ethereum.org/EIPS/eip-3085) to use when adding chain to connector (when supported). ::: code-group ```ts [index.ts] import { switchChain } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const result = await switchChain(config, { addEthereumChainParameter: { // [!code focus] iconUrls: ['https://example.com/icon.png'], // [!code focus] }, // [!code focus] chainId: mainnet.id, }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to switch to. ::: code-group ```ts [index.ts] import { switchChain } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const result = await switchChain(config, { chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### connector `Connector` [Connector](/core/api/connectors) to switch chain with. ::: code-group ```ts [index.ts] import { getConnection, switchChain } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const connection = getConnection(config) const result = await switchChain(config, { chainId: mainnet.id, connector: connection?.connector, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type SwitchChainReturnType } from '@wagmi/core' ``` `Chain` Chain that was switched to. ## Error ```ts import { type SwitchChainErrorType } from '@wagmi/core' ``` ## Viem - [`switchChain`](https://viem.sh/docs/actions/wallet/switchChain) when connected. ================================================ FILE: site/core/api/actions/switchConnection.md ================================================ # switchConnection Action for switching the current account. ## Import ```ts import { switchConnection } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { getConnections, switchConnection } from '@wagmi/core' import { config } from './config' const connections = getConnections(config) const result = await switchConnection(config, { connector: connections[0]?.connector, }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type SwitchConnectionParameters } from '@wagmi/core' ``` ### connector `Connector` [Connector](/core/api/connectors) to switch to. ::: code-group ```ts [index.ts] import { getConnections, switchConnection } from '@wagmi/core' import { config } from './config' const connections = getConnections(config) const result = await switchConnection(config, { connector: connections[0]?.connector, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type SwitchConnectionReturnType } from '@wagmi/core' ``` ### accounts `readonly [Address, ...Address[]]` Connected accounts from connector. ### chainId `number` Connected chain ID from connector. ## Error ```ts import { type SwitchConnectionErrorType } from '@wagmi/core' ``` ================================================ FILE: site/core/api/actions/verifyMessage.md ================================================ # verifyMessage Action for verify that a message was signed by the provided address. It supports verifying messages that were signed by either a Smart Contract Account or Externally Owned Account. ## Import ```ts import { verifyMessage } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { verifyMessage } from '@wagmi/core' import { config } from './config' await verifyMessage(config, { address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type VerifyMessageParameters } from '@wagmi/core' ``` ### address `Address` The Ethereum address that signed the original message. ::: code-group ```ts [index.ts] import { verifyMessage } from '@wagmi/core' import { config } from './config' await verifyMessage(config, { address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus] message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### message `string | { raw: Hex | ByteArray }` The message to be verified. By default, wagmi verifies the UTF-8 representation of the message. ::: code-group ```ts [index.ts] import { verifyMessage } from '@wagmi/core' import { config } from './config' await verifyMessage(config, { address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', // [!code focus] signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ::: tip By default, viem signs the UTF-8 representation of the message. To sign the data representation of the message, you can use the `raw` attribute. ```ts import { verifyMessage } from '@wagmi/core' import { config } from './config' await verifyMessage(config, { address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: { raw: '0x68656c6c6f20776f726c64' } // [!code focus] signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ``` ::: ### signature `Hex | ByteArray ` The signature that was generated by signing the message with the address's signer. ::: code-group ```ts [index.ts] import { verifyMessage } from '@wagmi/core' import { config } from './config' await verifyMessage(config, { address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` Only used when verifying a message that was signed by a Smart Contract Account. The ID of chain to check if the contract was already deployed. ::: code-group ```ts [index.ts] import { verifyMessage } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' await verifyMessage(config, { chainId: mainnet.id, // [!code focus] address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockNumber `bigint | undefined` Only used when verifying a message that was signed by a Smart Contract Account. The block number to check if the contract was already deployed. ::: code-group ```ts [index.ts] import { verifyMessage } from '@wagmi/core' import { config } from './config' await verifyMessage(config, { blockNumber: 12345678n, // [!code focus] address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Only used when verifying a message that was signed by a Smart Contract Account. The block tag to check if the contract was already deployed. ::: code-group ```ts [index.ts] import { verifyMessage } from '@wagmi/core' import { config } from './config' await verifyMessage(config, { blockTag: 'latest', // [!code focus] address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type VerifyMessageReturnType } from '@wagmi/core' ``` `boolean` Whether the signed message is valid for the given address. ## Error ```ts import { type VerifyMessageErrorType } from '@wagmi/core' ``` ## Viem - [`verifyMessage`](https://viem.sh/docs/actions/public/verifyMessage) ================================================ FILE: site/core/api/actions/verifyTypedData.md ================================================ # verifyTypedData Action for verify that a typed data was signed by the provided address. It supports verifying typed data that were signed by either a Smart Contract Account or Externally Owned Account. ## Import ```ts import { verifyTypedData } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { verifyTypedData } from '@wagmi/core' import { domain, types } from './data' import { config } from './config' const valid = await verifyTypedData(config, { domain, types, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) // true ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type VerifyTypedDataParameters } from '@wagmi/core' ``` ### address `Address` The Ethereum address that signed the original typed data. ::: code-group ```ts [index.ts] import { verifyTypedData } from '@wagmi/core' import { domain, types } from './data' import { config } from './config' const valid = await verifyTypedData(config, { domain, types, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus] signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) // true ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` <<< @/snippets/core/config.ts[config.ts] ::: ### domain `TypedDataDomain` The typed data domain. ::: code-group ```ts [index.ts] import { verifyTypedData } from '@wagmi/core' import { types } from './data' import { config } from './config' const valid = await verifyTypedData(config, { domain: { // [!code focus:6] name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', }, types, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) // true ``` ```ts [data.ts] // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` <<< @/snippets/core/config.ts[config.ts] ::: ### types The type definitions for the typed data. ::: code-group ```ts [index.ts] import { verifyTypedData } from '@wagmi/core' import { domain } from './data' import { config } from './config' const valid = await verifyTypedData(config, { domain, types: { // [!code focus:11] Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) // true ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const ``` <<< @/snippets/core/config.ts[config.ts] ::: ### primaryType `string` The primary `type` to extract from types and use in `value`. ::: code-group ```ts [index.ts] import { verifyTypedData } from '@wagmi/core' import { domain } from './data' import { config } from './config' const valid = await verifyTypedData(config, { domain, types: { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ // [!code focus:5] { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', // [!code focus] address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) // true ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const ``` <<< @/snippets/core/config.ts[config.ts] ::: ### message Type inferred from `types` & `primaryType`. The message to be verified. ::: code-group ```ts [index.ts] import { verifyTypedData } from '@wagmi/core' import { domain, types } from './data' import { config } from './config' const valid = await verifyTypedData(config, { domain, types, message: { // [!code focus:11] from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) // true ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` <<< @/snippets/core/config.ts[config.ts] ::: ### signature `Hex | ByteArray` The signature that was generated by signing the typed data with the address's signer. ::: code-group ```ts [index.ts] import { verifyTypedData } from '@wagmi/core' import { domain, types } from './data' import { config } from './config' const valid = await verifyTypedData(config, { domain, types, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', // [!code focus] }) // true ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` Only used when verifying a typed data that was signed by a Smart Contract Account. The ID of chain to check if the contract was already deployed. ::: code-group ```ts [index.ts] import { verifyTypedData } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { domain, types } from './data' import { config } from './config' const valid = await verifyTypedData(config, { chainId: mainnet.id, // [!code focus] domain, types, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) // true ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockNumber `bigint | undefined` Only used when verifying a typed data that was signed by a Smart Contract Account. The block number to check if the contract was already deployed. ::: code-group ```ts [index.ts] import { verifyTypedData } from '@wagmi/core' import { domain, types } from './data' import { config } from './config' const valid = await verifyTypedData(config, { blockNumber: 12345678n, // [!code focus] domain, types, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) // true ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` <<< @/snippets/core/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Only used when verifying a typed data that was signed by a Smart Contract Account. The block number to check if the contract was already deployed. ::: code-group ```ts [index.ts] import { verifyTypedData } from '@wagmi/core' import { domain, types } from './data' import { config } from './config' const valid = await verifyTypedData(config, { blockTag: 'latest', // [!code focus] domain, types, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) // true ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type VerifyTypedDataReturnType } from '@wagmi/core' ``` `boolean` Whether the signed message is valid for the given address. ## Type Inference With [`types`](#types) setup correctly, TypeScript will infer the correct types for [`domain`](#domain), [`message`](#message), and [`primaryType`](#primarytype). See the Wagmi [TypeScript docs](/core/typescript) for more information. ## Error ```ts import { type VerifyTypedDataErrorType } from '@wagmi/core' ``` ## Viem - [`verifyTypedData`](https://viem.sh/docs/actions/public/verifyTypedData) ================================================ FILE: site/core/api/actions/waitForCallsStatus.md ================================================ # waitForCallsStatus Waits for a call bundle to be confirmed & included on a block before returning the status & receipts. ## Import ```ts import { waitForCallsStatus } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { parseEther } from 'viem' import { sendCalls, waitForCallsStatus } from '@wagmi/core' import { config } from './config' const id = await sendCalls(config, { calls: [{ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1') }] }) const { status, receipts } = await waitForCallsStatus(config, { // [!code focus] id, // [!code focus] }) // [!code focus] ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type WaitForCallsStatusParameters } from '@wagmi/core' ``` ### connector `Connector | undefined` Connector to get call statuses with. ::: code-group ```ts [index.ts] import { getConnections, waitForCallsStatus } from '@wagmi/core' import { config } from './config' const connections = getConnections(config) const status = await waitForCallsStatus(config, { connector: connections[0]?.connector, // [!code focus] id: '0x1234567890abcdef', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### id `string` Identifier of the call batch. ::: code-group ```ts [index.ts] import { waitForCallsStatus } from '@wagmi/core' import { config } from './config' const status = await waitForCallsStatus(config, { id: '0x1234567890abcdef', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### pollingInterval `number` Polling interval in milliseconds. ::: code-group ```ts [index.ts] import { waitForCallsStatus } from '@wagmi/core' import { config } from './config' const status = await waitForCallsStatus(config, { id: '0x1234567890abcdef', pollingInterval: 1_000, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### timeout `number` Timeout in milliseconds before `waitForCallsStatus` stops polling. ::: code-group ```ts [index.ts] import { waitForCallsStatus } from '@wagmi/core' import { config } from './config' const status = await waitForCallsStatus(config, { id: '0x1234567890abcdef', timeout: 10_000, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type WaitForCallsStatusReturnType } from '@wagmi/core' ``` `{ status: 'PENDING' | 'CONFIRMED', receipts: TransactionReceipt[] }` The status and receipts of the call batch. ## Error ```ts import { type WaitForCallsStatusErrorType } from '@wagmi/core' ``` ## Viem - [`waitForCallsStatus`](https://viem.sh/docs/actions/wallet/waitForCallsStatus) ================================================ FILE: site/core/api/actions/waitForTransactionReceipt.md ================================================ # waitForTransactionReceipt Action that waits for the transaction to be included on a block, and then returns the transaction receipt. If the transaction reverts, then the action will throw an error. Replacement detection (e.g. sped up transactions) is also supported. ## Import ```ts import { waitForTransactionReceipt } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { waitForTransactionReceipt } from '@wagmi/core' import { config } from './config' const transactionReceipt = waitForTransactionReceipt(config, { hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type WaitForTransactionReceiptParameters } from '@wagmi/core' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { waitForTransactionReceipt } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const transactionReceipt = await waitForTransactionReceipt(config, { chainId: mainnet.id, // [!code focus] hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### confirmations `number | undefined` The number of confirmations (blocks that have passed) to wait before resolving. ::: code-group ```ts [index.ts] import { waitForTransactionReceipt } from '@wagmi/core' import { config } from './config' const transactionReceipt = await waitForTransactionReceipt(config, { confirmations: 2, // [!code focus] hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### onReplaced ` (({ reason: 'replaced' | 'repriced' | 'cancelled'; replacedTransaction: Transaction; transaction: Transaction; transactionReceipt: TransactionReceipt }) => void) | undefined ` Optional callback to emit if the transaction has been replaced. ::: code-group ```ts [index.ts] import { waitForTransactionReceipt } from '@wagmi/core' import { config } from './config' const transactionReceipt = await waitForTransactionReceipt(config, { hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', onReplaced: replacement => console.log(replacement), // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### hash `` `0x${string}` `` The transaction hash to wait for. ::: code-group ```ts [index.ts] import { waitForTransactionReceipt } from '@wagmi/core' import { config } from './config' const transactionReceipt = await waitForTransactionReceipt(config, { hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### pollingInterval `number | undefined` - Polling frequency (in milliseconds). - Defaults to the [Config's `pollingInterval` config](/core/api/createConfig#pollinginterval). ::: code-group ```ts [index.ts] import { waitForTransactionReceipt } from '@wagmi/core' import { config } from './config' const transactionReceipt = await waitForTransactionReceipt(config, { hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', pollingInterval: 1_000, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type WaitForTransactionReceiptReturnType } from '@wagmi/core' ``` [`TransactionReceipt`](https://viem.sh/docs/glossary/types#transactionreceipt) The transaction receipt. ## Error ```ts import { type WaitForTransactionReceiptErrorType } from '@wagmi/core' ``` ## Viem - [`waitForTransactionReceipt`](https://viem.sh/docs/actions/public/waitForTransactionReceipt) ================================================ FILE: site/core/api/actions/watchAsset.md ================================================ # watchAsset Action for requesting user tracks the token in their wallet. Returns a boolean indicating if the token was successfully added. ## Import ```ts import { watchAsset } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { watchAsset } from '@wagmi/core' import { config } from './config' await watchAsset(config, { type: 'ERC20', options: { address: '0x0000000000000000000000000000000000000000', symbol: 'WAGMI', decimals: 18, }, }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type WatchAssetParameters } from '@wagmi/core' ``` ### connector `Connector | undefined` [Connector](/core/api/connectors) to sign message with. ::: code-group ```ts [index.ts] import { getConnection, watchAsset } from '@wagmi/core' import { config } from './config' const { connector } = getConnection(config) const result = await watchAsset(config, { connector, // [!code focus] options: { address: '0x0000000000000000000000000000000000000000', symbol: 'WAGMI', decimals: 18, }, type: 'ERC20', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### options `{ address: string; symbol: string; decimals: number; image?: string | undefined; }` Asset options. ::: code-group ```ts [index.ts] import { watchAsset } from '@wagmi/core' import { config } from './config' const result = await watchAsset(config, { options: { // [!code focus] address: '0x0000000000000000000000000000000000000000', // [!code focus] symbol: 'WAGMI', // [!code focus] decimals: 18, // [!code focus] }, // [!code focus] type: 'ERC20', }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### type `'ERC20'` Type of asset. ::: code-group ```ts [index.ts] import { watchAsset } from '@wagmi/core' import { config } from './config' const result = await watchAsset(config, { options: { address: '0x0000000000000000000000000000000000000000', symbol: 'WAGMI', decimals: 18, }, type: 'ERC20', // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type WatchAssetReturnType } from '@wagmi/core' ``` `boolean` Returns a boolean indicating if the token was successfully added. ## Error ```ts import { type WatchAssetErrorType } from '@wagmi/core' ``` ## Viem - [`watchAsset`](https://viem.sh/docs/actions/wallet/watchAsset) ================================================ FILE: site/core/api/actions/watchBlockNumber.md ================================================ # watchBlockNumber Action that watches for block number changes. ## Import ```ts import { watchBlockNumber } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { watchBlockNumber } from '@wagmi/core' import { config } from './config' const unwatch = watchBlockNumber(config, { onBlockNumber(blockNumber) { console.log('Block number changed!', blockNumber) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type WatchBlockNumberParameters } from '@wagmi/core' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { watchBlockNumber } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const unwatch = watchBlockNumber(config, { chainId: mainnet.id, // [!code focus] onBlockNumber(blockNumber) { console.log('Block number changed!', blockNumber) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ### emitOnBegin `boolean | undefined` Whether or not to emit the latest block number to the callback when the subscription opens. ::: code-group ```ts [index.ts] import { watchBlockNumber } from '@wagmi/core' import { config } from './config' const unwatch = watchBlockNumber(config, { emitOnBegin: true, // [!code focus] onBlockNumber(blockNumber) { console.log('Block number changed!', blockNumber) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ### emitMissed `boolean | undefined` Whether or not to emit the missed block numbers to the callback. ::: code-group ```ts [index.ts] import { watchBlockNumber } from '@wagmi/core' import { config } from './config' const unwatch = watchBlockNumber(config, { emitMissed: true, // [!code focus] onBlockNumber(blockNumber) { console.log('Block number changed!', blockNumber) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ### onBlockNumber `(blockNumber: bigint, prevBlockNumber: bigint | undefined) => void` Callback for when block number changes. ::: code-group ```ts [index.ts] import { watchBlockNumber } from '@wagmi/core' import { config } from './config' const unwatch = watchBlockNumber(config, { onBlockNumber(blockNumber) { // [!code focus] console.log('Block number changed!', blockNumber) // [!code focus] }, // [!code focus] }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ### onError `((error: Error) => void) | undefined` Error thrown from getting the block number. ::: code-group ```ts [index.ts] import { watchBlockNumber } from '@wagmi/core' import { config } from './config' const unwatch = watchBlockNumber(config, { onBlockNumber(blockNumber) { console.log('Block number changed!', blockNumber) }, onError(error) { // [!code focus] console.error('Block number error', error) // [!code focus] }, // [!code focus] }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ### poll `boolean | undefined` - Whether or not to use a polling mechanism to check for new blocks instead of a WebSocket subscription. - Defaults to `false` for WebSocket Clients, and `true` for non-WebSocket Clients. ::: code-group ```ts [index.ts] import { watchBlockNumber } from '@wagmi/core' import { config } from './config' const unwatch = watchBlockNumber(config, { onBlockNumber(blockNumber) { console.log('Block number changed!', blockNumber) }, poll: true, // [!code focus] }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ### pollingInterval `number | undefined` - Polling frequency (in milliseconds). - Defaults to the [Config's `pollingInterval` config](/core/api/createConfig#pollinginterval). ::: code-group ```ts [index.ts] import { watchBlockNumber } from '@wagmi/core' import { config } from './config' const unwatch = watchBlockNumber(config, { onBlockNumber(blockNumber) { console.log('Block number changed!', blockNumber) }, pollingInterval: 1_000, // [!code focus] }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ### syncConnectedChain `boolean | undefined` - Set up subscriber for connected chain changes. - Defaults to [`Config['syncConnectedChain']`](/core/api/createConfig#syncconnectedchain). ::: code-group ```ts [index.ts] import { watchBlockNumber } from '@wagmi/core' import { config } from './config' const unwatch = watchBlockNumber(config, { onBlockNumber(blockNumber) { console.log('Block number changed!', blockNumber) }, syncConnectedChain: false, // [!code focus] }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type WatchBlockNumberReturnType } from '@wagmi/core' ``` Function for cleaning up watcher. ## Viem - [`watchBlockNumber`](https://viem.sh/docs/actions/public/watchBlockNumber) ================================================ FILE: site/core/api/actions/watchBlocks.md ================================================ # watchBlocks Action that watches for block changes. ## Import ```ts import { watchBlocks } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { watchBlocks } from '@wagmi/core' import { config } from './config' const unwatch = watchBlocks(config, { onBlock(block) { console.log('Block changed!', block) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type WatchBlocksParameters } from '@wagmi/core' ``` ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized'` Watch for new blocks on a given tag. Defaults to `'latest'`. ::: code-group ```ts [index.ts] import { watchBlocks } from '@wagmi/core' import { config } from './config' const unwatch = watchBlocks(config, { blockTag: 'pending', // [!code focus] onBlock(block) { console.log('Block changed!', block) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { watchBlocks } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const unwatch = watchBlocks(config, { chainId: mainnet.id, // [!code focus] onBlock(block) { console.log('Block changed!', block) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ### emitMissed `boolean` Whether or not to emit missed blocks to the callback. Defaults to `false`. Missed blocks may occur in instances where internet connection is lost, or the block time is lesser than the polling interval of the client. ::: code-group ```ts [index.ts] import { watchBlocks } from '@wagmi/core' import { config } from './config' const unwatch = watchBlocks(config, { emitMissed: true, // [!code focus] onBlock(block) { console.log('Block changed!', block) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ### emitOnBegin `boolean` Whether or not to emit the block to the callback when the subscription opens. Defaults to `false`. ::: code-group ```ts [index.ts] import { watchBlocks } from '@wagmi/core' import { config } from './config' const unwatch = watchBlocks(config, { emitOnBegin: true, // [!code focus] onBlock(block) { console.log('Block changed!', block) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ### onBlock `(block: Block, prevblock: Block | undefined) => void` Callback for when block changes. ::: code-group ```ts [index.ts] import { watchBlocks } from '@wagmi/core' import { config } from './config' const unwatch = watchBlocks(config, { onBlock(block) { // [!code focus] console.log('Block changed!', block) // [!code focus] }, // [!code focus] }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ### onError `((error: Error) => void) | undefined` Error thrown from getting the block. ::: code-group ```ts [index.ts] import { watchBlocks } from '@wagmi/core' import { config } from './config' const unwatch = watchBlocks(config, { onBlock(block) { console.log('Block changed!', block) }, onError(error) { // [!code focus] console.error('Block error', error) // [!code focus] }, // [!code focus] }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ### poll `boolean | undefined` - Whether or not to use a polling mechanism to check for new blocks instead of a WebSocket subscription. - Defaults to `false` for WebSocket Clients, and `true` for non-WebSocket Clients. ::: code-group ```ts [index.ts] import { watchBlocks } from '@wagmi/core' import { config } from './config' const unwatch = watchBlocks(config, { poll: true, // [!code focus] onBlock(block) { console.log('Block changed!', block) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ### pollingInterval `number | undefined` - Polling frequency (in milliseconds). - Defaults to the [Config's `pollingInterval` config](/core/api/createConfig#pollinginterval). ::: code-group ```ts [index.ts] import { watchBlocks } from '@wagmi/core' import { config } from './config' const unwatch = watchBlocks(config, { pollingInterval: 1_000, // [!code focus] onBlock(block) { console.log('Block changed!', block) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ### syncConnectedChain `boolean | undefined` - Set up subscriber for connected chain changes. - Defaults to [`Config['syncConnectedChain']`](/core/api/createConfig#syncconnectedchain). ::: code-group ```ts [index.ts] import { watchBlocks } from '@wagmi/core' import { config } from './config' const unwatch = watchBlocks(config, { onBlock(block) { console.log('Block changed!', block) }, syncConnectedChain: false, // [!code focus] }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type WatchBlocksReturnType } from '@wagmi/core' ``` Function for cleaning up watcher. ## Viem - [`watchBlocks`](https://viem.sh/docs/actions/public/watchBlocks) ================================================ FILE: site/core/api/actions/watchChainId.md ================================================ # watchChainId Subscribe to chain ID changes. ## Import ```ts import { watchChainId } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { watchChainId } from '@wagmi/core' import { config } from './config' const unwatch = watchChainId(config, { onChange(chainId) { console.log('Chain ID changed!', chainId) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type WatchChainIdParameters } from '@wagmi/core' ``` ### onChange `onChange(chainId: GetChainIdReturnType, prevChainId: GetChainIdReturnType): void` Callback function called when chain ID changes. ::: code-group ```ts [index.ts] import { watchChainId } from '@wagmi/core' import { config } from './config' const unwatch = watchChainId(config, { onChange(chainId) { // [!code focus:3] console.log('Chain ID changed!', chainId) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type WatchChainIdReturnType } from '@wagmi/core' ``` Function for cleaning up watcher. ================================================ FILE: site/core/api/actions/watchClient.md ================================================ # watchClient Subscribe to Client changes. ## Import ```ts import { watchClient } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { watchClient } from '@wagmi/core' import { config } from './config' const unwatch = watchClient(config, { onChange(client) { console.log('Client changed!', client) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type WatchClientParameters } from '@wagmi/core' ``` ### onChange `onChange(client: GetClientReturnType, prevClient: GetClientReturnType): void` Callback function called when Client changes. ::: code-group ```ts [index.ts] import { watchClient } from '@wagmi/core' import { config } from './config' const unwatch = watchClient(config, { onChange(client) { // [!code focus:3] console.log('Client changed!', client) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type WatchClientReturnType } from '@wagmi/core' ``` Function for cleaning up watcher. ================================================ FILE: site/core/api/actions/watchConnection.md ================================================ # watchConnection Subscribe to connection changes. ## Import ```ts import { watchConnection } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { watchConnection } from '@wagmi/core' import { config } from './config' const unwatch = watchConnection(config, { onChange(data) { console.log('Connection changed!', data) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type WatchConnectionParameters } from '@wagmi/core' ``` ### onChange `onChange(connection: GetConnectionReturnType, prevConnection: GetConnectionReturnType): void` Callback function called when connection changes. ::: code-group ```ts [index.ts] import { watchConnection } from '@wagmi/core' import { config } from './config' const unwatch = watchConnection(config, { onChange(connection) { // [!code focus:3] console.log('Connection changed!', connection) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type WatchConnectionReturnType } from '@wagmi/core' ``` Function for cleaning up watcher. ================================================ FILE: site/core/api/actions/watchConnections.md ================================================ # watchConnections Subscribe to connections changes. ## Import ```ts import { watchConnections } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { watchConnections } from '@wagmi/core' import { config } from './config' const unwatch = watchConnections(config, { onChange(data) { console.log('Connections changed!', data) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type WatchConnectionsParameters } from '@wagmi/core' ``` ### onChange `onChange(connections: GetConnectionsReturnType, prevConnections: GetConnectionsReturnType): void` Callback function called when connections changes. ::: code-group ```ts [index.ts] import { watchConnections } from '@wagmi/core' import { config } from './config' const unwatch = watchConnections(config, { onChange(data) { // [!code focus:3] console.log('Connections changed!', data) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type WatchConnectionsReturnType } from '@wagmi/core' ``` Function for cleaning up watcher. ================================================ FILE: site/core/api/actions/watchConnectors.md ================================================ # watchConnectors Subscribe to connectors changes. ## Import ```ts import { watchConnectors } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { watchConnectors } from '@wagmi/core' import { config } from './config' const unwatch = watchConnectors(config, { onChange(connectors) { console.log('Connectors changed!', connectors) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type WatchConnectorsParameters } from '@wagmi/core' ``` ### onChange `onChange(connectors: GetConnectorsReturnType, prevConnectors: GetConnectorsReturnType): void` Callback function called when connectors changes. ::: code-group ```ts [index.ts] import { watchConnectors } from '@wagmi/core' import { config } from './config' const unwatch = watchConnectors(config, { onChange(connectors) { // [!code focus:3] console.log('Connectors changed!', connectors) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type WatchConnectorsReturnType } from '@wagmi/core' ``` Function for cleaning up watcher. ================================================ FILE: site/core/api/actions/watchContractEvent.md ================================================ # watchContractEvent Action that watches and returns emitted contract event logs. ## Import ```ts import { watchContractEvent } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { watchContractEvent } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const unwatch = watchContractEvent(config, { address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, eventName: 'Transfer', onLogs(logs) { console.log('New logs!', logs) }, }) unwatch() ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type WatchContractEventParameters } from '@wagmi/core' ``` ### abi `Abi` The contract's ABI. Check out the [TypeScript docs](/react/typescript#const-assert-abis-typed-data) for how to set up ABIs for maximum type inference and safety. ::: code-group ```ts [index.ts] import { watchContractEvent } from '@wagmi/core' import { abi } from './abi' // [!code focus] import { config } from './config' const unwatch = watchContractEvent(config, { abi, // [!code focus] onLogs(logs) { console.log('Logs changed!', logs) }, }) unwatch() ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### address `Address | undefined` The contract's address. ::: code-group ```ts [index.ts] import { watchContractEvent } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const unwatch = watchContractEvent(config, { address: '0x6b175474e89094c44da98b954eedeac495271d0f', // [!code focus] abi, onLogs(logs) { console.log('Logs changed!', logs) }, }) unwatch() ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### args `object | readonly unknown[] | undefined` - Arguments to pass when calling the contract. - Inferred from [`abi`](#abi) and [`eventName`](#eventname). ::: code-group ```ts [index.ts] import { watchContractEvent } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const unwatch = watchContractEvent(config, { abi, args: { // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] }, // [!code focus] onLogs(logs) { console.log('Logs changed!', logs) }, }) unwatch() ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### batch `boolean | undefined` - Whether or not the events should be batched on each invocation. - Defaults to `true`. ::: code-group ```ts [index.ts] import { watchContractEvent } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const unwatch = watchContractEvent(config, { abi, batch: false, // [!code focus] onLogs(logs) { console.log('Logs changed!', logs) }, }) unwatch() ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { watchContractEvent } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { abi } from './abi' import { config } from './config' const unwatch = watchContractEvent(config, { abi, chainId: mainnet.id, // [!code focus] onLogs(logs) { console.log('Logs changed!', logs) }, }) unwatch() ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### eventName `string` - Event to listen for the contract. - Inferred from [`abi`](#abi). ::: code-group ```ts [index.ts] import { watchContractEvent } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const unwatch = watchContractEvent(config, { abi, eventName: 'Approval', // [!code focus] onLogs(logs) { console.log('Logs changed!', logs) }, }) unwatch() ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### onError `((error: Error) => void) | undefined` Error thrown from getting the block number. ::: code-group ```ts [index.ts] import { watchContractEvent } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const unwatch = watchContractEvent(config, { abi, onLogs(logs) { console.log('Logs changed!', logs) }, onError(error) { // [!code focus] console.error('Logs error', error) // [!code focus] }, // [!code focus] }) unwatch() ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### onLogs `(logs: Log[], prevLogs: Log[] | undefined) => void` Callback for when logs changes. ::: code-group ```ts [index.ts] import { watchContractEvent } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const unwatch = watchContractEvent(config, { abi, onLogs(logs) { // [!code focus] console.log('Logs changed!', logs) // [!code focus] }, // [!code focus] }) unwatch() ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### poll `boolean | undefined` - Whether or not to use a polling mechanism to check for new blocks instead of a WebSocket subscription. - Defaults to `false` for WebSocket Clients, and `true` for non-WebSocket Clients. ::: code-group ```ts [index.ts] import { watchContractEvent } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const unwatch = watchContractEvent(config, { abi, onLogs(logs) { console.log('Logs changed!', logs) }, poll: true, // [!code focus] }) unwatch() ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### pollingInterval `number | undefined` - Polling frequency (in milliseconds). - Defaults to the [Config's `pollingInterval` config](/core/api/createConfig#pollinginterval). ::: code-group ```ts [index.ts] import { watchContractEvent } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const unwatch = watchContractEvent(config, { abi, onLogs(logs) { console.log('Logs changed!', logs) }, pollingInterval: 1_000, // [!code focus] }) unwatch() ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### strict `boolean | undefined` - Defaults to `false`. ::: code-group ```ts [index.ts] import { watchContractEvent } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const unwatch = watchContractEvent(config, { abi, onLogs(logs) { console.log('Logs changed!', logs) }, strict: true, // [!code focus] }) unwatch() ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### syncConnectedChain `boolean | undefined` - Set up subscriber for connected chain changes. - Defaults to [`Config['syncConnectedChain']`](/core/api/createConfig#syncconnectedchain). ::: code-group ```ts [index.ts] import { watchContractEvent } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const unwatch = watchContractEvent(config, { abi, onLogs(logs) { console.log('Logs changed!', logs) }, syncConnectedChain: false, // [!code focus] }) unwatch() ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type WatchContractEventReturnType } from '@wagmi/core' ``` Function for cleaning up watcher. ## Type Inference With [`abi`](#abi) setup correctly, TypeScript will infer the correct types for [`eventName`](#eventname), [`args`](#args), and [`onLogs`](#onlogs) parameters. See the Wagmi [TypeScript docs](/core/typescript) for more information. ## Error ```ts import { type WatchContractEventError } from '@wagmi/core' ``` ## Viem - [`watchContractEvent`](https://viem.sh/docs/contract/watchContractEvent) ================================================ FILE: site/core/api/actions/watchPendingTransactions.md ================================================ # watchPendingTransactions Action that watches and returns pending transaction hashes. ## Import ```ts import { watchPendingTransactions } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { watchPendingTransactions } from '@wagmi/core' import { config } from './config' const unwatch = watchPendingTransactions(config, { onTransactions(transactions) { console.log('New transactions!', transactions) }, }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type WatchPendingTransactionsParameters } from '@wagmi/core' ``` ### batch `boolean | undefined` - Whether or not the transactions should be batched on each invocation. - Defaults to `true`. ::: code-group ```ts [index.ts] import { watchPendingTransactions } from '@wagmi/core' const unwatch = watchPendingTransactions(config, { batch: false, // [!code focus] onTransactions(transactions) { console.log('New transactions!', transactions) }, }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```ts [index.ts] import { watchPendingTransactions } from '@wagmi/core' import { mainnet } from '@wagmi/core/chains' import { config } from './config' const unwatch = watchPendingTransactions(config, { chainId: mainnet.id, // [!code focus] onTransactions(transactions) { console.log('New transactions!', transactions) }, }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### onError `((error: Error) => void) | undefined` Error thrown from watching pending transactions. ::: code-group ```ts [index.ts] import { watchPendingTransactions } from '@wagmi/core' import { config } from './config' const unwatch = watchPendingTransactions(config, { onError(error) { // [!code focus] console.log('Error', error) // [!code focus] }, // [!code focus] onTransactions(transactions) { console.log('New transactions!', transactions) }, }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### onTransactions `(transactions: Hash[], prevTransactions: Hash[] | undefined) => void` Callback when new incoming pending transactions are detected. ::: code-group ```ts [index.ts] import { watchPendingTransactions } from '@wagmi/core' import { config } from './config' const unwatch = watchPendingTransactions(config, { onTransactions(transactions) { // [!code focus] console.log('New transactions!', transactions) // [!code focus] }, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### poll `boolean | undefined` - Whether or not to use a polling mechanism to check for new pending transactions instead of a WebSocket subscription. - Defaults to `false` for WebSocket Clients, and `true` for non-WebSocket Clients. ::: code-group ```ts [index.ts] import { watchPendingTransactions } from '@wagmi/core' import { config } from './config' const unwatch = watchPendingTransactions(config, { onTransactions(transactions) { console.log('New transactions!', transactions) }, poll: false, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### pollingInterval `number | undefined` - Polling frequency (in milliseconds). - Defaults to the [Config's `pollingInterval` config](/core/api/createConfig#pollinginterval). ::: code-group ```ts [index.ts] import { watchPendingTransactions } from '@wagmi/core' import { config } from './config' const unwatch = watchPendingTransactions(config, { onTransactions(transactions) { console.log('New transactions!', transactions) }, pollingInterval: 1_000, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### syncConnectedChain `boolean | undefined` - Set up subscriber for connected chain changes. - Defaults to [`Config['syncConnectedChain']`](/core/api/createConfig#syncconnectedchain). ::: code-group ```ts [index.ts] import { watchPendingTransactions } from '@wagmi/core' import { config } from './config' const unwatch = watchPendingTransactions(config, { onTransactions(transactions) { console.log('New transactions!', transactions) }, syncConnectedChain: false, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type WatchPendingTransactionsReturnType } from '@wagmi/core' ``` Function to unsubscribe from pending transaction listener. ## Error ```ts import { type WatchPendingTransactionsError } from '@wagmi/core' ``` ## Viem - [`watchPendingTransactions`](https://viem.sh/docs/actions/public/watchPendingTransactions) ================================================ FILE: site/core/api/actions/watchPublicClient.md ================================================ # watchPublicClient Subscribe to Public Client changes. ## Import ```ts import { watchPublicClient } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { watchPublicClient } from '@wagmi/core' import { config } from './config' const unwatch = watchPublicClient(config, { onChange(client) { console.log('Public Client changed!', client) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type WatchPublicClientParameters } from '@wagmi/core' ``` ### onChange `onChange(client: GetPublicClientReturnType, prevClient: GetPublicClientReturnType): void` Callback function called when Public Client changes. ::: code-group ```ts [index.ts] import { watchPublicClient } from '@wagmi/core' import { config } from './config' const unwatch = watchPublicClient(config, { onChange(client) { // [!code focus:3] console.log('Public Client changed!', client) }, }) unwatch() ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type WatchPublicClientReturnType } from '@wagmi/core' ``` Function for cleaning up watcher. ================================================ FILE: site/core/api/actions/writeContract.md ================================================ # writeContract Action for executing a write function on a contract. A "write" function on a Solidity contract modifies the state of the blockchain. These types of functions require gas to be executed, hence a transaction is broadcasted in order to change the state. ## Import ```ts import { writeContract } from '@wagmi/core' ``` ## Usage ::: code-group ```ts [index.ts] import { writeContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await writeContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ::::tip Pairing with `simulateContract` Pairing [`simulateContract`](/core/api/actions/simulateContract) with `writeContract` allows you to validate if the transaction will succeed ahead of time. If the simulate succeeds, `writeContract` can execute the transaction. ::: code-group ```ts [index.ts] import { simulateContract, writeContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const { request } = await simulateContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], }) const hash = await writeContract(config, request) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: :::: ### Synchronous Usage If you want to wait for the transaction to be included in a block before returning, you can use `writeContractSync`: ::: code-group ```ts [index.ts] import { writeContractSync } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const receipt = await writeContractSync(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type WriteContractParameters } from '@wagmi/core' ``` ### abi `Abi` The contract's ABI. Check out the [TypeScript docs](/react/typescript#const-assert-abis-typed-data) for how to set up ABIs for maximum type inference and safety. ::: code-group ```ts [index.ts] import { writeContract } from '@wagmi/core' import { abi } from './abi' // [!code focus] import { config } from './config' const result = await writeContract(config, { abi, // [!code focus] address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### accessList `AccessList | undefined` The access list. ::: code-group ```ts [index.ts] import { writeContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await writeContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], accessList: [{ // [!code focus] address: '0x1', // [!code focus] storageKeys: ['0x1'], // [!code focus] }], // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### account `Address | Account | undefined` Account to use when signing data. Throws if account is not found on [`connector`](#connector). ::: code-group ```ts [index.ts] import { writeContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await writeContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], account: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### address `Address` The contract's address. ::: code-group ```ts [index.ts] import { writeContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await writeContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', // [!code focus] functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### args `readonly unknown[] | undefined` - Arguments to pass when calling the contract. - Inferred from [`abi`](#abi) and [`functionName`](#functionname). ::: code-group ```ts [index.ts] import { writeContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await writeContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ // [!code focus] '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', // [!code focus] 123n, // [!code focus] ] // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` Chain ID to validate against before sending transaction. ::: code-group ```ts [index.ts] import { writeContract } from '@wagmi/core' import { mainnet } from 'wagmi/chains' // [!code focus] import { abi } from './abi' import { config } from './config' const result = await writeContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], chainId: mainnet.id, // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### connector `Connector | undefined` [Connector](/core/api/connectors) to sign data with. ::: code-group ```ts [index.ts] import { getConnection, writeContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const { connector } = getConnection(config) const result = await writeContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], connector, // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### dataSuffix `` `0x${string}` | undefined `` Data to append to the end of the calldata. Useful for adding a ["domain" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f). ::: code-group ```ts [index.ts] import { writeContract } from '@wagmi/core' import { parseGwei } from 'viem' import { abi } from './abi' import { config } from './config' const result = await writeContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], dataSuffix: '0xdeadbeef', // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### functionName `string` - Function to call on the contract. - Inferred from [`abi`](#abi). ::: code-group ```ts [index.ts] import { writeContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await writeContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'approve', // [!code focus] args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### gas `bigint | undefined` Gas provided for transaction execution. ::: code-group ```ts [index.ts] import { writeContract } from '@wagmi/core' import { parseGwei } from 'viem' import { abi } from './abi' import { config } from './config' const result = await writeContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], gas: parseGwei('20'), // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: --- ### gasPrice `bigint | undefined` The price in wei to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction). ::: code-group ```ts [index.ts] import { writeContract } from '@wagmi/core' import { parseGwei } from 'viem' import { abi } from './abi' import { config } from './config' const result = await writeContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], gasPrice: parseGwei('20'), // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### maxFeePerGas `bigint | undefined` Total fee per gas in wei, inclusive of [`maxPriorityFeePerGas`](#maxPriorityFeePerGas). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```ts [index.ts] import { writeContract } from '@wagmi/core' import { parseGwei } from 'viem' import { abi } from './abi' import { config } from './config' const result = await writeContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], maxFeePerGas: parseGwei('20'), // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### maxPriorityFeePerGas `bigint | undefined` Max priority fee per gas in wei. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```ts [index.ts] import { writeContract } from '@wagmi/core' import { parseGwei } from 'viem' import { abi } from './abi' import { config } from './config' const result = await writeContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: --- ### nonce `number` Unique number identifying this transaction. ::: code-group ```ts [index.ts] import { writeContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await writeContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], nonce: 123, // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### type `'legacy' | 'eip1559' | 'eip2930' | undefined` Optional transaction request type to narrow parameters. ::: code-group ```ts [index.ts] import { writeContract } from '@wagmi/core' import { abi } from './abi' import { config } from './config' const result = await writeContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], type: 'eip1559', // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ### value `bigint | undefined` Value in wei sent with this transaction. ::: code-group ```ts [index.ts] import { writeContract } from '@wagmi/core' import { parseEther } from 'viem' import { abi } from './abi' import { config } from './config' const result = await writeContract(config, { abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], value: parseEther('0.01'), // [!code focus] }) ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type WriteContractReturnType } from '@wagmi/core' ``` [`Hash`](https://viem.sh/docs/glossary/types#hash) The transaction hash. ## Type Inference With [`abi`](#abi) setup correctly, TypeScript will infer the correct types for [`functionName`](#functionname), [`args`](#args), and [`value`](#value). See the Wagmi [TypeScript docs](/core/typescript) for more information. ## Error ```ts import { type WriteContractErrorType } from '@wagmi/core' ``` ## Viem - [`writeContract`](https://viem.sh/docs/contract/writeContract) ================================================ FILE: site/core/api/actions/writeContracts.md ================================================ # writeContracts Action that requests for the wallet to sign and broadcast a batch of write contract calls (transactions) to the network. [Read more.](https://github.com/ethereum/EIPs/blob/815028dc634463e1716fc5ce44c019a6040f0bef/EIPS/eip-5792.md#wallet_sendcalls) ## Import ```ts import { writeContracts } from '@wagmi/core/experimental' ``` ## Usage ::: code-group ```ts [index.ts] import { parseAbi } from 'viem' import { writeContracts } from '@wagmi/core/experimental' import { config } from './config' const abi = parseAbi([ 'function approve(address, uint256) returns (bool)', 'function transferFrom(address, address, uint256) returns (bool)', ]) const id = await writeContracts(config, { contracts: [ { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi, functionName: 'approve', args: [ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', 100n ], }, { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi, functionName: 'transferFrom', args: [ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', '0x0000000000000000000000000000000000000000', 100n ], }, ], }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Parameters ```ts import { type WriteContractsParameters } from '@wagmi/core/experimental' ``` ### account `Account | Address | undefined` Account to execute the calls. ::: code-group ```ts [index.ts] import { parseAbi } from 'viem' import { writeContracts } from '@wagmi/core/experimental' import { config } from './config' const abi = parseAbi([ 'function approve(address, uint256) returns (bool)', 'function transferFrom(address, address, uint256) returns (bool)', ]) const id = await writeContracts(config, { account: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', // [!code focus] contracts: [ { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi, functionName: 'approve', args: [ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', 100n ], }, { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi, functionName: 'transferFrom', args: [ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', '0x0000000000000000000000000000000000000000', 100n ], }, ], }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### contracts `{ to: Hex, data?: Hex, value?: bigint }[]` Calls to execute. ::: code-group ```ts [index.ts] import { parseAbi } from 'viem' import { writeContracts } from '@wagmi/core/experimental' import { config } from './config' const abi = parseAbi([ 'function approve(address, uint256) returns (bool)', 'function transferFrom(address, address, uint256) returns (bool)', ]) const id = await writeContracts(config, { contracts: [ // [!code focus] { // [!code focus] address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', // [!code focus] abi, // [!code focus] functionName: 'approve', // [!code focus] args: [ // [!code focus] '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', // [!code focus] 100n // [!code focus] ], // [!code focus] }, // [!code focus] { // [!code focus] address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', // [!code focus] abi, // [!code focus] functionName: 'transferFrom', // [!code focus] args: [ // [!code focus] '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', // [!code focus] '0x0000000000000000000000000000000000000000', // [!code focus] 100n // [!code focus] ], // [!code focus] }, // [!code focus] ], // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### capabilities `WalletCapabilities | undefined` Capability metadata for the calls (e.g. specifying a paymaster). ::: code-group ```ts [index.ts] import { parseAbi } from 'viem' import { writeContracts } from '@wagmi/core/experimental' import { config } from './config' const abi = parseAbi([ 'function approve(address, uint256) returns (bool)', 'function transferFrom(address, address, uint256) returns (bool)', ]) const id = await writeContracts(config, { contracts: [ { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi, functionName: 'approve', args: [ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', 100n ], }, { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi, functionName: 'transferFrom', args: [ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', '0x0000000000000000000000000000000000000000', 100n ], }, ], capabilities: { // [!code focus] paymasterService: { // [!code focus] url: 'https://...' // [!code focus] } // [!code focus] } // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `number | undefined` The target chain ID to broadcast the calls. ::: code-group ```ts [index.ts] import { parseAbi } from 'viem' import { writeContracts } from '@wagmi/core/experimental' import { config } from './config' const abi = parseAbi([ 'function approve(address, uint256) returns (bool)', 'function transferFrom(address, address, uint256) returns (bool)', ]) const id = await writeContracts(config, { contracts: [ { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi, functionName: 'approve', args: [ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', 100n ], }, { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi, functionName: 'transferFrom', args: [ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', '0x0000000000000000000000000000000000000000', 100n ], }, ], chainId: 10, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ### connector `Connector | undefined` Connector to get send the calls with. ::: code-group ```ts [index.ts] import { parseAbi } from 'viem' import { getConnections } from '@wagmi/core' import { writeContracts } from '@wagmi/core/experimental' import { config } from './config' const abi = parseAbi([ 'function approve(address, uint256) returns (bool)', 'function transferFrom(address, address, uint256) returns (bool)', ]) const connections = getConnections(config) const id = await writeContracts(config, { contracts: [ { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi, functionName: 'approve', args: [ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', 100n ], }, { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi, functionName: 'transferFrom', args: [ '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', '0x0000000000000000000000000000000000000000', 100n ], }, ], connector: connections[0]?.connector, // [!code focus] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type WriteContractsReturnType } from '@wagmi/core/experimental' ``` `{ id: string; capabilities?: WalletCapabilities | undefined }` Identifier of the call batch. ## Error ```ts import { type WriteContractsErrorType } from '@wagmi/core/experimental' ``` ## Viem - [`writeContracts`](https://viem.sh/experimental/eip5792/writeContracts) ================================================ FILE: site/core/api/actions.md ================================================ # Actions Actions for accounts, wallets, contracts, transactions, signing, ENS, and more. ## Import ```ts import { getConnection } from '@wagmi/core' ``` ## Available Actions ================================================ FILE: site/core/api/chains.md ================================================ # Chains ## Import Import via the `'@wagmi/core/chains'` entrypoint (proxies all chains from `'viem/chains'`). ```ts import { mainnet } from '@wagmi/core/chains' ``` ## Available Chains Chain definitions as of `viem@{{viemVersion}}`. For `viem@latest`, visit the [Viem repo](https://github.com/wevm/viem/blob/main/src/chains/index.ts). ================================================ FILE: site/core/api/connectors/baseAccount.md ================================================ --- title: baseAccount --- ================================================ FILE: site/core/api/connectors/coinbaseWallet.md ================================================ ================================================ FILE: site/core/api/connectors/injected.md ================================================ --- title: injected --- ================================================ FILE: site/core/api/connectors/metaMask.md ================================================ --- title: metaMask --- ================================================ FILE: site/core/api/connectors/mock.md ================================================ --- title: mock --- ================================================ FILE: site/core/api/connectors/porto.md ================================================ --- title: porto --- ================================================ FILE: site/core/api/connectors/safe.md ================================================ --- title: safe --- ================================================ FILE: site/core/api/connectors/walletConnect.md ================================================ --- title: walletConnect --- ================================================ FILE: site/core/api/connectors.md ================================================ # Connectors Connectors for popular wallet providers and protocols. ## Import Available via the `'@wagmi/connectors'` package. ```ts import { injected } from '@wagmi/connectors' ``` ## Built-In Connectors ::: tip Some connectors require third-party packages. See the "Install" section on each connector's page for more info on license, version, and more. ::: ================================================ FILE: site/core/api/createConfig.md ================================================ --- title: createConfig --- ================================================ FILE: site/core/api/createConnector.md ================================================ # createConnector Creates new [`CreateConnectorFn`](#parameters). ## Import ```ts import { createConnector } from '@wagmi/core' ``` ## Usage ```ts import { createConnector } from '@wagmi/core' export type InjectedParameters = {} export function injected(parameters: InjectedParameters = {}) { return createConnector((config) => ({ // ... })) } ``` ## Parameters ```ts import { type CreateConnectorFn } from '@wagmi/core' ``` Read [Creating Connectors](/dev/creating-connectors) for more info on the `CreateConnectorFn` type. ================================================ FILE: site/core/api/createStorage.md ================================================ --- title: createStorage --- ================================================ FILE: site/core/api/errors.md ================================================ # Errors Error classes used by Wagmi. ================================================ FILE: site/core/api/transports/custom.md ================================================ --- title: custom --- ================================================ FILE: site/core/api/transports/fallback.md ================================================ --- title: fallback --- ================================================ FILE: site/core/api/transports/http.md ================================================ --- title: http --- ================================================ FILE: site/core/api/transports/unstable_connector.md ================================================ --- title: unstable_connector --- ================================================ FILE: site/core/api/transports/webSocket.md ================================================ --- title: webSocket --- ================================================ FILE: site/core/api/transports.md ================================================ # Transports [`createConfig`](/core/api/createConfig) can be instantiated with a set of Transports for each chain. A Transport is the intermediary layer that is responsible for executing outgoing JSON-RPC requests to the RPC Provider (e.g. Alchemy, Infura, etc). ## Import ```ts import { http } from '@wagmi/core' ``` ## Built-In Transports Available via the `'@wagmi/core'` entrypoint. ================================================ FILE: site/core/api/utilities/cookieToInitialState.md ================================================ --- title: cookieToInitialState --- ================================================ FILE: site/core/api/utilities/deserialize.md ================================================ --- title: deserialize --- ================================================ FILE: site/core/api/utilities/serialize.md ================================================ --- title: serialize --- ================================================ FILE: site/core/getting-started.md ================================================ # Getting Started ## Overview Wagmi Core is a VanillaJS library for Ethereum. You can learn more about the rationale behind the project in the [Why Wagmi](/core/why) section. ## Manual Installation To manually add Wagmi to your project, install the required packages. ::: code-group ```bash-vue [pnpm] pnpm add @wagmi/core @wagmi/connectors viem@{{viemVersion}} ``` ```bash-vue [npm] npm install @wagmi/core @wagmi/connectors viem@{{viemVersion}} ``` ```bash-vue [yarn] yarn add @wagmi/core @wagmi/connectors viem@{{viemVersion}} ``` ```bash-vue [bun] bun add @wagmi/core @wagmi/connectors viem@{{viemVersion}} ``` ::: - [Wagmi Connectors](/core/api/connectors) is a collection of interfaces for linking accounts/wallets to Wagmi. - [Viem](https://viem.sh) is a TypeScript interface for Ethereum that performs blockchain operations. - [TypeScript](/react/typescript) is optional, but highly recommended. Learn more about [TypeScript support](/core/typescript). ### Create Config Create and export a new Wagmi config using `createConfig`. ::: code-group <<< @/snippets/core/config.ts[config.ts] ::: In this example, Wagmi is configured to use the Mainnet and Sepolia chains. Check out the [`createConfig` docs](/core/api/createConfig) for more configuration options. ### Use Wagmi Now that everything is set up, you can pass the `config` to use actions. ::: code-group ```tsx [index.ts] import { getConnection, getEnsName } from '@wagmi/core' import { config } from './config' const { address } = getConnection(config) const ensName = await getEnsName(config, { address }) ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Next Steps For more information on what to do next, check out the following topics. - [**TypeScript**](/core/typescript) Learn how to get the most out of Wagmi's type-safety and inference for an enlightened developer experience. - [**Actions**](/core/api/actions) Browse the collection of actions and learn how to use them. - [**Framework Adapters**](/core/guides/framework-adapters) Learn how to create a Wagmi-like adapter for your favorite framework. - [**Viem docs**](https://viem.sh) Wagmi Core is a wrapper around Viem that manages account and client reactivity. Learn more about Viem and how to use it. ================================================ FILE: site/core/guides/chain-properties.md ================================================ # Chain Properties Some chains support additional properties related to blocks and transactions. This is powered by Viem's [formatters](https://viem.sh/docs/chains/formatters) and [serializers](https://viem.sh/docs/chains/serializers). For example, Celo, ZkSync, OP Stack chains support all additional properties. In order to use these properties in a type-safe way, there are a few things you should be aware of. ## Narrowing Parameters When you pass your `config` to an action, you are ready to access chain-specific properties! For example, Celo's `feeCurrency` is available. ::: code-group ```ts [index.ts] import { parseEther } from 'viem' import { simulateContract } from '@wagmi/core' import { config } from './config' const result = await simulateContract(config, { to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), feeCurrency: '0x…', // [!code focus] }) ``` <<< @/snippets/core/config-chain-properties.ts[config.ts] ::: This is great, but if you have multiple chains that support additional properties, your autocomplete could be overwhelmed with all of them. By setting the `chainId` property to a specific value (e.g. `celo.id`), you can narrow parameters to a single chain. ::: code-group ```ts [index.ts] import { parseEther } from 'viem' import { simulateContract } from '@wagmi/core' import { celo } from 'wagmi/chains' const result = await simulateContract({ to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), chainId: celo.id, // [!code focus] feeCurrency: '0x…', // [!code focus] // ^? (property) feeCurrency?: `0x${string}` | undefined // [!code focus] }) ``` <<< @/snippets/core/config-chain-properties.ts[config.ts] ::: ## Narrowing Return Types Return types can also have chain-specific properties attached to them. There are a couple approaches for extracting these properties. ### `chainId` Parameter Not only can you use the `chainId` parameter to [narrow parameters](#narrowing-parameters), you can also use it to narrow the return type. ::: code-group ```ts [index.tsx] import { waitForTransactionReceipt } from '@wagmi/core' import { zkSync } from '@wagmi/core/chains' const result = await waitForTransactionReceipt({ chainId: zkSync.id, hash: '0x16854fcdd0219cacf5aec5e4eb2154dac9e406578a1510a6fc48bd0b67e69ea9', }) result.logs // ^? (property) logs: ZkSyncLog[] | undefined ``` <<< @/snippets/core/config-chain-properties.ts[config.ts] ::: ### `chainId` Data Property Wagmi internally will set a `chainId` property on return types that you can use to narrow results. The `chainId` is determined from the `chainId` parameter or global state (e.g. connector). You can use this property to help TypeScript narrow the type. ::: code-group ```ts [index.tsx] import { waitForTransactionReceipt } from '@wagmi/core' import { zkSync } from '@wagmi/core/chains' const result = await waitForTransactionReceipt({ hash: '0x16854fcdd0219cacf5aec5e4eb2154dac9e406578a1510a6fc48bd0b67e69ea9', }) if (result.chainId === zkSync.id) { result.logs // ^? (property) logs: ZkSyncLog[] | undefined } ``` <<< @/snippets/core/config-chain-properties.ts[config.ts] ::: ## Troubleshooting If chain properties aren't working, make sure [TypeScript](/core/guides/faq#type-inference-doesn-t-work) is configured correctly. Not all chains have additional properties, to check which ones do, see the [Viem repo](https://github.com/wevm/viem/tree/main/src/chains) (chains that have a top-level directory under [`src/chains`](https://github.com/wevm/viem/tree/main/src/chains) support additional properties). ================================================ FILE: site/core/guides/error-handling.md ================================================ # Error Handling Every module in Wagmi Core exports an accompanying error type which you can use to strongly type your `catch` statements. These types come in the form of `ErrorType`. For example, the `getBlockNumber` action exports a `GetBlockNumberErrorType` type. Unfortunately, [TypeScript doesn't have an abstraction for typed exceptions](https://github.com/microsoft/TypeScript/issues/13219), so the most pragmatic & vanilla approach would be to explicitly cast error types in the `catch` statement. ::: code-group ```tsx [index.tsx] import { type GetBlockNumberErrorType, getBlockNumber } from '@wagmi/core' import { config } from './config' try { const blockNumber = await getBlockNumber(config) } catch (e) { const error = e as GetBlockNumberErrorType error.name // ^? (property) name: "Error" | "ChainDisconnectedError" | "HttpRequestError" | "InternalRpcError" | "InvalidInputRpcError" | "InvalidParamsRpcError" | "InvalidRequestRpcError" | "JsonRpcVersionUnsupportedError" | ... 16 more ... | "WebSocketRequestError" if (error.name === 'InternalRpcError') error.code // ^? (property) code: -32603 if (error.name === 'HttpRequestError') error.headers // ^? (property) headers: Headers error.status // ^? (property) status: number } ``` <<< @/snippets/core/config.ts[config.ts] ::: ::: tip If you are using [Wagmi Hooks](/react/api/hooks), errors are [already strongly typed](/react/guides/error-handling) via the `error` property. ::: ================================================ FILE: site/core/guides/ethers.md ================================================ # Ethers.js Adapters It is recommended for projects to migrate to [Viem](https://viem.sh) when using Wagmi, but there are some cases where you might still need to use [Ethers.js](https://ethers.org) in your project: - You may want to **incrementally migrate** Ethers.js usage to Viem - Some **third-party libraries & SDKs** may only support Ethers.js - Personal preference We have provided reference implementations for Viem → Ethers.js adapters that you can copy + paste in your project. ## Client → Provider ### Reference Implementation Copy the following reference implementation into a file of your choice: ::: code-group ```ts [Ethers v5] import { type Config, getClient } from '@wagmi/core' import { providers } from 'ethers' import type { Client, Chain, Transport } from 'viem' export function clientToProvider(client: Client) { const { chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } if (transport.type === 'fallback') return new providers.FallbackProvider( (transport.transports as ReturnType[]).map( ({ value }) => new providers.JsonRpcProvider(value?.url, network), ), ) return new providers.JsonRpcProvider(transport.url, network) } /** Action to convert a viem Public Client to an ethers.js Provider. */ export function getEthersProvider( config: Config, { chainId }: { chainId?: number } = {}, ) { const client = getClient(config, { chainId }) if (!client) return return clientToProvider(client) } ``` ```ts [Ethers v6] import { type Config, getClient } from '@wagmi/core' import { FallbackProvider, JsonRpcProvider } from 'ethers' import type { Client, Chain, Transport } from 'viem' export function clientToProvider(client: Client) { const { chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } if (transport.type === 'fallback') { const providers = (transport.transports as ReturnType[]).map( ({ value }) => new JsonRpcProvider(value?.url, network), ) if (providers.length === 1) return providers[0] return new FallbackProvider(providers) } return new JsonRpcProvider(transport.url, network) } /** Action to convert a viem Client to an ethers.js Provider. */ export function getEthersProvider( config: Config, { chainId }: { chainId?: number } = {}, ) { const client = getClient(config, { chainId }) if (!client) return return clientToProvider(client) } ``` ::: ### Usage Now you can use the `getEthersProvider` function in your components: ::: code-group ```ts [example.ts] import { getEthersProvider } from './ethers' import { config } from './config' function example() { const provider = getEthersProvider(config) ... } ``` ```ts [ethers.ts (Ethers v5)] import { type Config, getClient } from '@wagmi/core' import { providers } from 'ethers' import type { Client, Chain, Transport } from 'viem' export function clientToProvider(client: Client) { const { chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } if (transport.type === 'fallback') return new providers.FallbackProvider( (transport.transports as ReturnType[]).map( ({ value }) => new providers.JsonRpcProvider(value?.url, network), ), ) return new providers.JsonRpcProvider(transport.url, network) } /** Action to convert a viem Public Client to an ethers.js Provider. */ export function getEthersProvider( config: Config, { chainId }: { chainId?: number } = {}, ) { const client = getClient(config, { chainId }) if (!client) return return clientToProvider(client) } ``` ```ts [ethers.ts (Ethers v6)] import { type Config, getClient } from '@wagmi/core' import { FallbackProvider, JsonRpcProvider } from 'ethers' import type { Client, Chain, Transport } from 'viem' export function clientToProvider(client: Client) { const { chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } if (transport.type === 'fallback') { const providers = (transport.transports as ReturnType[]).map( ({ value }) => new JsonRpcProvider(value?.url, network), ) if (providers.length === 1) return providers[0] return new FallbackProvider(providers) } return new JsonRpcProvider(transport.url, network) } /** Action to convert a viem Client to an ethers.js Provider. */ export function getEthersProvider( config: Config, { chainId }: { chainId?: number } = {}, ) { const client = getClient(config, { chainId }) if (!client) return return clientToProvider(client) } ``` ::: ## Connector Client → Signer ### Reference Implementation Copy the following reference implementation into a file of your choice: ::: code-group ```ts [Ethers v5] import { Config, getConnectorClient } from '@wagmi/core' import { providers } from 'ethers' import type { Account, Chain, Client, Transport } from 'viem' export function clientToSigner(client: Client) { const { account, chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } const provider = new providers.Web3Provider(transport, network) const signer = provider.getSigner(account.address) return signer } /** Action to convert a Viem Client to an ethers.js Signer. */ export async function getEthersSigner( config: Config, { chainId }: { chainId?: number } = {}, ) { const client = await getConnectorClient(config, { chainId }) return clientToSigner(client) } ``` ```ts [Ethers v6] import { Config, getConnectorClient } from '@wagmi/core' import { BrowserProvider, JsonRpcSigner } from 'ethers' import type { Account, Chain, Client, Transport } from 'viem' export function clientToSigner(client: Client) { const { account, chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } const provider = new BrowserProvider(transport, network) const signer = new JsonRpcSigner(provider, account.address) return signer } /** Action to convert a viem Wallet Client to an ethers.js Signer. */ export async function getEthersSigner( config: Config, { chainId }: { chainId?: number } = {}, ) { const client = await getConnectorClient(config, { chainId }) return clientToSigner(client) } ``` ::: ### Usage Now you can use the `getEthersSigner` function in your components: ::: code-group ```ts [example.ts] import { getEthersSigner } from './ethers' import { config } from './config' function example() { const provider = getEthersSigner(config) ... } ``` ```ts [ethers.ts (Ethers v5)] import { Config, getConnectorClient } from '@wagmi/core' import { providers } from 'ethers' import type { Account, Chain, Client, Transport } from 'viem' export function clientToSigner(client: Client) { const { account, chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } const provider = new providers.Web3Provider(transport, network) const signer = provider.getSigner(account.address) return signer } /** Action to convert a Viem Client to an ethers.js Signer. */ export async function getEthersSigner( config: Config, { chainId }: { chainId?: number } = {}, ) { const client = await getConnectorClient(config, { chainId }) return clientToSigner(client) } ``` ```ts [ethers.ts (Ethers v6)] import { Config, getConnectorClient } from '@wagmi/core' import { BrowserProvider, JsonRpcSigner } from 'ethers' import type { Account, Chain, Client, Transport } from 'viem' export function clientToSigner(client: Client) { const { account, chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } const provider = new BrowserProvider(transport, network) const signer = new JsonRpcSigner(provider, account.address) return signer } /** Action to convert a viem Wallet Client to an ethers.js Signer. */ export async function getEthersSigner( config: Config, { chainId }: { chainId?: number } = {}, ) { const client = await getConnectorClient(config, { chainId }) return clientToSigner(client) } ``` ::: ================================================ FILE: site/core/guides/faq.md ================================================ # FAQ / Troubleshooting Collection of frequently asked questions with ideas on how to troubleshoot and resolve them. ================================================ FILE: site/core/guides/framework-adapters.md ================================================ # Framework Adapters Folks often ask if they can use Wagmi with other frameworks, like Svelte, Solid.js, and more. The short answer is — you already can! Wagmi Core is pure VanillaJS that you can use with any framework. For some, this answer is (understandably) unsatisfying as they want a tight integration between Wagmi Core and their favorite framework's reactivity system, e.g. what Wagmi is for React and Vue. Someday, we would love to support additional frameworks, but unfortunately the core team doesn't have time to build and support them in a high-quality way at the moment. This could change in the future with additional [sponsors](https://github.com/sponsors/wevm), reshuffling of the roadmap, or if someone from the community wants to lead the effort. In the meantime, here are some tips on how to create tighter bonds between Wagmi Core and other frameworks. ## Dependency Injection Once you create a Wagmi Config, you'll need to make sure your framework has access to it inside your higher-level functions (e.g. hooks for React, composables for Vue). For example, Wagmi uses [React Context](https://react.dev/learn/passing-data-deeply-with-context) to inject the Config into React Hooks and update it if it changes. This makes it so your users don't need to pass a Config object every time they use a hook. ## Reactivity Layer All frameworks approach reactivity in a different way. To hook into your favorite frameworks, reactivity system, it's often helpful to see what other popular libraries for your framework are doing. The most important thing to hook up Wagmi Core with your framework is to make sure changes to the Wagmi Config are tracked. This enables behavior, like switching chains or connecting accounts, to propagate throughout your app and update state. Check out [`useConnection`](https://github.com/wevm/wagmi/blob/main/packages/react/src/hooks/useConnection.ts), [`useChainId`](https://github.com/wevm/wagmi/blob/main/packages/react/src/hooks/useChainId.ts), [`useClient`](https://github.com/wevm/wagmi/blob/main/packages/react/src/hooks/useClient.ts), and [`useConnectorClient`](https://github.com/wevm/wagmi/blob/main/packages/react/src/hooks/useConnectorClient.ts) — versions of these for your framework are important to get right as they power a lot of internals. ## TanStack Query Wagmi uses [TanStack Query](https://tanstack.com/query) to enable caching, deduplication, persistence, and more in React and Vue applications. Normally, you would need to find a similar library for your framework, but the good news is TanStack Query supports other frameworks! (Svelte, Solid, and Angular at the time of writing.) To get started with your framework, install and set up the related TanStack Query adapter. Next, import query keys/functions and mutation functions from the `'@wagmi/core/query'` entrypoint. You can plug these directly into your framework's TanStack Query adapter functions. If you are building a library, you'll also want to make sure that you wire up generics correctly so type-inference and safety work correctly. The best way to make sure you are doing this correctly, is to see how we do this for React with Wagmi by checking out the [source code](https://github.com/wevm/wagmi/tree/main/packages/react/src/hooks). ## Testing If you are building a library, you'll want to write tests. Wagmi uses [React Testing Library](https://testing-library.com/docs/react-testing-library/intro) to test hooks. [Testing Library](https://testing-library.com) also supports other frameworks, like Svelte, Solid, and more. You can take a look at how the React tests work and do something similar for your code. ## Proxy Exports Wagmi proxies exports directly from Wagmi Core and [Viem](https://viem.sh) to make importing easier. You'll likely want to imitate this behavior for your framework. ================================================ FILE: site/core/guides/migrate-from-v1-to-v2.md ================================================ --- title: Migrate from v1 to v2 titleTemplate: Wagmi Core description: Guide for migrating from Wagmi Core v1 to v2. --- # Migrate from v1 to v2 Wagmi Core v2 redesigns the core APIs to mesh better with [Viem](https://viem.sh). This major version transforms Wagmi into a light wrapper around Viem, sprinkling in multichain support and account management. As such, there are some breaking changes and deprecations to be aware of outlined in this guide. To get started, install the latest version of Wagmi and it's required peer dependencies. ::: code-group ```bash-vue [pnpm] pnpm add @wagmi/core viem@{{viemVersion}} @wagmi/connectors ``` ```bash-vue [npm] npm install @wagmi/core viem@{{viemVersion}} @wagmi/connectors ``` ```bash-vue [yarn] yarn add @wagmi/core viem@{{viemVersion}} @wagmi/connectors ``` ```bash-vue [bun] bun add @wagmi/core viem@{{viemVersion}} @wagmi/connectors ``` ::: ::: info Wagmi Core v2 should be the last major version that will have this many actionable breaking changes. Moving forward, new functionality will be opt-in with old functionality being deprecated alongside the new features. This means upgrading to the latest major versions will not require immediate changes. ::: ::: info Not ready to migrate yet? The Wagmi Core v1 docs are still available at [1.x.wagmi.sh/core](https://1.x.wagmi.sh/core). ::: ## Dependencies ### Dropped CommonJS support Wagmi v2 no longer publishes a separate `cjs` tag since very few people use this tag and ESM is the future. See [Sindre Sorhus' guide](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c) for more info about switching to ESM. ## Actions ### Removed `config` singleton Before v2, when you called [`createConfig`](/core/api/createConfig), it set a global `config` singleton that was used internally by actions. For v2, `config` is now a required first parameter for actions. ::: code-group ```ts [index.ts] import { getAccount, readContract } from '@wagmi/core' import { parseAbi } from 'viem' import { config } from './config' // [!code ++] const account = getAccount() // [!code --] const account = getAccount(config) // [!code ++] const balanceOf = readContract({ // [!code --] const balanceOf = readContract(config, { // [!code ++] address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', abi: parseAbi(['function balanceOf(address) view returns (uint256)']), functionName: 'balanceOf', args: ['0xd2135CfB216b74109775236E36d4b433F1DF507B'], }) ``` <<< @/snippets/core/config.ts[config.ts] ::: The previous global `config` singleton made it so you couldn't use multiple `Config` objects in the same project. In addition, we think passing `config` is more explicit and makes it easier to understand what's going on. Finally, types can be inferred directly from the `config`, like [chain properties](/core/guides/chain-properties) and more. ### Removed `getContract` Removed `getContract` export. Use Viem's [`getContract`](https://viem.sh/docs/contract/getContract) instead. ```ts import { getContract } from '@wagmi/core' // [!code --] import { getContract } from 'viem' // [!code ++] const contract = getContract() // [!code --] const contract = getContract() // [!code ++] ``` ### Removed `getNetwork` and `watchNetwork` The `getNetwork` and `watchNetwork` actions were removed since the connected chain is typically based on the connected account. - Use [`config.chains`](/core/api/createConfig#chains-1) instead to get `chains`. ::: code-group ```ts [index.ts] import { getNetwork } from '@wagmi/core' // [!code --] const { chains } = getNetwork() // [!code --] const chains = config.chains // [!code ++] ``` <<< @/snippets/core/config.ts[config.ts] ::: - Use [`getAccount`](/core/api/actions/getConnection) and `config.chains` instead to get `chain`. ::: code-group ```ts [index.ts] import { getNetwork } from '@wagmi/core' // [!code --] import { getAccount } from '@wagmi/core' // [!code ++] import { config } from './config' // [!code ++] const { chain } = getNetwork() // [!code --] const { chainId } = getAccount(config) // [!code ++] const chain = chains.find(chain => chain.id === chainId) // [!code ++] ``` <<< @/snippets/core/config.ts[config.ts] ::: Before v2, `getNetwork().chain` could result in an invalid chain if the active connector's `chainId` was not configured in the list of `config.chains`. Using `getAccount` and `config.chains` is more work, but ensures that chain is either valid or not defined. You can also use `getAccount(config).chain` if you don't care about the chain being `undefined` when not configured. - Use `watchAccount` instead of `watchNetwork`. ::: code-group ```ts [index.ts] import { watchNetwork } from '@wagmi/core' // [!code --] import { watchAccount } from '@wagmi/core' // [!code ++] import { config } from './config' // [!code ++] const unwatch = watchNetwork((data) => console.log('Changed!', data)) // [!code --] const unwatch = watchAccount(config, { // [!code ++] onChange(data) { // [!code ++] const chains = config.chains // [!code ++] const chain = chains.find(chain => chain.id === data.chainId) // [!code ++] }, // [!code ++] }) // [!code ++] ``` <<< @/snippets/core/config.ts[config.ts] ::: ### Removed `getWebSocketPublicClient` and `watchWebSocketPublicClient` Viem [Transports](https://viem.sh/docs/clients/intro#transports) now determine the type of client that is returned. You can use [`getPublicClient`](/core/api/actions/getPublicClient) and [`watchPublicClient`](/core/api/actions/watchPublicClient) to retrieve Viem [`PublicClient`](https://viem.sh/docs/clients/public) instances. Alternatively, you can use [`getClient`](/core/api/actions/getClient) and [`watchClient`](/core/api/actions/watchClient) to retrieve plain Viem [`Client`](https://viem.sh/docs/clients/custom) instances. This is a better option for users that care about optimizing bundle size to be as small as possible. ### Removed `watchReadContract`, `watchReadContracts`, and `watchReadMulticall` Use [`watchBlockNumber`](/core/api/actions/watchBlockNumber) along with [`readContract`](/core/api/actions/readContract), [`readContracts`](/core/api/actions/readContracts), and [`multicall`](/core/api/actions/multicall) actions instead. Before v2, `watchReadContract`, `watchReadContracts`, and `watchReadMulticall` were all wrappers around `watchBlockNumber` and this simplifies the API. ::: code-group ```ts [index.ts] import { watchReadContract } from '@wagmi/core' // [!code --] import { watchBlockNumber, readContract } from '@wagmi/core' // [!code ++] import { config } from './config' // [!code ++] const unwatch = watchReadContract( // [!code --] { // [!code --] address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', // [!code --] abi: parseAbi(['function balanceOf(address) view returns (uint256)']), // [!code --] functionName: 'balanceOf', // [!code --] args: ['0xd2135CfB216b74109775236E36d4b433F1DF507B'], // [!code --] }, // [!code --] (result) => console.log('Changed!', result), // [!code --] ) // [!code --] const unwatch = watchBlockNumber(config, { // [!code ++] onBlockNumber() { // [!code ++] const balanceOf = readContract(config, { // [!code ++] address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', // [!code ++] abi: parseAbi(['function balanceOf(address) view returns (uint256)']), // [!code ++] functionName: 'balanceOf', // [!code ++] args: ['0xd2135CfB216b74109775236E36d4b433F1DF507B'], // [!code ++] }) // [!code ++] console.log('Changed!', balanceOf)// [!code ++] }, // [!code ++] }) // [!code ++] ``` <<< @/snippets/core/config.ts[config.ts] ::: ### Removed `fetchFeeData` Removed `fetchFeeData`. Use [`estimateFeesPerGas`](/core/api/actions/estimateFeesPerGas) instead. ::: code-group ```ts [index.ts] import { fetchFeeData } from '@wagmi/core' // [!code --] import { estimateFeesPerGas } from '@wagmi/core' // [!code ++] import { config } from './config' // [!code ++] const result = await fetchFeeData() // [!code --] const result = await estimateFeesPerGas(config) // [!code ++] ``` <<< @/snippets/core/config.ts[config.ts] ::: ### Removed `prepareWriteContract` Removed `prepareWriteContract`. Use [`simulateContract`](/core/api/actions/simulateContract) instead. ::: code-group ```ts [index.ts] import { prepareWriteContract } from '@wagmi/core' // [!code --] import { simulateContract } from '@wagmi/core' // [!code ++] import { config } from './config' // [!code ++] const result = await prepareWriteContract({ ... }) // [!code --] const result = await simulateContract(config, { ... }) // [!code ++] ``` <<< @/snippets/core/config.ts[config.ts] ::: ### Removed `prepareSendTransaction` Removed `prepareSendTransaction`. Use [`estimateGas`](/core/api/actions/estimateGas) instead. ::: code-group ```ts [index.ts] import { prepareSendTransaction } from '@wagmi/core' // [!code --] import { estimateGas } from '@wagmi/core' // [!code ++] import { config } from './config' // [!code ++] const result = await prepareSendTransaction({ ... }) // [!code --] const result = await estimateGas(config, { ... }) // [!code ++] ``` <<< @/snippets/core/config.ts[config.ts] ::: ### Updated `sendTransaction` and `writeContract` return type Updated [`sendTransaction`](/core/api/actions/sendTransaction) and [`writeContract`](/core/api/actions/writeContract) return type from `` { hash: `0x${string}` } `` to `` `0x${string}` ``. ```ts const result = await sendTransaction({ hash: '0x...' }) result.hash // [!code --] result // [!code ++] ``` ### Updated `connect` return type Updated [`connect`](/core/api/actions/connect) return type from `` { account: Address; chain: { id: number; unsupported?: boolean }; connector: Connector } `` to `` { accounts: readonly Address[]; chainId: number } ``. This better reflects the ability to have multiple accounts per connector. ### Renamed parameters and return types All hook parameters and return types follow the naming pattern of `[PascalCaseActionName]Parameters` and `[PascalCaseActionName]ReturnType`. For example, `GetAccountParameters` and `GetAccountReturnType`. ```ts import { GetAccountConfig, GetAccountResult } from '@wagmi/core' // [!code --] import { GetAccountParameters, GetAccountReturnType } from '@wagmi/core' // [!code ++] ``` ## Connectors ### Moved Wagmi Connectors to peer dependencies Wagmi Core v2 no longer exports connectors via the `'@wagmi/core/connectors/*'` entrypoints. Instead, you should install the `@wagmi/connectors` package. ::: code-group ```bash-vue [pnpm] pnpm add @wagmi/connectors ``` ```bash-vue [npm] npm install @wagmi/connectors ``` ```bash-vue [yarn] yarn add @wagmi/connectors ``` ```bash-vue [bun] bun add @wagmi/connectors ``` ::: And import connectors from there. ```ts import { injected } from '@wagmi/connectors' ``` See the [connectors documentation](/core/api/connectors) for more information. ### Updated connector API In order to maximize type-safety and ease of creating connectors, the connector API changed. Follow the [Creating Connectors guide](/dev/creating-connectors) for more info on creating new connectors and converting Wagmi v1 connectors. ### Removed individual entrypoints Previously, each connector had its own entrypoint to optimize tree-shaking. Since all connectors now have [`package.json#sideEffects`](https://webpack.js.org/guides/tree-shaking/#mark-the-file-as-side-effect-free) enabled, this is no longer necessary and the entrypoint is unified. Use the `'@wagmi/connectors'` package instead. ```ts import { InjectedConnector } from '@wagmi/core/connectors/injected' // [!code --] import { CoinbaseWalletConnector } from '@wagmi/core/connectors/coinbaseWallet' // [!code --] import { coinbaseWallet, injected } from '@wagmi/connectors' // [!code ++] ``` ### Removed `MetaMaskConnector` The `MetaMaskConnector` was removed since it was nearly the same thing as the `InjectedConnector`. Use the [`injected`](/core/api/connectors/injected) connector instead, along with the [`target`](/core/api/connectors/injected#target) parameter set to `'metaMask'`, for the same behavior. ```ts import { MetaMaskConnector } from '@wagmi/core/connectors/metaMask' // [!code --] import { injected } from '@wagmi/connectors' // [!code ++] const connector = new MetaMaskConnector() // [!code --] const connector = injected({ target: 'metaMask' }) // [!code ++] ``` ### Renamed connectors In Wagmi v1, connectors were classes you needed to instantiate. In Wagmi v2, connectors are functions. As a result, the API has changed. Connectors have the following new names: - `CoinbaseWalletConnector` is now [`coinbaseWallet`](/core/api/connectors/coinbaseWallet). - `InjectedConnector` is now [`injected`](/core/api/connectors/injected). - `SafeConnector` is now [`safe`](/core/api/connectors/safe). - `WalletConnectConnector` is now [`walletConnect`](/core/api/connectors/walletConnect). To create a connector, you now call the connector function with parameters. ```ts import { WalletConnectConnector } from '@wagmi/core/connectors/walletConnect' // [!code --] import { walletConnect } from '@wagmi/connectors' // [!code ++] const connector = new WalletConnectConnector({ // [!code --] const connector = walletConnect({ // [!code ++] projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', }) ``` ### Removed `WalletConnectLegacyConnector` WalletConnect v1 was sunset June 28, 2023. Use the [`walletConnect`](/core/api/connectors/walletConnect) connector instead. ```ts import { WalletConnectLegacyConnector } from '@wagmi/core/connectors/walletConnectLegacy' // [!code --] import { walletConnect } from '@wagmi/connectors' // [!code ++] const connector = new WalletConnectLegacyConnector({ // [!code --] const connector = walletConnect({ // [!code ++] projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', }) ``` ## Chains ### Updated `'@wagmi/core/chains'` entrypoint Chains now live in the [Viem repository](https://github.com/wevm/viem). As a result, the `'@wagmi/core/chains'` entrypoint now proxies all chains from `'viem/chains'` directly. ### Removed `mainnet` and `sepolia` from main entrypoint Since the `'@wagmi/core/chains'` entrypoint now proxies `'viem/chains'`, `mainnet` and `sepolia` were removed from the main entrypoint. Use the `'@wagmi/core/chains'` entrypoint instead. ```ts import { mainnet, sepolia } from '@wagmi/core' // [!code --] import { mainnet, sepolia } from '@wagmi/core/chains' // [!code ++] ``` ## Errors A number of errors were renamed to better reflect their functionality or replaced by Viem errors. ## Miscellaneous ### Removed internal ENS normalization Before v2, Wagmi handled ENS name normalization internally for `getEnsAddress`, `getEnsAvatar`, and `getEnsResolver`, using Viem's [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function. This added extra bundle size as full normalization is quite heavy. For v2, you must normalize ENS names yourself before passing them to these actions. You can use Viem's `normalize` function or any other function that performs [UTS-46 normalization](https://unicode.org/reports/tr46). ::: code-group ```ts [index.ts] import { getEnsAddress } from '@wagmi/core' import { normalize } from 'viem' // [!code ++] import { config } from './config' const result = await getEnsAddress(config, { name: 'wevm.eth', // [!code --] name: normalize('wevm.eth'), // [!code ++] }) ``` <<< @/snippets/core/config.ts[config.ts] ::: By inverting control, Wagmi lets you choose how much normalization to do. For example, maybe your project only allows ENS names that are numeric so no normalization is not needed. Check out the [ENS documentation](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) for more information on normalizing names. ### Removed `configureChains` The Wagmi v2 `Config` now has native multichain support using the [`chains`](/core/api/createConfig) parameter so the `configureChains` function is no longer required. ```ts import { configureChains, createConfig } from '@wagmi/core' // [!code --] import { http, createConfig } from '@wagmi/core' // [!code ++] import { mainnet, sepolia } from '@wagmi/core/chains' const { chains, publicClient } = configureChains( // [!code --] [mainnet, sepolia], // [!code --] [publicProvider(), publicProvider()], // [!code --] ) // [!code --] export const config = createConfig({ publicClient, // [!code --] chains: [mainnet, sepolia], // [!code ++] transports: { // [!code ++] [mainnet.id]: http(), // [!code ++] [sepolia.id]: http(), // [!code ++] }, // [!code ++] }) ``` ### Removed ABI exports Import from Viem instead. ```ts import { erc20ABI } from '@wagmi/core' // [!code --] import { erc20Abi } from 'viem' // [!code ++] ``` ### Removed `'@wagmi/core/providers/*` entrypoints It never made sense that we would have provider URLs hardcoded in the Wagmi codebase. Use [Viem transports](https://viem.sh/docs/clients/intro#transports) along with RPC provider URLs instead. ```ts import { alchemyProvider } from '@wagmi/core/providers/alchemy' // [!code --] import { http } from 'viem' // [!code ++] const transport = http('https://mainnet.example.com') ``` ### Updated `createConfig` parameters - Removed `autoConnect`. The reconnecting behavior must be managed manually and is not related to the Wagmi `Config`. Use the [`reconnect`](/core/api/actions/reconnect) action instead. - Removed `publicClient` and `webSocketPublicClient`. Use [`transports`](/core/api/createConfig#transports) or [`client`](/core/api/createConfig#client) instead. - Removed `logger`. Wagmi no longer logs debug information to console. ### Updated `Config` object - Removed `config.connector`. Use `config.state.connections.get(config.state.current)?.connector` instead. - Removed `config.data`. Use `config.state.connections.get(config.state.current)` instead. - Removed `config.error`. Was unused and not needed. - Removed `config.lastUsedChainId`. Use `config.state.connections.get(config.state.current)?.chainId` instead. - Removed `config.publicClient`. Use [`config.getClient()`](/core/api/createConfig#getclient) or [`getPublicClient`](/core/api/actions/getPublicClient) instead. - Removed `config.status`. Use [`config.state.status`](/core/api/createConfig#status) instead. - Removed `config.webSocketClient`. Use [`config.getClient()`](/core/api/createConfig#getclient) or [`getPublicClient`](/core/api/actions/getPublicClient) instead. - Removed `config.clearState`. Was unused and not needed. - Removed `config.autoConnect()`. Use [`reconnect`](/core/api/actions/reconnect) action instead. - Renamed `config.setConnectors`. Use `config._internal.setConnectors` instead. - Removed `config.setLastUsedConnector`. Use `config.storage?.setItem('recentConnectorId', connectorId)` instead. - Removed `getConfig`. `config` should be passed explicitly to actions instead of using global `config`. ## Deprecations ### Deprecated `getBalance` `token` parameter Moving forward, `getBalance` will only work for native currencies, thus the `token` parameter is no longer supported. Use [`readContracts`](/core/api/actions/readContracts) instead. ```ts import { getBalance } from '@wagmi/core' // [!code --] import { readContracts } from '@wagmi/core' // [!code ++] import { erc20Abi } from 'viem' // [!code ++] import { config } from './config' // [!code ++] const result = await getBalance(config, { // [!code --] address: '0x4557B18E779944BFE9d78A672452331C186a9f48', // [!code --] token: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code --] }) // [!code --] const result = await readContracts(config, { // [!code ++] allowFailure: false, // [!code ++] contracts: [ // [!code ++] { // [!code ++] address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code ++] abi: erc20Abi, // [!code ++] functionName: 'balanceOf', // [!code ++] args: ['0x4557B18E779944BFE9d78A672452331C186a9f48'], // [!code ++] }, // [!code ++] { // [!code ++] address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code ++] abi: erc20Abi, // [!code ++] functionName: 'decimals', // [!code ++] }, // [!code ++] { // [!code ++] address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code ++] abi: erc20Abi, // [!code ++] functionName: 'symbol', // [!code ++] }, // [!code ++] ] // [!code ++] }) // [!code ++] ``` ### Deprecated `getBalance` `unit` parameter and `formatted` return value Moving forward, `getBalance` will not accept the `unit` parameter or return a `formatted` value. Instead you can call `formatUnits` from Viem directly or use another number formatting library, like [dnum](https://github.com/bpierre/dnum) instead. ```ts import { formatUnits } from 'viem' // [!code ++] import { getBalance } from '@wagmi/core' const result = await getBalance({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', unit: 'ether', // [!code --] }) result.formatted // [!code --] formatUnits(result.value, result.decimals) // [!code ++] ``` ### Deprecated `getToken` Moving forward, `getToken` is no longer supported. Use [`readContracts`](/core/api/actions/readContracts) instead. ```ts import { getToken } from '@wagmi/core' // [!code --] import { readContracts } from '@wagmi/core' // [!code ++] import { erc20Abi } from 'viem' // [!code ++] import { config } from './config' // [!code ++] const result = await getToken(config, { // [!code --] address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code --] }) // [!code --] const result = await readContracts(config, { // [!code ++] allowFailure: false, // [!code ++] contracts: [ // [!code ++] { // [!code ++] address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code ++] abi: erc20Abi, // [!code ++] functionName: 'decimals', // [!code ++] }, // [!code ++] { // [!code ++] address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code ++] abi: erc20Abi, // [!code ++] functionName: 'name', // [!code ++] }, // [!code ++] { // [!code ++] address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code ++] abi: erc20Abi, // [!code ++] functionName: 'symbol', // [!code ++] }, // [!code ++] { // [!code ++] address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code ++] abi: erc20Abi, // [!code ++] functionName: 'totalSupply', // [!code ++] }, // [!code ++] ] // [!code ++] }) // [!code ++] ``` ### Deprecated `formatUnits` parameters and return values The `formatUnits` parameter and related return values (e.g. `result.formatted`) are deprecated for the following actions: - [`estimateFeesPerGas`](/core/api/actions/estimateFeesPerGas) - `getToken` Instead you can call `formatUnits` from Viem directly or use another number formatting library, like [dnum](https://github.com/bpierre/dnum) instead. ```ts import { formatUnits } from 'viem' // [!code ++] import { getToken } from '@wagmi/core' const result = await getToken({ address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', formatUnits: 'ether', }) result.totalSupply.formatted // [!code --] formatUnits(result.totalSupply.value, 18) // [!code ++] ``` This allows us to invert control to users so they can handle number formatting however they want, taking into account precision, localization, and more. ### Renamed actions The following actions were renamed to better reflect their functionality and underlying [Viem](https://viem.sh) actions: - `fetchBalance` is now [`getBalance`](/core/api/actions/getBalance) - `fetchBlockNumber` is now [`getBlockNumber`](/core/api/actions/getBlockNumber) - `fetchEnsAddress` is now [`getEnsAddress`](/core/api/actions/getEnsAddress) - `fetchEnsAvatar` is now [`getEnsAvatar`](/core/api/actions/getEnsAvatar) - `fetchEnsName` is now [`getEnsName`](/core/api/actions/getEnsName) - `fetchEnsResolver` is now [`getEnsResolver`](/core/api/actions/getEnsResolver) - `fetchToken` is now `getToken` - `fetchTransaction` is now [`getTransaction`](/core/api/actions/getTransaction) - `switchNetwork` is now [`switchChain`](/core/api/actions/switchChain) - `waitForTransaction` is now [`waitForTransactionReceipt`](/core/api/actions/waitForTransactionReceipt) ================================================ FILE: site/core/guides/migrate-from-v2-to-v3.md ================================================ --- title: Migrate from v2 to v3 description: Guide for migrating from Wagmi v2 to v3. --- # Migrate from v2 to v3 ## Overview Wagmi v3 gives you total control over connector dependencies. Since Wagmi's initial release, Wagmi included required connector dependencies as part of its package to eliminate the need to manage multiple third-party dependencies. This worked worked well in the early years as a "batteries-included" approach, but didn't allow for more fine-grained control over your dependency tree. By giving you control over connector dependencies, you can decide to only install what you need, manage version bumps at your own pace, and have total control over what third-party code and licenses you bring into your project To get started, install the latest version of Wagmi. ::: code-group ```bash [pnpm] pnpm add @wagmi/core@3 ``` ```bash [npm] npm install @wagmi/core@3 ``` ```bash [yarn] yarn add @wagmi/core@3 ``` ```bash [bun] bun add @wagmi/core@3 ``` ::: ::: info Not ready to migrate yet? The Wagmi v2 docs are still available at [2.x.wagmi.sh/core](https://2.x.wagmi.sh/core). ::: ## Deprecations ### Renamed Account Actions At the core of Wagmi are connections between apps and Ethereum providers (e.g. EIP-1193), `getAccount`, `switchAccount`, and `watchAccount` are renamed to `getConnection`, `switchConnection`, and `watchConnection` to more accurately represent to how Wagmi works. ```ts import { getAccount, // [!code --] getConnection, // [!code ++] switchAccount, // [!code --] switchConnection, // [!code ++] watchAccount, // [!code --] watchConnection, // [!code ++] } from '@wagmi/core' ``` `switchAccountMutationOptions` is also updated to `switchConnectionMutationOptions`. ```ts import { switchAccountMutationOptions, // [!code --] switchConnectionMutationOptions, // [!code ++] } from '@wagmi/core/query' ``` ================================================ FILE: site/core/guides/testing.md ================================================ # Testing ================================================ FILE: site/core/guides/viem.md ================================================ # Viem [Viem](https://viem.sh) is a low-level TypeScript Interface for Ethereum that enables developers to interact with the Ethereum blockchain, including: JSON-RPC API abstractions, Smart Contract interaction, wallet & signing implementations, coding/parsing utilities and more. **Wagmi Core** is essentially a wrapper over **Viem** that provides multi-chain functionality via [Wagmi Config](/core/api/createConfig) and automatic account management via [Connectors](/core/api/connectors). ## Leveraging Viem Actions All of the core [Wagmi Actions](/core/api/actions) are friendly wrappers around [Viem Actions](https://viem.sh/docs/actions/public/introduction) that inject a multi-chain and connector aware [Wagmi Config](/core/api/createConfig). There may be cases where you might want to dig deeper and utilize Viem Actions directly (maybe an Action doesn't exist in Wagmi yet). In these cases, you can import Viem Actions directly via `viem/actions` and plug in a Viem Client returned by the [`getClient` Action](/core/api/actions/getClient). The example below demonstrates two different ways to utilize Viem Actions: 1. **Tree-shakable Actions (recommended):** Uses `getClient` (for public actions) and `getConnectorClient` (for wallet actions). 2. **Client Actions:** Uses `getPublicClient` (for public actions) and `getWalletClient` (for wallet actions). ::: tip It is highly recommended to use the **tree-shakable** method to ensure that you are only pulling modules you use, and keep your bundle size low. ::: ::: code-group ```tsx [Tree-shakable Actions] // 1. Import modules. import { http, createConfig, getClient, getConnectorClient } from '@wagmi/core' import { base, mainnet, optimism, zora } from '@wagmi/core/chains' import { getLogs, watchAsset } from 'viem/actions' // [!code hl] // 2. Set up a Wagmi Config export const config = createConfig({ chains: [base, mainnet, optimism, zora], transports: { [base.id]: http(), [mainnet.id]: http(), [optimism.id]: http(), [zora.id]: http(), }, }) // 3. Extract a Viem Client for the current active chain. const publicClient = getClient(config) const logs = await getLogs(publicClient, /* ... */) // [!code hl] // 4. Extract a Viem Client for the current active chain & account. const walletClient = getConnectorClient(config) const success = await watchAsset(walletClient, /* ... */) // [!code hl] ``` ```tsx [Client Actions] // 1. Import modules. import { http, createConfig, getPublicClient, getWalletClient } from '@wagmi/core' import { base, mainnet, optimism, zora } from '@wagmi/core/chains' // 2. Set up a Wagmi Config export const config = createConfig({ chains: [base, mainnet, optimism, zora], transports: { [base.id]: http(), [mainnet.id]: http(), [optimism.id]: http(), [zora.id]: http(), }, }) // 3. Extract a Viem Public Client for the current active chain. const publicClient = getPublicClient(config) const logs = await publicClient.getLogs(publicClient, /* ... */) // [!code hl] // 4. Extract a Viem Wallet Client for the current active chain & account. const walletClient = getWalletClient(config) const success = await walletClient.watchAsset(walletClient, /* ... */) // [!code hl] ``` ::: ## Multi-chain Viem Client The [Viem Client](https://viem.sh/docs/clients/intro) provides an interface to interact with an JSON-RPC Provider. By nature, JSON-RPC Providers are single-chain, so the Viem Client is designed to be instantiated with a single `chain`. As a result, setting up Viem to be multi-chain aware can get a bit verbose. The good news is that you can create a **"multi-chain Viem Client"** with **Wagmi** by utilizing [`createConfig`](/core/api/createConfig) and [`getClient`](/core/api/actions/getClient). ::: code-group ```tsx [Wagmi Usage] // 1. Import modules. import { http, createConfig, getClient, getConnectorClient } from '@wagmi/core' import { base, mainnet, optimism, zora } from '@wagmi/core/chains' import { getBlockNumber, sendTransaction } from 'viem/actions' // [!code hl] // 2. Set up a Wagmi Config export const config = createConfig({ chains: [base, mainnet, optimism, zora], transports: { [base.id]: http(), [mainnet.id]: http(), [optimism.id]: http(), [zora.id]: http(), }, }) // 3. Extract a Viem Client for the current active chain. const publicClient = getClient(config) const blockNumber = await getBlockNumber(publicClient) // [!code hl] // 4. Extract a Viem Client for the current active chain & account. const walletClient = getConnectorClient(config) const hash = await sendTransaction(walletClient, /* ... */) // [!code hl] ``` ```tsx [Viem Usage] // Manually set up Viem Clients without wagmi. Don't do this, it's only here // to demonstrate the amount of boilerplate required. import { createPublicClient, createWalletClient, http } from 'viem' import { base, mainnet, optimism, zora } from 'viem/chains' const publicClient = { base: createPublicClient({ chain: base, transport: http() }), mainnet: createPublicClient({ chain: mainnet, transport: http() }), optimism: createPublicClient({ chain: optimism, transport: http() }), zora: createPublicClient({ chain: zora, transport: http() }) } as const const walletClient = { base: createWalletClient({ chain: base, transport: custom(window.ethereum) }), mainnet: createWalletClient({ chain: mainnet, transport: custom(window.ethereum) }), optimism: createWalletClient({ chain: optimism, transport: custom(window.ethereum) }), zora: createWalletClient({ chain: zora, transport: custom(window.ethereum) }) } as const const blockNumber = await publicClient.mainnet.getBlockNumber() const hash = await walletClient.mainnet.sendTransaction(/* ... */) ``` ::: ## Private Key & Mnemonic Accounts It is possible to utilize Viem's [Private Key & Mnemonic Accounts](https://viem.sh/docs/accounts/local) with Wagmi by explicitly passing through the account via the `account` argument on Wagmi Actions. ```tsx import { http, createConfig, sendTransaction } from '@wagmi/core' import { base, mainnet, optimism, zora } from '@wagmi/core/chains' import { parseEther } from 'viem' import { privateKeyToAccount } from 'viem/accounts' export const config = createConfig({ chains: [base, mainnet, optimism, zora], transports: { [base.id]: http(), [mainnet.id]: http(), [optimism.id]: http(), [zora.id]: http(), }, }) const account = privateKeyToAccount('0x...') // [!code hl] const hash = await sendTransaction({ account, // [!code hl] to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', value: parseEther('0.001') }) ``` ::: info Wagmi currently does not support hoisting Private Key & Mnemonic Accounts to the top-level Wagmi Config – meaning you have to explicitly pass through the account to every Action. If you feel like this is a feature that should be added, please [open a discussion](https://github.com/wevm/wagmi/discussions/new?category=ideas). ::: ================================================ FILE: site/core/installation.md ================================================ # Installation Install Wagmi Core via your package manager, a ` ``` ================================================ FILE: site/core/typescript.md ================================================ # TypeScript ## Requirements Wagmi Core is designed to be as type-safe as possible! Things to keep in mind: - Types currently require using TypeScript {{typescriptVersion}}. - [TypeScript doesn't follow semver](https://www.learningtypescript.com/articles/why-typescript-doesnt-follow-strict-semantic-versioning) and often introduces breaking changes in minor releases. - Changes to types in this repository are considered non-breaking and are usually released as patch changes (otherwise every type enhancement would be a major version!). - It is highly recommended that you lock your `@wagmi/core` and `typescript` versions to specific patch releases and upgrade with the expectation that types may be fixed or upgraded between any release. - The non-type-related public API of Wagmi Core still follows semver very strictly. To ensure everything works correctly, make sure your `tsconfig.json` has [`strict`](https://www.typescriptlang.org/tsconfig#strict) mode set to `true`. ::: code-group ```json [tsconfig.json] { "compilerOptions": { "strict": true } } ``` ::: ## Const-Assert ABIs & Typed Data Wagmi Core can infer types based on [ABIs](https://docs.soliditylang.org/en/latest/abi-spec.html#json) and [EIP-712](https://eips.ethereum.org/EIPS/eip-712) Typed Data definitions, powered by [Viem](https://viem.sh) and [ABIType](https://github.com/wevm/abitype). This achieves full end-to-end type-safety from your contracts to your frontend and enlightened developer experience by autocompleting ABI item names, catching misspellings, inferring argument and return types (including overloads), and more. For this to work, you must either [const-assert](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions) ABIs and Typed Data (more info below) or define them inline. For example, `useReadContract`'s `abi` configuration parameter: ```ts const result = await readContract({ abi: […], // <--- defined inline // [!code focus] }) ``` ```ts const abi = […] as const // <--- const assertion // [!code focus] const result = readContract({ abi }) ``` If type inference isn't working, it's likely you forgot to add a `const` assertion or define the configuration parameter inline. Also, make sure your ABIs, Typed Data definitions, and [TypeScript configuration](#requirements) are valid and set up correctly. ::: tip Unfortunately [TypeScript doesn't support importing JSON `as const` yet](https://github.com/microsoft/TypeScript/issues/32063). Check out the [Wagmi CLI](/cli/getting-started) to help with this! It can automatically fetch ABIs from Etherscan and other block explorers, resolve ABIs from your Foundry/Hardhat projects, and more. ::: Anywhere you see the `abi` or `types` configuration property, you can likely use const-asserted or inline ABIs and Typed Data to get type-safety and inference. These properties are also called out in the docs. Here's what [`readContract`](/core/api/actions/readContract) looks like with and without a const-asserted `abi` property. ::: code-group ```ts twoslash [Const-Asserted] // @twoslash-cache: {"v":1,"hash":"ce7669bfd8403077642e11ee62585359f9005b3491bb5cb9aa7196e861042c9f","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJ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QTHyu8+2AzIXmGeZS9m6uTXIqVuq+i+bJmbMjeK5p/7K3hIwHYB4F9iyewwAA7J14FGAQ7teAAHIAAC4c0TRxkAf+k9IO71+zLwImDhJSEa38XMQFw4Tpu3DG64B/7JFAAEKeAbSOjyDMABjuRQCuSli+TeTnTLRHhHgFSmjTT8DyDgH8CxQeSmh+QH4UA3g1DXATaQarA3gS7CoH6oroqay4FX6QR0Ff4B51q/60CeABjyD8BYHzR2h1gAAirkjgpoAhC0dYjg5iYUAYCBzArkdYq03kYU3kDo/AGqdoMAB+CQAs3AtBt+aA9I3IzwzASAoA4wtg5QeAikIAUYUYQAA="} import { createConfig, http } from '@wagmi/core' import { mainnet, sepolia } from '@wagmi/core/chains' const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) const erc721Abi = [ { name: 'balanceOf', type: 'function', stateMutability: 'view', inputs: [{ type: 'address', name: 'owner' }], outputs: [{ type: 'uint256' }], }, { name: 'isApprovedForAll', type: 'function', stateMutability: 'view', inputs: [ { type: 'address', name: 'owner' }, { type: 'address', name: 'operator' }, ], outputs: [{ type: 'bool' }], }, { name: 'getApproved', type: 'function', stateMutability: 'view', inputs: [{ type: 'uint256', name: 'tokenId' }], outputs: [{ type: 'address' }], }, { name: 'ownerOf', type: 'function', stateMutability: 'view', inputs: [{ type: 'uint256', name: 'tokenId' }], outputs: [{ type: 'address' }], }, { name: 'tokenURI', type: 'function', stateMutability: 'pure', inputs: [{ type: 'uint256', name: 'tokenId' }], outputs: [{ type: 'string' }], }, ] as const // ---cut--- import { readContract } from '@wagmi/core' const result = await readContract(config, { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: erc721Abi, functionName: 'balanceOf', // ^? args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'], // ^? }) result // ^? ``` ```ts twoslash [Not Const-Asserted] // @twoslash-cache: {"v":1,"hash":"32e9700c30963257f6c79b087bc2f37aa4f1bb4bb135b24ec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XJNK5dy7S7kTIeb0kANRXlDJcp8sZnZfmzP+UmQFHduxansGQEQ7l67eHYNC2FNLBXItJJaulMFMUwBxXi9gBKMC2pZSpMluKeWmT5TagVdrfVbgtQGj1N42VxA5Vy71lK/U4HdUK8NIqwARvFfaEsXZbmdPNNQRseBDXGrtKapV/oVXdlGTMWu7kNX+i1W3IF7pQUQHWRCikmpjhAOJWmxAdpazZwrLnGsjo5XuiSO2iEJbSyqsreMn5sYm6aoAI6CDIBgHVwKm0ts2W2o4EIE3dt7f2rNQ6C55oFGO3dJxJ2IH7dXGd6r50opHNq8cjbVnNvBdu6EcAPG7zAJECAMR4gMyMBk5mUAD1DWlZ0sthd5XfuvTmu94ZZ01rwMu1d6631go2VspYv6MF5kA9LEDTMsmQalQOjpNZYNnoVUsRD06UMPqHLW1uCyG1pn1QEFsC8wj/vzN2h0hVoM1nrLmnpTZMzZmvcO8tXzxkBjQwKDDpA12vq47YDMvHoZEZiEJkTVGZXibg1JnTsmq4VuY4GQpwZoC1v9iyewwAg5p14FGAQnteAAHIAACUc0RxxkN5+k9Iu7NlbLwQmDhJTsAzHOeSRse6WDQc8yR1xvN2SKAAIU8OtR08hmABjclAFyJYfJeTOktQ8h58qmimvweQxX+AxXcqaXy3mKDXhqNcAtJrVjXgveCRl3mVasDVprfgnXQsQVm1ub91xkCZdoJ4AM8h+Btbmr2gAIi5Rwpp9vzVrI4Es0UAw1eYC5WsK0vKhS8g6fgwm7QwG8wkAW3AZsRezPSbkzxmBIFAOMWw5Q8AKRAFGKMQA=="} import { createConfig, http } from '@wagmi/core' import { mainnet, sepolia } from '@wagmi/core/chains' const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) declare const erc721Abi: { name: string; type: string; stateMutability: string; inputs: { type: string; name: string; }[]; outputs: { type: string; }[]; }[] // ---cut--- import { readContract } from '@wagmi/core' const result = await readContract(config, { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: erc721Abi, functionName: 'balanceOf', // ^? args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'], // ^? }) result // ^? ``` ::: You can prevent runtime errors and be more productive by making sure your ABIs and Typed Data definitions are set up appropriately. 🎉 ```ts twoslash // @twoslash-cache: {"v":1,"hash":"1302572cb196fc0dde6d7e01c4f069233f8e54486c2e57cde92bd7a1bf18508b","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvUjGZQAwpLSlmYgDwjJ/dgHNedGmChxeisNp0VemsHDS9mAI3b76MIyYCCz3gB9pslCSrBi8wgDWkADuYMgAulZCouKSAHLMALYwrobGpkoqYgBiwmISYOlZak7sVgA6IFiCMg1+vA1E7DBRDQB8VjZ2DqQ6JgbueWbKqmglyeWeI3DVzvWNzTCt/h1dPZQCpSkVmTC9vYw2FojWWrpWWMwqWTSkcNcASoFThWgACo8nF7LGqJQ7lSowKyPUYDW46Xrca6/UgQDLsOAwNSfOTfGafNDNMAAFWwmJBB3maROUKWZzqYHYGSwEFI9hkOIKM0oICCIgQiAIaDQWDeAHpRVFmDo0QA6OD4UWaGSi5hYdgqsqSOCi9kKTlibl2R4MRAATiorHcOjQ+CQAEYAExUNDQmAmkC63EGi3sMC4RAABioInwALEZCQpoAvhR0KS8IQSORnQYmGxODwAhywNN1GYLGpdcFQqh6bxy7xHKwICJwgBRWhYasyV7XYBliudotgEK8WD8ZiCVhoNsdzvjrNBHuhMAna4NOs2shwETMMANADcY4nFe7vearHnguFYtFbvwy9XYBlEk3253k+LDjVAFVSIf2seRYhxar2DLz0vNcbwgFU1TvKQdyjLdIPLaDtyrGtwiJRkYGuR0A0wmDOxsXM0DeXh21g8c91Cdw4BfBkkzgNhPjgCBWCTUdiIfUiHCgKAZDgAiGgDWgYAEwSBLtAAWKAAHY7QADhEB1HBE8SoFNU0HQAZlgJw7VU1SAFYYFEkShIgh8u0CJ9ENreR2RoKBrjUgMpJ0pyp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LynSe03Yx5/HhP2aczANzPmIBgcyl4AAEUe7wDAMrxr/RB2DvH6LgerVKTAEgrBnukE23NpAOl3kJy+at/0/6kx/eAx0rpZAIUUnxRCI8uOIfooG/aXbt7Ll5IO4++5Ao9PHCyIrjJKuv2x3V+nLXWd3S65LT0vpSxrjIF4rQTwAZ5D8D2QVO06VuciUcKaJPhV0qOB0tpAMKzmAiXSmVKSqkpIOn4Jqu0mwQD9aoNt+0FU9t5PfWkp9Dyliu5vYt8M37vkJBA7AK7TIWT2GACbD2MmBDaxBwAARtmiB2MhQfrjABHPCFw4QZdjdcYHfERljNNBMqZMy5kLKWQ6FZayNlbJEjszJ+yHTA4oB2Go1wptQZg/fyCTvjcg9N/E6md+H/B4bU33D0j2j1NFj3j0T2TzAPSjTwz1UizzrBzzz2kkL2L1LxgGBwSCRm4G5GeGYCQFAHGFsHKDwHuyjCjCAA"} // @errors: 2820 import { createConfig, http } from '@wagmi/core' import { mainnet, sepolia } from '@wagmi/core/chains' const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) const erc721Abi = [ { name: 'balanceOf', type: 'function', stateMutability: 'view', inputs: [{ type: 'address', name: 'owner' }], outputs: [{ type: 'uint256' }], }, { name: 'isApprovedForAll', type: 'function', stateMutability: 'view', inputs: [ { type: 'address', name: 'owner' }, { type: 'address', name: 'operator' }, ], outputs: [{ type: 'bool' }], }, { name: 'getApproved', type: 'function', stateMutability: 'view', inputs: [{ type: 'uint256', name: 'tokenId' }], outputs: [{ type: 'address' }], }, { name: 'ownerOf', type: 'function', stateMutability: 'view', inputs: [{ type: 'uint256', name: 'tokenId' }], outputs: [{ type: 'address' }], }, { name: 'tokenURI', type: 'function', stateMutability: 'pure', inputs: [{ type: 'uint256', name: 'tokenId' }], outputs: [{ type: 'string' }], }, ] as const // ---cut--- import { readContract } from '@wagmi/core' readContract(config, { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: erc721Abi, functionName: 'balanecOf', args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'], }) ``` ## Configure Internal Types For advanced use-cases, you may want to configure wagmi's internal types. Most of wagmi's types relating to ABIs and EIP-712 Typed Data are powered by [ABIType](https://github.com/wevm/abitype). See the [ABIType docs](https://abitype.dev) for more info on how to configure types. ================================================ FILE: site/core/why.md ================================================ # Why Wagmi Core ## The Problems Building Ethereum applications is hard. Apps need to support connecting wallets, multiple chains, signing messages and data, sending transactions, listening for events and state changes, refreshing stale blockchain data, and much more. This is all on top of solving for app-specific use-cases and providing polished user experiences. The ecosystem is also continuously evolving, meaning you need to adapt to new improvements or get left behind. App developers should not need to worry about connecting tens of different wallets, the intricacies of multi-chain support, typos accidentally sending an order of magnitude more ETH or calling a misspelled contract function, or accidentally spamming their RPC provider, costing thousands in compute units. Wagmi Core solves all these problems and more — allowing app developers to focus on building high-quality and performant experiences for Ethereum — by focusing on **developer experience**, **performance**, **feature coverage**, and **stability.** ## Developer Experience Wagmi Core delivers a great developer experience through modular and composable APIs, automatic type safety and inference, and comprehensive documentation. It provides developers with intuitive building blocks to build their Ethereum apps. While Wagmi Core's APIs might seem more verbose at first, it makes Wagmi Core's modular building blocks extremely flexible. Easy to move around, change, and remove. It also allows developers to better understand Ethereum concepts as well as understand _what_ and _why_ certain properties are being passed through. Learning how to use Wagmi Core is a great way to learn how to interact with Ethereum in general. Wagmi Core also provides [strongly typed APIs](/core/typescript), allowing consumers to get the best possible experience through [autocomplete](https://twitter.com/awkweb/status/1555678944770367493), [type inference](https://twitter.com/jakemoxey/status/1570244174502588417?s=20), as well as static validation. You often just need to provide an ABI and Wagmi Core can help you autocomplete your way to success, identify type errors before your users do, drill into blockchain errors [at compile and runtimes](/core/guides/error-handling) with surgical precision, and much more. The API documentation is comprehensive and contains usage info for _every_ module in Wagmi Core. The core team uses a [documentation](https://gist.github.com/zsup/9434452) and [test driven](https://en.wikipedia.org/wiki/Test-driven_development#:~:text=Test%2Ddriven%20development%20(TDD),software%20against%20all%20test%20cases.) development approach to building modules, which leads to predictable and stable APIs. ## Performance Performance is critical for applications on all sizes. Slow page load and interactions can cause users to stop using applications. Wagmi Core uses and is built by the same team behind [Viem](https://viem.sh), the most performant production-ready Ethereum library. End users should not be required to download a module of over 100kB in order to interact with Ethereum. Wagmi Core is optimized for tree-shaking and dead-code elimination, allowing apps to minimize bundle size for fast page load times. Data layer performance is also critical. Slow, unnecessary, and manual data fetching can make apps unusable and cost thousands in RPC compute units. Wagmi Core supports caching, deduplication, persistence, and much more through [TanStack Query](/react/guides/tanstack-query) via the `'@wagmi/core/query'` entrypoint so you can [plug it into your framework](/core/guides/framework-adapters) of choice, like Vue, Svelte, and more. ## Feature Coverage Wagmi Core supports the most popular and commonly-used Ethereum features out of the box with 40+ VanillaJS Actions for accounts, wallets, contracts, transactions, signing, ENS, and more. Wagmi Core also supports just about any wallet out there through its official [connectors](/core/api/connectors), [EIP-6963 support](/core/api/createConfig#multiinjectedproviderdiscovery), and [extensible API](/dev/creating-connectors). If you need lower-level control, you can always drop down to [Viem](https://viem.sh), which Wagmi Core uses internally to perform blockchain operations. Wagmi Core also manages multi-chain support automatically so developers can focus on their applications instead of adding custom code. Finally, Wagmi Core has a [CLI](/cli/getting-started) to manage ABIs as well as a robust ecosystem of third-party libraries, like [ConnectKit](https://docs.family.co/connectkit), [Dynamic](https://www.dynamic.xyz), [Privy](https://privy.io), and many more, so you can get started quickly without needing to build everything from scratch. ## Stability Stability is a fundamental principle for Wagmi Core. Many organizations, large and small, rely heavily on Wagmi Core and expect it to be entirely stable for their users and applications. Wagmi Core's test suite runs against forked Ethereum nodes to make sure functions work across chains. The test suite also runs type tests against many different versions of peer dependencies, like TypeScript, to ensure compatibility with the latest releases of other popular software. Wagmi Core follows semver so developers can upgrade between versions with confidence. Starting with Wagmi Core v2, new functionality will be opt-in with old functionality being deprecated alongside the new features. This means upgrading to the latest major versions will not require immediate changes. Lastly, the core team works full-time on Wagmi Core and [related projects](https://github.com/wevm), and is constantly improving Wagmi Core and keeping it up-to-date with industry trends and changes. ================================================ FILE: site/dev/contributing.md ================================================ # Contributing Thanks for your interest in contributing to Wagmi! Please take a moment to review this document **before submitting a pull request.** ## Overview This guide is intended to help you get started with contributing. By following these steps, you will understand the development process and workflow. If you want to contribute, but aren't sure where to start, you can create a [new discussion](https://github.com/wevm/wagmi/discussions/new/choose). :::warning **Please ask first before starting work on any significant new features. This includes things like adding new hooks, actions, connectors, etc.** It's never a fun experience to have your pull request declined after investing time and effort into a new feature. To avoid this from happening, we request that contributors first create a [feature request](https://github.com/wevm/wagmi/discussions/new?category=ideas) to discuss any API changes or significant new ideas. ::: ## 1. Cloning the repository To start contributing to the project, clone it to your local machine using git: ```bash git clone https://github.com/wevm/wagmi.git ``` Or the [GitHub CLI](https://cli.github.com): ```bash gh repo clone wevm/wagmi ``` ## 2. Installing Node.js and pnpm Wagmi uses Node.js with [pnpm workspaces](https://pnpm.io/workspaces) to manage multiple projects. You can run the following command in your terminal to check your local Node.js version. ```bash node -v ``` If **`node@{{nodeVersion}}`** is not installed, you can install via [fnm](https://github.com/Schniz/fnm) or from the [official website](https://nodejs.org). Once Node.js is installed, run the following to install [Corepack](https://nodejs.org/api/corepack.html). Corepack automatically installs and manages **`{{packageManager}}`**. ```bash corepack enable ``` ## 3. Installing dependencies Once in the project's root directory, run the following command to install pnpm (via Corepack) and the project's dependencies: ```bash pnpm install ``` After the install completes, pnpm links packages across the project for development and [git hooks](https://github.com/toplenboren/simple-git-hooks) are set up. ## 4. Adding the env variables The [dev playgrounds](#_5-running-the-dev-playgrounds) and [test suite](#_6-running-the-test-suite) require environment variables to be set. Copy over the following environment variables to `.env`, and fill them out. ```bash VITE_MAINNET_FORK_URL=https://eth.merkle.io VITE_OPTIMISM_FORK_URL=https://mainnet.optimism.io NEXT_PUBLIC_WC_PROJECT_ID=3fbb6bba6f1de962d911bb5b5c9dba88 NUXT_PUBLIC_WC_PROJECT_ID=3fbb6bba6f1de962d911bb5b5c9dba88 VITE_WC_PROJECT_ID=3fbb6bba6f1de962d911bb5b5c9dba88 NEXT_TELEMETRY_DISABLED=1 NUXT_TELEMETRY_DISABLED=1 ``` You might want to change `*_FORK_URL` to a paid RPC provider for better performance. ## 5. Running the dev playgrounds To start the local development playgrounds, run one of the following commands. These commands run playground apps, located at `./playgrounds`, that are set up for trying out code while making changes. ```bash pnpm dev # `wagmi` playground pnpm dev:core # `@wagmi/core` playground pnpm dev:create-wagmi # `create-wagmi` cli tool pnpm dev:cli # `@wagmi/cli` tool pnpm dev:next # `wagmi` playground with Next.js pnpm dev:nuxt # `@wagmi/vue` playground with Nuxt.js pnpm dev:react # `wagmi` playground (same as `pnpm dev`) pnpm dev:vue # `@wagmi/vue` playground ``` Once a playground dev server is running, you can make changes to any of the package source files (e.g. `packages/react`) and it will automatically update the playground. ## 6. Running the test suite Wagmi uses [Vitest](https://vitest.dev) to run tests and [Prool](https://github.com/wevm/prool) to execute tests against locally running chain forks. First, make sure you have Docker ([OrbStack](https://orbstack.dev) works great!) and install [Anvil](https://github.com/foundry-rs/foundry/tree/master/crates/anvil) via [Foundryup](https://book.getfoundry.sh/getting-started/installation). ```bash curl -L https://foundry.paradigm.xyz | bash foundryup ``` You'll also need to install [Playwright](https://playwright.dev/) browser binaries: ```bash pnpm exec playwright install ``` Next, make sure you have set up your [env variables](#_4-adding-the-env-variables). Now you are ready to run the tests! You have the following options for running tests: - `pnpm test [package?]` — runs tests in watch mode - `pnpm test:cov` — runs tests and reports coverage When adding new features or fixing bugs, it's important to add test cases to cover the new or updated behavior. If snapshot tests fail, you can run the `test:update` command to update the snapshots. ## 7. Writing documentation Documentation is crucial to helping developers of all experience levels use Wagmi. Wagmi uses [VitePress](https://vitepress.dev) for the documentation site (located at `./site`). To start the site in dev mode, run: ```bash pnpm docs:dev ``` Try to keep documentation brief and use plain language so folks of all experience levels can understand. If you think something is unclear or could be explained better, you are welcome to open a pull request. ## 8. Submitting a pull request When you're ready to submit a pull request, you can follow these naming conventions: - Pull request titles use the [Imperative Mood](https://en.wikipedia.org/wiki/Imperative_mood) (e.g., `Add something`, `Fix something`). - [Changesets](#versioning) use past tense verbs (e.g., `Added something`, `Fixed something`). When you submit a pull request, GitHub will automatically lint, build, and test your changes. If you see an ❌, it's most likely a bug in your code. Please, inspect the logs through the GitHub UI to find the cause. **Please make sure that "Allow edits from maintainers" is enabled so the core team can make updates to your pull request if necessary.** ## 9. Versioning When adding new features or fixing bugs, we'll need to bump the package versions. We use [Changesets](https://github.com/changesets/changesets) to do this. ::: tip Only changes to the codebase that affect the public API or existing behavior (e.g. bugs) need changesets. ::: Each changeset defines which packages should be published and whether the change should be a major/minor/patch release, as well as providing release notes that will be added to the changelog upon release. To create a new changeset, run `pnpm changeset`. This will run the Changesets CLI, prompting you for details about the change. You’ll be able to edit the file after it’s created — don’t worry about getting everything perfect up front. Even though you can technically use any markdown formatting you like, headings should be avoided since each changeset will ultimately be nested within a bullet list. Instead, bold text should be used as section headings. If your PR is making changes to an area that already has a changeset (e.g. there’s an existing changeset covering theme API changes but you’re making further changes to the same API), you should update the existing changeset in your PR rather than creating a new one. ### Releasing to npm The first time a PR with a changeset is merged after a release, a new PR will automatically be created called `chore: version packages`. Any subsequent PRs with changesets will automatically update this existing version packages PR. Merging this PR triggers the release process by publishing to npm and cleaning up the changeset files. ### Creating a snapshot release If a PR has changesets, you can create a [snapshot release](https://github.com/changesets/changesets/blob/main/docs/snapshot-releases.md) by [manually dispatching](https://github.com/wevm/wagmi/actions/workflows/canary.yml) the Canary workflow. This publishes a tagged version to npm with the PR branch name and timestamp. ## 10. Updating dependencies Use [Taze](https://github.com/antfu/taze) by running: ```bash pnpm deps # prints outdated deps pnpm deps patch # print outdated deps with new patch versions pnpm deps -w # updates deps (best done with clean working tree) ``` Update GitHub Actions via [Actions Up!](https://github.com/azat-io/actions-up) by running: ```bash pnpm deps:ci ``` [Socket](https://socket.dev) checks pull requests for vulnerabilities when new dependencies and versions are added, but you should also be vigilant! When updating dependencies, you should check release notes and source code as well as lock versions when possible. ================================================ FILE: site/dev/creating-connectors.md ================================================ # Creating Connectors Thanks for your interest in adding a new connector to Wagmi! Please take a moment to review this document **before starting work on a new connector.** ## Overview This guide details how to create new connectors and upstream them back into Wagmi. By following these steps, you will understand the development process, workflow, and requirements for new connectors. **Not all connectors will be accepted into Wagmi** for a variety of reasons outlined in this document. In addition, for connector requests to be accepted, the team creating the connector must [sponsor Wagmi](https://github.com/sponsors/wevm). It takes time and effort to maintain third-party connectors. Wagmi is an OSS project that depends on sponsors and grants to continue our work. Please get in touch via [dev@wevm.dev](mailto:dev@wevm.dev) if you have questions about sponsoring. ::: warning **Please ask first before starting work on a new connector.** To avoid having your pull request declined after investing time and effort into a new connector, we ask that contributors create a [Connector Request](https://github.com/wevm/wagmi/discussions/new?category=connector-request) before starting work. This ensures the connector solves for an important or general use-case of interest to Wagmi users and is well supported by the Wagmi and connector teams. ::: ## 1. Follow the contributing guide Check out the [Contributing Guide](/dev/contributing) to get your local development environment set up and learn more about the contributing workflow. ## 2. Create a new file for the connector Create a new file in `packages/connectors/src` named after the connector you want to add. For example, if you want to add Foo, you would create a file named `foo.ts`. File names should be camel-cased and as short as possible. ## 3. Create the connector object. Import `createConnector` from `@wagmi/core` and export a new function that accepts a parameters object and returns the `createConnector` result. This is the base of all connectors. The name of the connector name should be the same as the file name. ```ts import { createConnector } from '@wagmi/core' export type FooBarBazParameters = {} export function fooBarBaz(parameters: FooBarBazParameters = {}) { return createConnector((config) => ({})) } ``` ## 4. Add the missing properties to the object Now that the base of the connector is set up, you should see a type error that looks something like this: ```ts twoslash // @twoslash-cache: {"v":1,"hash":"51529c3efa008aca29b1a99d6189d29f0675b46bfd307c0fa712fc44cfd1d5b5","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIBjUjGY0AwhDBgY/NBFIAeAK5gA1pADuYCrwBK0uVHlw0pdmADm25WoiaAfNr38DRk2cu9rGsA96ihIjDiktKypABiYEqq3o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JMs5gOAMwGDogooWDbowjD6dJpnyYZIwC7FQuoyxvDfF1b1yBmLGoxI5rwHARby4wFJwBbwI1NJRASWQZu20W+nmQBM6a8LvBPTUEnaHTMDaOLIcCFMMjaK5kk9QbQiiqVMAkKw21taVsIVWCVUohqSC9RizZgmNhUXIajQK0VDL6Ywj3cNwNwUoCSCgFmH0SHg60gBiGJAA=="} // @errors: 2740 import { createConnector } from '@wagmi/core' // ---cut--- createConnector((config) => ({})) ``` The type error tells you what properties are missing from `createConnector`'s return type. Add them all in! #### Properties - `icon`: Optional icon URL for the connector. - `id`: The ID for the connector. This should be camel-cased and as short as possible. Example: `fooBarBaz`. - `name`: Human-readable name for the connector. Example: `'Foo Bar Baz'`. - `rdns`: Optional reverse DNS for the connector. This is used to filter out duplicate [EIP-6963](https://eips.ethereum.org/EIPS/eip-6963) injected providers when `createConfig#multiInjectedProviderDiscovery` is enabled. #### Methods - `connect`: Function for connecting the connector. - `disconnect`: Function for disconnecting the connector. - `getAccounts`: Function that returns the connected accounts for the connector. - `getChainId`: Function that returns the connected chain ID for the connector. - `getProvider`: Function that returns the underlying provider interface for internal use throughout the connector. - `isAuthorized`: Function that returns whether the connector has connected previously and is still authorized. - `setup`: Optional function for running when the connector is first created. - `switchChain`: Optional function for switching the connector's active chain. #### Events - `onAccountsChanged`: Function for subscribing to account changes internally in the connector. - `onChainChanged`: Function for subscribing to chain changes internally in the connector. - `onConnect`: Function for subscribing to connection events internally in the connector. - `onDisconnect`: Function for subscribing to disconnection events internally in the connector. - `onMessage`: Optional function for subscribing to messages internally in the connector. #### Parameters `createConnector` also has the following config properties you can use within the connector: - `chains`: List of chains configured by the user. - `emitter`: Emitter for emitting events. Used to sync connector state with Wagmi `Config`. The following events are available: - `change`: Emitted when the connected accounts or chain changes. - `connect`: Emitted when the connector connects. - `disconnect`: Emitted when the connector disconnects. - `error`: Emitted when the connector receives an error. - `message`: Emitted when the connector receives a message. - `storage`: Optional storage configured by the user. Defaults to wrapper around localStorage. ::: tip If you plan to use a third-party SDK, it should have minimal dependencies (limit bundle size, supply chain attacks, etc.) and use the most permissive license possible (ideally MIT). Any third-party packages, should also have [`"sideEffects": false`](https://webpack.js.org/guides/tree-shaking/#mark-the-file-as-side-effect-free) in their `package.json` file for maximum tree-shakability support. ::: ::: tip All address values returned and emitted by the connector should be checksummed using Viem's [`getAddress`](https://viem.sh/docs/utilities/getAddress). ::: ## 5. Export the connector Export the connector from `packages/connectors/src/exports/index.ts` in alphabetic order. ```ts export { fooBarBaz } from './fooBarBaz.js' ``` ## 6. Try out the connector and add tests While building a connector, it can be useful to try it out with Wagmi. You can use the [development playgrounds](/dev/contributing#_5-running-the-dev-playgrounds) for testing your changes. Ideally, you should also be able to add tests for the connector in a `connectorName.test.ts` file. This isn't always easy so at a minimum please create a test file with instructions for how to test the connector manually. The test file should include actual tests or "instruction tests" for the following: - How to connect the connector. - How to disconnect the connector. - How to switch the connector's active chain (if applicable). Remember to include all info required to test the connector, like software to install (browser extension, mobile app, etc.), smart contracts to interact with/deploy, etc. Finally, you should also update the test file in `packages/connectors/src/exports/index.test.ts` to include the new connector. You can do this manually or by running: ```bash pnpm test:update packages/connectors/src/exports/index.test.ts ``` ## 7. Add your team to CODEOWNERS It is critical that connectors are updated in a timely manner and actively maintained so that users of Wagmi can rely on them in production settings. The Wagmi core team will provide as much assistance as possible to keep connectors up-to-date with breaking changes from Wagmi, but it is your responsibility to ensure that any dependencies and issues/discussions related to the connector are handled in a timely manner. If issues are not resolved in a timely manner, the connector may be removed from Wagmi. In support of this goal, add at least one member of your team to the [CODEOWNERS](https://github.com/wevm/wagmi/blob/main/.github/CODEOWNERS) file so that you get notified of pull requests, issues, etc. related to the connector. You can add your team like this: ``` /packages/connectors/src/fooBarBaz @tmm @jxom ``` For more info about GitHub code owners, check out the [GitHub Documentation](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners). ## 8. Document the connector The connector should be documented. Follow the step on [writing documentation](/dev/contributing#_7-writing-documentation) to get set up with running the docs site locally and add the required pages. ## 9. Create a changeset Now that the connector works and has tests, it's time to create a changeset to prepare for release. Run the following to create a changeset: ```bash pnpm changeset ``` The changeset should be a `patch` applied to the `@wagmi/connectors` repository with the description `Added [ConnectorName]`, For example, `Added Foo Bar Baz`. ## 10. Create a pull request The connector is ready to go! Create a [pull request](/dev/contributing#_8-submitting-a-pull-request) and the connector should make it into a future release of Wagmi after some review. ================================================ FILE: site/index.md ================================================ --- # https://vitepress.dev/reference/default-theme-home-page layout: home description: Type Safe, Extensible, and Modular by design. Build high-performance blockchain frontends. title: 'Wagmi | Reactivity for Ethereum apps' titleTemplate: false hero: name: Wagmi text: Reactivity for Ethereum apps tagline: Type Safe, Extensible, and Modular by design. Build high-performance blockchain frontends. actions: - theme: brand text: Get Started link: /react/getting-started - theme: alt text: Why Wagmi link: /react/why - theme: alt text: View on GitHub link: https://github.com/wevm/wagmi image: src: /logo-dark.svg alt: Wagmi Logo features: - icon: 🚀 title: 20+ React Hooks details: React Hooks for accounts, wallets, contracts, transactions, signing, ENS, and more. link: /react/api/hooks linkText: See all hooks - icon: 🦄 title: TypeScript Ready details: Infer types from ABIs and EIP-712 Typed Data and autocomplete your way to productivity. link: /react/typescript linkText: Learn about TypeScript support - icon: 💼 title: Connect Wallet details: Official connectors for MetaMask, EIP-6963, WalletConnect, Coinbase Wallet, and more. link: /react/api/connectors linkText: See all connectors - icon: 👟 title: Caching. Deduplication. Persistence. details: Built-in caching, deduplication, persistence powered by TanStack Query. link: /react/guides/tanstack-query linkText: How to use TanStack Query - icon: 🌳 title: Modular By Design details: Don't use React, Vue, Solid? Use VanillaJS or build an adapter for your favorite framework. link: /core/getting-started linkText: Learn about Wagmi Core - icon: ✌️ title: Built on Viem details: The modern, low-level TypeScript interface for Ethereum that performs blockchain operations. link: https://viem.sh linkText: Check out Viem --- ================================================ FILE: site/package.json ================================================ { "name": "site", "private": true, "type": "module", "scripts": { "dev": "vitepress dev", "build": "NODE_OPTIONS=\"--max-old-space-size=16384\" vitepress build", "preview": "vitepress preview" }, "devDependencies": { "@shikijs/vitepress-twoslash": "3.20.0", "@tanstack/query-core": "catalog:", "@tanstack/react-query": "catalog:", "@tanstack/vue-query": "catalog:", "@types/react": "catalog:", "@wagmi/connectors": "workspace:*", "@wagmi/core": "workspace:*", "@wagmi/solid": "workspace:*", "@wagmi/vue": "workspace:*", "abitype": "*", "nuxt": "^3.19.2", "react": "catalog:", "solid-js": "catalog:", "unocss": "^66.5.6", "viem": "~2.46.0", "vitepress": "1.6.3", "vitepress-plugin-group-icons": "^1.6.5", "vitepress-plugin-llms": "1.11.1", "vue": "catalog:", "wagmi": "workspace:*" } } ================================================ FILE: site/react/api/WagmiProvider.md ================================================ # WagmiProvider React Context Provider for Wagmi. ## Import ```ts import { WagmiProvider } from 'wagmi' ``` ## Usage ::: code-group ```tsx [app.tsx] import { WagmiProvider } from 'wagmi' import { config } from './config' function App() { return ( {/** ... */} ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type WagmiProviderProps } from 'wagmi' ``` ### config [`Config`](/react/api/createConfig#config) object to inject with context. ::: code-group ```tsx [app.tsx] import { WagmiProvider } from 'wagmi' import { config } from './config' function App() { return ( {/** ... */} ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### initialState `State | undefined` - Initial state to hydrate into the [Wagmi Config](/react/api/createConfig). Useful for SSR. ::: code-group ```tsx [app.tsx] import { WagmiProvider } from 'wagmi' import { config } from './config' function App() { return ( {/** ... */} ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### reconnectOnMount `boolean | undefined` - Whether or not to reconnect previously connected [connectors](/react/api/createConfig#connectors) on mount. - Defaults to `true`. ::: code-group ```tsx [app.tsx] import { WagmiProvider } from 'wagmi' import { config } from './config' function App() { return ( {/** ... */} ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Context ```ts import { type WagmiContext } from 'wagmi' ``` ================================================ FILE: site/react/api/actions.md ================================================ # Actions Sometimes the declarative nature of React Hooks doesn't work for parts of your app. For those cases, you can use Wagmi Core Actions directly! All the Wagmi Core Actions are importable using the `wagmi/actions` entrypoint. For example, you can use the `watchBlockNumber` action to watch for block number changes. ::: code-group ```ts [index.tsx] import { useConfig } from 'wagmi' import { watchBlockNumber } from 'wagmi/actions' import { useEffect } from 'react' function App() { const config = useConfig() useEffect(() => { return watchBlockNumber(config, { onBlockNumber(blockNumber) { console.log('Block number changed!', blockNumber) }, }) }, []) } ``` <<< @/snippets/react/config.ts[config.ts] ::: See the [Wagmi Core docs](/core/api/actions) for more info on what actions are available. ================================================ FILE: site/react/api/chains.md ================================================ # Chains Viem `Chain` objects. More info at the [Viem docs](https://viem.sh/docs/chains/introduction). ## Import Import via the `'wagmi/chains'` entrypoint (proxies all chains from `'viem/chains'`). ```ts import { mainnet } from 'wagmi/chains' ``` ## Available Chains Chain definitions as of `viem@{{viemVersion}}`. For `viem@latest`, visit the [Viem repo](https://github.com/wevm/viem/blob/main/src/chains/index.ts). ================================================ FILE: site/react/api/connectors/baseAccount.md ================================================ --- title: baseAccount --- ================================================ FILE: site/react/api/connectors/coinbaseWallet.md ================================================ ================================================ FILE: site/react/api/connectors/injected.md ================================================ --- title: injected --- ================================================ FILE: site/react/api/connectors/metaMask.md ================================================ --- title: metaMask --- ================================================ FILE: site/react/api/connectors/mock.md ================================================ --- title: mock --- ================================================ FILE: site/react/api/connectors/porto.md ================================================ --- title: porto --- ================================================ FILE: site/react/api/connectors/safe.md ================================================ --- title: safe --- ================================================ FILE: site/react/api/connectors/walletConnect.md ================================================ --- title: walletConnect --- ================================================ FILE: site/react/api/connectors.md ================================================ # Connectors Connectors for popular wallet providers and protocols. ## Import Import via the `'wagmi/connectors'` entrypoint. ```ts import { injected } from 'wagmi/connectors' ``` ## Available Connectors ::: tip Some connectors require third-party packages. See the "Install" section on each connector's page for more info on license, version, and more. ::: ================================================ FILE: site/react/api/createConfig.md ================================================ --- title: createConfig --- ================================================ FILE: site/react/api/createStorage.md ================================================ --- title: createStorage --- ================================================ FILE: site/react/api/errors.md ================================================ # Errors Error classes used by Wagmi. ## React ### WagmiProviderNotFoundError When a Wagmi hook is used outside of a [`WagmiProvider`](/react/api/WagmiProvider). ```ts import { WagmiProviderNotFoundError } from 'wagmi' ``` ================================================ FILE: site/react/api/hooks/useBalance.md ================================================ --- title: useBalance description: Hook for fetching native currency balance. --- # useBalance Hook for fetching native currency balance. ## Import ```ts import { useBalance } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useBalance } from 'wagmi' function App() { const result = useBalance({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseBalanceParameters } from 'wagmi' ``` ### address `Address | undefined` Address to get balance for. [`enabled`](#enabled) set to `false` if `address` is `undefined`. ::: code-group ```tsx [index.tsx] import { useBalance } from 'wagmi' import { mainnet } from 'wagmi/chains' function App() { const result = useBalance({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: --- ### blockNumber `bigint | undefined` Block number to get balance at. ::: code-group ```ts [index.ts] import { useBalance } from 'wagmi' function App() { const result = useBalance({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', blockNumber: 17829139n, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get balance at. ::: code-group ```ts [index.ts] import { useBalance } from 'wagmi' function App() { const result = useBalance({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', blockTag: 'latest', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useBalance } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] function App() { const result = useBalance({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', chainId: mainnet.id, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useBalance } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useBalance({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useBalance } from 'wagmi' function App() { const result = useBalance({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', scopeKey: 'foo', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseBalanceReturnType } from 'wagmi' ``` ## Action - [`getBalance`](/core/api/actions/getBalance) ================================================ FILE: site/react/api/hooks/useBlobBaseFee.md ================================================ --- title: useBlobBaseFee description: Hook for fetching the current blob base fee (in wei). --- # useBlobBaseFee Hook for fetching the current blob base fee (in wei). ## Import ```ts import { useBlobBaseFee } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useBlobBaseFee } from 'wagmi' function App() { const result = useBlobBaseFee() } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseBlobBaseFeeParameters } from 'wagmi' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useBlobBaseFee } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] function App() { const result = useBlobBaseFee({ chainId: mainnet.id, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useBlobBaseFee } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useBlobBaseFee({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useBlobBaseFee } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useBlobBaseFee({ scopeKey: 'foo', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseBlobBaseFeeReturnType } from 'wagmi' ``` ## Action - [`getBlobBaseFee`](/core/api/actions/getBlobBaseFee) ================================================ FILE: site/react/api/hooks/useBlock.md ================================================ --- title: useBlock description: Hook for fetching information about a block at a block number, hash or tag. --- # useBlock Hook for fetching information about a block at a block number, hash or tag. ## Import ```ts import { useBlock } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useBlock } from 'wagmi' function App() { const result = useBlock() } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseBlockParameters } from 'wagmi' ``` ### blockHash `` `0x${string}` `` Information at a given block hash. ::: code-group ```tsx [index.tsx] import { useBlock } from 'wagmi' function App() { const result = useBlock({ blockHash: '0x89644bbd5c8d682a2e9611170e6c1f02573d866d286f006cbf517eec7254ec2d' // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockNumber `` bigint `` Information at a given block number. ::: code-group ```tsx [index.tsx] import { useBlock } from 'wagmi' function App() { const result = useBlock({ blockNumber: 42069n // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `` 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' `` Information at a given block tag. Defaults to `'latest'`. ::: code-group ```tsx [index.tsx] import { useBlock } from 'wagmi' function App() { const result = useBlock({ blockTag: 'pending' // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useBlock } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] function App() { const result = useBlock({ chainId: mainnet.id, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useBlock } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useBlock({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### includeTransactions `boolean` Whether or not to include transactions as objects. ::: code-group ```tsx [index.tsx] import { useBlock } from 'wagmi' import { config } from './config' function App() { const result = useBlock({ includeTransactions: true // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useBlock } from 'wagmi' import { config } from './config' function App() { const result = useBlock({ scopeKey: 'foo' // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### watch `boolean | UseWatchBlockParameters | undefined` - Enables/disables listening for block changes. - Can pass a subset of [`UseWatchBlocksParameters`](/react/api/hooks/useWatchBlocks#parameters) directly to [`useWatchBlocks`](/react/api/hooks/useWatchBlocks). ::: code-group ```tsx [index.tsx] import { useBlock } from 'wagmi' function App() { const result = useBlock({ watch: true, // [!code focus] }) } ``` ```tsx [index-2.tsx] import { useBlock } from 'wagmi' function App() { const result = useBlock({ watch: { // [!code focus] pollingInterval: 4_000, // [!code focus] }, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseBlockReturnType } from 'wagmi' ``` ## Action - [`getBlock`](/core/api/actions/getBlock) - [`watchBlockNumber`](/core/api/actions/watchBlockNumber) ================================================ FILE: site/react/api/hooks/useBlockNumber.md ================================================ --- title: useBlockNumber description: Hook for fetching the number of the most recent block seen. --- # useBlockNumber Hook for fetching the number of the most recent block seen. ## Import ```ts import { useBlockNumber } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useBlockNumber } from 'wagmi' function App() { const result = useBlockNumber() } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseBlockNumberParameters } from 'wagmi' ``` ### cacheTime `number | undefined` Time in milliseconds that cached block number will remain in memory. ::: code-group ```tsx [index.tsx] import { useBlockNumber } from 'wagmi' function App() { const result = useBlockNumber({ cacheTime: 4_000, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useBlockNumber } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] function App() { const result = useBlockNumber({ chainId: mainnet.id, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useBlockNumber } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useBlockNumber({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useBlockNumber } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useBlockNumber({ scopeKey: 'foo', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### watch `boolean | UseWatchBlockNumberParameters | undefined` - Enables/disables listening for block number changes. - Can pass a subset of [`UseWatchBlockNumberParameters`](/react/api/hooks/useWatchBlockNumber#parameters)directly to [`useWatchBlockNumber`](/react/api/hooks/useWatchBlockNumber). ::: code-group ```tsx [index.tsx] import { useBlockNumber } from 'wagmi' function App() { const result = useBlockNumber({ watch: true, // [!code focus] }) } ``` ```tsx [index-2.tsx] import { useBlockNumber } from 'wagmi' function App() { const result = useBlockNumber({ watch: { // [!code focus] pollingInterval: 4_000, // [!code focus] }, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseBlockNumberReturnType } from 'wagmi' ``` ## Action - [`getBlockNumber`](/core/api/actions/getBlockNumber) - [`watchBlockNumber`](/core/api/actions/watchBlockNumber) ================================================ FILE: site/react/api/hooks/useBlockTransactionCount.md ================================================ --- title: useBlockTransactionCount description: Hook for fetching the number of Transactions at a block number, hash or tag. --- # useBlockTransactionCount Hook for fetching the number of Transactions at a block number, hash or tag. ## Import ```ts import { useBlockTransactionCount } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useBlockTransactionCount } from 'wagmi' function App() { const result = useBlockTransactionCount() } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseBlockTransactionCountParameters } from 'wagmi' ``` ### blockHash `` `0x${string}` `` Transaction count at a given block hash. ::: code-group ```tsx [index.tsx] import { useBlock } from 'wagmi' function App() { const result = useBlock({ blockHash: '0x89644bbd5c8d682a2e9611170e6c1f02573d866d286f006cbf517eec7254ec2d' // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockNumber `` bigint `` Transaction count at a given block number. ::: code-group ```tsx [index.tsx] import { useBlock } from 'wagmi' function App() { const result = useBlock({ blockNumber: 42069n // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `` 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' `` Transaction count at a given block tag. Defaults to `'latest'`. ::: code-group ```tsx [index.tsx] import { useBlock } from 'wagmi' function App() { const result = useBlock({ blockTag: 'pending' // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useBlock } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] function App() { const result = useBlock({ chainId: mainnet.id, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useBlockTransactionCount } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useBlockTransactionCount({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useBlockTransactionCount } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useBlockTransactionCount({ scopeKey: 'foo', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseBlockTransactionCountReturnType } from 'wagmi' ``` ## Action - [`getBlockTransactionCount`](/core/api/actions/getBlockTransactionCount) ================================================ FILE: site/react/api/hooks/useBytecode.md ================================================ --- title: useBytecode description: Hook for retrieving the bytecode at an address. --- # useBytecode Hook for retrieving the bytecode at an address. ## Import ```ts import { useBytecode } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useBytecode } from 'wagmi' function App() { const result = useBytecode({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseBytecodeParameters } from 'wagmi' ``` ### address `Address | undefined` The contract address. ::: code-group ```tsx [index.tsx] import { useBytecode } from 'wagmi' function App() { const result = useBytecode({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockNumber `bigint | undefined` The block number to check the bytecode at. ::: code-group ```tsx [index.tsx] import { useBytecode } from 'wagmi' function App() { const result = useBytecode({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', blockNumber: 16280770n, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` The block tag to check the bytecode at. ::: code-group ```tsx [index.tsx] import { useBytecode } from 'wagmi' function App() { const result = useBytecode({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', blockTag: 'safe', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` The chain ID to check the bytecode at. ::: code-group ```tsx [index.tsx] import { useBytecode } from 'wagmi' import { mainnet } from 'wagmi/chains' function App() { const result = useBytecode({ chainId: mainnet.id, // [!code focus] address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useBytecode } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useBytecode({ config, // [!code focus] address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useBytecode } from 'wagmi' import { config } from './config' function App() { const result = useBytecode({ scopeKey: 'foo' // [!code focus] address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseBytecodeReturnType } from 'wagmi' ``` ## Action - [`getBytecode`](/core/api/actions/getBytecode) ================================================ FILE: site/react/api/hooks/useCall.md ================================================ --- title: useCall description: Hook for executing a new message call immediately without submitting a transaction to the network. --- # useCall Hook for executing a new message call immediately without submitting a transaction to the network. ## Import ```ts import { useCall } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useCall } from 'wagmi' function App() { const result = useCall({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseCallParameters } from 'wagmi' ``` ### account `Account | Address | undefined` The Account to call from. ::: code-group ```tsx [index.tsx] import { useCall } from 'wagmi' function App() { const result = useCall({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus] data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### data `0x${string} | undefined` A contract hashed method call with encoded args. ::: code-group ```tsx [index.tsx] import { useCall } from 'wagmi' function App() { const result = useCall({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### to `Address | undefined` The contract address or recipient. ::: code-group ```tsx [index.tsx] import { useCall } from 'wagmi' function App() { const result = useCall({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### accessList `AccessList | undefined` The access list. ::: code-group ```tsx [index.tsx] import { useCall } from 'wagmi' function App() { const result = useCall({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', accessList: [ // [!code focus:6] { address: '0x1', storageKeys: ['0x1'], }, ], data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### gas `bigint | undefined` The gas provided for transaction execution. ::: code-group ```tsx [index.tsx] import { useCall } from 'wagmi' function App() { const result = useCall({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', gas: 1_000_000n, // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### gasPrice `bigint | undefined` The price (in wei) to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction). ::: code-group ```tsx [index.tsx] import { useCall } from 'wagmi' function App() { const result = useCall({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', gasPrice: parseGwei('20'), // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### maxFeePerGas `bigint | undefined` Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```tsx [index.tsx] import { useCall } from 'wagmi' function App() { const result = useCall({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', maxFeePerGas: parseGwei('20'), // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### maxPriorityFeePerGas `bigint | undefined` Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```tsx [index.tsx] import { useCall } from 'wagmi' function App() { const result = useCall({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### nonce `number | undefined` Unique number identifying this transaction. ::: code-group ```tsx [index.tsx] import { useCall } from 'wagmi' function App() { const result = useCall({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', nonce: 420, // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### value `bigint | undefined` Value (in wei) sent with this transaction. ::: code-group ```tsx [index.tsx] import { useCall } from 'wagmi' function App() { const result = useCall({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockNumber `number | undefined` The block number to perform the call against. ::: code-group ```tsx [index.tsx] import { useCall } from 'wagmi' function App() { const result = useCall({ blockNumber: 15121123n, // [!code focus] account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` The block tag to perform the call against. ::: code-group ```tsx [index.tsx] import { useCall } from 'wagmi' function App() { const result = useCall({ blockTag: 'safe', // [!code focus] account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` The block tag to perform the call against. ::: code-group ```tsx [index.tsx] import { useCall } from 'wagmi' import { mainnet } from '@wagmi/core/chains' function App() { const result = useCall({ chainId: mainnet.id, // [!code focus] account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useCall } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useCall({ config, // [!code focus] account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useCall } from 'wagmi' import { config } from './config' function App() { const result = useCall({ scopeKey: 'foo' // [!code focus] account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseCallReturnType } from 'wagmi' ``` ## Action - [`call`](/core/api/actions/call) ================================================ FILE: site/react/api/hooks/useCallsStatus.md ================================================ --- title: useCallsStatus description: Hook for fetching the number of the most recent block seen. --- # useCallsStatus Hook to fetch the status and receipts of a call batch that was sent via [`useSendCalls`](/react/api/hooks/useSendCalls). ## Import ```ts import { useCallsStatus } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useCallsStatus } from 'wagmi' function App() { const result = useCallsStatus({ id: '0x...', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseCallsStatusParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useCallsStatus } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useCallsStatus({ config, // [!code focus] id: '0x...', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### connector `Connector | undefined` Connector to get call statuses with. ::: code-group ```tsx [index.tsx] import { useCallsStatus, useConnections } from 'wagmi' import { config } from './config' // [!code focus] function App() { const connections = useConnections() const result = useCallsStatus({ connector: connections[0]?.connector, // [!code focus] id: '0x...', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### id `string` Identifier of the call batch. ::: code-group ```ts [index.ts] import { useCallsStatus } from '@wagmi/core' import { config } from './config' const status = await useCallsStatus({ id: '0x1234567890abcdef', // [!code focus] }) ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useCallsStatus } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useCallsStatus({ id: '0x...', scopeKey: 'foo', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseCallsStatusReturnType } from 'wagmi' ``` ## Action - [`getCallsStatus`](https://viem.sh/docs/actions/wallet/getCallsStatus) ================================================ FILE: site/react/api/hooks/useCapabilities.md ================================================ --- title: useCapabilities description: Hook for fetching the number of the most recent block seen. --- # useCapabilities Hook to extract capabilities (grouped by chain ID) that a connected wallet supports (e.g. paymasters, session keys, etc). [Read more.](https://github.com/ethereum/EIPs/blob/815028dc634463e1716fc5ce44c019a6040f0bef/EIPS/eip-5792.md#wallet_getcapabilities) ## Import ```ts import { useCapabilities } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useCapabilities } from 'wagmi' function App() { const result = useCapabilities() } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseCapabilitiesParameters } from 'wagmi' ``` ### account `Account | Address | undefined` Fetch capabilities for the provided account. ::: code-group ```ts [index.ts] import { useCapabilities } from '@wagmi/core' import { config } from './config' const status = await useCapabilities({ account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', // [!code focus] }) ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useCapabilities } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useCapabilities({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### connector `Connector | undefined` Connector to get call statuses with. ::: code-group ```tsx [index.tsx] import { useCapabilities, useConnections } from 'wagmi' import { config } from './config' // [!code focus] function App() { const connections = useConnections() const result = useCapabilities({ connector: connections[0]?.connector, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useCapabilities } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useCapabilities({ scopeKey: 'foo', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseCapabilitiesReturnType } from 'wagmi' ``` ## Action - [`getCapabilities`](https://viem.sh/docs/actions/wallet/getCapabilities) ================================================ FILE: site/react/api/hooks/useChainId.md ================================================ --- title: useChainId description: Hook for getting current chain ID. --- # useChainId Hook for getting current chain ID. ## Import ```ts import { useChainId } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useChainId } from 'wagmi' function App() { const chainId = useChainId() } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseChainIdParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useChainId } from 'wagmi' import { config } from './config' // [!code focus] function App() { const chainId = useChainId({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseChainIdReturnType } from 'wagmi' ``` `number` Current chain ID from [`config.state.chainId`](/react/api/createConfig#chainid). ::: info Only returns chain IDs for chains configured via `createConfig`'s [`chains`](/react/api/createConfig#chains) parameter. If the active [connection](/react/api/createConfig#connection) [`chainId`](/react/api/createConfig#chainid-1) is not from a chain included in your Wagmi `Config`, `useChainId` will return the last configured chain ID. ::: ## Action - [`getChainId`](/core/api/actions/getChainId) - [`watchChainId`](/core/api/actions/watchChainId) ================================================ FILE: site/react/api/hooks/useChains.md ================================================ --- title: useChains description: Hook for getting configured chains --- # useChains Hook for getting configured chains ## Import ```ts import { useChains } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useChains } from 'wagmi' function App() { const chains = useChains() } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseChainsParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useChains } from 'wagmi' import { config } from './config' // [!code focus] function App() { const chains = useChains({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseChainsReturnType } from 'wagmi' ``` `readonly [Chain, ...Chain[]]` Chains from [`config.chains`](/react/api/createConfig#chains). ## Action - [`getChains`](/core/api/actions/getChains) ================================================ FILE: site/react/api/hooks/useClient.md ================================================ --- title: useClient description: Hook for getting Viem `Client` instance. --- # useClient Hook for getting Viem [`Client`](https://viem.sh/docs/clients/custom) instance. ## Import ```ts import { useClient } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useClient } from 'wagmi' function App() { const client = useClient() } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseClientParameters } from 'wagmi' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when getting Viem Client. ::: code-group ```ts [index.ts] import { useClient } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] import { config } from './config' function App() { const client = useClient({ chainId: mainnet.id, // [!code focus] }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useClient } from 'wagmi' import { config } from './config' // [!code focus] function App() { const client = useClient({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseClientReturnType } from 'wagmi' ``` `Client | undefined` Viem [`Client`](https://viem.sh/docs/clients/custom) instance. ## Action - [`getClient`](/core/api/actions/getClient) - [`watchClient`](/core/api/actions/watchClient) ================================================ FILE: site/react/api/hooks/useConfig.md ================================================ --- title: useConfig description: Hook for getting `Config` from nearest `WagmiProvider`. --- # useConfig Hook for getting [`Config`](/react/api/createConfig#config) from nearest [`WagmiProvider`](/react/api/WagmiProvider). ## Import ```ts import { useConfig } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useConfig } from 'wagmi' function App() { const config = useConfig() } ``` ::: ## Return Type ```ts import { type UseConfigReturnType } from 'wagmi' ``` If you use TypeScript and [register your `Config`](/react/typescript#register-config), the return type will be inferred. ::: code-group ```ts twoslash [index.tsx] // @twoslash-cache: {"v":1,"hash":"914af31f2d67af9b6a0eb3594b780105455023fedc851e1b259e6312534bc63b","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgBhSf3YBzADwjFK3nRpgocXgrBLlvALyHNa0jGZRJrDL1QAdKbw8AjVhBEBrAFFaLB8bUjhEXmA3D1jYmzsHJ1h+ZkFWNEjo9zjc3gT7MEdeMGYAWxhIlxAAtHwyOBFmMGqAbhi83IKk6VJWKoI0NCwIgHpRmDqGprAAOgk2js7420Li5ix2AFU+gfwhkcRxjfZZyfrwmfmIUZPFnNyAX3aH56Xeb18/ABV2CsiAIwAJgADGCXnENGA0KR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=="} import { type Config } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' declare module 'wagmi' { interface Register { config: Config } } // ---cut--- import { useConfig } from 'wagmi' function App() { const config = useConfig() // ^? } ``` ```ts [config.ts] import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' declare module 'wagmi' { interface Register { config: typeof config } } export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` ::: ================================================ FILE: site/react/api/hooks/useConnect.md ================================================ --- title: useConnect description: Hook for connecting accounts with connectors. --- # useConnect Hook for connecting accounts with [connectors](/react/api/connectors). ## Import ```ts import { useConnect } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useConnect } from 'wagmi' import { injected } from 'wagmi/connectors' function App() { const connect = useConnect() return ( ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseConnectParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useConnect } from 'wagmi' import { config } from './config' // [!code focus] function App() { const connect = useConnect({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseConnectReturnType } from 'wagmi' ``` ### connectors [deprecated](/react/guides/migrate-from-v2-to-v3#removed-useconnect-connectors-usereconnect-connectors) `readonly Connector[]` Globally configured connectors via [`createConfig`](/react/api/createConfig#connectors). Useful for rendering a list of available connectors. ::: code-group ```tsx [index.tsx] import { useConnect } from 'wagmi' function App() { const connect = useConnect() return (
{connect.connectors.map((connector) => ( ))}
) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ::: tip Not all connectors support connecting directly to a `chainId` (e.g. they don't support programmatic chain switching). In those cases, the connector will connect to whatever chain the connector's provider (e.g. wallet) is connected to. ::: ## Action - [`connect`](/core/api/actions/connect) ================================================ FILE: site/react/api/hooks/useConnection.md ================================================ --- title: useConnection description: Hook for getting current connection. --- # useConnection Hook for getting current connection. ## Import ```ts import { useConnection } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useConnection } from 'wagmi' function App() { const connection = useConnection() } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseConnectionParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useConnection } from 'wagmi' import { config } from './config' // [!code focus] function App() { const connection = useConnection({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseConnectionReturnType } from 'wagmi' ``` ## Action - [`getConnection`](/core/api/actions/getConnection) ================================================ FILE: site/react/api/hooks/useConnectionEffect.md ================================================ --- title: useConnectionEffect description: Hook for listening to connection lifecycle events. --- # useConnectionEffect Hook for listening to connection lifecycle events. ## Import ```ts import { useConnectionEffect } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useConnectionEffect } from 'wagmi' function App() { useConnectionEffect({ onConnect(data) { console.log('Connected!', data) }, onDisconnect() { console.log('Disconnected!') }, }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseConnectionEffectParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useConnectionEffect } from 'wagmi' import { config } from './config' // [!code focus] function App() { useConnectionEffect({ config, // [!code focus] onConnect(data) { console.log('Connected!', data) }, onDisconnect() { console.log('Disconnected!') }, }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### onConnect `` ((data: { address: `0x${string}`; addresses: readonly [`0x${string}`, ...`0x${string}`[]]; chain: Chain | undefined chainId: number; connector: Connector; isReconnected: boolean }) => void) | undefined `` Callback that is called when connection is made. ::: code-group ```tsx [index.tsx] import { useConnectionEffect } from 'wagmi' function App() { useConnectionEffect({ onConnect(data) { // [!code focus] console.log('Connected!', data) // [!code focus] }, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### onDisconnect `(() => void) | undefined` Callback that is called when there no more connections. ::: code-group ```tsx [index.tsx] import { useConnectionEffect } from 'wagmi' function App() { useConnectionEffect({ onDisconnect() { // [!code focus] console.log('Disconnected!') // [!code focus] }, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Action - [`getConnection`](/core/api/actions/getConnection) - [`watchConnection`](/core/api/actions/watchConnection) ================================================ FILE: site/react/api/hooks/useConnections.md ================================================ --- title: useConnections description: Hook for getting active connections. --- # useConnections Hook for getting active connections. ## Import ```ts import { useConnections } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useConnections } from 'wagmi' function App() { const connections = useConnections() } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseConnectionsParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useConnections } from 'wagmi' import { config } from './config' // [!code focus] function App() { const connections = useConnections({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseConnectionsReturnType } from 'wagmi' ``` ## Action - [`getConnections`](/core/api/actions/getConnections) - [`watchConnections`](/core/api/actions/watchConnections) ================================================ FILE: site/react/api/hooks/useConnectorClient.md ================================================ --- title: useConnectorClient description: Hook for getting a Viem `Client` object for the current or provided connector. --- # useConnectorClient Hook for getting a Viem [`Client`](https://viem.sh/docs/clients/custom) object for the current or provided connector. ## Import ```ts import { useConnectorClient } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useConnectorClient } from 'wagmi' function App() { const result = useConnectorClient() } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseConnectorClientParameters } from 'wagmi' ``` ### account `Address | Account | undefined` Account to use with client. Throws if account is not found on [`connector`](#connector). ```ts import { useConnectorClient } from 'wagmi' function App() { const result = useConnectorClient({ account: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] }) } ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use with client. ```ts import { useConnectorClient } from 'wagmi' function App() { const result = useConnectorClient({ chainId: mainnet.id, // [!code focus] }) } ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useConnectorClient } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useConnectorClient({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### connector `Connector | undefined` - Connector to get client for. - Defaults to current connector. ```ts import { useConnections, useConnectorClient } from 'wagmi' function App() { const connections = useConnections(config) const result = useConnectorClient({ connector: connections[0]?.connector, // [!code focus] }) } ``` ## Return Type ```ts import { type UseConnectorClientReturnType } from 'wagmi' ``` ## Action - [`getConnectorClient`](/core/api/actions/getConnectorClient) ================================================ FILE: site/react/api/hooks/useConnectors.md ================================================ --- title: useConnectors description: Hook for getting configured connectors. --- # useConnectors Hook for getting configured connectors. ## Import ```ts import { useConnectors } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useConnectors } from 'wagmi' function App() { const connectors = useConnectors() } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseConnectorsReturnType } from 'wagmi' ``` `readonly Connector[]` Connectors from [`config.connectors`](/react/api/createConfig#connectors-1). ## Action - [`getConnectors`](/core/api/actions/getConnectors) ================================================ FILE: site/react/api/hooks/useContractEvents.md ================================================ --- title: useContractEvents description: Hook that fetches a list of contract event logs matching the provided parameters. --- # useContractEvents Hook that fetches a list of contract event logs matching the provided parameters. ## Import ```ts import { useContractEvents } from 'wagmi' ``` ## Usage By default, `useContractEvents` returns all matched events on the ABI. In practice, you must use scoping to filter for specific events. ::: code-group ```tsx [index.tsx] import { useContractEvents } from 'wagmi' import { abi } from './abi' function App() { // Fetch event logs for every event on every ERC-20 contract. const result = useContractEvents({ abi }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseContractEventsParameters } from 'wagmi' ``` ### abi `Abi` The contract's ABI. Check out the [TypeScript docs](/react/typescript#const-assert-abis-typed-data) for how to set up ABIs for maximum type inference and safety. ::: code-group ```tsx [index.tsx] import { useContractEvents } from 'wagmi' import { abi } from './abi' function App() { const result = useContractEvents({ abi, // [!code focus] }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### address `Address | undefined` The contract's address. ::: code-group ```tsx [index.tsx] import { useContractEvents } from 'wagmi' import { abi } from './abi' function App() { const result = useContractEvents({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', // [!code focus] abi, }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### args `object | readonly unknown[] | undefined` - Logs can be scoped to given indexed arguments. - Inferred from [`abi`](#abi) and [`eventName`](#eventname). ::: code-group ```tsx [index.tsx] import { useContractEvents } from 'wagmi' import { abi } from './abi' function App() { const result = useContractEvents({ abi, eventName: 'Transfer', args: { // [!code focus] from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B' // [!code focus] } // [!code focus] }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: Only indexed arguments in `event` are candidates for `args`. An argument can also be an array to indicate that other values can exist in the position: ::: code-group ```tsx [index.tsx] import { useContractEvents } from 'wagmi' import { abi } from './abi' function App() { const result = useContractEvents({ abi, eventName: 'Transfer', args: { from: '0xd8da6bf26964af9d7eed9e03e53415d37aa96045', to: [ // [!code focus] '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] '0xa5cc3c03994db5b0d9a5eedd10cabab0813678ac', // [!code focus] '0xa152f8bb749c55e9943a3a0a3111d18ee2b3f94e', // [!code focus] ], // [!code focus] } }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### blockHash `` `0x${string}` | undefined `` - Block hash to include logs from. Mutually exclusive with `fromBlock`/`toBlock`. ::: code-group ```tsx [index.tsx] import { useContractEvents } from 'wagmi' import { abi } from './abi' function App() { const result = useContractEvents({ abi, blockHash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', // [!code focus] }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useContractEvents } from 'wagmi' import { mainnet } from '@wagmi/core/chains' import { abi } from './abi' function App() { const result = useContractEvents({ abi, chainId: mainnet.id, // [!code focus] }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useContractEvents } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { const result = useContractEvents({ abi, config, // [!code focus] }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### eventName `string | undefined` - Event to filter for the contract. - Inferred from [`abi`](#abi). ::: code-group ```tsx [index.tsx] import { useContractEvents } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { const result = useContractEvents({ abi, eventName: 'Transfer', // [!code focus] }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### fromBlock `bigint | 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` - Block to start including logs from. Mutually exclusive with `blockHash`. ::: code-group ```tsx [index.tsx] import { useContractEvents } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { const result = useContractEvents({ abi, fromBlock: 69420n, // [!code focus] }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### strict `boolean | undefined` - Flag to only return logs that conform to the indexed & non-indexed arguments on the `event`, meaning that `args` will always be defined. Defaults to `false`. ::: code-group ```tsx [index.tsx] import { useContractEvents } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { const result = useContractEvents({ abi, strict: true, // [!code focus] }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### toBlock `bigint | 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` - Block to stop including logs from. Mutually exclusive with `blockHash`. ::: code-group ```tsx [index.tsx] import { useContractEvents } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { const result = useContractEvents({ abi, toBlock: 70120n, // [!code focus] }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseContractEventsReturnType } from 'wagmi' ``` A list of event logs. ## Action - [`getContractEvents`](/core/api/actions/getContractEvents) ================================================ FILE: site/react/api/hooks/useDeployContract.md ================================================ --- title: useDeployContract description: Hook for deploying a contract to the network, given bytecode & constructor arguments. --- # useDeployContract Hook for deploying a contract to the network, given bytecode, and constructor arguments. ## Import ```ts import { useDeployContract } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useDeployContract } from 'wagmi' import { parseEther } from 'viem' import { wagmiAbi } from './abi' function App() { const deployContract = useDeployContract() return ( ) } ``` ```ts [abi.ts] export const wagmiAbi = [ ... { inputs: [], stateMutability: "nonpayable", type: "constructor", }, ... ] as const ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Deploying with Constructor Args ::: code-group ```tsx [index.tsx] import { useDeployContract } from 'wagmi' import { parseEther } from 'viem' import { wagmiAbi } from './abi' function App() { const deployContract = useDeployContract() return ( ) } ``` ```ts [abi.ts] export const wagmiAbi = [ ... { inputs: [{ name: "x", type: "uint32" }], stateMutability: "nonpayable", type: "constructor", }, ... ] as const; ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type useDeployContractParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useDeployContract } from 'wagmi' import { config } from './config' // [!code focus] function App() { const deployContract = useDeployContract({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type useDeployContractReturnType } from 'wagmi' ``` ## Action - [`deployContract`](/core/api/actions/deployContract) ================================================ FILE: site/react/api/hooks/useDisconnect.md ================================================ --- title: useDisconnect description: Hook for disconnecting connections. --- # useDisconnect Hook for disconnecting connections. ## Import ```ts import { useDisconnect } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useDisconnect } from 'wagmi' function App() { const disconnect = useDisconnect() return ( ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseDisconnectParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useDisconnect } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useDisconnect({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseDisconnectReturnType } from 'wagmi' ``` ### connectors [deprecated](/react/guides/migrate-from-v2-to-v3#removed-usedisconnect-connectors-useswitchconnection-connectors) `readonly Connector[]` Connectors that are currently connected. Useful for rendering a list of connectors to disconnect. ::: code-group ```tsx [index.tsx] import { useConnectors, useDisconnect } from 'wagmi' import { mainnet } from 'wagmi/chains' function App() { const disconnect = useDisconnect() const connectors = useConnectors() return (
{connectors.map((connector) => ( ))}
) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Action - [`disconnect`](/core/api/actions/disconnect) ================================================ FILE: site/react/api/hooks/useEnsAddress.md ================================================ --- title: useEnsAddress description: Hook for fetching ENS address for name. --- # useEnsAddress Hook for fetching ENS address for name. ## Import ```ts import { useEnsAddress } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useEnsAddress } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsAddress({ name: normalize('wevm.eth'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ::: warning Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `useEnsAddress`. You can use Viem's built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this. ::: ## Parameters ```ts import { type UseEnsAddressParameters } from 'wagmi' ``` --- ### blockNumber `bigint | undefined` Block number to get ENS address at. ::: code-group ```ts [index.ts] import { useEnsAddress } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsAddress({ blockNumber: 17829139n, // [!code focus] name: normalize('wevm.eth'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get ENS address at. ::: code-group ```ts [index.ts] import { useEnsAddress } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsAddress({ name: normalize('wevm.eth'), blockTag: 'latest', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useEnsAddress } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] import { normalize } from 'viem/ens' function App() { const result = useEnsAddress({ chainId: mainnet.id, // [!code focus] name: normalize('wevm.eth'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### coinType `number | undefined` The [ENSIP-9](https://docs.ens.domains/ens-improvement-proposals/ensip-9-multichain-address-resolution) coin type to fetch the address for. ::: code-group ```ts [index.ts] import { useEnsAddress } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsAddress({ coinType: 60, // [!code focus] name: normalize('wevm.eth'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useEnsAddress } from 'wagmi' import { normalize } from 'viem/ens' import { config } from './config' // [!code focus] function App() { const result = useEnsAddress({ config, // [!code focus] name: normalize('wevm.eth'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### name `string | undefined` Name to get the address for. [`enabled`](#enabled) set to `false` if `name` is `undefined`. ::: code-group ```ts [index.ts] import { useEnsAddress } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsAddress({ name: normalize('wevm.eth'), // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```ts [index.ts] import { useEnsAddress } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsAddress({ name: normalize('wevm.eth'), scopeKey: 'foo', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### universalResolverAddress `Address | undefined` - Address of ENS Universal Resolver Contract. - Defaults to current chain's Universal Resolver Contract address. ::: code-group ```ts [index.ts] import { useEnsAddress } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsAddress({ name: normalize('wevm.eth'), universalResolverAddress: '0x74E20Bd2A1fE0cdbe45b9A1d89cb7e0a45b36376', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseEnsAddressReturnType } from 'wagmi' ``` ## Action - [`getEnsAddress`](/core/api/actions/getEnsAddress) ================================================ FILE: site/react/api/hooks/useEnsAvatar.md ================================================ --- title: useEnsAvatar description: Hook for fetching ENS avatar for name. --- # useEnsAvatar Hook for fetching ENS avatar for name. ## Import ```ts import { useEnsAvatar } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useEnsAvatar } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsAvatar({ name: normalize('wevm.eth'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ::: warning Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `useEnsAvatar`. You can use Viem's built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this. ::: ## Parameters ```ts import { type UseEnsAvatarParameters } from 'wagmi' ``` --- ### assetGatewayUrls `{ ipfs?: string | undefined; arweave?: string | undefined } | undefined` Gateway urls to resolve IPFS and/or Arweave assets. ::: code-group ```ts [index.ts] import { getEnsAvatar } from '@wagmi/core' import { normalize } from 'viem/ens' import { config } from './config' function App() { const result = useEnsAvatar({ assetGatewayUrls: { // [!code focus] ipfs: 'https://cloudflare-ipfs.com', // [!code focus] }, // [!code focus] name: normalize('wevm.eth'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockNumber `bigint | undefined` Block number to get ENS avatar at. ::: code-group ```ts [index.ts] import { useEnsAvatar } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsAvatar({ blockNumber: 17829139n, // [!code focus] name: normalize('wevm.eth'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get ENS avatar at. ::: code-group ```ts [index.ts] import { useEnsAvatar } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsAvatar({ name: normalize('wevm.eth'), blockTag: 'latest', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useEnsAvatar } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] import { normalize } from 'viem/ens' function App() { const result = useEnsAvatar({ chainId: mainnet.id, // [!code focus], name: normalize('wevm.eth'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useEnsAvatar } from 'wagmi' import { normalize } from 'viem/ens' import { config } from './config' // [!code focus] function App() { const result = useEnsAvatar({ config, // [!code focus] name: normalize('wevm.eth'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### gatewayUrls `string[] | undefined` A set of Universal Resolver gateways, used for resolving CCIP-Read requests made through the ENS Universal Resolver Contract. ::: code-group ```ts [index.ts] import { useEnsAvatar } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsAvatar({ gatewayUrls: ['https://cloudflare-ipfs.com'] { // [!code focus] name: normalize('wevm.eth'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### name `string | undefined` Name to get the avatar for. [`enabled`](#enabled) set to `false` if `name` is `undefined`. ::: code-group ```ts [index.ts] import { useEnsAvatar } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsAvatar({ name: normalize('wevm.eth'), // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```ts [index.ts] import { useEnsAvatar } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsAvatar({ name: normalize('wevm.eth'), scopeKey: 'foo', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### universalResolverAddress `Address | undefined` - Address of ENS Universal Resolver Contract. - Defaults to current chain's Universal Resolver Contract address. ::: code-group ```ts [index.ts] import { useEnsAvatar } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsAvatar({ name: normalize('wevm.eth'), universalResolverAddress: '0x74E20Bd2A1fE0cdbe45b9A1d89cb7e0a45b36376', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseEnsAvatarReturnType } from 'wagmi' ``` ## Action - [`getEnsAvatar`](/core/api/actions/getEnsAvatar) ================================================ FILE: site/react/api/hooks/useEnsName.md ================================================ --- title: useEnsName description: Hook for fetching primary ENS name for address. --- # useEnsName Hook for fetching primary ENS name for address. ## Import ```ts import { useEnsName } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useEnsName } from 'wagmi' function App() { const result = useEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseEnsNameParameters } from 'wagmi' ``` ### address `Address | undefined` Name to get the resolver for. [`enabled`](#enabled) set to `false` if `address` is `undefined`. ::: code-group ```ts [index.ts] import { useEnsName } from 'wagmi' function App() { const result = useEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: --- ### blockNumber `bigint | undefined` Block number to get ENS name at. ::: code-group ```ts [index.ts] import { useEnsName } from 'wagmi' function App() { const result = useEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', blockNumber: 17829139n, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get ENS name at. ::: code-group ```ts [index.ts] import { useEnsName } from 'wagmi' function App() { const result = useEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', blockTag: 'latest', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useEnsName } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] function App() { const result = useEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', chainId: mainnet.id, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useEnsName } from 'wagmi' import { normalize } from 'viem/ens' import { config } from './config' // [!code focus] function App() { const result = useEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```ts [index.ts] import { useEnsName } from 'wagmi' function App() { const result = useEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', scopeKey: 'foo', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### universalResolverAddress `Address | undefined` - Address of ENS Universal Resolver Contract. - Defaults to current chain's Universal Resolver Contract address. ::: code-group ```ts [index.ts] import { useEnsName } from 'wagmi' function App() { const result = useEnsName({ address: '0xd2135CfB216b74109775236E36d4b433F1DF507B', universalResolverAddress: '0x74E20Bd2A1fE0cdbe45b9A1d89cb7e0a45b36376', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseEnsNameReturnType } from 'wagmi' ``` ## Action - [`getEnsName`](/core/api/actions/getEnsName) ================================================ FILE: site/react/api/hooks/useEnsResolver.md ================================================ --- title: useEnsResolver description: Hook for fetching ENS resolver for name. --- # useEnsResolver Hook for fetching ENS resolver for name. ## Import ```ts import { useEnsResolver } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useEnsResolver } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsResolver({ name: normalize('wevm.eth'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ::: warning Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `useEnsResolver`. You can use Viem's built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this. ::: ## Parameters ```ts import { type UseEnsResolverParameters } from 'wagmi' ``` --- ### blockNumber `bigint | undefined` Block number to get ENS resolver at. ::: code-group ```ts [index.ts] import { useEnsResolver } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsResolver({ blockNumber: 17829139n, // [!code focus] name: normalize('wevm.eth'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get ENS resolver at. ::: code-group ```ts [index.ts] import { useEnsResolver } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsResolver({ name: normalize('wevm.eth'), blockTag: 'latest', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useEnsResolver } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] import { normalize } from 'viem/ens' function App() { const result = useEnsResolver({ chainId: mainnet.id, // [!code focus] name: normalize('wevm.eth'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useEnsResolver } from 'wagmi' import { normalize } from 'viem/ens' import { config } from './config' // [!code focus] function App() { const result = useEnsResolver({ config, // [!code focus] name: normalize('wevm.eth'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### name `string | undefined` Name to get the resolver for. [`enabled`](#enabled) set to `false` if `name` is `undefined`. ::: code-group ```ts [index.ts] import { useEnsResolver } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsResolver({ name: normalize('wevm.eth'), // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```ts [index.ts] import { useEnsResolver } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsResolver({ name: normalize('wevm.eth'), scopeKey: 'foo', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### universalResolverAddress `Address | undefined` - Resolver of ENS Universal Resolver Contract. - Defaults to current chain's Universal Resolver Contract address. ::: code-group ```ts [index.ts] import { useEnsResolver } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsResolver({ name: normalize('wevm.eth'), universalResolverAddress: '0x74E20Bd2A1fE0cdbe45b9A1d89cb7e0a45b36376', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseEnsResolverReturnType } from 'wagmi' ``` ## Action - [`getEnsResolver`](/core/api/actions/getEnsResolver) ================================================ FILE: site/react/api/hooks/useEnsText.md ================================================ --- title: useEnsText description: Hook for fetching a text record for a specified ENS name and key. --- # useEnsText Hook for fetching a text record for a specified ENS name and key. ## Import ```ts import { useEnsText } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useEnsText } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsText({ name: normalize('wevm.eth'), key: 'com.twitter', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ::: warning Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `useEnsText`. You can use Viem's built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this. ::: ## Parameters ```ts import { type UseEnsTextParameters } from 'wagmi' ``` --- ### blockNumber `bigint | undefined` Block number to get the text at. ::: code-group ```ts [index.ts] import { useEnsText } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsText({ blockNumber: 17829139n, // [!code focus] name: normalize('wevm.eth'), key: 'com.twitter', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get the text at. ::: code-group ```ts [index.ts] import { useEnsText } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsText({ blockTag: 'latest', // [!code focus] name: normalize('wevm.eth'), key: 'com.twitter', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useEnsText } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] import { normalize } from 'viem/ens' function App() { const result = useEnsText({ chainId: mainnet.id, // [!code focus] name: normalize('wevm.eth'), key: 'com.twitter', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### key `string | undefined` ENS key to get Text for. ::: code-group ```ts [index.ts] import { useEnsText } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsText({ name: normalize('wevm.eth'), key: 'com.twitter', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### name `string | undefined` Name to get the text for. [`enabled`](#enabled) set to `false` if `name` is `undefined`. ::: code-group ```ts [index.ts] import { useEnsText } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsText({ name: normalize('wevm.eth'), // [!code focus] key: 'com.twitter', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useEnsText } from 'wagmi' import { normalize } from 'viem/ens' import { config } from './config' // [!code focus] function App() { const result = useEnsText({ config, // [!code focus] name: normalize('wevm.eth'), key: 'com.twitter', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```ts [index.ts] import { useEnsText } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsText({ scopeKey: 'foo', // [!code focus] name: normalize('wevm.eth'), key: 'com.twitter', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### universalResolverAddress `Address | undefined` - Resolver of ENS Universal Resolver Contract. - Defaults to current chain's Universal Resolver Contract address. ::: code-group ```ts [index.ts] import { useEnsText } from 'wagmi' import { normalize } from 'viem/ens' function App() { const result = useEnsText({ name: normalize('wevm.eth'), key: 'com.twitter', universalResolverAddress: '0x74E20Bd2A1fE0cdbe45b9A1d89cb7e0a45b36376', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseEnsTextReturnType } from 'wagmi' ``` ## Action - [`getEnsText`](/core/api/actions/getEnsText) ================================================ FILE: site/react/api/hooks/useEstimateFeesPerGas.md ================================================ --- title: useEstimateFeesPerGas description: Hook for fetching an estimate for the fees per gas (in wei) for a transaction to be likely included in the next block. --- # useEstimateFeesPerGas Hook for fetching an estimate for the fees per gas (in wei) for a transaction to be likely included in the next block. ## Import ```ts import { useEstimateFeesPerGas } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useEstimateFeesPerGas } from 'wagmi' function App() { const result = useEstimateFeesPerGas() } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseEstimateFeesPerGas } from 'wagmi' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useEstimateFeesPerGas } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] function App() { const result = useEstimateFeesPerGas({ chainId: mainnet.id, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useEstimateFeesPerGas } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useEstimateFeesPerGas({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```ts [index.ts] import { useEstimateFeesPerGas } from 'wagmi' function App() { const result = useEstimateFeesPerGas({ scopeKey: 'foo', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### type `'legacy' | 'eip1559'` - Defaults to `'eip1559'` ::: code-group ```ts [index.ts] import { useEstimateFeesPerGas } from 'wagmi' function App() { const result = useEstimateFeesPerGas({ type: 'legacy', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseEstimateFeesPerGasReturnType } from 'wagmi' ``` ## Action - [`estimateFeesPerGas`](/core/api/actions/estimateFeesPerGas) ================================================ FILE: site/react/api/hooks/useEstimateGas.md ================================================ --- title: useEstimateGas description: Hook for estimating the gas necessary to complete a transaction without submitting it to the network. --- # useEstimateGas Hook for estimating the gas necessary to complete a transaction without submitting it to the network. ## Import ```ts import { useEstimateGas } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useEstimateGas } from 'wagmi' function App() { const result = useEstimateGas() } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseEstimateGasParameters } from 'wagmi' ``` ### accessList `AccessList | undefined` The access list. ::: code-group ```ts [index.ts] import { useEstimateGas } from 'wagmi' import { parseEther } from 'viem' import { config } from './config' function App() { const result = useEstimateGas({ accessList: [{ // [!code focus] address: '0x1', // [!code focus] storageKeys: ['0x1'], // [!code focus] }], // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### account `Address | Account | undefined` Account to use when estimating gas. ::: code-group ```ts [index.ts] import { useEstimateGas } from 'wagmi' import { parseEther } from 'viem' import { config } from './config' function App() { const result = useEstimateGas({ account: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` Chain ID to target when estimating gas. ::: code-group ```ts [index.ts] import { useEstimateGas } from 'wagmi' import { mainnet } from '@wagmi/core/chains' import { parseEther } from 'viem' import { config } from './config' function App() { const result = useEstimateGas({ chainId: mainnet.id, // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### connector `Connector | undefined` Connector to estimate with. If no [`account`](#account) is provided, will use default account from connector. ::: code-group ```ts [index.ts] import { getConnections, estimateGas } from '@wagmi/core' import { parseEther } from 'viem' import { config } from './config' function App() { const connections = getConnections(config) const result = useEstimateGas({ connector: connections[0]?.connector, // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### data `` `0x${string}` | undefined `` A contract hashed method call with encoded function data. ::: code-group ```ts [index.ts] import { useEstimateGas } from 'wagmi' import { parseEther } from 'viem' import { config } from './config' function App() { const result = useEstimateGas({ data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### gas `bigint | undefined` Gas provided for transaction execution. ::: code-group ```ts [index.ts] import { useEstimateGas } from 'wagmi' import { parseEther, parseGwei } from 'viem' import { config } from './config' function App() { const result = useEstimateGas({ gas: parseGwei('20'), // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: --- ### gasPrice `bigint | undefined` The price in wei to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction). ::: code-group ```ts [index.ts] import { useEstimateGas } from 'wagmi' import { parseEther, parseGwei } from 'viem' import { config } from './config' function App() { const result = useEstimateGas({ gasPrice: parseGwei('20'), // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### maxFeePerGas `bigint | undefined` Total fee per gas in wei, inclusive of [`maxPriorityFeePerGas`](#maxPriorityFeePerGas). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```ts [index.ts] import { useEstimateGas } from 'wagmi' import { parseEther, parseGwei } from 'viem' import { config } from './config' function App() { const result = useEstimateGas({ maxFeePerGas: parseGwei('20'), // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### maxPriorityFeePerGas `bigint | undefined` Max priority fee per gas in wei. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```ts [index.ts] import { useEstimateGas } from 'wagmi' import { parseEther, parseGwei } from 'viem' import { config } from './config' function App() { const result = useEstimateGas({ maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: --- ### nonce `number` Unique number identifying this transaction. ::: code-group ```ts [index.ts] import { useEstimateGas } from 'wagmi' import { parseEther } from 'viem' import { config } from './config' function App() { const result = useEstimateGas({ nonce: 123, // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```ts [index.ts] import { useEstimateGas } from 'wagmi' import { parseEther } from 'viem' import { config } from './config' function App() { const result = useEstimateGas({ scopeKey: 'foo', // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### to `Address | undefined` The transaction recipient or contract address. ::: code-group ```ts [index.ts] import { useEstimateGas } from 'wagmi' import { parseEther } from 'viem' import { config } from './config' function App() { const result = useEstimateGas({ to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] value: parseEther('0.01'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### type `'legacy' | 'eip1559' | 'eip2930' | undefined` Optional transaction request type to narrow parameters. ::: code-group ```ts [index.ts] import { useEstimateGas } from 'wagmi' import { parseEther } from 'viem' import { config } from './config' function App() { const result = useEstimateGas({ to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', type: 'eip1559', // [!code focus] value: parseEther('0.01'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### value `bigint | undefined` Value in wei sent with this transaction. ::: code-group ```ts [index.ts] import { useEstimateGas } from 'wagmi' import { parseEther } from 'viem' import { config } from './config' function App() { const result = useEstimateGas({ to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseEstimateGasReturnType } from 'wagmi' ``` ## Action - [`estimateGas`](/core/api/actions/estimateGas) ================================================ FILE: site/react/api/hooks/useEstimateMaxPriorityFeePerGas.md ================================================ --- title: useEstimateMaxPriorityFeePerGas description: Hook for fetching an estimate for the max priority fee per gas (in wei) for a transaction to be likely included in the next block. --- # useEstimateMaxPriorityFeePerGas Hook for fetching an estimate for the fees per gas (in wei) for a transaction to be likely included in the next block. ## Import ```ts import { useEstimateMaxPriorityFeePerGas } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useEstimateMaxPriorityFeePerGas } from 'wagmi' function App() { const result = useEstimateMaxPriorityFeePerGas() } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseEstimateMaxPriorityFeePerGas } from 'wagmi' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useEstimateMaxPriorityFeePerGas } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] function App() { const result = useEstimateMaxPriorityFeePerGas({ chainId: mainnet.id, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useEstimateMaxPriorityFeePerGas } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useEstimateMaxPriorityFeePerGas({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```ts [index.ts] import { useEstimateMaxPriorityFeePerGas } from 'wagmi' function App() { const result = useEstimateMaxPriorityFeePerGas({ scopeKey: 'foo', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseEstimateMaxPriorityFeePerGasReturnType } from 'wagmi' ``` ## Action - [`estimateMaxPriorityFeePerGas`](/core/api/actions/estimateMaxPriorityFeePerGas) ================================================ FILE: site/react/api/hooks/useFeeHistory.md ================================================ --- title: useFeeHistory description: Hook for fetching a collection of historical gas information. --- # useFeeHistory Hook for fetching a collection of historical gas information. ## Import ```ts import { useFeeHistory } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useFeeHistory } from 'wagmi' function App() { const result = useFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseFeeHistoryParameters } from 'wagmi' ``` ### blockCount `number | undefined` Number of blocks in the requested range. Between 1 and 1024 blocks can be requested in a single query. Less than requested may be returned if not all blocks are available. ::: code-group ```tsx [index.tsx] import { useFeeHistory } from 'wagmi' function App() { const result = useFeeHistory({ blockCount: 4, // [!code focus] rewardPercentiles: [25, 75] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### rewardPercentiles `number[] | undefined` A monotonically increasing list of percentile values to sample from each block's effective priority fees per gas in ascending order, weighted by gas used. ::: code-group ```tsx [index.tsx] import { useFeeHistory } from 'wagmi' function App() { const result = useFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75] // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockNumber `bigint | undefined` Highest number block of the requested range. ::: code-group ```tsx [index.tsx] import { useFeeHistory } from 'wagmi' function App() { const result = useFeeHistory({ blockCount: 4, blockNumber: 1551231n, // [!code focus] rewardPercentiles: [25, 75] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag of the highest number block of the requested range. ::: code-group ```tsx [index.tsx] import { useFeeHistory } from 'wagmi' function App() { const result = useFeeHistory({ blockCount: 4, blockTag: 'safe', // [!code focus] rewardPercentiles: [25, 75] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useFeeHistory } from 'wagmi' import { mainnet } from '@wagmi/core/chains' function App() { const result = useFeeHistory({ blockCount: 4, chainId: mainnet.id, // [!code focus] rewardPercentiles: [25, 75] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useFeeHistory } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75] config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useFeeHistory } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75] scopeKey: 'foo', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseFeeHistoryReturnType } from 'wagmi' ``` ## Action - [`getFeeHistory`](/core/api/actions/getFeeHistory) ================================================ FILE: site/react/api/hooks/useGasPrice.md ================================================ --- title: useGasPrice description: Hook for fetching the current price of gas (in wei). --- # useGasPrice Hook for fetching the current price of gas (in wei). ## Import ```ts import { useGasPrice } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useGasPrice } from 'wagmi' function App() { const result = useGasPrice() } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseGasPriceParameters } from 'wagmi' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useGasPrice } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] function App() { const result = useGasPrice({ chainId: mainnet.id, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useGasPrice } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useGasPrice({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useGasPrice } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useGasPrice({ scopeKey: 'foo', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseGasPriceReturnType } from 'wagmi' ``` ## Action - [`getGasPrice`](/core/api/actions/getGasPrice) ================================================ FILE: site/react/api/hooks/useInfiniteReadContracts.md ================================================ --- title: useInfiniteReadContracts description: Hook for calling multiple read methods on a contract with "infinite scroll"/"fetch more" support. --- # useInfiniteReadContracts Hook for calling multiple contract read-only methods with "infinite scrolling"/"fetch more" support. ## Import ```ts import { useInfiniteReadContracts } from 'wagmi' ``` ## Usage The example below shows how to demonstrate how to fetch a set of [mloot](https://etherscan.io/address/0x1dfe7ca09e99d10835bf73044a23b73fc20623df) attributes (chestwear, footwear, and handwear) with "fetch more" support. ::: code-group ```tsx [index.tsx] import { useInfiniteReadContracts } from 'wagmi' import { abi } from './abi' const mlootContractConfig = { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi, } as const function App() { const result = useInfiniteReadContracts({ cacheKey: 'mlootAttributes', contracts(pageParam) { const args = [pageParam] as const return [ { ...mlootContractConfig, functionName: 'getChest', args }, { ...mlootContractConfig, functionName: 'getFoot', args }, { ...mlootContractConfig, functionName: 'getHand', args }, ] } query: { initialPageParam: 0, getNextPageParam: (_lastPage, _allPages, lastPageParam) => { return lastPageParam + 1 } } }) } ``` <<< @/snippets/abi-infinite-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: In the above example, we are setting a few things: - [`cacheKey`](#cachekey): A unique key to store the data in the cache. - [`query.initialPageParam`](#initialpageparam): An initial page parameter to use when fetching the first set of contracts. - [`query.getNextPageParam`](#getnextpageparam): A function that returns the next page parameter to use when fetching the next set of contracts. - [`contracts`](#contracts): A function that provides `pageParam` (derived from the above) as an argument and expects to return an array of contracts. ### Paginated Parameters We can also leverage properties like `getNextPageParam` with a custom `limit` variable to achieve "pagination" of parameters. For example, we can fetch the first 10 contract functions, then fetch the next 10 contract functions, and so on. ::: code-group ```tsx [index.tsx] import { useInfiniteReadContracts } from 'wagmi' import { abi } from './abi' function Example({ limit = 10 }: { limit?: number } = {}) { const result = useInfiniteReadContracts({ cacheKey: 'mlootAttributes', contracts(pageParam) { return [...new Array(limit)].map( (_, i) => ({ address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi, functionName: 'getHand', args: [BigInt(pageParam + i)], }) as const, ) }, query: { initialPageParam: 1, getNextPageParam(_lastPage, _allPages, lastPageParam) { return lastPageParam + limit }, } }) } ``` <<< @/snippets/abi-infinite-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseInfiniteReadContractsParameters } from 'wagmi' ``` ### cacheKey `string` A unique key to store the data in the cache. ::: code-group ```tsx [index.tsx] import { useInfiniteReadContracts } from 'wagmi' import { abi } from './abi' function App() { const result = useInfiniteReadContracts({ cacheKey: 'mlootAttributes', // [!code hl] contracts(pageParam) { // ... } query: { initialPageParam: 0, getNextPageParam: (_lastPage, _allPages, lastPageParam) => { return lastPageParam + 1 } } }) } ``` <<< @/snippets/abi-infinite-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### contracts `(pageParam: {{TPageParam}}) => Contract[]` A function that provides `pageParam` (derived from the above) as an argument and expects to return an array of contracts. #### abi `Abi | undefined` The contract's ABI. Check out the [TypeScript docs](/react/typescript#const-assert-abis-typed-data) for how to set up ABIs for maximum type inference and safety. ::: code-group ```tsx [index.tsx] import { useInfiniteReadContracts } from 'wagmi' import { abi } from './abi' function App() { const result = useInfiniteReadContracts({ cacheKey: 'mlootAttributes', contracts(pageParam) { const args = [pageParam] as const return [ // ... { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi, // [!code hl] functionName: 'getChest', args }, // ... ] } query: { initialPageParam: 0, getNextPageParam: (_lastPage, _allPages, lastPageParam) => { return lastPageParam + 1 } } }) } ``` <<< @/snippets/abi-infinite-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: #### address `Address | undefined` The contract's address. ::: code-group ```tsx [index.tsx] import { useInfiniteReadContracts } from 'wagmi' import { abi } from './abi' function App() { const result = useInfiniteReadContracts({ cacheKey: 'mlootAttributes', contracts(pageParam) { const args = [pageParam] as const return [ // ... { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', // [!code hl] abi, functionName: 'getChest', args }, // ... ] } query: { initialPageParam: 0, getNextPageParam: (_lastPage, _allPages, lastPageParam) => { return lastPageParam + 1 } } }) } ``` <<< @/snippets/abi-infinite-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: #### functionName `string | undefined` - Function to call on the contract. - Inferred from [`abi`](#abi). ::: code-group ```tsx [index.tsx] import { useInfiniteReadContracts } from 'wagmi' import { abi } from './abi' function App() { const result = useInfiniteReadContracts({ cacheKey: 'mlootAttributes', contracts(pageParam) { const args = [pageParam] as const return [ // ... { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi, functionName: 'getChest', // [!code hl] args }, // ... ] } query: { initialPageParam: 0, getNextPageParam: (_lastPage, _allPages, lastPageParam) => { return lastPageParam + 1 } } }) } ``` <<< @/snippets/abi-infinite-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: #### args `readonly unknown[] | undefined` - Arguments to pass when calling the contract. - Inferred from [`abi`](#abi) and [`functionName`](#functionname). ::: code-group ```tsx [index.tsx] import { useInfiniteReadContracts } from 'wagmi' import { abi } from './abi' function App() { const result = useInfiniteReadContracts({ cacheKey: 'mlootAttributes', contracts(pageParam) { return [ // ... { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi, functionName: 'getChest', args: [pageParam] // [!code hl] }, // ... ] } query: { initialPageParam: 0, getNextPageParam: (_lastPage, _allPages, lastPageParam) => { return lastPageParam + 1 } } }) } ``` <<< @/snippets/abi-infinite-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: #### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useInfiniteReadContracts } from 'wagmi' import { abi } from './abi' function App() { const result = useInfiniteReadContracts({ cacheKey: 'mlootAttributes', contracts(pageParam) { const args = [pageParam] as const return [ // ... { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi, functionName: 'getChest', args, chainId: 1 // [!code hl] }, // ... ] } query: { initialPageParam: 0, getNextPageParam: (_lastPage, _allPages, lastPageParam) => { return lastPageParam + 1 } } }) } ``` <<< @/snippets/abi-infinite-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseInfiniteReadContractsReturnType } from 'wagmi' ``` ================================================ FILE: site/react/api/hooks/usePrepareTransactionRequest.md ================================================ --- title: usePrepareTransactionRequest description: Hook for preparing a transaction request for signing by populating a nonce, gas limit, fee values, and a transaction type. --- # usePrepareTransactionRequest Hook for preparing a transaction request for signing by populating a nonce, gas limit, fee values, and a transaction type. ## Import ```ts import { usePrepareTransactionRequest } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { usePrepareTransactionRequest } from 'wagmi' import { parseEther } from 'viem' function App() { const result = usePrepareTransactionRequest({ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UsePrepareTransactionRequestParameters } from 'wagmi' ``` ### account `Account | Address | undefined` The Account to send the transaction from. ::: code-group ```tsx [index.tsx] import { usePrepareTransactionRequest } from 'wagmi' import { parseEther } from 'viem' function App() { const result = usePrepareTransactionRequest({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### to `` `0x${string}` | undefined `` The transaction recipient or contract address. ::: code-group ```tsx [index.tsx] import { usePrepareTransactionRequest } from 'wagmi' import { parseEther } from 'viem' function App() { const result = usePrepareTransactionRequest({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', // [!code focus] value: parseEther('1'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### accessList `AccessList | undefined` The access list. ::: code-group ```tsx [index.tsx] import { usePrepareTransactionRequest } from 'wagmi' import { parseEther } from 'viem' function App() { const result = usePrepareTransactionRequest({ accessList: [ // [!code focus:6] { address: '0x1', storageKeys: ['0x1'], }, ], account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` Chain ID to prepare the transaction request for. ::: code-group ```tsx [index.tsx] import { usePrepareTransactionRequest } from 'wagmi' import { parseEther } from 'viem' function App() { const result = usePrepareTransactionRequest({ chainId: mainnet.id, // [!code focus] account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### data `` `0x${string}` | undefined `` A contract hashed method call with encoded args. ::: code-group ```tsx [index.tsx] import { usePrepareTransactionRequest } from 'wagmi' import { parseEther } from 'viem' function App() { const result = usePrepareTransactionRequest({ data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // [!code focus] account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### gasPrice `bigint | undefined` The price (in wei) to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction). ::: code-group ```tsx [index.tsx] import { usePrepareTransactionRequest } from 'wagmi' import { parseEther, parseGwei } from 'viem' function App() { const result = usePrepareTransactionRequest({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', gasPrice: parseGwei('20'), // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### maxFeePerGas `bigint | undefined` Total fee per gas (in wei), inclusive of `maxPriorityFeePerGas`. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```tsx [index.tsx] import { usePrepareTransactionRequest } from 'wagmi' import { parseEther, parseGwei } from 'viem' function App() { const result = usePrepareTransactionRequest({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', maxFeePerGas: parseGwei('20'), // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### maxPriorityFeePerGas `bigint | undefined` Max priority fee per gas (in wei). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```tsx [index.tsx] import { usePrepareTransactionRequest } from 'wagmi' import { parseEther, parseGwei } from 'viem' function App() { const result = usePrepareTransactionRequest({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### nonce `number | undefined` Unique number identifying this transaction. ::: code-group ```tsx [index.tsx] import { usePrepareTransactionRequest } from 'wagmi' import { parseEther } from 'viem' function App() { const result = usePrepareTransactionRequest({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), nonce: 5, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### parameters `("fees" | "gas" | "nonce" | "type")[] | undefined` Parameters to prepare. For instance, if `["gas", "nonce"]` is provided, then only the `gas` and `nonce` parameters will be prepared. ::: code-group ```tsx [index.tsx] import { usePrepareTransactionRequest } from 'wagmi' import { parseEther } from 'viem' function App() { const result = usePrepareTransactionRequest({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', parameters: ['gas', 'nonce'], // [!code focus] to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### value `bigint | undefined` Value in wei sent with this transaction. ::: code-group ```tsx [index.tsx] import { usePrepareTransactionRequest } from 'wagmi' import { parseEther } from 'viem' function App() { const result = usePrepareTransactionRequest({ account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { usePrepareTransactionRequest } from 'wagmi' import { parseEther } from 'viem' import { config } from './config' // [!code focus] function App() { const result = usePrepareTransactionRequest({ config, // [!code focus] account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { usePrepareTransactionRequest } from 'wagmi' import { parseEther } from 'viem' import { config } from './config' function App() { const result = usePrepareTransactionRequest({ scopeKey: 'foo' // [!code focus] account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: parseEther('1'), }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UsePrepareTransactionRequestReturnType } from 'wagmi' ``` ## Action - [`prepareTransactionRequest`](/core/api/actions/prepareTransactionRequest) ================================================ FILE: site/react/api/hooks/useProof.md ================================================ --- title: useProof description: Hook for return the account and storage values of the specified account including the Merkle-proof. --- # useProof Hook for return the account and storage values of the specified account including the Merkle-proof. ## Import ```ts import { useProof } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useProof } from 'wagmi' function App() { const result = useProof({ address: '0x4200000000000000000000000000000000000016', storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseProofParameters } from 'wagmi' ``` ### address `Address | undefined` The account address to get the proof for. ::: code-group ```tsx [index.tsx] import { useProof } from 'wagmi' function App() { const result = useProof({ address: '0x4200000000000000000000000000000000000016', // [!code focus] storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### storageKeys `` `0x${string}`[] | undefined `` Array of storage-keys that should be proofed and included. ::: code-group ```tsx [index.tsx] import { useProof } from 'wagmi' function App() { const result = useProof({ address: '0x4200000000000000000000000000000000000016', storageKeys: [ // [!code focus:3] '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockNumber `bigint | undefined` Proof at a given block number. ::: code-group ```tsx [index.tsx] import { useProof } from 'wagmi' function App() { const result = useProof({ address: '0x4200000000000000000000000000000000000016', blockNumber: 42069n, // [!code focus] storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Proof at a given block tag. ::: code-group ```tsx [index.tsx] import { useProof } from 'wagmi' function App() { const result = useProof({ address: '0x4200000000000000000000000000000000000016', blockTag: 'latest', // [!code focus] storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` The ID of chain to get the proof for. ::: code-group ```tsx [index.tsx] import { useProof } from 'wagmi' import { optimism } from 'wagmi/chains' function App() { const result = useProof({ chainId: optimism.id, // [!code focus] address: '0x4200000000000000000000000000000000000016', storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useProof } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useProof({ config, // [!code focus] address: '0x4200000000000000000000000000000000000016', storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useProof } from 'wagmi' import { config } from './config' function App() { const result = useProof({ scopeKey: 'foo' // [!code focus] address: '0x4200000000000000000000000000000000000016', storageKeys: [ '0x4a932049252365b3eedbc5190e18949f2ec11f39d3bef2d259764799a1b27d99', ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseProofReturnType } from 'wagmi' ``` ## Action - [`getProof`](/core/api/actions/getProof) ================================================ FILE: site/react/api/hooks/usePublicClient.md ================================================ --- title: usePublicClient description: Hook for getting Viem `PublicClient` instance. --- # usePublicClient Hook for getting Viem [`PublicClient`](https://viem.sh/docs/clients/public) instance. ## Import ```ts import { usePublicClient } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { usePublicClient } from 'wagmi' function App() { const client = usePublicClient() } ``` <<< @/snippets/react/config.ts[config.ts] ::: ::: warning If you want to optimize bundle size, you should use [`useClient`](/react/api/hooks/useClient) along with Viem's [tree-shakable actions](https://viem.sh/docs/clients/custom#tree-shaking) instead. Since Public Client has all public actions attached directly to it. ::: ## Parameters ```ts import { type UsePublicClientParameters } from 'wagmi' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when getting Viem Public Client. ::: code-group ```ts [index.ts] import { usePublicClient } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] import { config } from './config' function App() { const client = usePublicClient({ chainId: mainnet.id, // [!code focus] }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { usePublicClient } from 'wagmi' import { config } from './config' // [!code focus] function App() { const client = usePublicClient({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UsePublicClientReturnType } from 'wagmi' ``` `PublicClient | undefined` Viem [`PublicClient`](https://viem.sh/docs/clients/public) instance. ## Action - [`getPublicClient`](/core/api/actions/getPublicClient) - [`watchPublicClient`](/core/api/actions/watchPublicClient) ================================================ FILE: site/react/api/hooks/useReadContract.md ================================================ --- title: useReadContract description: Hook for calling a read-only function on a contract, and returning the response. --- # useReadContract Hook for calling a **read-only** function on a contract, and returning the response. A **read-only** function (constant function) on a Solidity contract is denoted by a pure or view keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas. ## Import ```ts import { useReadContract } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useReadContract } from 'wagmi' import { abi } from './abi' function App() { const result = useReadContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'totalSupply', }) } ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseReadContractParameters } from 'wagmi' ``` ### abi `Abi | undefined` The contract's ABI. Check out the [TypeScript docs](/react/typescript#const-assert-abis-typed-data) for how to set up ABIs for maximum type inference and safety. ::: code-group ```tsx [index.tsx] import { useReadContract } from 'wagmi' import { abi } from './abi' // [!code focus] function App() { const result = useReadContract({ abi, // [!code focus] address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'totalSupply', }) } ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### account `Account | undefined` Account to use when calling the contract (`msg.sender`). ::: code-group ```tsx [index.tsx] import { useReadContract } from 'wagmi' import { abi } from './abi' function App() { const result = useReadContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'balanceOf', args: ['0x6b175474e89094c44da98b954eedeac495271d0f'], account: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] }) } ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### address `Address | undefined` The contract's address. ::: code-group ```tsx [index.tsx] import { useReadContract } from 'wagmi' import { abi } from './abi' function App() { const result = useReadContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', // [!code focus] functionName: 'totalSupply', }) } ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### args `readonly unknown[] | undefined` - Arguments to pass when calling the contract. - Inferred from [`abi`](#abi) and [`functionName`](#functionname). ::: code-group ```tsx [index.tsx] import { useReadContract } from 'wagmi' import { abi } from './abi' function App() { const result = useReadContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'balanceOf', args: ['0x6b175474e89094c44da98b954eedeac495271d0f'], // [!code focus] }) } ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: --- ### blockNumber `bigint | undefined` Block number to call contract at. ::: code-group ```tsx [index.tsx] import { useReadContract } from 'wagmi' import { abi } from './abi' function App() { const result = useReadContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'totalSupply', blockNumber: 17829139n, // [!code focus] }) } ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to call contract at. ::: code-group ```tsx [index.tsx] import { useReadContract } from 'wagmi' import { abi } from './abi' function App() { const result = useReadContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'totalSupply', blockTag: 'safe', // [!code focus] }) } ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useReadContract } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] import { abi } from './abi' function App() { const result = useReadContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'totalSupply', chainId: mainnet.id, // [!code focus] }) } ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useReadContract } from 'wagmi' import { abi } from './abi' import { config } from './config' // [!code focus] function App() { const result = useReadContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'totalSupply', config, // [!code focus] }) } ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### functionName `string | undefined` - Function to call on the contract. - Inferred from [`abi`](#abi). ::: code-group ```tsx [index.tsx] import { useReadContract } from 'wagmi' import { abi } from './abi' function App() { const result = useReadContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'balanceOf', // [!code focus] args: ['0x6b175474e89094c44da98b954eedeac495271d0f'], }) } ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useReadContract } from 'wagmi' import { abi } from './abi' function App() { const result = useReadContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'balanceOf', args: ['0x6b175474e89094c44da98b954eedeac495271d0f'], scopeKey: 'foo', // [!code focus] }) } ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseReadContractReturnType } from 'wagmi' ``` The return type's [`data`](#data) property is inferrable via the combination of [`abi`](#abi), [`functionName`](#functionname), and [`args`](#args). Check out the [TypeScript docs](/react/typescript#const-assert-abis-typed-data) for more info. ## Type Inference With [`abi`](#abi) setup correctly, TypeScript will infer the correct types for [`functionName`](#functionname), [`args`](#args), and the return type. See the Wagmi [TypeScript docs](/react/typescript) for more information. ::: code-group ```ts twoslash [Inline] // @twoslash-cache: {"v":1,"hash":"8bfa3d1e805ee2d7a8b83c91b1e75f961b748f9d5c3b79a8bca9b7494b57cb8e","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BjCMONAAlPgFcAbNROwCqcGACUYAQygBhFmlKTGaCWm6kwAFWwwAPF2kteGdqgA6Ydlc5SoRk5hyCzIAGbcwygJYsXAbgtrG0MwY3YwSQBbGGcQACNJXklPGAB5V39A6wM7UJM2SRoAWW40STivXi9MWKIvGAB3TMts23t2LzAsUrhBHPbzFqCrfrzwqJj2FyVmDzRm4daQsMdJ6agoLjg4BesAXwBdAKHg3LCIUu60XtOB4CzF0ZWdWO5OtAAmAFYANl2rQ7HPYUdj3E5PBwvKZuDzeXwgY5BCHjaKxNAQMq8ADK3CwWGM/1uYwKxVK5Uq1QwtXqTQRDyJYU6VxuyOQR3pyIuaGZfTaY0GixGfLCEVR0LguPxGEJSOFkKc0LeYE+v0JgIshxBLgSSRS6RcINZLgADLQfnEAIwAdi+ABYrbaYAAOACcxpdtsYtttUEkLqdcRddpgMFgSltQY+VotUGNGRABxBFQA5u8AHyUEAFUgMRA/Ki8GBgZNofBIfPUSSkZMwXMgLZ8BgFzq4RDGqiMf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KOMaQlIvYBcX3YXNGR3CwTMBKSQJAUASOIsOAc8FhBAPYPYIAA="} import { createConfig, http, useReadContract } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) // ---cut--- const result = useReadContract({ abi: [ { type: 'function', name: 'balanceOf', stateMutability: 'view', inputs: [{ name: 'account', type: 'address' }], outputs: [{ type: 'uint256' }], }, { type: 'function', name: 'totalSupply', stateMutability: 'view', inputs: [], outputs: [{ name: 'supply', type: 'uint256' }], }, ], address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'balanceOf', // ^? args: ['0x6b175474e89094c44da98b954eedeac495271d0f'], // ^? }) result.data // ^? ``` ```ts twoslash [Const-Asserted] // @twoslash-cache: {"v":1,"hash":"9f8b59d36cf11dedf27c45ac2abd580ec38459b071c6641a3e4025c048f71072","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BjCMONAAgEMAjAS0XakYnKCwA2GdqgA6YdvMHDRYCe0w4B0kADMArmEZpeLLQG5ZCxSPGSwnALYxNIbpzGcDMAPLazFhULWKpJsnDQAsrpoPLxivJjORLwwAO5+cgFKNuy8YFhRcAKByqoyGZbyxdl2js6cjMz6aOkVmUGq6k7sWiJQQnBwLQoAvgC65uVWJZIQUflohVPZZa2VWcFq2F1aurloAEwArABsQ/JjE8MU7MD+a+2Snc56BkYmIBOWVRs129QQ0TEAGVdFgsBIzksNqEIlEYnEEt0QElUpDvqpcvNFujJMhxncoapZmgsUV1qVbpMvuTbA4/nBQeCMJDqQ9NhokbswAcTpCLrIxpQQKFSAxEMcqGIYGAAOZofBIADMVGipBlMDFIBiQriYFwiAADFRGPhOKR6jRyOKrugtnhCCRyCq6JqABRYUgQHCijAASnZfxehmMYC0QpFYv2+0l0rlCsQABYVWb1ZrOjrcvroyATWaLWQkAmbdQ7YgCMQC876Hh3Z7vZh/b9nK53J4fGGqB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sIvQyQww5g1ohQ7g5Qzo2w2ono+o/oiIoY4wmI0YjoggyY7orQhogY5ojwkYnwsYqwlYwIhwmYsQuY9w4Yrw2In/BMBIqaZIiQ1IzTFaTI0ZHMaAaKWPDgGIdgIeZAfwUhByAAcnyQBIoAJHQgBP3xXhBIJFPURABN3mhMmF8VQH3XYABOlxBL2nRNuwBOYVBMmCFRRMBMGVxO/X8CuD+IJEBOBPxMsHBIyzKURMsFhJ1XhNPCZIUGRNGQJEJOAFRIBJfQwExOJLSVJO5IyApLABV0RV7j4WaHMI+Pj1kW+NwwLQIzg0MFdANhiFpK4FuwEABLmVPz9Qv0DWvxDTv3DUfyuWjUODuVf20A5O+2NghOLyhPxK4PkAlwEGQENJ9TP39UvyDRv1DXvwjRtJuTtNjSeQBPFOGF9C4KALQAA1oNkCFCzU4CQFABdGlDgBDHrgQGGGGCAA="} import { createConfig, http, useReadContract } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) // ---cut--- const abi = [ { type: 'function', name: 'balanceOf', stateMutability: 'view', inputs: [{ name: 'account', type: 'address' }], outputs: [{ type: 'uint256' }], }, { type: 'function', name: 'totalSupply', stateMutability: 'view', inputs: [], outputs: [{ name: 'supply', type: 'uint256' }], }, ] as const const result = useReadContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'balanceOf', // ^? args: ['0x6b175474e89094c44da98b954eedeac495271d0f'], // ^? }) result.data // ^? ``` ::: ## Action - [`readContract`](/core/api/actions/readContract) ================================================ FILE: site/react/api/hooks/useReadContracts.md ================================================ --- title: useReadContracts description: Hook for calling multiple read methods on a contract. --- # useReadContracts Hook for calling multiple read methods on a contract. ## Import ```ts import { useReadContracts } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useReadContracts } from 'wagmi' const wagmigotchiContract = { address: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1', abi: wagmigotchiABI, } as const const mlootContract = { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, } as const function App() { const result = useReadContracts({ contracts: [ { ...wagmigotchiContract, functionName: 'getAlive', }, { ...wagmigotchiContract, functionName: 'getBoredom', }, { ...mlootContract, functionName: 'getChest', args: [69], }, { ...mlootContract, functionName: 'getWaist', args: [69], }, ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseReadContractsParameters } from 'wagmi' ``` ### contracts `readonly Contract[]` Set of contracts to call. #### abi `Abi | undefined` The contract's ABI. Check out the [TypeScript docs](/react/typescript#const-assert-abis-typed-data) for how to set up ABIs for maximum type inference and safety. ::: code-group ```tsx [index.tsx] import { useReadContracts } from 'wagmi' function App() { const result = useReadContracts({ contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, // [!code hl] functionName: 'getChest', args: [69], }, // ... ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: #### address `Address | undefined` The contract's address. ::: code-group ```tsx [index.tsx] import { useReadContracts } from 'wagmi' function App() { const result = useReadContracts({ contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', // [!code hl] abi: mlootABI, functionName: 'getChest', args: [69], }, // ... ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: #### functionName `string | undefined` - Function to call on the contract. - Inferred from [`abi`](#abi). ::: code-group ```tsx [index.tsx] import { useReadContracts } from 'wagmi' function App() { const result = useReadContracts({ contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', // [!code hl] args: [69], }, // ... ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: #### args `readonly unknown[] | undefined` - Arguments to pass when calling the contract. - Inferred from [`abi`](#abi) and [`functionName`](#functionname). ::: code-group ```tsx [index.tsx] import { useReadContracts } from 'wagmi' function App() { const result = useReadContracts({ contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69], // [!code hl] }, // ... ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: #### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useReadContracts } from 'wagmi' function App() { const result = useReadContracts({ contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69], chainId: 1 // [!code hl] }, // ... ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### allowFailure `boolean` Whether or not the Hook should throw if a call reverts. If set to `true` (default), and a call reverts, then `useReadContracts` will fail silently and its error will be logged in the results array. Defaults to `true`. ::: code-group ```tsx [index.tsx] import { useReadContracts } from 'wagmi' function App() { const result = useReadContracts({ allowFailure: false, // [!code hl] contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69] }, // ... ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### batchSize `number` The maximum size (in bytes) for each calldata chunk. Set to `0` to disable the size limit. Defaults to `1024`. > Note: Some RPC Providers limit the amount of calldata (`data`) that can be sent in a single `eth_call` request. It is best to check with your RPC Provider to see if there are any calldata size limits to `eth_call` requests. ::: code-group ```tsx [index.tsx] import { useReadContracts } from 'wagmi' function App() { const result = useReadContracts({ batchSize: 1024, // [!code hl] contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69] }, // ... ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockNumber `number` The block number to perform the read against. ::: code-group ```tsx [index.tsx] import { useReadContracts } from 'wagmi' function App() { const result = useReadContracts({ blockNumber: 69420n, // [!code hl] contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69] }, // ... ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to read against. ::: code-group ```tsx [index.tsx] import { useReadContracts } from 'wagmi' function App() { const result = useReadContracts({ blockTag: 'safe', // [!code hl] contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69] }, // ... ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useReadContracts } from 'wagmi' import { config } from './config' function App() { const result = useReadContracts({ config, // [!code hl] contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69] }, // ... ], }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### multicallAddress `Address` Address of multicall contract. ::: code-group ```tsx [index.tsx] import { useReadContracts } from 'wagmi' function App() { const result = useReadContracts({ contracts: [ { address: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df', abi: mlootABI, functionName: 'getChest', args: [69] }, // ... ], multicallAddress: '0xca11bde05977b3631167028862be2a173976ca11', // [!code hl] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseReadContractsReturnType } from 'wagmi' ``` ## Action - [`readContracts`](/core/api/actions/readContracts) ================================================ FILE: site/react/api/hooks/useReconnect.md ================================================ --- title: useReconnect description: Hook for reconnecting connectors. --- # useReconnect Hook for reconnecting [connectors](/core/api/connectors). ## Import ```ts import { useReconnect } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useReconnect } from 'wagmi' import { useEffect } from 'react' function App() { const reconnect = useReconnect() useEffect(() => { reconnect.mutate() }, []) } ``` ::: ::: tip When [`WagmiProvider['reconnectOnMount']`](/react/api/WagmiProvider#reconnectonmount) is `true`, `reconnect` is called automatically on mount. ::: ## Parameters ```ts import { type UseReconnectParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useReconnect } from 'wagmi' import { config } from './config' // [!code focus] function App() { const reconnect = useReconnect({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseReconnectReturnType } from 'wagmi' ``` ### connectors [deprecated](/react/guides/migrate-from-v2-to-v3#removed-useconnect-connectors-usereconnect-connectors) `readonly Connector[]` Globally configured connectors via [`createConfig`](/react/api/createConfig#connectors). ::: code-group ```tsx [index.tsx] import { useReconnect } from 'wagmi' import { mainnet } from 'wagmi/chains' import { useEffect } from 'react' function App() { const reconnect = useReconnect() useEffect(() => { reconnect.mutate({ connectors: reconnect.connectors }) }, []) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Action - [`reconnect`](/core/api/actions/reconnect) ================================================ FILE: site/react/api/hooks/useSendCalls.md ================================================ --- title: useSendCalls description: Hook that requests for the wallet to sign and broadcast a batch of calls (transactions) to the network. --- # useSendCalls Hook that requests for the wallet to sign and broadcast a batch of calls (transactions) to the network. [Read more.](https://github.com/ethereum/EIPs/blob/815028dc634463e1716fc5ce44c019a6040f0bef/EIPS/eip-5792.md#wallet_sendcalls) ## Import ```ts import { useSendCalls } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useSendCalls } from 'wagmi' import { parseEther } from 'viem' function App() { const sendCalls = useSendCalls() return ( ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### Synchronous Usage If you want to wait for the calls to be included in a block, you can use `useSendCallsSync`: ::: code-group ```tsx [index.tsx] import { useSendCallsSync } from 'wagmi' import { parseEther } from 'viem' function App() { const sendCallsSync = useSendCallsSync() return ( ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseSendCallsParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useSendCalls } from 'wagmi' import { config } from './config' // [!code focus] function App() { const sendCalls = useSendCalls({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseSendCallsReturnType } from 'wagmi' ``` ## Action - [`sendCalls`](/core/api/actions/sendCalls) ================================================ FILE: site/react/api/hooks/useSendTransaction.md ================================================ --- title: useSendTransaction description: Hook for creating, signing, and sending transactions to networks. --- # useSendTransaction Hook for creating, signing, and sending transactions to networks. ## Import ```ts import { useSendTransaction } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useSendTransaction } from 'wagmi' import { parseEther } from 'viem' function App() { const sendTransaction = useSendTransaction() return ( ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### Synchronous Usage If you want to wait for the transaction to be included in a block, you can use `useSendTransactionSync`: ::: code-group ```tsx [index.tsx] import { useSendTransactionSync } from 'wagmi' import { parseEther } from 'viem' function App() { const sendTransactionSync = useSendTransactionSync() return ( ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseSendTransactionParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useSendTransaction } from 'wagmi' import { config } from './config' // [!code focus] function App() { const sendTransaction = useSendTransaction({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseSendTransactionReturnType } from 'wagmi' ``` ## Action - [`sendTransaction`](/core/api/actions/sendTransaction) ================================================ FILE: site/react/api/hooks/useShowCallsStatus.md ================================================ --- title: useShowCallsStatus description: Action to request for the wallet to show information about a call batch --- # useShowCallsStatus Action to request for the wallet to show information about a call batch that was sent via `useSendCalls`. [Read more.](https://github.com/ethereum/EIPs/blob/1663ea2e7a683285f977eda51c32cec86553f585/EIPS/eip-5792.md#wallet_showcallsstatus) ## Import ```ts import { useShowCallsStatus } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useShowCallsStatus } from 'wagmi' import { parseEther } from 'viem' function App() { const showCallsStatus = useShowCallsStatus() return ( ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseShowCallsStatusParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useShowCallsStatus } from 'wagmi' import { config } from './config' // [!code focus] function App() { const showCallsStatus = useShowCallsStatus({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseShowCallsStatusReturnType } from 'wagmi' ``` ## Action - [`showCallsStatus`](/core/api/actions/showCallsStatus) ================================================ FILE: site/react/api/hooks/useSignMessage.md ================================================ --- title: useSignMessage description: Hook for signing messages. --- # useSignMessage Hook for signing messages. ## Import ```ts import { useSignMessage } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useSignMessage } from 'wagmi' function App() { const signMessage = useSignMessage() return ( ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseSignMessageParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useSignMessage } from 'wagmi' import { config } from './config' // [!code focus] function App() { const signMessage = useSignMessage({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseSignMessageReturnType } from 'wagmi' ``` ## Action - [`signMessage`](/core/api/actions/signMessage) ================================================ FILE: site/react/api/hooks/useSignTransaction.md ================================================ --- title: useSignTransaction description: Hook for signing transactions. --- # useSignTransaction Hook for signing transactions. ## Import ```ts import { useSignTransaction } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useSignTransaction } from 'wagmi' import { parseEther } from 'viem' function App() { const signTransaction = useSignTransaction() return ( ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseSignTransactionParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useSignTransaction } from 'wagmi' import { config } from './config' // [!code focus] function App() { const signTransaction = useSignTransaction({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseSignTransactionReturnType } from 'wagmi' ``` ## Action - [`signTransaction`](/core/api/actions/signTransaction) ================================================ FILE: site/react/api/hooks/useSignTypedData.md ================================================ --- title: useSignTypedData description: Hook for signing typed data and calculating an Ethereum-specific EIP-712 signature. --- # useSignTypedData Hook for signing typed data and calculating an Ethereum-specific [EIP-712](https://eips.ethereum.org/EIPS/eip-712) signature. ## Import ```ts import { useSignTypedData } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useSignTypedData } from 'wagmi' function App() { const signTypedData = useSignTypedData() return ( ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseSignTypedDataParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useSignTypedData } from 'wagmi' import { config } from './config' // [!code focus] function App() { const signTypedData = useSignTypedData({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseSignTypedDataReturnType } from 'wagmi' ``` ## Type Inference With [`types`](/core/api/actions/signTypedData#types) setup correctly, TypeScript will infer the correct types for [`domain`](/core/api/actions/signTypedData#domain), [`message`](/core/api/actions/signTypedData#message), and [`primaryType`](/core/api/actions/signTypedData#primarytype). See the Wagmi [TypeScript docs](/react/typescript) for more information. ::: code-group ```ts twoslash [Inline] // @twoslash-cache: {"v":1,"hash":"d2bde2039b22db2dad4de0b0b1a903198c36d1f3885f32042523a928c54eac6c","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BjCMONAAjgEsBzMAFWwwoAEQCGaMYnYBVODADKvAUNESxAJRhoArqRU4APDrABrSAHcwAPkog2Y0g0QA2KgBsYYHmnxIAjADMVJKkPNp43HyCOGqSdu5cYLiIAAxUjPiOYow05K4AvhToQniEJOQhdM4gABRiiWJwAJTsOvJK0ariksZmlja1WNkAttpkcAD80sAAOmDsi+zMYABmvNPsAMIs6zzsAD5tYLDryVAA3PNL7CM6kmhcLJtzCzdLLACy9xIwm7W1IiOLhiABGnjgM2u7xhmBwkPYrxhyKWyFo0jYpCSPAAutJSDAxFAWO4MOwYsIemIAAqjcakZA4q5vFEwtHSAAGmOxyAAJMBud4CjiOXjjqcksJmazkez2BzViZck8wHyBWgsUKRWKTBLztKZe85RyiVACXA4GrBTxhaLpLqYGcpdDDaj0fLQRAIO4rRrsbadSdHZLLi7XexjaCMDRLfzrQH7UGnaGWeHI9H4P5fZqbdrE3rnanXemYwAmbP+vPi4P6sPF90cqMxwIVrV26vJg3hiMNpvwAAsrdz7YdnbrhpL8AArEOEx2Q12072M3AXLOq6OF+OZZO4AB2dcjpNbosT5cxgAch8DBZT3cWu4AnNf8zXC/ee5y+3B/KkX/Pa1PHdz0zLM4z9NsbzfO9713fxy3AnM503QCPzgltEMrI9b0XesvxXfxB0wyDXzHIDWTgmdiOHKCyLQkCfzXajkOPVDYIY/wD2YjdWPfdj8Jjfwr247DoNws8BMzZ8RNok96MkuBSz/GTSLk/iPRXUswPVJCeJw7cKIY0sEJ0rDZLY7td1LDDTJIgC+MsoyiNsmjVIspcFNLKiXJY/TyJRKymJ8vSxIMgKjK44LRLo9TG004SovMhyPI0stpMStzkrw1L4ECZSMvsmDHIUwJtPjEKYuKnK4ECEzyuitSqo5JI0H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OgZgRGZapqcKVim8KoXAOQdymmbmemXmXmTcNkeOI6TsBYKmaeAUaqcwVsCIKWGIIEFAI+AAGKPiBAXgACiQQtZXRe4HZjAqQU4AAgqCFsHuM2R2XuIEP2CIKsBeCICIBeBvhWRcrGTcHsSWV6QAEIQCggrnvBVnMGghbnHlblnmginknkXlXlXnXknm3nHmPmnnHn7mQprlLChlqkAASMAWyEAMaO5oIAAhPufGQUM0HYGMPEIgKANUF4NwCwO7ggAUAUEAA=="} import { useSignTypedData } from 'wagmi' // ---cut--- const signTypedData = useSignTypedData() signTypedData.mutate({ types: { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }, primaryType: 'Mail', // ^? message: { // ^? from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) ``` ```ts twoslash [Const-Asserted] // @twoslash-cache: {"v":1,"hash":"8427c5e54a9e414e6af6101fcf5a4a859fe80517a66aac11a86d69f45d4b46b5","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BjCMONAAkxzkXeAB0w7Ye1IwAhlBYAbDOwAKZOC15jJMuakEidoiVLCz2YcQFsYvfuDMwrAbm27hag0a4X2VtqQCWYAOb2jsIAvhR8wbouGsY2liAA7uLS0jBoQUJOeuqGcu7xklBicHAZOiEAug6ZzvoxALLiPtKqdbnsWjVRbUYm5vEAZqQQpmVZ0e35niCKpMpgY6HhAl06E71x02gQi905btgeVrPzu2ERqyLrcn1HIMxgNI+lINVZ2a55h/HefoGvkUq1RClBAbHEpAYiAAbFRUgE0PgkABWKhoCH+NJ4dwIOF+XCIAAMVEY+Ah4kYNHIMLC6EOeEIJHIaLoUJAAAosMMcJCMABK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gBITit0FMuuJISSuyqSrypIVypyoKqKqKuKpytKuysqtyuyvSqWDZP+I5MAoAAkYAUgIBwgUqSEABCdKyCtSPkUEN+LeRAUAVkZ0fOFgbEBAEIEIIAA=="} import { useSignTypedData } from 'wagmi' // ---cut--- const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const const signTypedData = useSignTypedData() signTypedData.mutate({ types, primaryType: 'Mail', // ^? message: { // ^? from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) ``` ::: ## Action - [`signTypedData`](/core/api/actions/signTypedData) ================================================ FILE: site/react/api/hooks/useSimulateContract.md ================================================ --- title: useSimulateContract description: Hook for simulating/validating a contract interaction. --- # useSimulateContract Hook for simulating/validating a contract interaction. ## Import ```ts import { useSimulateContract } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useSimulateContract } from 'wagmi' import { abi } from './abi' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ::: details Composing with `useWriteContract` `useSimulateContract` can be combined with [`useWriteContract`](/react/api/hooks/useWriteContract) to reduce the amount of validation required by wallets. ::: code-group ```tsx [index.tsx] import { useSimulateContract, useWriteContract } from 'wagmi' import { abi } from './abi' function App() { const { data } = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], }) const { writeContract } = useWriteContract() return ( ) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseSimulateContractParameters } from 'wagmi' ``` ### abi `Abi | undefined` The contract's ABI. Check out the [TypeScript docs](/react/typescript#const-assert-abis-typed-data) for how to set up ABIs for maximum type inference and safety. ::: code-group ```tsx [index.tsx] import { useSimulateContract } from 'wagmi' import { abi } from './abi' // [!code focus] function App() { const result = useSimulateContract({ abi, // [!code focus] address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### accessList `AccessList | undefined` The access list. ::: code-group ```tsx [index.ts] import { useSimulateContract } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], accessList: [{ // [!code focus] address: '0x1', // [!code focus] storageKeys: ['0x1'], // [!code focus] }], // [!code focus] }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### account `Account | undefined` Account to use when calling the contract (`msg.sender`). Throws if account is not found on [`connector`](#connector). ::: code-group ```tsx [index.tsx] import { useSimulateContract } from 'wagmi' import { abi } from './abi' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], account: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### address `Address | undefined` The contract's address. ::: code-group ```tsx [index.tsx] import { useSimulateContract } from 'wagmi' import { abi } from './abi' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', // [!code focus] functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### args `readonly unknown[] | undefined` - Arguments to pass when calling the contract. - Inferred from [`abi`](#abi) and [`functionName`](#functionname). ::: code-group ```tsx [index.tsx] import { useSimulateContract } from 'wagmi' import { abi } from './abi' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ // [!code focus] '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', // [!code focus] 123n, // [!code focus] ], // [!code focus] }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: --- ### blockNumber `bigint | undefined` Block number to call contract at. ::: code-group ```tsx [index.tsx] import { useSimulateContract } from 'wagmi' import { abi } from './abi' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], blockNumber: 17829139n, // [!code focus] }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to call contract at. ::: code-group ```tsx [index.tsx] import { useSimulateContract } from 'wagmi' import { abi } from './abi' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], blockTag: 'safe', // [!code focus] }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useSimulateContract } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] import { abi } from './abi' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], chainId: mainnet.id, // [!code focus] }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useSimulateContract } from 'wagmi' import { abi } from './abi' import { config } from './config' // [!code focus] function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], config, // [!code focus] }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### connector `Connector | undefined` [Connector](/react/api/connectors) to simulate transaction with. ::: code-group ```tsx [index.ts] import { useConnectorClient, useSimulateContract } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { const { data: connector } = useConnectorClient() const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], connector, // [!code focus] }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### dataSuffix `` `0x${string}` | undefined `` Data to append to the end of the calldata. Useful for adding a ["domain" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f). ::: code-group ```tsx [index.ts] import { useSimulateContract } from 'wagmi' import { parseGwei } from 'viem' import { abi } from './abi' import { config } from './config' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], dataSuffix: '0xdeadbeef', // [!code focus] }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### functionName `string | undefined` - Function to call on the contract. - Inferred from [`abi`](#abi). ::: code-group ```tsx [index.tsx] import { useSimulateContract } from 'wagmi' import { abi } from './abi' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', // [!code focus] args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### gas `bigint | undefined` Gas provided for transaction execution. ::: code-group ```tsx [index.ts] import { useSimulateContract } from 'wagmi' import { parseGwei } from 'viem' import { abi } from './abi' import { config } from './config' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], gas: parseGwei('20'), // [!code focus] }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: --- ### gasPrice `bigint | undefined` The price in wei to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction). ::: code-group ```tsx [index.ts] import { useSimulateContract } from 'wagmi' import { parseGwei } from 'viem' import { abi } from './abi' import { config } from './config' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], gasPrice: parseGwei('20'), // [!code focus] }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### maxFeePerGas `bigint | undefined` Total fee per gas in wei, inclusive of [`maxPriorityFeePerGas`](#maxPriorityFeePerGas). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```tsx [index.ts] import { useSimulateContract } from 'wagmi' import { parseGwei } from 'viem' import { abi } from './abi' import { config } from './config' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], maxFeePerGas: parseGwei('20'), // [!code focus] }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### maxPriorityFeePerGas `bigint | undefined` Max priority fee per gas in wei. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```tsx [index.ts] import { useSimulateContract } from 'wagmi' import { parseGwei } from 'viem' import { abi } from './abi' import { config } from './config' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], maxFeePerGas: parseGwei('20'), maxPriorityFeePerGas: parseGwei('2'), // [!code focus] }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: --- ### nonce `number` Unique number identifying this transaction. ::: code-group ```tsx [index.ts] import { useSimulateContract } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], nonce: 123, // [!code focus] }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### type `'legacy' | 'eip1559' | 'eip2930' | undefined` Optional transaction request type to narrow parameters. ::: code-group ```tsx [index.ts] import { useSimulateContract } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], type: 'eip1559', // [!code focus] }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### value `bigint | undefined` Value in wei sent with this transaction. ::: code-group ```tsx [index.ts] import { useSimulateContract } from 'wagmi' import { parseEther } from 'viem' import { abi } from './abi' import { config } from './config' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], value: parseEther('0.01'), // [!code focus] }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.ts] import { useSimulateContract } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { const result = useSimulateContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'transferFrom', args: [ '0xd2135CfB216b74109775236E36d4b433F1DF507B', '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e', 123n, ], scopeKey: 'foo', // [!code focus] }) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseSimulateContractReturnType } from 'wagmi' ``` The return type's [`data`](#data) property is inferrable via the combination of [`abi`](#abi), [`functionName`](#functionname), and [`args`](#args). Check out the [TypeScript docs](/react/typescript#const-assert-abis-typed-data) for more info. ## Type Inference With [`abi`](#abi) setup correctly, TypeScript will infer the correct types for [`functionName`](#functionname), [`args`](#args), and [`value`](#value). See the Wagmi [TypeScript docs](/react/typescript) for more information. ## Action - [`simulateContract`](/core/api/actions/simulateContract) ================================================ FILE: site/react/api/hooks/useStorageAt.md ================================================ --- title: useStorageAt description: Hook for returning the value from a storage slot at a given address. --- # useStorageAt Hook for returning the value from a storage slot at a given address. ## Import ```ts import { useStorageAt } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useStorageAt } from 'wagmi' function App() { const result = useStorageAt({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', slot: '0x0', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseStorageAtParameters } from 'wagmi' ``` ### address `Address | undefined` The contract address. ::: code-group ```tsx [index.tsx] import { useStorageAt } from 'wagmi' function App() { const result = useStorageAt({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', // [!code focus] slot: '0x0', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### slot `Hex | undefined` The storage position (as a hex encoded value). ::: code-group ```tsx [index.tsx] import { useStorageAt } from 'wagmi' function App() { const result = useStorageAt({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', slot: '0x0', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## blockNumber `bigint | undefined` The block number to check the storage at. ::: code-group ```tsx [index.tsx] import { useStorageAt } from 'wagmi' function App() { const result = useStorageAt({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', blockNumber: 16280770n, // [!code focus] slot: '0x0', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` The block tag to check the storage at. ::: code-group ```tsx [index.tsx] import { useStorageAt } from 'wagmi' function App() { const result = useStorageAt({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', blockTag: 'safe', // [!code focus] slot: '0x0', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` The chain ID to check the storage at. ::: code-group ```tsx [index.tsx] import { useStorageAt } from 'wagmi' import { mainnet } from '@wagmi/core/chains' function App() { const result = useStorageAt({ chainId: mainnet.id, // [!code focus] address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', slot: '0x0', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useStorageAt } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useStorageAt({ config, // [!code focus] address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', slot: '0x0', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useStorageAt } from 'wagmi' import { config } from './config' function App() { const result = useStorageAt({ scopeKey: 'foo' // [!code focus] address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', slot: '0x0', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseStorageAtReturnType } from 'wagmi' ``` ## Action - [`getStorageAt`](/core/api/actions/getStorageAt) ================================================ FILE: site/react/api/hooks/useSwitchChain.md ================================================ --- title: useSwitchChain description: Hook for switching the target chain for a connector or the Wagmi `Config`. --- # useSwitchChain Hook for switching the target chain for a connector or the Wagmi [`Config`](/react/api/createConfig#config). ## Import ```ts import { useSwitchChain } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useChains, useSwitchChain } from 'wagmi' function App() { const switchChain = useSwitchChain() const chains = useChains() return (
{chains.map((chain) => ( ))}
) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ::: tip When connected, `switchChain` will switch the target chain for the connector. When not connected, `switchChain` will switch the target chain for the Wagmi [`Config`](/react/api/createConfig#config). ::: ## Parameters ```ts import { type UseSwitchChainParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useSwitchChain } from 'wagmi' import { config } from './config' // [!code focus] function App() { const switchChain = useSwitchChain({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseSwitchChainReturnType } from 'wagmi' ``` ### chains [deprecated](/react/guides/migrate-from-v2-to-v3#removed-useswitchchain-chains) `readonly [Chain, ...Chain[]]` Globally configured chains. Useful for rendering a list of available chains to switch to. ::: code-group ```tsx [index.tsx] import { useSwitchChain } from 'wagmi' function App() { const switchChain = useSwitchChain() return (
{switchChain.chains.map((chain) => ( ))}
) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Action - [`switchChain`](/core/api/actions/switchChain) ================================================ FILE: site/react/api/hooks/useSwitchConnection.md ================================================ --- title: useSwitchConnection description: Hook for switching the current connection. --- # useSwitchConnection Hook for switching the current connection. ## Import ```ts import { useSwitchConnection } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useConnections, useSwitchConnection } from 'wagmi' function App() { const switchConnection = useSwitchConnection() const connections = useConnections() return (
{connections.map((connection) => ( ))}
) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseSwitchConnectionParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useSwitchConnection } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useSwitchConnection({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseSwitchConnectionReturnType } from 'wagmi' ``` ### connectors [deprecated](/react/guides/migrate-from-v2-to-v3#removed-usedisconnect-connectors-useswitchconnection-connectors) `readonly Connector[]` Globally configured and actively connected connectors. Useful for rendering a list of available connectors to switch to. ::: code-group ```tsx [index.tsx] import { useSwitchConnection } from 'wagmi' function App() { const switchConnection = useSwitchConnection() return (
{switchConnection.connectors.map((connector) => ( ))}
) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Action - [`switchConnection`](/core/api/actions/switchConnection) ================================================ FILE: site/react/api/hooks/useTransaction.md ================================================ --- title: useTransaction description: Hook for fetching transactions given hashes or block identifiers. --- # useTransaction Hook for fetching transactions given hashes or block identifiers. ## Import ```ts import { useTransaction } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useTransaction } from 'wagmi' function App() { const result = useTransaction({ hash: '0x0fa64daeae54e207aa98613e308c2ba8abfe274f75507e741508cc4db82c8cb5', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseTransactionParameters } from 'wagmi' ``` --- ### blockHash `bigint | undefined` Block hash to get transaction at (with [`index`](#index)). ```ts import { useTransaction } from 'wagmi' function App() { const result = useTransaction({ blockHash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', // [!code focus] index: 0, }) } ``` ### blockNumber `bigint | undefined` Block number to get transaction at (with [`index`](#index)). ```ts import { useTransaction } from 'wagmi' function App() { const result = useTransaction({ blockNumber: 17829139n, // [!code focus] index: 0, }) } ``` ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get transaction at (with [`index`](#index)). ```ts import { useTransaction } from 'wagmi' function App() { const result = useTransaction({ blockTag: 'safe', // [!code focus] index: 0, }) } ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ```ts import { useTransaction } from 'wagmi' import { mainnet } from 'wagmi/chains' function App() { const result = useTransaction({ chainId: mainnet.id, // [!code focus] hash: '0x0fa64daeae54e207aa98613e308c2ba8abfe274f75507e741508cc4db82c8cb5', }) } ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useTransaction } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useTransaction({ hash: '0x0fa64daeae54e207aa98613e308c2ba8abfe274f75507e741508cc4db82c8cb5', config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### hash `` `0x${string}` | undefined `` Hash to get transaction. [`enabled`](#enabled) set to `false` if `hash` and [`index`](#index) are `undefined`. ```ts import { useTransaction } from 'wagmi' function App() { const result = useTransaction({ hash: '0x0fa64daeae54e207aa98613e308c2ba8abfe274f75507e741508cc4db82c8cb5', // [!code focus] }) } ``` ### index `number | undefined` An index to be used with a block identifier ([hash](#blockhash), [number](#blocknumber), or [tag](#blocktag)). [`enabled`](#enabled) set to `false` if `index` and [`hash`](#hash) are `undefined`. ```ts import { useTransaction } from 'wagmi' function App() { const result = useTransaction({ blockTag: 'safe', index: 0 // [!code focus] }) } ``` ## Return Type ```ts import { type UseTransactionReturnType } from 'wagmi' ``` ## Action - [`getTransaction`](/core/api/actions/getTransaction) ================================================ FILE: site/react/api/hooks/useTransactionConfirmations.md ================================================ --- title: useTransactionConfirmations description: Hook for fetching the number of blocks passed (confirmations) since the transaction was processed on a block. --- # useTransactionConfirmations Hook for fetching the number of blocks passed (confirmations) since the transaction was processed on a block. If confirmations is 0, then the Transaction has not been confirmed & processed yet. ## Import ```ts import { useTransactionConfirmations } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useTransactionConfirmations } from 'wagmi' function App() { const result = useTransactionConfirmations({ hash: '0x0fa64daeae54e207aa98613e308c2ba8abfe274f75507e741508cc4db82c8cb5', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseTransactionConfirmationsParameters } from 'wagmi' ``` --- ### hash `` `0x${string}` | undefined `` The hash of the transaction. ```ts import { useTransactionConfirmations } from 'wagmi' function App() { const result = useTransactionConfirmations({ hash: '0x0fa64daeae54e207aa98613e308c2ba8abfe274f75507e741508cc4db82c8cb5', // [!code focus] }) } ``` ### transactionReceipt `TransactionReceipt | undefined` The transaction receipt. ```ts import { useTransactionConfirmations } from 'wagmi' function App() { const result = useTransactionConfirmations({ transactionReceipt: { ... }, // [!code focus] }) } ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ```ts import { useTransactionConfirmations } from 'wagmi' import { mainnet } from 'wagmi/chains' function App() { const result = useTransactionConfirmations({ chainId: mainnet.id, // [!code focus] hash: '0x0fa64daeae54e207aa98613e308c2ba8abfe274f75507e741508cc4db82c8cb5', }) } ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useTransactionConfirmations } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useTransactionConfirmations({ config, // [!code focus] hash: '0x0fa64daeae54e207aa98613e308c2ba8abfe274f75507e741508cc4db82c8cb5', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useBlock } from 'wagmi' import { config } from './config' function App() { const result = useTransactionConfirmations({ scopeKey: 'foo' // [!code focus] hash: '0x0fa64daeae54e207aa98613e308c2ba8abfe274f75507e741508cc4db82c8cb5', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseTransactionConfirmationsReturnType } from 'wagmi' ``` ## Action - [`getTransactionConfirmations`](/core/api/actions/getTransactionConfirmations) ================================================ FILE: site/react/api/hooks/useTransactionCount.md ================================================ --- title: useTransactionCount description: Hook for fetching the number of transactions an Account has broadcast / sent. --- # useTransactionCount Hook for fetching the number of transactions an Account has sent. ## Import ```ts import { useTransactionCount } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useTransactionCount } from 'wagmi' function App() { const result = useTransactionCount({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseTransactionCountParameters } from 'wagmi' ``` ### address `Address | undefined` Address to get the transaction count for. [`enabled`](#enabled) set to `false` if `address` is `undefined`. ::: code-group ```tsx [index.tsx] import { useTransactionCount } from 'wagmi' import { mainnet } from 'wagmi/chains' function App() { const result = useTransactionCount({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: --- ### blockNumber `bigint | undefined` Block number to get the transaction count at. ::: code-group ```ts [index.ts] import { useTransactionCount } from 'wagmi' function App() { const result = useTransactionCount({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', blockNumber: 17829139n, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get the transaction count at. ::: code-group ```ts [index.ts] import { useTransactionCount } from 'wagmi' function App() { const result = useTransactionCount({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', blockTag: 'latest', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useTransactionCount } from 'wagmi' import { mainnet } from 'wagmi/chains' // [!code focus] function App() { const result = useTransactionCount({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', chainId: mainnet.id, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useTransactionCount } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useTransactionCount({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useTransactionCount } from 'wagmi' function App() { const result = useTransactionCount({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', scopeKey: 'foo', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseTransactionCountReturnType } from 'wagmi' ``` ## Action - [`getTransactionCount`](/core/api/actions/getTransactionCount) ================================================ FILE: site/react/api/hooks/useTransactionReceipt.md ================================================ --- title: useTransactionReceipt description: Hook for return the Transaction Receipt given a Transaction hash. --- # useTransactionReceipt Hook for return the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. ## Import ```ts import { useTransactionReceipt } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useTransactionReceipt } from 'wagmi' function App() { const result = useTransactionReceipt({ hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseTransactionReceiptParameters } from 'wagmi' ``` ### hash `` `0x${string}` | undefined `` A transaction hash. ::: code-group ```tsx [index.tsx] import { useTransactionReceipt } from 'wagmi' function App() { const result = useTransactionReceipt({ hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` The ID of chain to return the transaction receipt from. ::: code-group ```tsx [index.tsx] import { useTransactionReceipt } from 'wagmi' import { mainnet } from 'wagmi/chains' function App() { const result = useTransactionReceipt({ chainId: mainnet.id, // [!code focus] hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useTransactionReceipt } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useTransactionReceipt({ config, // [!code focus] hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useTransactionReceipt } from 'wagmi' import { config } from './config' function App() { const result = useTransactionReceipt({ scopeKey: 'foo' // [!code focus] hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseTransactionReceiptReturnType } from 'wagmi' ``` ## Action - [`getTransactionReceipt`](/core/api/actions/getTransactionReceipt) ================================================ FILE: site/react/api/hooks/useVerifyMessage.md ================================================ --- title: useVerifyMessage description: Hook for verify that a message was signed by the provided address. --- # useVerifyMessage Hook for verify that a message was signed by the provided address. It supports verifying messages that were signed by either a Smart Contract Account or Externally Owned Account. ## Import ```ts import { useVerifyMessage } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useVerifyMessage } from 'wagmi' function App() { const result = useVerifyMessage({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseVerifyMessageParameters } from 'wagmi' ``` ### address `Address | undefined` The Ethereum address that signed the original message. ::: code-group ```tsx [index.tsx] import { useVerifyMessage } from 'wagmi' function App() { const result = useVerifyMessage({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus] message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### message `string | { raw: Hex | ByteArray } | undefined` The message to be verified. By default, wagmi verifies the UTF-8 representation of the message. ::: code-group ```tsx [index.tsx] import { useVerifyMessage } from 'wagmi' function App() { const result = useVerifyMessage({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', // [!code focus] signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ::: tip By default, viem signs the UTF-8 representation of the message. To sign the data representation of the message, you can use the `raw` attribute. ```ts import { useVerifyMessage } from 'wagmi' function App() { const result = useVerifyMessage({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: { raw: '0x68656c6c6f20776f726c64' } // [!code focus] signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` ::: ### signature `Hex | ByteArray | undefined` The signature that was generated by signing the message with the address's signer. ::: code-group ```tsx [index.tsx] import { useVerifyMessage } from 'wagmi' function App() { const result = useVerifyMessage({ address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` Only used when verifying a message that was signed by a Smart Contract Account. The ID of chain to check if the contract was already deployed. ::: code-group ```tsx [index.tsx] import { useVerifyMessage } from 'wagmi' import { mainnet } from 'wagmi/chains' function App() { const result = useVerifyMessage({ chainId: mainnet.id, // [!code focus] address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockNumber `bigint | undefined` Only used when verifying a message that was signed by a Smart Contract Account. The block number to check if the contract was already deployed. ::: code-group ```tsx [index.tsx] import { useVerifyMessage } from 'wagmi' import { mainnet } from 'wagmi/chains' function App() { const result = useVerifyMessage({ blockNumber: 12345678n, // [!code focus] address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Only used when verifying a message that was signed by a Smart Contract Account. The block tag to check if the contract was already deployed. ::: code-group ```tsx [index.tsx] import { useVerifyMessage } from 'wagmi' import { mainnet } from 'wagmi/chains' function App() { const result = useVerifyMessage({ blockTag: 'pending', // [!code focus] address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useVerifyMessage } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useVerifyMessage({ config, // [!code focus] address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useVerifyMessage } from 'wagmi' import { config } from './config' function App() { const result = useVerifyMessage({ scopeKey: 'foo' // [!code focus] address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', message: 'hello world', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseVerifyMessageReturnType } from 'wagmi' ``` ## Action - [`verifyMessage`](/core/api/actions/verifyMessage) ================================================ FILE: site/react/api/hooks/useVerifyTypedData.md ================================================ --- title: useVerifyTypedData description: Hook for verify that a typed data was signed by the provided address. --- # useVerifyTypedData Hook for verify that a typed data was signed by the provided address. It supports verifying typed data that were signed by either a Smart Contract Account or Externally Owned Account. ## Import ```ts import { useVerifyTypedData } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { domain, types } from './data' import { useVerifyTypedData } from 'wagmi' function App() { const result = useVerifyTypedData({ domain, types, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseVerifyTypedDataParameters } from 'wagmi' ``` ### address `Address | undefined` The Ethereum address that signed the original typed data. ::: code-group ```tsx [index.tsx] import { domain, types } from './data' import { useVerifyTypedData } from 'wagmi' function App() { const result = useVerifyTypedData({ domain, types, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus] signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` <<< @/snippets/react/config.ts[config.ts] ::: ### domain `TypedDataDomain | undefined` The typed data domain. ::: code-group ```tsx [index.tsx] import { types } from './data' import { useVerifyTypedData } from 'wagmi' function App() { const result = useVerifyTypedData({ domain: { // [!code focus:6] name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', }, types, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` ```ts [data.ts] // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` <<< @/snippets/react/config.ts[config.ts] ::: ### types The type definitions for the typed data. ::: code-group ```tsx [index.tsx] import { domain } from './data' import { useVerifyTypedData } from 'wagmi' function App() { const result = useVerifyTypedData({ domain, types: { // [!code focus:11] Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const ``` <<< @/snippets/react/config.ts[config.ts] ::: ### primaryType `string | undefined` The primary `type` to extract from types and use in `value`. ::: code-group ```tsx [index.tsx] import { domain } from './data' import { useVerifyTypedData } from 'wagmi' function App() { const result = useVerifyTypedData({ domain, types: { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ // [!code focus:5] { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }, primaryType: 'Mail', // [!code focus] message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const ``` <<< @/snippets/react/config.ts[config.ts] ::: ### message Type inferred from `types` & `primaryType`. The message to be verified. ::: code-group ```tsx [index.tsx] import { domain, types } from './data' import { useVerifyTypedData } from 'wagmi' function App() { const result = useVerifyTypedData({ domain, types, message: { // [!code focus:11] from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` <<< @/snippets/react/config.ts[config.ts] ::: ### signature `Hex | ByteArray | undefined` The signature that was generated by signing the typed data with the address's signer. ::: code-group ```tsx [index.tsx] import { domain, types } from './data' import { useVerifyTypedData } from 'wagmi' function App() { const result = useVerifyTypedData({ domain, types, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', // [!code focus] }) } ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` <<< @/snippets/react/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` Only used when verifying a typed data that was signed by a Smart Contract Account. The ID of chain to check if the contract was already deployed. ::: code-group ```tsx [index.tsx] import { domain, types } from './data' import { useVerifyTypedData } from 'wagmi' import { mainnet } from 'wagmi/chains' function App() { const result = useVerifyTypedData({ chainId: mainnet.id, // [!code focus] domain, types, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockNumber `bigint | undefined` Only used when verifying a typed data that was signed by a Smart Contract Account. The block number to check if the contract was already deployed. ::: code-group ```tsx [index.tsx] import { domain, types } from './data' import { useVerifyTypedData } from 'wagmi' function App() { const result = useVerifyTypedData({ blockNumber: 12345678n, // [!code focus] domain, types, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Only used when verifying a typed data that was signed by a Smart Contract Account. The block tag to check if the contract was already deployed. ::: code-group ```tsx [index.tsx] import { domain, types } from './data' import { useVerifyTypedData } from 'wagmi' function App() { const result = useVerifyTypedData({ blockTag: 'latest', // [!code focus] domain, types, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { domain, types } from './data' import { useVerifyTypedData } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useVerifyTypedData({ config, // [!code focus] domain, types, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { domain, types } from './data' import { useVerifyTypedData } from 'wagmi' function App() { const result = useVerifyTypedData({ scopeKey: 'foo' // [!code focus] domain, types, message: { from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, primaryType: 'Mail', address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', signature: '0x66edc32e2ab001213321ab7d959a2207fcef5190cc9abb6da5b0d2a8a9af2d4d2b0700e2c317c4106f337fd934fbbb0bf62efc8811a78603b33a8265d3b8f8cb1c', }) } ``` ```ts [data.ts] // All properties on a domain are optional export const domain = { name: 'Ether Mail', version: '1', chainId: 1, verifyingContract: '0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC', } as const // The named list of all type definitions export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseVerifyTypedDataReturnType } from 'wagmi' ``` ## Type Inference With [`types`](#types) setup correctly, TypeScript will infer the correct types for [`domain`](#domain), [`message`](#message), and [`primaryType`](#primarytype). See the Wagmi [TypeScript docs](/react/typescript) for more information. ## Action - [`verifyTypedData`](/core/api/actions/verifyTypedData) ================================================ FILE: site/react/api/hooks/useWaitForCallsStatus.md ================================================ --- title: useWaitForCallsStatus description: Waits for a call bundle to be confirmed & included on a block. --- # useWaitForCallsStatus Waits for a call bundle to be confirmed & included on a block before returning the status & receipts. ## Import ```ts import { useWaitForCallsStatus } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useWaitForCallsStatus } from 'wagmi' function App() { const result = useWaitForCallsStatus({ id: '0x...', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseWaitForCallsStatusParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useWaitForCallsStatus } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useWaitForCallsStatus({ config, // [!code focus] id: '0x...', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### connector `Connector | undefined` Connector to get call statuses with. ::: code-group ```tsx [index.tsx] import { useWaitForCallsStatus, useConnections } from 'wagmi' import { config } from './config' // [!code focus] function App() { const connections = useConnections() const result = useWaitForCallsStatus({ connector: connections[0]?.connector, // [!code focus] id: '0x...', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### id `string` Identifier of the call batch. ::: code-group ```ts [index.ts] import { useWaitForCallsStatus } from '@wagmi/core' import { config } from './config' const status = await useWaitForCallsStatus({ id: '0x1234567890abcdef', // [!code focus] }) ``` <<< @/snippets/react/config.ts[config.ts] ::: ### pollingInterval `number | undefined` Polling interval in milliseconds. ::: code-group ```ts [index.ts] import { useWaitForCallsStatus } from '@wagmi/core' import { config } from './config' const status = await useWaitForCallsStatus({ id: '0x1234567890abcdef', pollingInterval: 1_000, // [!code focus] }) ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```tsx [index.tsx] import { useWaitForCallsStatus } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useWaitForCallsStatus({ id: '0x...', scopeKey: 'foo', // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### timeout `number | undefined` Timeout in milliseconds. ::: code-group ```ts [index.ts] import { useWaitForCallsStatus } from '@wagmi/core' import { config } from './config' const status = await useWaitForCallsStatus({ id: '0x1234567890abcdef', timeout: 10_000, // [!code focus] }) ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseWaitForCallsStatusReturnType } from 'wagmi' ``` ## Action - [`waitForCallsStatus`](https://viem.sh/docs/actions/wallet/waitForCallsStatus) ================================================ FILE: site/react/api/hooks/useWaitForTransactionReceipt.md ================================================ --- title: useWaitForTransactionReceipt description: Hook that waits for the transaction to be included on a block, and then returns the transaction receipt. If the transaction reverts, then the action will throw an error. Replacement detection (e.g. sped up transactions) is also supported. --- # useWaitForTransactionReceipt Hook that waits for the transaction to be included on a block, and then returns the transaction receipt. If the transaction reverts, then the action will throw an error. Replacement detection (e.g. sped up transactions) is also supported. ## Import ```ts import { useWaitForTransactionReceipt } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useWaitForTransactionReceipt } from 'wagmi' function App() { const result = useWaitForTransactionReceipt({ hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseWaitForTransactionReceiptParameters } from 'wagmi' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ```ts [index.ts] import { useWaitForTransactionReceipt } from 'wagmi' import { mainnet } from 'wagmi/chains' function App() { const result = useWaitForTransactionReceipt({ chainId: mainnet.id, // [!code focus] hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', }) } ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useWaitForTransactionReceipt } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useWaitForTransactionReceipt({ hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### confirmations `number | undefined` The number of confirmations (blocks that have passed) to wait before resolving. ```ts [index.ts] import { useWaitForTransactionReceipt } from 'wagmi' function App() { const result = useWaitForTransactionReceipt({ confirmations: 2, // [!code focus] hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', }) } ``` ### onReplaced ` (({ reason: 'replaced' | 'repriced' | 'cancelled'; replacedTransaction: Transaction; transaction: Transaction; transactionReceipt: TransactionReceipt }) => void) | undefined ` Optional callback to emit if the transaction has been replaced. ```ts [index.ts] import { useWaitForTransactionReceipt } from 'wagmi' function App() { const result = useWaitForTransactionReceipt({ hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', onReplaced: replacement => console.log(replacement), // [!code focus] }) } ``` ### pollingInterval `number | undefined` - Polling frequency (in milliseconds). - Defaults to the [Config's `pollingInterval` config](/react/api/createConfig#pollinginterval). ```ts [index.ts] import { useWaitForTransactionReceipt } from 'wagmi' function App() { const result = useWaitForTransactionReceipt({ hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', pollingInterval: 1_000, // [!code focus] }) } ``` ### hash `` `0x${string}` | undefined `` The transaction hash to wait for. [`enabled`](#enabled) set to `false` if `hash` is `undefined`. ```ts [index.ts] import { useWaitForTransactionReceipt } from 'wagmi' function App() { const result = useWaitForTransactionReceipt({ hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d', // [!code focus] }) } ``` ## Return Type ```ts import { type UseWaitForTransactionReceiptReturnType } from 'wagmi' ``` ## Action - [`waitForTransactionReceipt`](/core/api/actions/waitForTransactionReceipt) ================================================ FILE: site/react/api/hooks/useWalletClient.md ================================================ --- title: useWalletClient description: Hook for getting a Viem `WalletClient` object for the current or provided connector. --- # useWalletClient Hook for getting a Viem [`WalletClient`](https://viem.sh/docs/clients/wallet) object for the current or provided connector. ## Import ```ts import { useWalletClient } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useWalletClient } from 'wagmi' function App() { const result = useWalletClient() } ``` <<< @/snippets/react/config.ts[config.ts] ::: ::: warning If you want to optimize bundle size, you should use [`useConnectorClient`](/react/api/hooks/useConnectorClient) along with Viem's [tree-shakable actions](https://viem.sh/docs/clients/custom#tree-shaking) instead. Since Wallet Client has all wallet actions attached directly to it. ::: ## Parameters ```ts import { type UseWalletClientParameters } from 'wagmi' ``` ### account `Address | Account | undefined` Account to use with client. Throws if account is not found on [`connector`](#connector). ```ts import { useWalletClient } from 'wagmi' function App() { const result = useWalletClient({ account: '0xd2135CfB216b74109775236E36d4b433F1DF507B', // [!code focus] }) } ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use with client. ```ts import { useWalletClient } from 'wagmi' function App() { const result = useWalletClient({ chainId: mainnet.id, // [!code focus] }) } ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useWalletClient } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useWalletClient({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### connector `Connector | undefined` - Connector to get client for. - Defaults to current connector. ```ts import { useConnections, useWalletClient } from 'wagmi' function App() { const connections = useConnections(config) const result = useWalletClient({ connector: connections[0]?.connector, // [!code focus] }) } ``` ## Return Type ```ts import { type UseWalletClientReturnType } from 'wagmi' ``` ## Action - [`getWalletClient`](/core/api/actions/getWalletClient) ================================================ FILE: site/react/api/hooks/useWatchAsset.md ================================================ --- title: useWatchAsset description: Hook for requesting user tracks the token in their wallet. Returns a boolean indicating if the token was successfully added. --- # useWatchAsset Hook for requesting user tracks the token in their wallet. Returns a boolean indicating if the token was successfully added. ## Import ```ts import { useWatchAsset } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useWatchAsset } from 'wagmi' function App() { const { watchAsset } = useWatchAsset() return ( ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseWatchAssetParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useWatchAsset } from 'wagmi' import { config } from './config' // [!code focus] function App() { const result = useWatchAsset({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseWatchAssetReturnType } from 'wagmi' ``` ## Action - [`watchAsset`](/core/api/actions/watchAsset) ================================================ FILE: site/react/api/hooks/useWatchBlockNumber.md ================================================ --- title: useWatchBlockNumber description: Hook that watches for block number changes. --- # useWatchBlockNumber Hook that watches for block number changes. ## Import ```ts import { useWatchBlockNumber } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useWatchBlockNumber } from 'wagmi' function App() { useWatchBlockNumber({ onBlockNumber(blockNumber) { console.log('Block number changed!', blockNumber) }, }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseWatchBlockNumberParameters } from 'wagmi' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to watch blocks at. ::: code-group ```ts [index.ts] import { useWatchBlockNumber } from 'wagmi' function App() { useWatchBlockNumber({ chainId: 1, // [!code focus] onBlockNumber(blockNumber) { console.log('New block number', blockNumber) }, }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```ts [index.ts] import { useWatchBlockNumber } from 'wagmi' import { config } from './config' function App() { useWatchBlockNumber({ config, // [!code focus] onBlockNumber(blockNumber) { console.log('New block number', blockNumber) }, }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### emitMissed `boolean` Whether or not to emit missed blocks to the callback. Defaults to `false`. Missed blocks may occur in instances where internet connection is lost, or the block time is lesser than the polling interval of the client. ::: code-group ```ts [index.ts] import { useWatchBlockNumber } from 'wagmi' function App() { useWatchBlockNumber({ emitMissed: true, // [!code focus] onBlockNumber(blockNumber) { console.log('New block number', blockNumber) }, }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### emitOnBegin `boolean` Whether or not to emit the block to the callback when the subscription opens. Defaults to `false`. ::: code-group ```ts [index.ts] import { useWatchBlockNumber } from 'wagmi' function App() { useWatchBlockNumber({ emitOnBegin: true, // [!code focus] onBlockNumber(blockNumber) { console.log('New block number', blockNumber) }, }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### enabled `boolean` Whether or not to watch for blocks. Defaults to `true`. ::: code-group ```ts [index.ts] import { useWatchBlockNumber } from 'wagmi' function App() { useWatchBlockNumber({ enabled: false, // [!code focus] onBlockNumber(blockNumber) { console.log('New block number', blockNumber) }, }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### onBlockNumber `(block: Block, prevblock: Block | undefined) => void` Callback for when block changes. ::: code-group ```ts [index.ts] import { useWatchBlockNumber } from 'wagmi' function App() { useWatchBlockNumber({ onBlockNumber(blockNumber) { // [!code focus] console.log('New block number', blockNumber) // [!code focus] }, // [!code focus] }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### onError `((error: Error) => void) | undefined` Error thrown from getting the block. ::: code-group ```ts [index.ts] import { useWatchBlockNumber } from 'wagmi' function App() { useWatchBlockNumber({ onBlockNumber(blockNumber) { console.log('New block number', blockNumber) }, onError(error) { // [!code focus] console.error('Block error', error) // [!code focus] }, // [!code focus] }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### poll `boolean | undefined` - Whether or not to use a polling mechanism to check for new blocks instead of a WebSocket subscription. - Defaults to `false` for WebSocket Clients, and `true` for non-WebSocket Clients. ::: code-group ```ts [index.ts] import { useWatchBlockNumber } from 'wagmi' function App() { useWatchBlockNumber({ onBlockNumber(blockNumber) { console.log('New block number', blockNumber) } poll: true, // [!code focus] }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### pollingInterval `number | undefined` - Polling frequency (in milliseconds). - Defaults to the [Config's `pollingInterval` config](/core/api/createConfig#pollinginterval). ::: code-group ```ts [index.ts] import { useWatchBlockNumber } from 'wagmi' function App() { useWatchBlockNumber({ onBlockNumber(blockNumber) { console.log('New block number', blockNumber) } pollingInterval: 1_000, // [!code focus] }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### syncConnectedChain `boolean | undefined` - Set up subscriber for connected chain changes. - Defaults to [`Config['syncConnectedChain']`](/core/api/createConfig#syncconnectedchain). ::: code-group ```ts [index.ts] import { useWatchBlockNumber } from 'wagmi' function App() { useWatchBlockNumber({ onBlockNumber(blockNumber) { console.log('New block number', blockNumber) } syncConnectedChain: false, // [!code focus] }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type UseWatchBlockNumberReturnType } from 'wagmi' ``` Function for cleaning up watcher. ## Action - [`watchBlockNumber`](/core/api/actions/watchBlockNumber) ================================================ FILE: site/react/api/hooks/useWatchBlocks.md ================================================ --- title: useWatchBlocks description: Hook that watches for block changes. --- # useWatchBlocks Hook that watches for block changes. ## Import ```ts import { useWatchBlocks } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useWatchBlocks } from 'wagmi' function App() { useWatchBlocks({ onBlock(block) { console.log('New block', block.number) }, }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseWatchBlocksParameters } from 'wagmi' ``` ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to watch blocks at. ::: code-group ```ts [index.ts] import { useWatchBlocks } from 'wagmi' function App() { useWatchBlocks({ blockTag: 'latest', // [!code focus] onBlock(block) { console.log('New block', block.number) }, }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to watch blocks at. ::: code-group ```ts [index.ts] import { useWatchBlocks } from 'wagmi' function App() { useWatchBlocks({ chainId: 1, // [!code focus] onBlock(block) { console.log('New block', block.number) }, }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```ts [index.ts] import { useWatchBlocks } from 'wagmi' import { config } from './config' function App() { useWatchBlocks({ config, // [!code focus] onBlock(block) { console.log('New block', block.number) }, }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### emitMissed `boolean` Whether or not to emit missed blocks to the callback. Defaults to `false`. Missed blocks may occur in instances where internet connection is lost, or the block time is lesser than the polling interval of the client. ::: code-group ```ts [index.ts] import { useWatchBlocks } from 'wagmi' function App() { useWatchBlocks({ emitMissed: true, // [!code focus] onBlock(block) { console.log('New block', block.number) }, }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### emitOnBegin `boolean` Whether or not to emit the block to the callback when the subscription opens. Defaults to `false`. ::: code-group ```ts [index.ts] import { useWatchBlocks } from 'wagmi' function App() { useWatchBlocks({ emitOnBegin: true, // [!code focus] onBlock(block) { console.log('New block', block.number) }, }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### enabled `boolean` Whether or not to watch for blocks. Defaults to `true`. ::: code-group ```ts [index.ts] import { useWatchBlocks } from 'wagmi' function App() { useWatchBlocks({ enabled: false, // [!code focus] onBlock(block) { console.log('New block', block.number) }, }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### includeTransactions `boolean` Whether or not to unwrap transactions as objects (instead of hashes) in blocks. Defaults to `false`. ::: code-group ```ts [index.ts] import { useWatchBlocks } from 'wagmi' function App() { useWatchBlocks({ includeTransactions: true, // [!code focus] onBlock(block) { console.log('New block', block.number) }, }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### onBlock `(block: Block, prevblock: Block | undefined) => void` Callback for when block changes. ::: code-group ```ts [index.ts] import { useWatchBlocks } from 'wagmi' function App() { useWatchBlocks({ onBlock(block) { // [!code focus] console.log('New block', block.number) // [!code focus] }, // [!code focus] }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### onError `((error: Error) => void) | undefined` Error thrown from getting the block. ::: code-group ```ts [index.ts] import { useWatchBlocks } from 'wagmi' function App() { useWatchBlocks({ onBlock(block) { console.log('New block', block.number) }, onError(error) { // [!code focus] console.error('Block error', error) // [!code focus] }, // [!code focus] }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### poll `boolean | undefined` - Whether or not to use a polling mechanism to check for new blocks instead of a WebSocket subscription. - Defaults to `false` for WebSocket Clients, and `true` for non-WebSocket Clients. ::: code-group ```ts [index.ts] import { useWatchBlocks } from 'wagmi' function App() { useWatchBlocks({ onBlock(block) { console.log('New block', block.number) } poll: true, // [!code focus] }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### pollingInterval `number | undefined` - Polling frequency (in milliseconds). - Defaults to the [Config's `pollingInterval` config](/core/api/createConfig#pollinginterval). ::: code-group ```ts [index.ts] import { useWatchBlocks } from 'wagmi' function App() { useWatchBlocks({ onBlock(block) { console.log('New block', block.number) } pollingInterval: 1_000, // [!code focus] }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ### syncConnectedChain `boolean | undefined` - Set up subscriber for connected chain changes. - Defaults to [`Config['syncConnectedChain']`](/core/api/createConfig#syncconnectedchain). ::: code-group ```ts [index.ts] import { useWatchBlocks } from 'wagmi' function App() { useWatchBlocks({ onBlock(block) { console.log('New block', block.number) } syncConnectedChain: false, // [!code focus] }) } ``` <<< @/snippets/core/config.ts[config.ts] ::: ## Return Type ```ts import { type UseWatchBlocksReturnType } from 'wagmi' ``` ## Action - [`watchBlocks`](/core/api/actions/watchBlocks) ================================================ FILE: site/react/api/hooks/useWatchContractEvent.md ================================================ --- title: useWatchContractEvent description: Hook that watches and returns emitted contract event logs. --- # useWatchContractEvent Hook that watches and returns emitted contract event logs. ## Import ```ts import { useWatchContractEvent } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, eventName: 'Transfer', onLogs(logs) { console.log('New logs!', logs) }, }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseWatchContractEventParameters } from 'wagmi' ``` ### abi `Abi` The contract's ABI. Check out the [TypeScript docs](/react/typescript#const-assert-abis-typed-data) for how to set up ABIs for maximum type inference and safety. ::: code-group ```tsx [index.tsx] import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, // [!code focus] eventName: 'Transfer', onLogs(logs) { console.log('New logs!', logs) }, }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### address `Address | undefined` The contract's address. ::: code-group ```tsx [index.tsx] import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', // [!code focus] abi, eventName: 'Transfer', onLogs(logs) { console.log('New logs!', logs) }, }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### args `object | readonly unknown[] | undefined` - Arguments to pass when calling the contract. - Inferred from [`abi`](#abi) and [`eventName`](#eventname). ::: code-group ```tsx [index.tsx] import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, args: { // [!code focus] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B' // [!code focus] } // [!code focus] eventName: 'Transfer', onLogs(logs) { console.log('New logs!', logs) }, }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### batch `boolean | undefined` - Whether or not the events should be batched on each invocation. - Defaults to `true`. ::: code-group ```tsx [index.tsx] import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, batch: false, // [!code focus] eventName: 'Transfer', onLogs(logs) { console.log('New logs!', logs) }, }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, chainId: 1, // [!code focus] eventName: 'Transfer', onLogs(logs) { console.log('New logs!', logs) }, }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, config, // [!code focus] eventName: 'Transfer', onLogs(logs) { console.log('New logs!', logs) }, }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### eventName `string` - Event to listen for the contract. - Inferred from [`abi`](#abi). ::: code-group ```tsx [index.tsx] import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' import { config } from './config' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, eventName: 'Transfer', // [!code focus] onLogs(logs) { console.log('New logs!', logs) }, }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### onError `((error: Error) => void) | undefined` Error thrown from getting the block number. ::: code-group ```tsx [index.tsx] import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, eventName: 'Transfer', onLogs(logs) { console.log('New logs!', logs) }, onError(error) { // [!code focus] console.log('Error', error) // [!code focus] } // [!code focus] }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### onLogs `(logs: Log[], prevLogs: Log[] | undefined) => void` Callback for when logs changes. ::: code-group ```tsx [index.tsx] import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, eventName: 'Transfer', onLogs(logs) { // [!code focus] console.log('New logs!', logs) // [!code focus] } // [!code focus] }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### poll `boolean | undefined` - Whether or not to use a polling mechanism to check for new blocks instead of a WebSocket subscription. - Defaults to `false` for WebSocket Clients, and `true` for non-WebSocket Clients. ::: code-group ```tsx [index.tsx] import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, eventName: 'Transfer', onLogs(logs) { console.log('New logs!', logs) }, poll: true // [!code focus] }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### pollingInterval `number | undefined` - Polling frequency (in milliseconds). - Defaults to the [Config's `pollingInterval` config](/core/api/createConfig#pollinginterval). ::: code-group ```tsx [index.tsx] import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, eventName: 'Transfer', onLogs(logs) { console.log('New logs!', logs) }, pollingInterval: 1_000 // [!code focus] }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### strict `boolean | undefined` - Defaults to `false`. ::: code-group ```tsx [index.tsx] import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, eventName: 'Transfer', onLogs(logs) { console.log('New logs!', logs) }, strict: true // [!code focus] }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### syncConnectedChain `boolean | undefined` - Set up subscriber for connected chain changes. - Defaults to [`Config['syncConnectedChain']`](/core/api/createConfig#syncconnectedchain). ::: code-group ```tsx [index.tsx] import { useWatchContractEvent } from 'wagmi' import { abi } from './abi' function App() { useWatchContractEvent({ address: '0x6b175474e89094c44da98b954eedeac495271d0f', abi, eventName: 'Transfer', onLogs(logs) { console.log('New logs!', logs) }, syncConnectedChain: true // [!code focus] }) } ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseWatchContractEventReturnType } from 'wagmi' ``` Hook returns `void` ## Action - [`watchContractEvent`](/core/api/actions/watchContractEvent) ================================================ FILE: site/react/api/hooks/useWatchPendingTransactions.md ================================================ --- title: useWatchPendingTransactions description: Hook that watches and returns pending transaction hashes. --- # useWatchPendingTransactions Hook that watches and returns pending transaction hashes. ## Import ```ts import { useWatchPendingTransactions } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useWatchPendingTransactions } from 'wagmi' function App() { useWatchPendingTransactions({ onTransactions(transactions) { console.log('New transactions!', transactions) }, }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseWatchPendingTransactionsParameters } from 'wagmi' ``` ### batch `boolean | undefined` - Whether or not the transactions should be batched on each invocation. - Defaults to `true`. ::: code-group ```tsx [index.tsx] import { useWatchPendingTransactions } from 'wagmi' function App() { useWatchPendingTransactions({ batch: true // [!code focus] onTransactions(transactions) { console.log('New transactions!', transactions) }, }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```tsx [index.tsx] import { useWatchPendingTransactions } from 'wagmi' function App() { useWatchPendingTransactions({ chainId: 1 // [!code focus] onTransactions(transactions) { console.log('New transactions!', transactions) }, }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useWatchPendingTransactions } from 'wagmi' import { config } from './config' function App() { useWatchPendingTransactions({ config // [!code focus] onTransactions(transactions) { console.log('New transactions!', transactions) }, }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### onError `((error: Error) => void) | undefined` Error thrown from watching pending transactions. ::: code-group ```tsx [index.tsx] import { useWatchPendingTransactions } from 'wagmi' function App() { useWatchPendingTransactions({ onError(error) { // [!code focus] console.log('Error', error) // [!code focus] }, // [!code focus] onTransactions(transactions) { console.log('New transactions!', transactions) }, }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### onTransactions `(transactions: Hash[], prevTransactions: Hash[] | undefined) => void` Callback when new incoming pending transactions are detected. ::: code-group ```tsx [index.tsx] import { useWatchPendingTransactions } from 'wagmi' function App() { useWatchPendingTransactions({ onTransactions(transactions) { // [!code focus] console.log('New transactions!', transactions) // [!code focus] }, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### poll `boolean | undefined` - Whether or not to use a polling mechanism to check for new pending transactions instead of a WebSocket subscription. - Defaults to `false` for WebSocket Clients, and `true` for non-WebSocket Clients. ::: code-group ```tsx [index.tsx] import { useWatchPendingTransactions } from 'wagmi' function App() { useWatchPendingTransactions({ onTransactions(transactions) { console.log('New transactions!', transactions) }, poll: true, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### pollingInterval `number | undefined` - Polling frequency (in milliseconds). - Defaults to the [Config's `pollingInterval` config](/core/api/createConfig#pollinginterval). ::: code-group ```tsx [index.tsx] import { useWatchPendingTransactions } from 'wagmi' function App() { useWatchPendingTransactions({ onTransactions(transactions) { console.log('New transactions!', transactions) }, pollingInterval: 1_000, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### syncConnectedChain `boolean | undefined` - Set up subscriber for connected chain changes. - Defaults to [`Config['syncConnectedChain']`](/core/api/createConfig#syncconnectedchain). ::: code-group ```tsx [index.tsx] import { useWatchPendingTransactions } from 'wagmi' function App() { useWatchPendingTransactions({ onTransactions(transactions) { console.log('New transactions!', transactions) }, syncConnectedChain: false, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseWatchPendingTransactionsReturnType } from 'wagmi' ``` ## Action - [`watchPendingTransactions`](/core/api/actions/watchPendingTransactions) ================================================ FILE: site/react/api/hooks/useWriteContract.md ================================================ --- title: useWriteContract description: Action for executing a write function on a contract. --- # useWriteContract Action for executing a write function on a contract. A "write" function on a Solidity contract modifies the state of the blockchain. These types of functions require gas to be executed, hence a transaction is broadcasted in order to change the state. ## Import ```ts import { useWriteContract } from 'wagmi' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useWriteContract } from 'wagmi' import { abi } from './abi' function App() { const writeContract = useWriteContract() return ( ) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ### Synchronous Usage If you want to wait for the transaction to be included in a block, you can use `useWriteContractSync`: ::: code-group ```tsx [index.tsx] import { useWriteContractSync } from 'wagmi' import { abi } from './abi' function App() { const writeContractSync = useWriteContractSync() return ( ) } ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseWriteContractParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useWriteContract } from 'wagmi' import { config } from './config' // [!code focus] function App() { const writeContract = useWriteContract({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseWriteContractReturnType } from 'wagmi' ``` The return type's [`data`](#data) property is inferrable via the combination of [`abi`](#abi), [`functionName`](#functionname), and [`args`](#args). Check out the [TypeScript docs](/react/typescript#const-assert-abis-typed-data) for more info. ## Type Inference With [`abi`](/core/api/actions/writeContract#abi) setup correctly, TypeScript will infer the correct types for [`functionName`](/core/api/actions/writeContract#functionname), [`args`](/core/api/actions/writeContract#args), and the [`value`](/core/api/actions/writeContract##value). See the Wagmi [TypeScript docs](/react/typescript) for more information. ## Action - [`writeContract`](/core/api/actions/writeContract) ================================================ FILE: site/react/api/hooks/useWriteContracts.md ================================================ --- title: useWriteContracts description: Hook that requests for the wallet to sign and broadcast a batch of calls (transactions) to the network. --- # useWriteContracts Hook that requests for the wallet to sign and broadcast a batch of write contract calls (transactions) to the network. [Read more.](https://github.com/ethereum/EIPs/blob/815028dc634463e1716fc5ce44c019a6040f0bef/EIPS/eip-5792.md#wallet_sendcalls) ## Import ```ts import { useWriteContracts } from 'wagmi/experimental' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useWriteContracts } from 'wagmi/experimental' import { parseAbi } from 'viem' const abi = parseAbi([ 'function approve(address, uint256) returns (bool)', 'function transferFrom(address, address, uint256) returns (bool)', ]) function App() { const { writeContracts } = useWriteContracts() return ( ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseWriteContractsParameters } from 'wagmi/experimental' ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```tsx [index.tsx] import { useWriteContracts } from 'wagmi/experimental' import { config } from './config' // [!code focus] function App() { const result = useWriteContracts({ config, // [!code focus] }) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseWriteContractsReturnType } from 'wagmi/experimental' ``` ## Action - [`writeContracts`](/core/api/actions/writeContracts) ================================================ FILE: site/react/api/hooks.md ================================================ # Hooks React Hooks for accounts, wallets, contracts, transactions, signing, ENS, and more. ## Import ```ts import { useConnection } from 'wagmi' ``` ## Available Hooks ================================================ FILE: site/react/api/transports/custom.md ================================================ --- title: custom --- ================================================ FILE: site/react/api/transports/fallback.md ================================================ --- title: fallback --- ================================================ FILE: site/react/api/transports/http.md ================================================ --- title: http --- ================================================ FILE: site/react/api/transports/unstable_connector.md ================================================ --- title: unstable_connector --- ================================================ FILE: site/react/api/transports/webSocket.md ================================================ --- title: webSocket --- ================================================ FILE: site/react/api/transports.md ================================================ # Transports [`createConfig`](/react/api/createConfig) can be instantiated with a set of Transports for each chain. A Transport is the intermediary layer that is responsible for executing outgoing JSON-RPC requests to the RPC Provider (e.g. Alchemy, Infura, etc). ## Import ```ts import { http } from 'wagmi' ``` ## Built-In Transports Available via the `'wagmi'` entrypoint. ================================================ FILE: site/react/api/utilities/cookieToInitialState.md ================================================ --- title: cookieToInitialState --- ================================================ FILE: site/react/api/utilities/deserialize.md ================================================ --- title: deserialize --- ================================================ FILE: site/react/api/utilities/serialize.md ================================================ --- title: serialize --- ================================================ FILE: site/react/comparisons.md ================================================ # Comparison There are multiple options when it comes to React libraries for Ethereum that help manage wallet connections, provide utility methods/hooks, etc. ::: tip Comparisons strive to be as accurate and as unbiased as possible. If you use any of these libraries and feel the information could be improved, feel free to suggest changes. ::: ## Overview | | [wagmi](https://github.com/wagmi-dev/wagmi) | [web3-react](https://github.com/NoahZinsmeister/web3-react) | [useDApp](https://github.com/EthWorks/useDApp) | | -------------------- | :---------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------- | | GitHub Stars | ![wagmi star count](https://img.shields.io/github/stars/wagmi-dev/wagmi?colorB=27292E&label=) | ![web3-react star count](https://img.shields.io/github/stars/Uniswap/web3-react?colorB=27292E&label=) | ![useDApp star count](https://img.shields.io/github/stars/EthWorks/useDApp?colorB=27292E&label=) | | Open Issues | ![wagmi issue count](https://img.shields.io/github/issues/wagmi-dev/wagmi?colorB=27292E&label=) | ![web3-react issue count](https://img.shields.io/github/issues/Uniswap/web3-react?colorB=27292E&label=) | ![useDApp issue count](https://img.shields.io/github/issues/EthWorks/useDApp?colorB=27292E&label=) | | Downloads | ![wagmi downloads](https://img.shields.io/npm/dw/wagmi?colorB=27292E&label=) | ![web3-react downloads](https://img.shields.io/npm/dw/@web3-react/core?colorB=27292E&label=) | ![useDApp downloads](https://img.shields.io/npm/dw/@usedapp/core?colorB=27292E&label=) | | License | ![wagmi license](https://img.shields.io/github/license/wagmi-dev/wagmi?colorB=27292E&label=) | ![web3-react license](https://img.shields.io/github/license/Uniswap/web3-react?colorB=27292E&label=) | ![useDApp license](https://img.shields.io/github/license/EthWorks/useDApp?colorB=27292E&label=) | | Their Comparison | – | none | none | | Supported Frameworks | React, Vanilla JS | React | React | | Documentation | ✅ | 🛑 | ✅ | | TypeScript | ✅ | 🔶 | 🔶 | | EIP-6963 Support | ✅ | 🔴 | 🔴 | | Test Suite | ✅ | 🔶 | 🔶 | | Examples | ✅ | 🔶 | ✅ | ::: details Comparison Key 1. Documentation - Comprehensive documentation for all library features ✅ - No documentation 🔴 2. Typescript - Infer types from ABIs, EIP-712 Typed Data, etc. ✅ - Can add types with explicit generics, type annotations, etc. 🔶 3. Test Suite - Runs against forked Ethereum network(s) ✅ - Mocking functionality (i.e. RPC calls) is 🔶 4. EIP-6963 Support - Fully compatible with EIP-6963 ✅ - Not compatible with EIP-6963 🔴 5. Examples - Has multiple examples ✅ - Has single example 🔶 ::: ## [Wagmi](https://github.com/wagmi-dev/wagmi) ### Pros - 20+ hooks for working with wallets, ENS, contracts, transactions, signing, etc. - Built-in wallet connectors for injected providers (EIP-6963 support), WalletConnect, MetaMask, Coinbase Wallet - Caching, request deduplication, and persistence powered by TanStack Query - Auto-refresh data on wallet, block, and network changes - Multicall support - Test suite running against forked Ethereum networks - TypeScript ready (infer types from ABIs and EIP-712 Typed Data) - Extensive documentation and examples - Used by Coinbase, Stripe, Shopify, Uniswap, Optimism, ENS, Sushi, and [many more](https://github.com/wagmi-dev/wagmi/discussions/201) - MIT License ### Cons - Not as many built-in connectors as `web3-react` ## [web3-react](https://github.com/Uniswap/web3-react) ### Pros - Supports many different connectors (conceptually similar to Wagmi's connectors) - Basic hooks for managing account ### Cons - Need to set up connectors and method for connecting wallet on your own - Need to install connectors separately - Almost no tests or documentation; infrequent updates - GPL-3.0 License ## [useDApp](https://github.com/EthWorks/useDApp) ### Pros - Auto-refresh on new blocks and wallet changes - Multicall support - Transaction notifications - Chrome extension and Firefox add-on - MIT License ### Cons - Non-standard hook API ================================================ FILE: site/react/getting-started.md ================================================ # Getting Started ## Overview Wagmi is a React Hooks library for Ethereum. You can learn more about the rationale behind the project in the [Why Wagmi](/react/why) section. ## Automatic Installation For new projects, it is recommended to set up your Wagmi app using the [`create-wagmi`](/cli/create-wagmi) command line interface (CLI). This will create a new Wagmi project using TypeScript and install the required dependencies. ::: code-group ```bash [pnpm] pnpm create wagmi ``` ```bash [npm] npm create wagmi@latest ``` ```bash [yarn] yarn create wagmi ``` ```bash [bun] bun create wagmi ``` ::: Once the command runs, you'll see some prompts to complete. ```ansi Project name: wagmi-project Select a framework: React / Vanilla ... ``` After the prompts, `create-wagmi` will create a directory with your project name and install the required dependencies. Check out the `README.md` for further instructions (if required). ## Manual Installation To manually add Wagmi to your project, install the required packages. ::: code-group ```bash-vue [pnpm] pnpm add wagmi viem@{{viemVersion}} @tanstack/react-query ``` ```bash-vue [npm] npm install wagmi viem@{{viemVersion}} @tanstack/react-query ``` ```bash-vue [yarn] yarn add wagmi viem@{{viemVersion}} @tanstack/react-query ``` ```bash-vue [bun] bun add wagmi viem@{{viemVersion}} @tanstack/react-query ``` ::: - [Viem](https://viem.sh) is a TypeScript interface for Ethereum that performs blockchain operations. - [TanStack Query](https://tanstack.com/query/v5) is an async state manager that handles requests, caching, and more. - [TypeScript](/react/typescript) is optional, but highly recommended. Learn more about [TypeScript support](/react/typescript). ### Create Config Create and export a new Wagmi config using `createConfig`. ::: code-group <<< @/snippets/react/config.ts[config.ts] ::: In this example, Wagmi is configured to use the Mainnet and Sepolia chains, and `injected` connector. Check out the [`createConfig` docs](/react/api/createConfig) for more configuration options. ::: details TypeScript Tip If you are using TypeScript, you can "register" the Wagmi config or use the hook `config` property to get strong type-safety across React Context in places that wouldn't normally have type info. ::: code-group ```ts twoslash [register config] // @twoslash-cache: {"v":1,"hash":"1e950b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TBmtxFjM1pc8V49Ktg11nE2XmDRRwwjhH8YW3DxZV3BjLQkxJ2iKzgFSGkKLYZwyZUyLWUdOS615AKYUYoJRSllPKJUngLaam1JYm2dt87GiLuaF2vBrS2ntPan2nrNVkoDt6NgId1WwwptqyOeNo4xjjDABMSYUzpkzOCbMuZ8yFh0BncslZqx5zKODR2zrLSl07Gmbs3rBUHxHGODQwMpzDlnC3F87dNzbn7r3fuQDh7TzMuiR8pBnxt3wI5Ues9fz/kAsBUCK9VJrzgghbeKE0JBAwkGkIb98IdOIfNSEaYTl9O3dQOhQz5GfWMGMxRe7DrTKKXyN5CyPnXWqT8o9I0hIQpcMe6FZK4WpARUDOIMqGXgwxdDZdYccWI1FSjLlNLs2MrJTjU45wqrUseHS71pLhjMopWyqq1xOVoxQ7yg4MGy3/R5qCUV/MJXvClaLf92KyXyrlkq1gFIVXK1IFih1IZQ2sl1fqg1BtjXGzNWbS1aprXW25DB9D7o82thdW6j2XsGW+xk9UP1QcA3+hA/RjDPHta0GrFGmNCd43J2TWnNNpYM3Zyzfy4NDsnXyYLfyItJaq4kewhWvkDcgmHzSPW/tHdm3dyRK20LA9Tznifl28evbJ5NUHc/J6I6F7juXhBKd0EZ3xOQrvRd+93irpPOuw5xS+Q33IdI3dFyrnDNcKepA56pmFPmjKY+B0FFaLAdlJIkDmE/2rgIMdzikHAScUEIITDv5cUYMAQixFSKtLFQqau3BJuIR3FeIJVaoD5CCU4sb7B3ESwMhs1E2yYC7NvCB8FJhEhlJgBAfgL6TD9A+IuoqN5mBIFAOYGWEgwB4H0R8D4QA==="} // @errors: 2322 import { type Config } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' declare const config: Config // ---cut--- import { useBlockNumber } from 'wagmi' useBlockNumber({ chainId: 123 }) declare module 'wagmi' { interface Register { config: typeof config } } ``` ```ts twoslash [hook config property] // @twoslash-cache: {"v":1,"hash":"849a5652cb34072baf13797118507e525565a80b04851946389914c2dc341926","data":"N4Igdg9gJgpgziAXAbV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Ajt6uepIJsqq7Koc5SHJldxumMXoBimrZZq64CyvK57rnmOEeU1V40HeL4fjG8qQTBCEoRhNV4V5U0qBREQ0UHbd8SJElyUpalaXpJcWRO9lOURj0+SoAVhgYRA5QNEBxUlaVEHlRVhmVXmQAJpHEW1B6kDfQ0vH/U19QtK0cDwMg9vtbmhUQHiyLFYJhaQY3YmgXVWLfJWQCMcUtjwHxYFoMkAKRHJtdIUgAFobbff25TlX2yKRGh6Dwb4cF4AByd8WNj3h2GsSAYS4OATGraNarQCBeEwGP45+gH/ocn7hFzHUoFjskkSaEhWG93X651RXlc2E1yFFsiNeoa10VtYmHUj9FBj2nBoQwPhDj8OTKtY/lBV5o2TYlKVzfF0hJbwWf/FbhXEDto06QmWVe8tfutcH4hh4jqXx4gSfMBn1xZm9CI/TM7MwxAyTlDjAmGqyZXqoVMilcyuZ8yFmMklLS1YxgDnrGOSYTYWwgEKmhb+vZVwDk3EOHcB5UETinBgmcnYtJLhXGuDcW5hynn3A2YhR4JCnkSmWUqkZOERn/k+RBC9Px6kKr+f8gFoYUOwWYBIUF2AwTgvARCyFQFJWSguCymFsI2XwsRYipEKLUVovRRizE2K0k4txPiAkhJkLAZpSR/8MrtEevJFiillI8VUuQ28mDwFqJ0oWdg+lDKwJMpQjR1kBx2Uio5Zyrl3KeR8n5AKQUQphQilFGKZE4rRPYSJLSDiZLOMqjlHieUCpeN4NwyphV6rFOqjSOqsMOxNRau1SkXUep9XYANd+w1RrjUmpsGaOxZgLVIEtNp+BVoQx2Jtbau19op1+MdU6zYLrXUrndauz13DiIjO9UEZpPpLx5ubQGgtTYb0QF5LeO90RhAiAfa2HdVbd18kcw0Vtna42hEBN06oEQZEqQIPaGg47U1JLHUEoIZYczIIwYAHgShz1fKxA4rhKncCRDNZgSBQDmAghIMAeAPZmjNEAA"} // @errors: 2322 import { type Config } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' declare const config: Config // ---cut--- import { useBlockNumber } from 'wagmi' useBlockNumber({ chainId: 123, config }) ``` By registering or using the hook `config` property, `useBlockNumber`'s `chainId` is strongly typed to only allow Mainnet and Sepolia IDs. Learn more by reading the [TypeScript docs](/react/typescript#config-types). ::: ### Wrap App in Context Provider Wrap your app in the `WagmiProvider` React Context Provider and pass the `config` you created earlier to the `config` property. ::: code-group ```tsx [app.tsx] import { WagmiProvider } from 'wagmi' // [!code focus] import { config } from './config' // [!code focus] function App() { return ( // [!code focus] {/** ... */} // [!code focus] // [!code focus] ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: Check out the [`WagmiProvider` docs](/react/api/WagmiProvider) to learn more about React Context in Wagmi. ### Setup TanStack Query Inside the `WagmiProvider`, wrap your app in a TanStack Query React Context Provider, e.g. `QueryClientProvider`, and pass a new `QueryClient` instance to the `client` property. ::: code-group ```tsx [app.tsx] import { QueryClient, QueryClientProvider } from '@tanstack/react-query' // [!code focus] import { WagmiProvider } from 'wagmi' import { config } from './config' const queryClient = new QueryClient() // [!code focus] function App() { return ( // [!code focus] {/** ... */} // [!code focus] // [!code focus] ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: Check out the [TanStack Query docs](https://tanstack.com/query/latest/docs/framework/react/overview) to learn about the library, APIs, and more. ### Use Wagmi Now that everything is set up, every component inside the Wagmi and TanStack Query Providers can use Wagmi React Hooks. ::: code-group ```tsx [profile.tsx] import { useConnection, useEnsName } from 'wagmi' export function Profile() { const { address } = useConnection() const { data, error, status } = useEnsName({ address }) if (status === 'pending') return
Loading ENS name
if (status === 'error') return
Error fetching ENS name: {error.message}
return
ENS name: {data}
} ``` ```tsx [app.tsx] import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { WagmiProvider } from 'wagmi' import { config } from './config' import { Profile } from './profile' const queryClient = new QueryClient() function App() { return ( ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Next Steps For more information on what to do next, check out the following topics. - [**TypeScript**](/react/typescript) Learn how to get the most out of Wagmi's type-safety and inference for an enlightened developer experience. - [**Connect Wallet**](/react/guides/connect-wallet) Learn how to enable wallets to connect to and disconnect from your apps and display information about connected accounts. - [**React Hooks**](/react/api/hooks) Browse the collection of React Hooks and learn how to use them. - [**Viem**](/react/guides/viem) Learn about Viem and how it works with Wagmi. ================================================ FILE: site/react/guides/chain-properties.md ================================================ # Chain Properties Some chains support additional properties related to blocks and transactions. This is powered by Viem's [formatters](https://viem.sh/docs/chains/formatters) and [serializers](https://viem.sh/docs/chains/serializers). For example, Celo, ZkSync, OP Stack chains all support additional properties. In order to use these properties in a type-safe way, there are a few things you should be aware of.
::: tip Make sure you follow the TypeScript guide's [Config Types](/react/typescript#config-types) section before moving on. The easiest way to do this is to use [Declaration Merging](/react/typescript#declaration-merging) to "register" your `config` globally with TypeScript. <<< @/snippets/react/config-chain-properties.ts[config.ts] ::: ## Narrowing Parameters Once your Config is registered with TypeScript, you are ready to access chain-specific properties! For example, Celo's `feeCurrency` is available. ::: code-group ```ts [index.tsx] import { parseEther } from 'viem' import { useSimulateContract } from 'wagmi' const result = useSimulateContract({ to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), feeCurrency: '0x…', // [!code focus] }) ``` <<< @/snippets/react/config-chain-properties.ts[config.ts] ::: This is great, but if you have multiple chains that support additional properties, your autocomplete could be overwhelmed with all of them. By setting the `chainId` property to a specific value (e.g. `celo.id`), you can narrow parameters to a single chain. ::: code-group ```ts [index.tsx] import { parseEther } from 'viem' import { useSimulateContract } from 'wagmi' import { celo } from 'wagmi/chains' const result = useSimulateContract({ to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), chainId: celo.id, // [!code focus] feeCurrency: '0x…', // [!code focus] // ^? (property) feeCurrency?: `0x${string}` | undefined // [!code focus] }) ``` <<< @/snippets/react/config-chain-properties.ts[config.ts] ::: ## Narrowing Return Types Return types can also have chain-specific properties attached to them. There are a couple approaches for extracting these properties. ### `chainId` Parameter Not only can you use the `chainId` parameter to [narrow parameters](#narrowing-parameters), you can also use it to narrow the return type. ::: code-group ```ts [index.tsx] import { useWaitForTransactionReceipt } from 'wagmi' import { zkSync } from 'wagmi/chains' const { data } = useWaitForTransactionReceipt({ chainId: zkSync.id, hash: '0x16854fcdd0219cacf5aec5e4eb2154dac9e406578a1510a6fc48bd0b67e69ea9', }) data?.logs // ^? (property) logs: ZkSyncLog[] | undefined ``` <<< @/snippets/react/config-chain-properties.ts[config.ts] ::: ### `chainId` Data Property Wagmi internally will set a `chainId` property on return types that you can use to narrow results. The `chainId` is determined from the `chainId` parameter or global state (e.g. connector). You can use this property to help TypeScript narrow the type. ::: code-group ```ts [index.tsx] import { useWaitForTransactionReceipt } from 'wagmi' import { zkSync } from 'wagmi/chains' const { data } = useWaitForTransactionReceipt({ hash: '0x16854fcdd0219cacf5aec5e4eb2154dac9e406578a1510a6fc48bd0b67e69ea9', }) if (data?.chainId === zkSync.id) { data?.logs // ^? (property) logs: ZkSyncLog[] | undefined } ``` <<< @/snippets/react/config-chain-properties.ts[config.ts] ::: ## Troubleshooting If chain properties aren't working, make sure [TypeScript](/react/guides/faq#type-inference-doesn-t-work) is configured correctly. Not all chains have additional properties, to check which ones do, see the [Viem repo](https://github.com/wevm/viem/tree/main/src/chains) (chains that have a top-level directory under [`src/chains`](https://github.com/wevm/viem/tree/main/src/chains) support additional properties). ================================================ FILE: site/react/guides/connect-wallet.md ================================================ # Connect Wallet The ability for a user to connect their wallet is a core function for any Dapp. It allows users to perform tasks such as: writing to contracts, signing messages, or sending transactions. Wagmi contains everything you need to get started with building a Connect Wallet module. To get started, you can either use a [third-party library](#third-party-libraries) or [build your own](#build-your-own). ## Third-party Libraries You can use a pre-built Connect Wallet module from a third-party library such as: - [ConnectKit](https://docs.family.co/connectkit) - [Guide](https://docs.family.co/connectkit/getting-started) - [Dynamic](https://www.dynamic.xyz/) - [Guide](https://docs.dynamic.xyz/quickstart) - [Privy](https://privy.io) - [Guide](https://docs.privy.io/guide/react/wallets/usage/wagmi) The above libraries are all built on top of Wagmi, handle all the edge cases around wallet connection, and provide a seamless Connect Wallet UX that you can use in your Dapp. ## Build Your Own Wagmi provides you with the Hooks to get started building your own Connect Wallet module. It takes less than five minutes to get up and running with Browser Wallets, WalletConnect, and Coinbase Wallet. ### 1. Configure Wagmi Before we get started with building the functionality of the Connect Wallet module, we will need to set up the Wagmi configuration. Let's create a `config.ts` file and export a `config` object. ::: code-group ```tsx [config.ts] import { http, createConfig } from 'wagmi' import { base, mainnet, optimism } from 'wagmi/chains' import { injected, metaMask, safe, walletConnect } from 'wagmi/connectors' const projectId = '' export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), }, }) ``` ::: In the above configuration, we want to set up connectors for Injected (browser), WalletConnect (browser + mobile), MetaMask, and Safe wallets. This configuration uses the **Mainnet** and **Base** chains, but you can use whatever you want. ::: warning Make sure to replace the `projectId` with your own WalletConnect Project ID, if you wish to use WalletConnect! [Get your Project ID](https://cloud.reown.com/) ::: ### 2. Wrap App in Context Provider Next, we will need to wrap our React App with Context so that our application is aware of Wagmi & React Query's reactive state and in-memory caching. ::: code-group ```tsx [app.tsx] // 1. Import modules import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { WagmiProvider } from 'wagmi' import { config } from './config' // 2. Set up a React Query client. const queryClient = new QueryClient() function App() { // 3. Wrap app with Wagmi and React Query context. return ( {/** ... */} ) } ``` ```tsx [config.ts] import { http, createConfig } from 'wagmi' import { base, mainnet, optimism } from 'wagmi/chains' import { injected, metaMask, safe, walletConnect } from 'wagmi/connectors' const projectId = '' export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), }, }) ``` ::: ### 3. Display Wallet Options After that, we will create a `WalletOptions` component that will display our connectors. This will allow users to select a wallet and connect. Below, we are rendering a list of `connectors` retrieved from `useConnect`. When the user clicks on a connector, the `connect` function will connect the users' wallet. ::: code-group ```tsx [wallet-options.tsx] import * as React from 'react' import { Connector, useConnect, useConnectors } from 'wagmi' export function WalletOptions() { const { connect } = useConnect() const connectors = useConnectors() return connectors.map((connector) => ( )) } ``` ```tsx [app.tsx] // 1. Import modules import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { WagmiProvider } from 'wagmi' import { config } from './config' // 2. Set up a React Query client. const queryClient = new QueryClient() function App() { // 3. Wrap app with Wagmi and React Query context. return ( {/* ... */} ) } ``` ```tsx [config.ts] import { http, createConfig } from 'wagmi' import { base, mainnet, optimism } from 'wagmi/chains' import { injected, metaMask, safe, walletConnect } from 'wagmi/connectors' const projectId = '' export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), }, }) ``` ::: ### 4. Display Connection Lastly, if an connection is made, we want to show some basic information, like the connected address and ENS name and avatar. Below, we are using hooks like `useConnection`, `useEnsAvatar` and `useEnsName` to extract this information. We are also utilizing `useDisconnect` to show a "Disconnect" button so a user can disconnect their wallet. ::: code-group ```tsx [connection.tsx] import { useConnection, useDisconnect, useEnsAvatar, useEnsName } from 'wagmi' export function Connection() { const { address } = useConnection() const { disconnect } = useDisconnect() const { data: ensName } = useEnsName({ address }) const { data: ensAvatar } = useEnsAvatar({ name: ensName! }) return (
{ensAvatar && ENS Avatar} {address &&
{ensName ? `${ensName} (${address})` : address}
}
) } ``` ```tsx [wallet-options.tsx] import * as React from 'react' import { Connector, useConnect, useConnectors } from 'wagmi' export function WalletOptions() { const { connect } = useConnect() const connectors = useConnectors() return connectors.map((connector) => ( connect({ connector })} /> )) } function WalletOption({ connector, onClick, }: { connector: Connector onClick: () => void }) { const [ready, setReady] = React.useState(false) React.useEffect(() => { ;(async () => { const provider = await connector.getProvider() setReady(!!provider) })() }, [connector]) return ( ) } ``` ```tsx [app.tsx] // 1. Import modules import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { WagmiProvider } from 'wagmi' import { config } from './config' // 2. Set up a React Query client. const queryClient = new QueryClient() function App() { // 3. Wrap app with Wagmi and React Query context. return ( {/* ... */} ) } ``` ```tsx [config.ts] import { http, createConfig } from 'wagmi' import { base, mainnet, optimism } from 'wagmi/chains' import { injected, metaMask, safe, walletConnect } from 'wagmi/connectors' const projectId = '' export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), }, }) ``` ::: ### 5. Wire it up! Finally, we can wire up our Wallet Options and Connection components to our application's entrypoint. ::: code-group ```tsx [app.tsx] import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { WagmiProvider, useConnection } from 'wagmi' import { config } from './config' import { Connection } from './connection' // [!code ++] import { WalletOptions } from './wallet-options' // [!code ++] const queryClient = new QueryClient() function ConnectWallet() { // [!code ++] const { isConnected } = useConnection() // [!code ++] if (isConnected) return // [!code ++] return // [!code ++] } // [!code ++] function App() { return ( // [!code ++] ) } ``` ```tsx [connection.tsx] import { useConnection, useDisconnect, useEnsAvatar, useEnsName } from 'wagmi' export function Connection() { const { address } = useConnection() const { disconnect } = useDisconnect() const { data: ensName } = useEnsName({ address }) const { data: ensAvatar } = useEnsAvatar({ name: ensName! }) return (
{ensAvatar && ENS Avatar} {address &&
{ensName ? `${ensName} (${address})` : address}
}
) } ``` ```tsx [wallet-options.tsx] import * as React from 'react' import { Connector, useConnect, useConnectors } from 'wagmi' export function WalletOptions() { const { connect } = useConnect() const connectors = useConnectors() return connectors.map((connector) => ( connect({ connector })} /> )) } function WalletOption({ connector, onClick, }: { connector: Connector onClick: () => void }) { const [ready, setReady] = React.useState(false) React.useEffect(() => { ;(async () => { const provider = await connector.getProvider() setReady(!!provider) })() }, [connector]) return ( ) } ``` ```tsx [config.ts] import { http, createConfig } from 'wagmi' import { base, mainnet, optimism } from 'wagmi/chains' import { injected, metaMask, safe, walletConnect } from 'wagmi/connectors' const projectId = '' export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), }, }) ``` ::: ### Playground Want to see the above steps all wired up together in an end-to-end example? Check out the below StackBlitz playground.
================================================ FILE: site/react/guides/error-handling.md ================================================ # Error Handling The `error` property in Wagmi Hooks is strongly typed with it's corresponding error type. This enables you to have granular precision with handling errors in your application. You can discriminate the error type by using the `name` property on the error object. ::: code-group ```tsx twoslash [index.tsx] // @twoslash-cache: {"v":1,"hash":"f5cf0003ac91d32dabedd71106481b4f3cd10de7f641dff78f479b328c2716e9","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgAhVhBEBrAHKCAtgCMyAHhGT+7AOa86NMFDi8AwoZO8AvLfvGKvEfmbswASShm9DCW1gZgRsbIADognt5gcDEAushgmjqkKTHsUMlOHq7RsV4+iSApadpkWSA5ye6yrDBiACLMaMz5WiY+aAB8jFjMpMwaMDSkcAD8iLwAqrIKSmrpZAAKw6PjZHD6ru5xPv4NME2t7cx93LML8ooq6lWkAErjgqRgACrYMLqNzWg2h0+lEwOwNFgIKQ0NJFvcVk9KCAoEoEIgCGg0Fg4IgAPS4gDuzGMGnYADo4PhcaQYMwxLjmFh2LjCBBlHBcTI7stHhkkXAOtCkABOKhNMDGND4JAARgALFRBcZxnguUsHqtyGKfLhEAAGKhxEZiMgigC+FHQPzwhBIWuo5jwQlE4kkvAAglgsIxrrxXnS0GSAFIAZQAGmSAKJNMZgGEAH2klhgRjAMCg/MFDEQctFIHFkuliAAzIrhsrsyBPVgkRw00gAEyGrzGibmy3Ua3o22mxWO9FhAW8KAXWbdYy9XiJ4SwVPppEokRokCffAwXisLgwuCCEQieBwISsVgYXg0uAQVgkAIjjoCKG8KXrgCOgjIGDJmeG2YAbAB2MVgkLJAFWocsVXRW9mFrHUkFLYpNhNchEBlPULStHAbWIXsHXoPBBxhMhSChWYAHFxnVBEMkjUhiNIb4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Y6vZE6KaxpY4gbMkvHeHk7DAeo4kxAiZ+qwDibQmSawngms7yYsnKZsk85qbybs6ZoJxc4ynIq86fG/r0ohgEi3yeCQkC7vx6g9HULEE0wQF/gTTbGOYD6K5bDIGHHO7q6T6YHrTYFOFe4JAwgGCwCzAaTFiQF6jOTB5+mmFjRWlTTOGwDIF5hHEq7J6DrsGxQekFDem8C+n+mBmS7ZjBm97y7UERntoNL1bRkOmJ4NgOGdJ+YuF0SzAo70nUY8YpEFnCJ5RcTF5RKl4JblQJJJI1QzHpYZJZLzHN5LFdQlJrFm7Fh+k5lVZ5meRD70HFkJ7IQNgyjlmp5dacE3GP58Fr5xgb5wBCE74iFiFH7cEBhkhn4yFQDf536KGSFP5yEqHsBqGf6aF/6GH9BAH6FaEfl9BBnORUHbFwHWmQSWGx4Niq4lnIQYFtZa4Vlp5JlekwA+l+l6gBlBnd7TnNqzmxSRngWQVLkgRyhrkz4jpXG9aL73k7kCGb7EofmiGIESHnmXkX7XlyG3kP73nKGYiqEf4aHfnvlHk6Ffk34GFCXgGZlwTCgWkUHAXhkIFgWFmNgEUeYuSrlJCGjQCOLcIbJVx8IhZNxmgCDEQaC8AADkRIJI7AZloIoIzoYg0qHoXoPoVcsM/mwAw4Fw7gBURlzgJiAiGQPotlmM8kUwZIbawVkV6C0V70SSjAoV4VWwTgjgzgZlWeOedEZlfA1c9M3uHltBvAvlqWUVnMNILCHwvAugiBfQ7oehnwawqWhUe47wNIUAh8fM0ehuwAtBZouguI1VsMZosMcVCVbayVqVtZVG6ONGOaWVrl4c7lyZ64RV8kwVnMzsZVrClV1Vzw8KG4dJgQ9ZbVLgKZwASFvV/Vh+IImMQ1mM+I38oIZoSIj00EiAoA5gwQB5kgeAhktAIAZoZoQAA=="} // @noErrors import { useBlockNumber } from 'wagmi' function App() { const { data, error } = useBlockNumber() // ^? error?.name // ^? if (error?.name === 'HttpRequestError') { const { status } = error // ^? return
A HTTP error occurred. Status: {status}
} if (error?.name === 'LimitExceededRpcError') { const { code } = error // ^? return
Rate limit exceeded. Code: {code}
} // ... } ``` <<< @/snippets/react/config.ts[config.ts] ::: ================================================ FILE: site/react/guides/ethers.md ================================================ # Ethers.js Adapters It is recommended for projects to migrate to [Viem](https://viem.sh) when using Wagmi, but there are some cases where you might still need to use [Ethers.js](https://ethers.org) in your project: - You may want to **incrementally migrate** Ethers.js usage to Viem - Some **third-party libraries & SDKs** may only support Ethers.js - Personal preference We have provided reference implementations for Viem → Ethers.js adapters that you can copy + paste in your project. ## Client → Provider ### Reference Implementation Copy the following reference implementation into a file of your choice: ::: code-group ```ts [Ethers v5] import { providers } from 'ethers' import { useMemo } from 'react' import type { Chain, Client, Transport } from 'viem' import { Config, useClient } from 'wagmi' export function clientToProvider(client: Client) { const { chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } if (transport.type === 'fallback') return new providers.FallbackProvider( (transport.transports as ReturnType[]).map( ({ value }) => new providers.JsonRpcProvider(value?.url, network), ), ) return new providers.JsonRpcProvider(transport.url, network) } /** Hook to convert a viem Client to an ethers.js Provider. */ export function useEthersProvider({ chainId, }: { chainId?: number | undefined } = {}) { const client = useClient({ chainId }) return useMemo(() => (client ? clientToProvider(client) : undefined), [client]) } ``` ```ts [Ethers v6] import { FallbackProvider, JsonRpcProvider } from 'ethers' import { useMemo } from 'react' import type { Chain, Client, Transport } from 'viem' import { type Config, useClient } from 'wagmi' export function clientToProvider(client: Client) { const { chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } if (transport.type === 'fallback') { const providers = (transport.transports as ReturnType[]).map( ({ value }) => new JsonRpcProvider(value?.url, network), ) if (providers.length === 1) return providers[0] return new FallbackProvider(providers) } return new JsonRpcProvider(transport.url, network) } /** Action to convert a viem Client to an ethers.js Provider. */ export function useEthersProvider({ chainId }: { chainId?: number } = {}) { const client = useClient({ chainId }) return useMemo(() => (client ? clientToProvider(client) : undefined), [client]) } ``` ::: ### Usage Now you can use the `useEthersProvider` function in your components: ::: code-group ```ts [example.ts] import { useEthersProvider } from './ethers' function Example() { const provider = useEthersProvider() ... } ``` ```ts [ethers.ts (Ethers v5)] import { providers } from 'ethers' import { useMemo } from 'react' import type { Chain, Client, Transport } from 'viem' import { Config, useClient } from 'wagmi' export function clientToProvider(client: Client) { const { chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } if (transport.type === 'fallback') return new providers.FallbackProvider( (transport.transports as ReturnType[]).map( ({ value }) => new providers.JsonRpcProvider(value?.url, network), ), ) return new providers.JsonRpcProvider(transport.url, network) } /** Hook to convert a viem Client to an ethers.js Provider. */ export function useEthersProvider({ chainId, }: { chainId?: number | undefined } = {}) { const client = useClient({ chainId }) return useMemo(() => (client ? clientToProvider(client) : undefined), [client]) } ``` ```ts [ethers.ts (Ethers v6)] import { FallbackProvider, JsonRpcProvider } from 'ethers' import { useMemo } from 'react' import type { Chain, Client, Transport } from 'viem' import { type Config, useClient } from 'wagmi' export function clientToProvider(client: Client) { const { chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } if (transport.type === 'fallback') { const providers = (transport.transports as ReturnType[]).map( ({ value }) => new JsonRpcProvider(value?.url, network), ) if (providers.length === 1) return providers[0] return new FallbackProvider(providers) } return new JsonRpcProvider(transport.url, network) } /** Action to convert a viem Client to an ethers.js Provider. */ export function useEthersProvider({ chainId }: { chainId?: number } = {}) { const client = useClient({ chainId }) return useMemo(() => (client ? clientToProvider(client) : undefined), [client]) } ``` ::: ## Connector Client → Signer ### Reference Implementation Copy the following reference implementation into a file of your choice: ::: code-group ```ts [Ethers v5] import { providers } from 'ethers' import { useMemo } from 'react' import type { Account, Chain, Client, Transport } from 'viem' import { Config, useConnectorClient } from 'wagmi' export function clientToSigner(client: Client) { const { account, chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } const provider = new providers.Web3Provider(transport, network) const signer = provider.getSigner(account.address) return signer } /** Hook to convert a Viem Client to an ethers.js Signer. */ export function useEthersSigner({ chainId }: { chainId?: number } = {}) { const { data: client } = useConnectorClient({ chainId }) return useMemo(() => (client ? clientToSigner(client) : undefined), [client]) } ``` ```ts [Ethers v6] import { BrowserProvider, JsonRpcSigner } from 'ethers' import { useMemo } from 'react' import type { Account, Chain, Client, Transport } from 'viem' import { type Config, useConnectorClient } from 'wagmi' export function clientToSigner(client: Client) { const { account, chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } const provider = new BrowserProvider(transport, network) const signer = new JsonRpcSigner(provider, account.address) return signer } /** Hook to convert a viem Wallet Client to an ethers.js Signer. */ export function useEthersSigner({ chainId }: { chainId?: number } = {}) { const { data: client } = useConnectorClient({ chainId }) return useMemo(() => (client ? clientToSigner(client) : undefined), [client]) } ``` ::: ### Usage Now you can use the `useEthersSigner` function in your components: ::: code-group ```ts [example.ts] import { useEthersSigner } from './ethers' function example() { const signer = useEthersSigner() ... } ``` ```ts [ethers.ts (Ethers v5)] import { providers } from 'ethers' import { useMemo } from 'react' import type { Account, Chain, Client, Transport } from 'viem' import { Config, useConnectorClient } from 'wagmi' export function clientToSigner(client: Client) { const { account, chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } const provider = new providers.Web3Provider(transport, network) const signer = provider.getSigner(account.address) return signer } /** Action to convert a Viem Client to an ethers.js Signer. */ export function useEthersSigner({ chainId }: { chainId?: number } = {}) { const { data: client } = useConnectorClient({ chainId }) return useMemo(() => (client ? clientToSigner(client) : undefined), [client]) } ``` ```ts [ethers.ts (Ethers v6)] import { BrowserProvider, JsonRpcSigner } from 'ethers' import { useMemo } from 'react' import type { Account, Chain, Client, Transport } from 'viem' import { type Config, useConnectorClient } from 'wagmi' export function clientToSigner(client: Client) { const { account, chain, transport } = client const network = { chainId: chain.id, name: chain.name, ensAddress: chain.contracts?.ensRegistry?.address, } const provider = new BrowserProvider(transport, network) const signer = new JsonRpcSigner(provider, account.address) return signer } /** Hook to convert a viem Wallet Client to an ethers.js Signer. */ export function useEthersSigner({ chainId }: { chainId?: number } = {}) { const { data: client } = useConnectorClient({ chainId }) return useMemo(() => (client ? clientToSigner(client) : undefined), [client]) } ``` ::: ================================================ FILE: site/react/guides/faq.md ================================================ # FAQ / Troubleshooting Collection of frequently asked questions with ideas on how to troubleshoot and resolve them. ## How does Wagmi work? Until there's a more in-depth write-up about Wagmi internals, here is the gist: - Wagmi is essentially a wrapper around [Viem](https://viem.sh) and TanStack Query that adds connector and multichain support. - [Connectors](/react/api/connectors) allow Wagmi and Ethereum accounts to communicate with each other. - The Wagmi [`Config`](/react/api/createConfig#config) manages connections established between Wagmi and Connectors, as well as some global state. [Connections](/react/api/createConfig#connection) come with one or more addresses and a chain ID. - If there are connections, the Wagmi `Config` listens for connection changes and updates the [`chainId`](/react/api/createConfig#chainid) based on the ["current" connection](/react/api/createConfig#current). (The Wagmi `Config` can have [many connections established](/react/api/createConfig#connections) at once, but only one connection can be the "current" connection. Usually this is the connection from the last connector that is connected, but can change based on event emitted from other connectors or through the [`useSwitchConnection`](/react/api/hooks/useSwitchConnection) hook and [`switchConnection`](/core/api/actions/switchConnection) action.) - If there are no connections, the Wagmi `Config` defaults the global state `chainId` to the first chain it was created with or last established connection. - The global `chainId` can be changed directly using the [`useSwitchChain`](/react/api/hooks/useSwitchChain) hook and [`switchChain`](/core/api/actions/switchChain) action. This works when there are no connections as well as for most connectors (not all connectors support chain switching). - Wagmi uses the global `chainId` (from the "current" connection or global state) to internally create Viem Client's, which are used by hooks and actions. - Hooks are constructed by TanStack Query options helpers, exported by the `'@wagmi/core/query'` entrypoint, and some additional code to wire up type parameters, hook into React Context, etc. - There are three types of hooks: query hooks, mutation hooks, and config hooks. Query hooks, like [`useCall`](/react/api/hooks/useCall), generally read blockchain state and mutation hooks, like [`useSendTransaction`](/react/api/hooks/useSendTransaction), usually change state through sending transactions via the "current" connection. Config hooks are for getting data from and managing the Wagmi `Config` instance, e.g. [`useChainId`](/react/api/hooks/useChainId) and `useSwitchConnection`. Query and mutation hooks usually have corresponding [Viem actions.](https://viem.sh) ================================================ FILE: site/react/guides/migrate-from-v1-to-v2.md ================================================ --- title: Migrate from v1 to v2 description: Guide for migrating from Wagmi v1 to v2. --- # Migrate from v1 to v2 ## Overview Wagmi v2 redesigns the core APIs to mesh better with [Viem](https://viem.sh) and [TanStack Query](https://tanstack.com/query/v5/docs/react). This major version transforms Wagmi into a light wrapper around these libraries, sprinkling in multichain support and account management. As such, there are some breaking changes and deprecations to be aware of outlined in this guide. To get started, install the latest version of Wagmi and it's required peer dependencies. ::: code-group ```bash-vue [pnpm] pnpm add wagmi viem@{{viemVersion}} @tanstack/react-query ``` ```bash-vue [npm] npm install wagmi viem@{{viemVersion}} @tanstack/react-query ``` ```bash-vue [yarn] yarn add wagmi viem@{{viemVersion}} @tanstack/react-query ``` ```bash-vue [bun] bun add wagmi viem@{{viemVersion}} @tanstack/react-query ``` ::: ::: info Wagmi v2 should be the last major version that will have this many actionable breaking changes. Moving forward after Wagmi v2, new functionality will be opt-in with old functionality being deprecated alongside the new features. This means upgrading to the latest major versions will not require immediate changes. ::: ::: info Not ready to migrate yet? The Wagmi v1 docs are still available at [1.x.wagmi.sh/react](https://1.x.wagmi.sh/react). ::: ## Dependencies ### Moved TanStack Query to peer dependencies Wagmi uses [TanStack Query](https://tanstack.com/query/v5/docs/react) to manage async state, handling requests, caching, and more. With Wagmi v1, TanStack Query was an internal implementation detail. With Wagmi v2, TanStack Query is a peer dependency. A lot of Wagmi users also use TanStack Query in their apps so making it a peer dependency gives them more control and removes some custom Wagmi code internally. If you don't normally use TanStack Query, all you need to do is set it up and mostly forget about it (we'll provide guidance around version updates). ::: code-group ```tsx [app.tsx] import { QueryClient, QueryClientProvider } from '@tanstack/react-query' // [!code ++] import { WagmiProvider } from 'wagmi' import { config } from './config' const queryClient = new QueryClient() // [!code ++] function App() { return ( // [!code ++] {/** ... */} // [!code ++] ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: For more information on setting up TanStack Query for Wagmi, follow the [Getting Started docs](/react/getting-started#setup-tanstack-query). If you want to set up persistence for your query cache (default behavior before Wagmi v2), check out the [TanStack Query docs](https://tanstack.com/query/v5/docs/react/plugins/persistQueryClient#usage-with-react). ### Dropped CommonJS support Wagmi v2 no longer publishes a separate `cjs` tag since very few people use this tag and ESM is the future. See [Sindre Sorhus' guide](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c) for more info about switching to ESM. ## Hooks ### Removed mutation setup arguments Mutation hooks are hooks that change network or application state, sign data, or perform write operations through mutation functions. With Wagmi v1, you could pass arguments directly to these hooks instead of using them with their mutation functions. For example: ```ts{3} // Wagmi v1 const { signMessage } = useSignMessage({ message: 'foo bar baz', }) ``` With Wagmi v2, you must pass arguments to the mutation function instead. This follows the same behavior as [TanStack Query](https://tanstack.com/query/v5/docs/react/guides/mutations) mutations and improves type-safety. ```tsx import { useSignMessage } from 'wagmi' const { signMessage } = useSignMessage({ message: 'foo bar baz' }) // [!code --] const { signMessage } = useSignMessage() // [!code ++] ``` ### Moved TanStack Query parameters to `query` property Previously, you could pass TanStack Query parameters, like `enabled` and `staleTime`, directly to hooks. In Wagmi v2, TanStack Query parameters are now moved to the `query` property. This allows Wagmi to better support TanStack Query type inference, control for future breaking changes since [TanStack Query is now a peer dependency](#moved-tanstack-query-to-peer-dependencies), and expose Wagmi-related hook property at the top-level of editor features, like autocomplete. ```tsx useReadContract({ enabled: false, // [!code --] staleTime: 1_000, // [!code --] query: { // [!code ++] enabled: false, // [!code ++] staleTime: 1_000, // [!code ++] }, // [!code ++] }) ``` ### Removed watch property The `watch` property was removed from all hooks besides [`useBlock`](/react/api/hooks/useBlock) and [`useBlockNumber`](/react/api/hooks/useBlockNumber). This property allowed hooks to internally listen for block changes and automatically refresh their data. In Wagmi v2, you can compose `useBlock` or `useBlockNumber` along with [`React.useEffect`](https://react.dev/reference/react/useEffect) to achieve the same behavior. Two different approaches are outlined for `useBalance` below. ::: code-group ```ts [invalidateQueries] import { useQueryClient } from '@tanstack/react-query' // [!code ++] import { useEffect } from 'react' // [!code ++] import { useBlockNumber, useBalance } from 'wagmi' // [!code ++] const queryClient = useQueryClient() // [!code ++] const { data: blockNumber } = useBlockNumber({ watch: true }) // [!code ++] const { data: balance, queryKey } = useBalance({ // [!code ++] address: '0x4557B18E779944BFE9d78A672452331C186a9f48', watch: true, // [!code --] }) useEffect(() => { // [!code ++] queryClient.invalidateQueries({ queryKey }) // [!code ++] }, [blockNumber, queryClient]) // [!code ++] ``` ```ts [refetch] import { useEffect } from 'react' // [!code ++] import { useBlockNumber, useBalance } from 'wagmi' // [!code ++] const { data: blockNumber } = useBlockNumber({ watch: true }) // [!code ++] const { data: balance, refetch } = useBalance({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', watch: true, // [!code --] }) useEffect(() => { // [!code ++] refetch() // [!code ++] }, [blockNumber]) // [!code ++] ``` ::: This is a bit more code, but removes a lot of internal code from hooks that can slow down your app when not used and gives you more control. For example, you can easily refresh data every five blocks instead of every block. ```ts const { data: blockNumber } = useBlockNumber({ watch: true }) const { data: balance, queryKey } = useBalance({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', }) useEffect(() => { if (blockNumber && blockNumber % 5n === 0n) // [!code focus] queryClient.invalidateQueries({ queryKey }) // [!code focus] }, [blockNumber, queryClient]) ``` ### Removed suspense property Wagmi used to support an experimental `suspense` property via TanStack Query. Since TanStack Query [removed `suspense`](https://tanstack.com/query/v5/docs/react/guides/migrating-to-v5#new-hooks-for-suspense) from its `useQuery` hook, it is no longer supported by Wagmi Hooks. Instead, you can use `useSuspenseQuery` along with TanStack Query-related exports from the `'wagmi/query'` entrypoint. ```ts import { useSuspenseQuery } from '@tanstack/react-query' // [!code ++] import { useConfig } from 'wagmi' // [!code ++] import { getBalanceQueryOptions } from 'wagmi/query' // [!code ++] import { useBalance } from 'wagmi' // [!code --] const config = useConfig() // [!code ++] const options = getBalanceQueryOptions(config, { address: '0x…' }) // [!code ++] const result = useSuspenseQuery(options) // [!code ++] const result = useBalance({ // [!code --] address: '0x…', // [!code --] suspense: true, // [!code --] }) // [!code --] ``` ### Removed prepare hooks `usePrepareContractWrite` and `usePrepareSendTransaction` were removed and replaced with idiomatic Viem alternatives. For `usePrepareContractWrite`, use [`useSimulateContract`](/react/api/hooks/useSimulateContract). Similar to `usePrepareContractWrite`, `useSimulateContract` composes well with `useWriteContract` ```tsx import { usePrepareContractWrite, useWriteContract } from 'wagmi' // [!code --] import { useSimulateContract, useWriteContract } from 'wagmi' // [!code ++] const { config } = usePrepareContractWrite({ // [!code --] const { data } = useSimulateContract({ // [!code ++] address: '0x', abi: [{ type: 'function', name: 'transferFrom', stateMutability: 'nonpayable', inputs: [ { name: 'sender', type: 'address' }, { name: 'recipient', type: 'address' }, { name: 'amount', type: 'uint256' }, ], outputs: [{ type: 'bool' }], }], functionName: 'transferFrom', args: ['0x', '0x', 123n], }) const { write } = useWriteContract(config) // [!code --] const { writeContract } = useWriteContract() // [!code ++] ``` Instead of `usePrepareSendTransaction`, use [`useEstimateGas`](/react/api/hooks/useEstimateGas). You can pass `useEstimateGas` `data` to `useSendTransaction` to compose the two hooks. ```tsx import { usePrepareSendTransaction, useSendTransaction } from 'wagmi' // [!code --] import { useEstimateGas, useSendTransaction } from 'wagmi' // [!code ++] import { parseEther } from 'viem' const { config } = usePrepareSendTransaction({ // [!code --] const { data } = useEstimateGas({ // [!code ++] to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), }) const { sendTransaction } = useSendTransaction(config) // [!code --] const { sendTransaction } = useSendTransaction() // [!code ++] ``` This might seem like more work, but it gives you more control and is more accurate representation of what is happening under the hood. ### Removed `useNetwork` hook The `useNetwork` hook was removed since the connected chain is typically based on the connected account. Use [`useAccount`](/react/api/hooks/useConnection) to get the connected `chain`. ```ts import { useNetwork } from 'wagmi' // [!code --] import { useAccount } from 'wagmi' // [!code ++] const { chain } = useNetwork() // [!code --] const { chain } = useAccount() // [!code ++] ``` Use `useConfig` for the list of `chains` set up with the Wagmi [`Config`](/react/api/createConfig#chains). ```ts import { useNetwork } from 'wagmi' // [!code --] import { useConfig } from 'wagmi' // [!code ++] const { chains } = useNetwork() // [!code --] const { chains } = useConfig() // [!code ++] ``` ### Removed `onConnect` and `onDisconnect` callbacks from `useAccount` The `onConnect` and `onDisconnect` callbacks were removed from the `useAccount` hook since it is frequently used without these callbacks so it made sense to extract these into a new API, [`useAccountEffect`](/react/api/hooks/useConnectionEffect), rather than clutter the `useAccount` hook. ```ts import { useAccount } from 'wagmi' // [!code --] import { useAccountEffect } from 'wagmi' // [!code ++] useAccount({ // [!code --] useAccountEffect({ // [!code ++] onConnect(data) { console.log('connected', data) }, onDisconnect() { console.log('disconnected') }, }) ``` ### Removed `useWebSocketPublicClient` The Wagmi [`Config`](/react/api/createConfig) does not separate transport types anymore. Simply use Viem's [`webSocket`](https://viem.sh/docs/clients/transports/websocket) transport instead when setting up your Wagmi `Config`. You can get Viem `Client` instance with this transport attached by using [`useClient`](/react/api/hooks/useClient) or [`usePublicClient`](/react/api/hooks/usePublicClient). ### Removed `useInfiniteReadContracts` `paginatedIndexesConfig` In the spirit of removing unnecessary abstractions, `paginatedIndexesConfig` was removed. Use `useInfiniteReadContracts`'s `initialPageParam` and `getNextPageParam` parameters along with `fetchNextPage`/`fetchPreviousPage` from the result instead or copy `paginatedIndexesConfig`'s implementation to your codebase. See the [TanStack Query docs](https://tanstack.com/query/v5/docs/react/guides/infinite-queries) for more information on infinite queries. ### Updated `useSendTransaction` and `useWriteContract` return type Updated [`useSendTransaction`](/react/api/hooks/useSendTransaction) and [`useWriteContract`](/react/api/hooks/useWriteContract) return type from `` { hash: `0x${string}` } `` to `` `0x${string}` ``. ```ts const result = useSendTransaction() result.data?.hash // [!code --] result.data // [!code ++] ``` ### Updated `useConnect` return type Updated [`useConnect`](/react/api/hooks/useConnect) return type from `` { account: Address; chain: { id: number; unsupported?: boolean }; connector: Connector } `` to `` { accounts: readonly Address[]; chainId: number } ``. This better reflects the ability to have multiple accounts per connector. ### Renamed parameters and return types All hook parameters and return types follow the naming pattern of `[PascalCaseHookName]Parameters` and `[PascalCaseHookName]ReturnType`. For example, `UseAccountParameters` and `UseAccountReturnType`. ```ts import { UseAccountConfig, UseAccountResult } from 'wagmi' // [!code --] import { UseAccountParameters, UseAccountReturnType } from 'wagmi' // [!code ++] ``` ## Connectors ### Updated connector API In order to maximize type-safety and ease of creating connectors, the connector API changed. Follow the [Creating Connectors guide](/dev/creating-connectors) for more info on creating new connectors and converting Wagmi v1 connectors. ### Removed individual entrypoints Previously, each connector had it's own entrypoint to optimize tree-shaking. Since all connectors now have [`package.json#sideEffects`](https://webpack.js.org/guides/tree-shaking/#mark-the-file-as-side-effect-free) enabled, this is no longer necessary and the entrypoint is unified. Use the `'wagmi/connectors'` entrypoint instead. ```ts import { InjectedConnector } from 'wagmi/connectors/injected' // [!code --] import { CoinbaseWalletConnector } from 'wagmi/connectors/coinbaseWallet' // [!code --] import { coinbaseWallet, injected } from 'wagmi/connectors' // [!code ++] ``` ### Removed `MetaMaskConnector` The `MetaMaskConnector` was removed since it was nearly the same thing as the `InjectedConnector`. Use the [`injected`](/react/api/connectors/injected) connector instead, along with the [`target`](/react/api/connectors/injected#target) parameter set to `'metaMask'`, for the same behavior. ```ts import { MetaMaskConnector } from 'wagmi/connectors/metaMask' // [!code --] import { injected } from 'wagmi/connectors' // [!code ++] const connector = new MetaMaskConnector() // [!code --] const connector = injected({ target: 'metaMask' }) // [!code ++] ``` ### Renamed connectors In Wagmi v1, connectors were classes you needed to instantiate. In Wagmi v2, connectors are functions. As a result, the API has changed. Connectors have the following new names: - `CoinbaseWalletConnector` is now [`coinbaseWallet`](/react/api/connectors/coinbaseWallet). - `InjectedConnector` is now [`injected`](/react/api/connectors/injected). - `SafeConnector` is now [`safe`](/react/api/connectors/safe). - `WalletConnectConnector` is now [`walletConnect`](/react/api/connectors/walletConnect). To create a connector, you now call the connector function with parameters. ```ts import { WalletConnectConnector } from 'wagmi/connectors/walletConnect' // [!code --] import { walletConnect } from 'wagmi/connectors' // [!code ++] const connector = new WalletConnectConnector({ // [!code --] const connector = walletConnect({ // [!code ++] projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', }) ``` ### Removed `WalletConnectLegacyConnector` WalletConnect v1 was sunset June 28, 2023. Use the [`walletConnect`](/react/api/connectors/walletConnect) connector instead. ```ts import { WalletConnectLegacyConnector } from 'wagmi/connectors/walletConnectLegacy' // [!code --] import { walletConnect } from 'wagmi/connectors' // [!code ++] const connector = new WalletConnectLegacyConnector({ // [!code --] const connector = walletConnect({ // [!code ++] projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', }) ``` ## Chains ### Updated `'wagmi/chains'` entrypoint Chains now live in the [Viem repository](https://github.com/wevm/viem). As a result, the `'wagmi/chains'` entrypoint now proxies all chains from `'viem/chains'` directly. ### Removed `mainnet` and `sepolia` from main entrypoint Since the `'wagmi/chains'` entrypoint now proxies `'viem/chains'`, `mainnet` and `sepolia` were removed from the main entrypoint. Use the `'wagmi/chains'` entrypoint instead. ```ts import { mainnet, sepolia } from 'wagmi' // [!code --] import { mainnet, sepolia } from 'wagmi/chains' // [!code ++] ``` ## Errors A number of errors were renamed to better reflect their functionality or replaced by Viem errors. ## Miscellaneous ### Removed internal ENS name normalization Before v2, Wagmi handled ENS name normalization internally for `useEnsAddress`, `useEnsAvatar`, and `useEnsResolver`, using Viem's [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function. This added extra bundle size as full normalization is quite heavy. For v2, you must normalize ENS names yourself before passing them to these hooks. You can use Viem's `normalize` function or any other function that performs [UTS-46 normalization](https://unicode.org/reports/tr46). ```ts import { useEnsAddress } from 'wagmi' import { normalize } from 'viem/ens' // [!code ++] const result = useEnsAddress({ name: 'wevm.eth', // [!code --] name: normalize('wevm.eth'), // [!code ++] }) ``` By inverting control, Wagmi let's you choose how much normalization to do. For example, maybe your project only allows ENS names that are numeric so no normalization is not needed. Check out the [ENS documentation](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) for more information on normalizing names. ### Removed `configureChains` The Wagmi v2 `Config` now has native multichain support using the [`chains`](/react/api/createConfig) parameter so the `configureChains` function is no longer required. ```ts import { configureChains, createConfig } from 'wagmi' // [!code --] import { http, createConfig } from 'wagmi' // [!code ++] import { mainnet, sepolia } from 'wagmi/chains' const { chains, publicClient } = configureChains( // [!code --] [mainnet, sepolia], // [!code --] [publicProvider(), publicProvider()], // [!code --] ) // [!code --] export const config = createConfig({ publicClient, // [!code --] chains: [mainnet, sepolia], // [!code ++] transports: { // [!code ++] [mainnet.id]: http(), // [!code ++] [sepolia.id]: http(), // [!code ++] }, // [!code ++] }) ``` ### Removed ABI exports Import from Viem instead. ```ts import { erc20ABI } from 'wagmi' // [!code --] import { erc20Abi } from 'viem' // [!code ++] ``` ### Removed `'wagmi/providers/*` entrypoints It never made sense that we would have provider URLs hardcoded in the Wagmi codebase. Use [Viem transports](https://viem.sh/docs/clients/intro#transports) along with RPC provider URLs instead. ```ts import { alchemyProvider } from 'wagmi/providers/alchemy' // [!code --] import { http } from 'viem' // [!code ++] const transport = http('https://mainnet.example.com') ``` ### Updated `createConfig` parameters - Removed `autoConnect`. The reconnecting behavior is now managed by React and not related to the Wagmi `Config`. Use `WagmiProvider` [`reconnectOnMount`](/react/api/WagmiProvider#reconnectonmount) or [`useReconnect`](/react/api/hooks/useReconnect) hook instead. - Removed `publicClient` and `webSocketPublicClient`. Use [`transports`](/react/api/createConfig#transports) or [`client`](/react/api/createConfig#client) instead. - Removed `logger`. Wagmi no longer logs debug information to console. ### Updated `Config` object - Removed `config.connector`. Use `config.state.connections.get(config.state.current)?.connector` instead. - Removed `config.data`. Use `config.state.connections.get(config.state.current)` instead. - Removed `config.error`. Was unused and not needed. - Removed `config.lastUsedChainId`. Use `config.state.connections.get(config.state.current)?.chainId` instead. - Removed `config.publicClient`. Use [`config.getClient()`](/react/api/createConfig#getclient) or [`getPublicClient`](/core/api/actions/getPublicClient) instead. - Removed `config.status`. Use [`config.state.status`](/react/api/createConfig#status) instead. - Removed `config.webSocketClient`. Use [`config.getClient()`](/react/api/createConfig#getclient) or [`getPublicClient`](/core/api/actions/getPublicClient) instead. - Removed `config.clearState`. Was unused and not needed. - Removed `config.autoConnect()`. Use [`reconnect`](/core/api/actions/reconnect) action instead. - Renamed `config.setConnectors`. Use `config._internal.setConnectors` instead. - Removed `config.setLastUsedConnector`. Use `config.storage?.setItem('recentConnectorId', connectorId)` instead. - Removed `getConfig`. `config` should be passed explicitly to actions instead of using global `config`. ## Deprecations ### Renamed `WagmiConfig` `WagmiConfig` was renamed to [`WagmiProvider`](/react/api/WagmiProvider) to reduce confusion with the Wagmi [`Config`](/react/api/createConfig) type. React Context Providers usually follow the naming schema `*Provider` so this is a more idiomatic name. Now that Wagmi no longer uses Ethers.js (since Wagmi v1), the term "Provider" is less overloaded. ::: code-group ```tsx [app.tsx] import { WagmiConfig } from 'wagmi' // [!code --] import { WagmiProvider } from 'wagmi' // [!code ++] import { config } from './config' function App() { return ( // [!code --] // [!code ++] {/** ... */} // [!code ++] // [!code --] ) } ``` <<< @/snippets/react/config.ts[config.ts] ::: ### Deprecated `useBalance` `token` parameter Moving forward, `useBalance` will only work for native currencies, thus the `token` parameter is no longer supported. Use [`useReadContracts`](/react/api/hooks/useReadContracts) instead. ```ts import { useBalance } from 'wagmi' // [!code --] import { useReadContracts } from 'wagmi' // [!code ++] import { erc20Abi } from 'viem' // [!code ++] const result = useBalance({ // [!code --] address: '0x4557B18E779944BFE9d78A672452331C186a9f48', // [!code --] token: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code --] }) // [!code --] const result = useReadContracts({ // [!code ++] allowFailure: false, // [!code ++] contracts: [ // [!code ++] { // [!code ++] address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code ++] abi: erc20Abi, // [!code ++] functionName: 'balanceOf', // [!code ++] args: ['0x4557B18E779944BFE9d78A672452331C186a9f48'], // [!code ++] }, // [!code ++] { // [!code ++] address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code ++] abi: erc20Abi, // [!code ++] functionName: 'decimals', // [!code ++] }, // [!code ++] { // [!code ++] address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code ++] abi: erc20Abi, // [!code ++] functionName: 'symbol', // [!code ++] }, // [!code ++] ] // [!code ++] }) // [!code ++] ``` ### Deprecated `useBalance` `unit` parameter and `formatted` return value Moving forward, `useBalance` will not accept the `unit` parameter or return a `formatted` value. Instead you can call `formatUnits` from Viem directly or use another number formatting library, like [dnum](https://github.com/bpierre/dnum) instead. ```ts import { formatUnits } from 'viem' // [!code ++] import { useBalance } from 'wagmi' const result = useBalance({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', unit: 'ether', // [!code --] }) result.data!.formatted // [!code --] formatUnits(result.data!.value, result.data!.decimals) // [!code ++] ``` ### Deprecated `useToken` Moving forward, `useToken` is no longer supported. Use [`useReadContracts`](/react/api/hooks/useReadContracts) instead. ```ts import { useToken } from 'wagmi' // [!code --] import { useReadContracts } from 'wagmi' // [!code ++] import { erc20Abi } from 'viem' // [!code ++] const result = useToken({ // [!code --] address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code --] }) // [!code --] const result = useReadContracts({ // [!code ++] allowFailure: false, // [!code ++] contracts: [ // [!code ++] { // [!code ++] address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code ++] abi: erc20Abi, // [!code ++] functionName: 'decimals', // [!code ++] }, // [!code ++] { // [!code ++] address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code ++] abi: erc20Abi, // [!code ++] functionName: 'name', // [!code ++] }, // [!code ++] { // [!code ++] address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code ++] abi: erc20Abi, // [!code ++] functionName: 'symbol', // [!code ++] }, // [!code ++] { // [!code ++] address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // [!code ++] abi: erc20Abi, // [!code ++] functionName: 'totalSupply', // [!code ++] }, // [!code ++] ] // [!code ++] }) // [!code ++] ``` ### Deprecated `formatUnits` parameters and return values The `formatUnits` parameter and related return values (e.g. `result.formatted`) are deprecated for the following hooks: - [`useEstimateFeesPerGas`](/react/api/hooks/useEstimateFeesPerGas) - `useToken` Instead you can call `formatUnits` from Viem directly or use another number formatting library, like [dnum](https://github.com/bpierre/dnum) instead. ```ts import { formatUnits } from 'viem' // [!code ++] const result = useToken({ address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', formatUnits: 'ether', }) result.data!.totalSupply.formatted // [!code --] formatUnits(result.data!.totalSupply.value, 18) // [!code ++] ``` This allows us to invert control to users so they can handle number formatting however they want, taking into account precision, localization, and more. ### Renamed hooks The following hooks were renamed to better reflect their functionality and underlying [Viem](https://viem.sh) actions: - `useContractRead` is now [`useReadContract`](/react/api/hooks/useReadContract) - `useContractReads` is now [`useReadContracts`](/react/api/hooks/useReadContracts) - `useContractWrite` is now [`useWriteContract`](/react/api/hooks/useWriteContract) - `useContractEvent` is now [`useWatchContractEvent`](/react/api/hooks/useWatchContractEvent) - `useContractInfiniteReads` is now [`useInfiniteReadContracts`](/react/api/hooks/useInfiniteReadContracts) - `useFeeData` is now [`useEstimateFeesPerGas`](/react/api/hooks/useEstimateFeesPerGas) - `useSwitchNetwork` is now [`useSwitchChain`](/react/api/hooks/useSwitchChain) - `useWaitForTransaction` is now [`useWaitForTransactionReceipt`](/react/api/hooks/useWaitForTransactionReceipt) ### Miscellaneous - `WagmiConfigProps` renamed to [`WagmiProviderProps`](/react/api/WagmiProvider#parameters). - `Context` renamed to [`WagmiContext`](/react/api/WagmiProvider#context). ================================================ FILE: site/react/guides/migrate-from-v2-to-v3.md ================================================ --- title: Migrate from v2 to v3 description: Guide for migrating from Wagmi v2 to v3. --- # Migrate from v2 to v3 ## Overview Wagmi v3 gives you total control over connector dependencies. Since Wagmi's initial release, Wagmi included required connector dependencies as part of its package to eliminate the need to manage multiple third-party dependencies. This worked worked well in the early years as a "batteries-included" approach, but didn't allow for more fine-grained control over your dependency tree. By giving you control over connector dependencies, you can decide to only install what you need, manage version bumps at your own pace, and have total control over what third-party code and licenses you bring into your project To get started, install the latest version of Wagmi. ::: code-group ```bash [pnpm] pnpm add wagmi@3 ``` ```bash [npm] npm install wagmi@3 ``` ```bash [yarn] yarn add wagmi@3 ``` ```bash [bun] bun add wagmi@3 ``` ::: ::: info Not ready to migrate yet? The Wagmi v2 docs are still available at [2.x.wagmi.sh/react](https://2.x.wagmi.sh/react). ::: ## Deprecations ### Renamed Account Hooks At the core of Wagmi are connections between apps and Ethereum providers (e.g. EIP-1193), `useAccount`, `useAccountEffect`, and `useSwitchAccount` are renamed to `useConnection`, `useConnectionEffect`, and `useSwitchConnection` to more accurately represent to how Wagmi works. ```ts import { useAccount, // [!code --] useConnection, // [!code ++] useAccountEffect, // [!code --] useConnectionEffect, // [!code ++] useSwitchAccount, // [!code --] useSwitchConnection, // [!code ++] } from 'wagmi' ``` ### Renamed mutateFn Renamed custom mutate function names to `mutate`/`mutateAsync` to reduce destructure key renaming fatigue and align with TanStack Query terminology. ##### Before Had to destructure hook result and often rename keys when using multiple of the same hook. Could decide not to destructure, but syntax becomes awkward for mutate functions (e.g. `connect.connect` or `connect.connectAsync`). ```ts const { connect, isPending: connectIsPending } = useConnect() const { writeContract: transfer, error: transferError, isPending: transferIsPending } = useWriteContract() const { writeContract: approve, error: approveError } = useWriteContract() ``` ##### After Allows you to name the hook result whatever you want and not worry about also renaming properties. ```ts const connect = useConnect() // connect.mutate, connect.isPending const transfer = useWriteContract() // transfer.mutate, transfer.error, transfer.isPending const approve = useWriteContract() // approve.mutate, approve.error ``` ### Removed `useConnect().connectors` & `useReconnect().connectors` Moving forward, `useConnect().connectors` and `useReconnect().connectors` are no longer supported. Use [`useConnectors`](/react/api/hooks/useConnectors) instead. ```ts import { useConnect, useReconnect } from 'wagmi' // [!code --] import { useConnectors } from 'wagmi' // [!code ++] const { connectors } = useConnect() // [!code --] const { connectors } = useReconnect() // [!code --] const connectors = useConnectors() // [!code ++] ``` ### Removed `useDisconnect().connectors` & `useSwitchConnection().connectors` Moving forward, `useDisconnect().connectors` and `useSwitchConnection().connectors` are no longer supported. Use [`useConnections`](/react/api/hooks/useConnections) instead. ```ts import { useDisconnect, useSwitchConnection } from 'wagmi' // [!code --] import { useConnections } from 'wagmi' // [!code ++] const { connectors } = useDisconnect() // [!code --] const { connectors } = useSwitchConnection() // [!code --] const connections = useConnections() // [!code ++] const connectors = connections.map((connection) => connection.connector) // [!code ++] ``` ### Removed `useSwitchChain().chains` Moving forward, `useSwitchChain().chains` is no longer supported. Use [`useChains`](/react/api/hooks/useChains) instead. ```ts import { useSwitchChain } from 'wagmi' // [!code --] import { useChains } from 'wagmi' // [!code ++] const { chains } = useSwitchChain() // [!code --] const chains = useChains() // [!code ++] ``` ================================================ FILE: site/react/guides/read-from-contract.md ================================================ # Read from Contract The [`useReadContract` Hook](/react/api/hooks/useReadContract) allows you to read data on a smart contract, from a `view` or `pure` (read-only) function. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas. The component below shows how to retrieve the token balance of an address from the [Wagmi Example](https://etherscan.io/token/0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2) contract :::code-group ```tsx [read-contract.tsx] import { useReadContract } from 'wagmi' import { wagmiContractConfig } from './contracts' function ReadContract() { const { data: balance } = useReadContract({ ...wagmiContractConfig, functionName: 'balanceOf', args: ['0x03A71968491d55603FFe1b11A9e23eF013f75bCF'], }) return (
Balance: {balance?.toString()}
) } ``` ```ts [contracts.ts] export const wagmiContractConfig = { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: [ { type: 'function', name: 'balanceOf', stateMutability: 'view', inputs: [{ name: 'account', type: 'address' }], outputs: [{ type: 'uint256' }], }, { type: 'function', name: 'totalSupply', stateMutability: 'view', inputs: [], outputs: [{ name: 'supply', type: 'uint256' }], }, ], } as const ``` ::: If `useReadContract` depends on another value (`address` in the example below), you can use the [`query.enabled`](/react/api/hooks/useReadContract#enabled) option to prevent the query from running until the dependency is ready. ```tsx const { data: balance } = useReadContract({ ...wagmiContractConfig, functionName: 'balanceOf', args: [address], query: { // [!code focus] enabled: !!address, // [!code focus] }, // [!code focus] }) ``` ## Loading & Error States The [`useReadContract` Hook](/react/api/hooks/useReadContract) also returns loading & error states, which can be used to display a loading indicator while the data is being fetched, or an error message if contract execution reverts. :::code-group ```tsx [read-contract.tsx] import { type BaseError, useReadContract } from 'wagmi' function ReadContract() { const { data: balance, error, // [!code ++] isPending // [!code ++] } = useReadContract({ ...wagmiContractConfig, functionName: 'balanceOf', args: ['0x03A71968491d55603FFe1b11A9e23eF013f75bCF'], }) if (isPending) return
Loading...
// [!code ++] if (error) // [!code ++] return ( // [!code ++]
// [!code ++] Error: {(error as BaseError).shortMessage || error.message} // [!code ++]
// [!code ++] ) // [!code ++] return (
Balance: {balance?.toString()}
) } ``` ## Refetching On Blocks The [`useBlockNumber` Hook](/react/api/hooks/useBlockNumber) can be utilized to refetch or [invalidate](https://tanstack.com/query/latest/docs/framework/react/guides/query-invalidation) the contract data on a specific block interval. :::code-group ```tsx [read-contract.tsx (refetch)] import { useEffect } from 'react' import { useBlockNumber, useReadContract } from 'wagmi' function ReadContract() { const { data: balance, refetch } = useReadContract({ ...wagmiContractConfig, functionName: 'balanceOf', args: ['0x03A71968491d55603FFe1b11A9e23eF013f75bCF'], }) const { data: blockNumber } = useBlockNumber({ watch: true }) useEffect(() => { // want to refetch every `n` block instead? use the modulo operator! // if (blockNumber % 5 === 0) refetch() // refetch every 5 blocks refetch() }, [blockNumber]) return (
Balance: {balance?.toString()}
) } ``` ```tsx [read-contract.tsx (invalidate)] import { useQueryClient } from '@tanstack/react-query' import { useEffect } from 'react' import { useBlockNumber, useReadContract } from 'wagmi' function ReadContract() { const queryClient = useQueryClient() const { data: balance, refetch } = useReadContract({ ...wagmiContractConfig, functionName: 'balanceOf', args: ['0x03A71968491d55603FFe1b11A9e23eF013f75bCF'], }) const { data: blockNumber } = useBlockNumber({ watch: true }) useEffect(() => { // if `useReadContract` is in a different hook/component, // you can import `readContractQueryKey` from `'wagmi/query'` and // construct a one-off query key to use for invalidation queryClient.invalidateQueries({ queryKey }) }, [blockNumber, queryClient]) return (
Balance: {balance?.toString()}
) } ``` ::: ## Calling Multiple Functions We can use the [`useReadContract` Hook](/react/api/hooks/useReadContract) multiple times in a single component to call multiple functions on the same contract, but this ends up being hard to manage as the number of functions increases, especially when we also want to deal with loading & error states. Luckily, to make this easier, we can use the [`useReadContracts` Hook](/react/api/hooks/useReadContracts) to call multiple functions in a single call. :::code-group ```tsx [read-contract.tsx] import { type BaseError, useReadContracts } from 'wagmi' function ReadContract() { const { data, error, isPending } = useReadContracts({ contracts: [{ ...wagmiContractConfig, functionName: 'balanceOf', args: ['0x03A71968491d55603FFe1b11A9e23eF013f75bCF'], }, { ...wagmiContractConfig, functionName: 'ownerOf', args: [69n], }, { ...wagmiContractConfig, functionName: 'totalSupply', }] }) const [balance, ownerOf, totalSupply] = data || [] if (isPending) return
Loading...
if (error) return (
Error: {(error as BaseError).shortMessage || error.message}
) return ( <>
Balance: {balance?.toString()}
Owner of Token 69: {ownerOf?.toString()}
Total Supply: {totalSupply?.toString()}
) } ``` ::: ================================================ FILE: site/react/guides/send-transaction.md ================================================ # Send Transaction The following guide teaches you how to send transactions in Wagmi. The example below builds on the [Connect Wallet guide](/react/guides/connect-wallet) and uses the [useSendTransaction](/react/api/hooks/useSendTransaction) & [useWaitForTransactionReceipt](/react/api/hooks/useWaitForTransactionReceipt) hooks. ## Example Feel free to check out the example before moving on: ## Steps ### 1. Connect Wallet Follow the [Connect Wallet guide](/react/guides/connect-wallet) guide to get this set up. ### 2. Create a new component Create your `SendTransaction` component that will contain the send transaction logic. ::: code-group ```tsx [send-transaction.tsx] import * as React from 'react' export function SendTransaction() { return (
) } ``` ::: ### 3. Add a form handler Next, we will need to add a handler to the form that will send the transaction when the user hits "Send". This will be a basic handler in this step. ::: code-group ```tsx [send-transaction.tsx] import * as React from 'react' export function SendTransaction() { async function submit(e: React.FormEvent) { // [!code ++] e.preventDefault() // [!code ++] const formData = new FormData(e.target as HTMLFormElement) // [!code ++] const to = formData.get('address') as `0x${string}` // [!code ++] const value = formData.get('value') as string // [!code ++] } // [!code ++] return (
// [!code --] // [!code ++]
) } ``` ::: ### 4. Hook up the `useSendTransaction` Hook Now that we have the form handler, we can hook up the [`useSendTransaction` Hook](/react/api/hooks/useSendTransaction) to send the transaction. ::: code-group ```tsx [send-transaction.tsx] import * as React from 'react' import { useSendTransaction } from 'wagmi' // [!code ++] import { parseEther } from 'viem' // [!code ++] export function SendTransaction() { const { data: hash, sendTransaction } = useSendTransaction() // [!code ++] async function submit(e: React.FormEvent) { e.preventDefault() const formData = new FormData(e.target as HTMLFormElement) const to = formData.get('address') as `0x${string}` const value = formData.get('value') as string sendTransaction({ to, value: parseEther(value) }) // [!code ++] } return (
{hash &&
Transaction Hash: {hash}
} // [!code ++]
) } ``` ::: ### 5. Add loading state (optional) We can optionally add a loading state to the "Send" button while we are waiting confirmation from the user's wallet. ::: code-group ```tsx [send-transaction.tsx] import * as React from 'react' import { useSendTransaction } from 'wagmi' import { parseEther } from 'viem' export function SendTransaction() { const { data: hash, isPending, // [!code ++] sendTransaction } = useSendTransaction() async function submit(e: React.FormEvent) { e.preventDefault() const formData = new FormData(e.target as HTMLFormElement) const to = formData.get('address') as `0x${string}` const value = formData.get('value') as string sendTransaction({ to, value: parseEther(value) }) } return (
{hash &&
Transaction Hash: {hash}
}
) } ``` ::: ### 6. Wait for transaction receipt (optional) We can also display the transaction confirmation status to the user by using the [`useWaitForTransactionReceipt` Hook](/react/api/hooks/useWaitForTransactionReceipt). ::: code-group ```tsx [send-transaction.tsx] import * as React from 'react' import { useSendTransaction, useWaitForTransactionReceipt // [!code ++] } from 'wagmi' import { parseEther } from 'viem' export function SendTransaction() { const { data: hash, isPending, sendTransaction } = useSendTransaction() async function submit(e: React.FormEvent) { e.preventDefault() const formData = new FormData(e.target as HTMLFormElement) const to = formData.get('address') as `0x${string}` const value = formData.get('value') as string sendTransaction({ to, value: parseEther(value) }) } const { isLoading: isConfirming, isSuccess: isConfirmed } = // [!code ++] useWaitForTransactionReceipt({ // [!code ++] hash, // [!code ++] }) // [!code ++] return (
{hash &&
Transaction Hash: {hash}
} {isConfirming &&
Waiting for confirmation...
} // [!code ++] {isConfirmed &&
Transaction confirmed.
} // [!code ++]
) } ``` ::: ### 7. Handle errors (optional) If the user rejects the transaction, or the user does not have enough funds to cover the transaction, we can display an error message to the user. ::: code-group ```tsx [send-transaction.tsx] import * as React from 'react' import { type BaseError, // [!code ++] useSendTransaction, useWaitForTransactionReceipt } from 'wagmi' import { parseEther } from 'viem' export function SendTransaction() { const { data: hash, error, // [!code ++] isPending, sendTransaction } = useSendTransaction() async function submit(e: React.FormEvent) { e.preventDefault() const formData = new FormData(e.target as HTMLFormElement) const to = formData.get('address') as `0x${string}` const value = formData.get('value') as string sendTransaction({ to, value: parseEther(value) }) } const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({ hash, }) return (
{hash &&
Transaction Hash: {hash}
} {isConfirming &&
Waiting for confirmation...
} {isConfirmed &&
Transaction confirmed.
} {error && ( // [!code ++]
Error: {(error as BaseError).shortMessage || error.message}
// [!code ++] )} // [!code ++]
) } ``` ::: ### 8. Wire it up! Finally, we can wire up our Send Transaction component to our application's entrypoint. ::: code-group ```tsx [app.tsx] import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { WagmiProvider } from 'wagmi' import { config } from './config' import { SendTransaction } from './send-transaction' // [!code ++] const queryClient = new QueryClient() function App() { return ( // [!code ++] ) } ``` ```tsx [send-transaction.tsx] import * as React from 'react' import { type BaseError, useSendTransaction, useWaitForTransactionReceipt } from 'wagmi' import { parseEther } from 'viem' export function SendTransaction() { const { data: hash, error, isPending, sendTransaction } = useSendTransaction() async function submit(e: React.FormEvent) { e.preventDefault() const formData = new FormData(e.target as HTMLFormElement) const to = formData.get('address') as `0x${string}` const value = formData.get('value') as string sendTransaction({ to, value: parseEther(value) }) } const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({ hash, }) return (
{hash &&
Transaction Hash: {hash}
} {isConfirming &&
Waiting for confirmation...
} {isConfirmed &&
Transaction confirmed.
} {error && (
Error: {(error as BaseError).shortMessage || error.message}
)}
) } ``` ```tsx [config.ts] import { http, createConfig } from 'wagmi' import { base, mainnet, optimism } from 'wagmi/chains' import { injected, metaMask, safe, walletConnect } from 'wagmi/connectors' const projectId = '' export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), }, }) ``` ::: [See the Example.](#example) ================================================ FILE: site/react/guides/ssr.md ================================================ --- outline: deep --- # SSR Wagmi uses client-only external stores (such as `localStorage` and `mipd`) to show the user the most relevant data as quickly as possible on first render. However, the caveat of using these external client stores is that frameworks which incorporate SSR (such as Next.js) will throw hydration warnings on the client when it identifies mismatches between the server-rendered HTML and the client-rendered HTML. To stop this from happening, you can toggle on the [`ssr`](/react/api/createConfig#ssr) property in the Wagmi Config. ```tsx import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' const config = createConfig({ // [!code focus:99] chains: [mainnet, sepolia], ssr: true, // [!code ++] transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` Turning on the `ssr` property means that content from the external stores will be hydrated on the client after the initial mount. ## Persistence using Cookies As a result of turning on the `ssr` property, external persistent stores like `localStorage` will be hydrated on the client **after the initial mount**. This means that you will still see a flash of "empty" data on the client (e.g. a `"disconnected"` account instead of a `"reconnecting"` account, or an empty address instead of the last connected address) until after the first mount, when the store hydrates. In order to persist data between the server and the client, you can use cookies. ### 1. Set up cookie storage First, we will set up cookie storage in the Wagmi Config. ```tsx import { createConfig, http, cookieStorage, // [!code ++] createStorage // [!code ++] } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export function getConfig() { return createConfig({ chains: [mainnet, sepolia], ssr: true, storage: createStorage({ // [!code ++] storage: cookieStorage, // [!code ++] }), // [!code ++] transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) } ``` ### 2. Hydrate the cookie Next, we will need to add some mechanisms to hydrate the stored cookie in Wagmi. #### Next.js App Directory In our `app/layout.tsx` file (a [Server Component](https://nextjs.org/docs/app/building-your-application/rendering/server-components)), we will need to extract the cookie from the `headers` function and pass it to [`cookieToInitialState`](/react/api/utilities/cookieToInitialState). We will need to pass this result to the [`initialState` property](/react/api/WagmiProvider#initialstate) of the `WagmiProvider`. The `WagmiProvider` **must** be in a Client Component tagged with `"use client"` (see `app/providers.tsx` tab). ::: code-group ```tsx [app/layout.tsx] import { type ReactNode } from 'react' import { headers } from 'next/headers' // [!code ++] import { cookieToInitialState } from 'wagmi' // [!code ++] import { getConfig } from './config' import { Providers } from './providers' export default async function Layout({ children }: { children: ReactNode }) { const initialState = cookieToInitialState( // [!code ++] getConfig(), // [!code ++] (await headers()).get('cookie') // [!code ++] ) // [!code ++] return ( // [!code --] // [!code ++] {children} ) } ``` ```tsx [app/providers.tsx] 'use client' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { type ReactNode, useState } from 'react' import { type State, WagmiProvider } from 'wagmi' import { getConfig } from './config' type Props = { children: ReactNode, initialState: State | undefined, // [!code ++] } export function Providers({ children }: Props) { // [!code --] export function Providers({ children, initialState }: Props) { // [!code ++] const [config] = useState(() => getConfig()) const [queryClient] = useState(() => new QueryClient()) return ( // [!code --] // [!code ++] {children} ) } ``` ```tsx [app/config.ts] import { createConfig, http, cookieStorage, createStorage } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export function getConfig() { return createConfig({ chains: [mainnet, sepolia], ssr: true, storage: createStorage({ // [!code ++] storage: cookieStorage, // [!code ++] }), // [!code ++] transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) } ``` ::: #### Next.js Pages Directory Would you like to contribute this content? Feel free to [open a Pull Request](https://github.com/wevm/wagmi/pulls)! #### Vanilla SSR Would you like to contribute this content? Feel free to [open a Pull Request](https://github.com/wevm/wagmi/pulls)! ================================================ FILE: site/react/guides/tanstack-query.md ================================================ # TanStack Query Wagmi Hooks are not only a wrapper around the core [Wagmi Actions](/core/api/actions), but they also utilize [TanStack Query](https://tanstack.com/query/v5) to enable trivial and intuitive fetching, caching, synchronizing, and updating of asynchronous data in your React applications. Without an asynchronous data fetching abstraction, you would need to handle all the negative side-effects that comes as a result, such as: representing finite states (loading, error, success), handling race conditions, caching against a deterministic identifier, etc. ## Queries & Mutations Wagmi Hooks represent either a **Query** or a **Mutation**. **Queries** are used for fetching data (e.g. fetching a block number, reading from a contract, etc), and are typically invoked on mount by default. All queries are coupled to a unique [Query Key](#query-keys), and can be used for further operations such as refetching, prefetching, or modifying the cached data. **Mutations** are used for mutating data (e.g. connecting/disconnecting accounts, writing to a contract, switching chains, etc), and are typically invoked in response to a user interaction. Unlike **Queries**, they are not coupled with a query key. ## Terms - **Query**: An asynchronous data fetching (e.g. read data) operation that is tied against a unique Query Key. - **Mutation**: An asynchronous mutating (e.g. create/update/delete data or side-effect) operation. - **Query Key**: A unique identifier that is used to deterministically identify a query. It is typically a tuple of the query name and the query arguments. - **Stale Data**: Data that is unused or inactive after a certain period of time. - **Query Fetching**: The process of invoking an async query function. - **Query Refetching**: The process of refetching **rendered** queries. - **[Query Invalidation](https://tanstack.com/query/v5/docs/react/guides/query-invalidation)**: The process of marking query data as stale (e.g. inactive/unused), and refetching **rendered** queries. - **[Query Prefetching](https://tanstack.com/query/v5/docs/react/guides/prefetching)**: The process of prefetching queries and seeding the cache. ## Persistence via External Stores By default, TanStack Query persists all query data in-memory. This means that if you refresh the page, all in-memory query data will be lost. If you want to persist query data to an external storage, you can utilize TanStack Query's [`createSyncStoragePersister`](https://tanstack.com/query/v5/docs/react/plugins/createSyncStoragePersister) or [`createAsyncStoragePersister`](https://tanstack.com/query/v5/docs/react/plugins/createAsyncStoragePersister) to plug external storage like `localStorage`, `sessionStorage`, [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) or [`AsyncStorage`](https://reactnative.dev/docs/asyncstorage) (React Native). ### Sync Storage Below is an example of how to set up Wagmi + TanStack Query with sync external storage like `localStorage` or `sessionStorage`. #### Install ::: code-group ```bash [pnpm] pnpm i @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client ``` ```bash [npm] npm i @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client ``` ```bash [yarn] yarn add @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client ``` ```bash [bun] bun i @tanstack/query-sync-storage-persister @tanstack/react-query-persist-client ``` ::: #### Usage ```tsx // 1. Import modules. // [!code hl] import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister' // [!code hl] import { QueryClient } from '@tanstack/react-query' // [!code hl] import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client' // [!code hl] import { WagmiProvider, deserialize, serialize } from 'wagmi' // [!code hl] // 2. Create a new Query Client with a default `gcTime`. // [!code hl] const queryClient = new QueryClient({ // [!code hl] defaultOptions: { // [!code hl] queries: { // [!code hl] gcTime: 1_000 * 60 * 60 * 24, // 24 hours // [!code hl] }, // [!code hl] }, // [!code hl] }) // [!code hl] // 3. Set up the persister. // [!code hl] const persister = createSyncStoragePersister({ // [!code hl] serialize, // [!code hl] storage: window.localStorage, // [!code hl] deserialize, // [!code hl] }) // [!code hl] function App() { return ( {/* 4. Wrap app in PersistQueryClientProvider */} // [!code hl] // [!code hl] {/* ... */} // [!code hl] ) } ``` Read more about [Sync Storage Persistence](https://tanstack.com/query/v5/docs/react/plugins/createSyncStoragePersister). ### Async Storage Below is an example of how to set up Wagmi + TanStack Query with async external storage like [`IndexedDB`](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) or [`AsyncStorage`](https://reactnative.dev/docs/asyncstorage). #### Install ::: code-group ```bash [pnpm] pnpm i @tanstack/query-async-storage-persister @tanstack/react-query-persist-client ``` ```bash [npm] npm i @tanstack/query-async-storage-persister @tanstack/react-query-persist-client ``` ```bash [yarn] yarn add @tanstack/query-async-storage-persister @tanstack/react-query-persist-client ``` ```bash [bun] bun i @tanstack/query-async-storage-persister @tanstack/react-query-persist-client ``` ::: #### Usage ```tsx // 1. Import modules. // [!code hl] import AsyncStorage from '@react-native-async-storage/async-storage' // [!code hl] import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister' // [!code hl] import { QueryClient } from '@tanstack/react-query' // [!code hl] import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client' // [!code hl] import { WagmiProvider, deserialize, serialize } from 'wagmi' // [!code hl] // 2. Create a new Query Client with a default `gcTime`. // [!code hl] const queryClient = new QueryClient({ // [!code hl] defaultOptions: { // [!code hl] queries: { // [!code hl] gcTime: 1_000 * 60 * 60 * 24, // 24 hours // [!code hl] }, // [!code hl] }, // [!code hl] }) // [!code hl] // 3. Set up the persister. // [!code hl] const persister = createAsyncStoragePersister({ // [!code hl] serialize, // [!code hl] storage: AsyncStorage, // [!code hl] deserialize, // [!code hl] }) // [!code hl] function App() { return ( {/* 4. Wrap app in PersistQueryClientProvider */} // [!code hl] // [!code hl] {/* ... */} // [!code hl] ) } ``` Read more about [Async Storage Persistence](https://tanstack.com/query/v5/docs/react/plugins/createAsyncStoragePersister). ## Query Keys Query Keys are typically used to perform advanced operations on the query such as: invalidation, refetching, prefetching, etc. Wagmi exports Query Keys for every Hook, and they can be retrieved via the [Hook (React)](#hook-react) or via an [Import (Vanilla JS)](#import-vanilla-js). Read more about **Query Keys** on the [TanStack Query docs.](https://tanstack.com/query/v5/docs/react/guides/query-keys) ### Hook (React) Each Hook returns a `queryKey` value. You would use this approach when you want to utilize the query key in a React component as it handles reactivity for you, unlike the [Import](#import-vanilla-js) method below. ```ts import { useBlock } from 'wagmi' // [!code hl] function App() { const { queryKey } = useBlock() // [!code hl] } ``` ### Import (Vanilla JS) Each Hook has a corresponding `getQueryOptions` function that returns a query key. You would use this method when you want to utilize the query key outside of a React component in a Vanilla JS context, like in a utility function. ```ts import { getBlockQueryOptions } from 'wagmi/query' // [!code hl] import { config } from './config' function perform() { const { queryKey } = getBlockQueryOptions(config, { // [!code hl] chainId: config.state.chainId // [!code hl] }) // [!code hl] } ``` ::: warning The caveat of this method is that it does not handle reactivity for you (e.g. active account/chain changes, argument changes, etc). You would need to handle this yourself by explicitly passing through the arguments to `getQueryOptions`. ::: ## Invalidating Queries Invalidating a query is the process of marking the query data as stale (e.g. inactive/unused), and refetching the queries that are already rendered. Read more about **Invalidating Queries** on the [TanStack Query docs.](https://tanstack.com/query/v5/docs/react/guides/query-invalidation) #### Example: Watching a Users' Balance You may want to "watch" a users' balance, and invalidate the balance after each incoming block. We can invoke `invalidateQueries` inside a `useEffect` with the block number as it's only dependency – this will refetch all rendered balance queries when the `blockNumber` changes. ```tsx import { useQueryClient } from '@tanstack/react-query' import { useEffect } from 'react' import { useBlockNumber, useBalance } from 'wagmi' function App() { const queryClient = useQueryClient() const { data: blockNumber } = useBlockNumber({ watch: true }) // [!code hl] const { data: balance, queryKey } = useBalance() // [!code hl] useEffect(() => { // [!code hl] queryClient.invalidateQueries({ queryKey }) // [!code hl] }, [blockNumber]) // [!code hl] return
{balance}
} ``` #### Example: After User Interaction Maybe you want to invalidate a users' balance after some interaction. This would mark the balance as stale, and consequently refetch all rendered balance queries. ```tsx import { useBalance } from 'wagmi' function App() { // 1. Extract `queryKey` from the useBalance Hook. // [!code hl] const { queryKey } = useBalance() // [!code hl] return ( ) } function Example() { // 3. Other `useBalance` Hooks in your rendered React tree will be refetched! // [!code hl] const { data: balance } = useBalance() // [!code hl] return
{balance}
} ``` ## Fetching Queries Fetching a query is the process of invoking the query function to retrieve data. If the query exists and the data is not invalidated or older than a given `staleTime`, then the data from the cache will be returned. Otherwise, the query will fetch for the latest data. ::: code-group ```tsx [example.tsx] import { getBlockQueryOptions } from 'wagmi' import { queryClient } from './app' import { config } from './config' export async function fetchBlockData() { return queryClient.fetchQuery( // [!code hl] getBlockQueryOptions(config, { // [!code hl] chainId: config.state.chainId, // [!code hl] } // [!code hl] )) // [!code hl] } ``` <<< @/snippets/react/app.tsx[app.tsx] <<< @/snippets/react/config.ts[config.ts] ::: ## Retrieving & Updating Query Data You can retrieve and update query data imperatively with `getQueryData` and `setQueryData`. This is useful for scenarios where you want to retrieve or update a query outside of a React component. Note that these functions do not invalidate or refetch queries. ::: code-group ```tsx [example.tsx] import { getBlockQueryOptions } from 'wagmi' import type { Block } from 'viem' import { queryClient } from './app' import { config } from './config' export function getPendingBlockData() { return queryClient.getQueryData( // [!code hl] getBlockQueryOptions(config, { // [!code hl] chainId: config.state.chainId, // [!code hl] tag: 'pending' // [!code hl] } // [!code hl] )) // [!code hl] } export function setPendingBlockData(data: Block) { return queryClient.setQueryData( // [!code hl] getBlockQueryOptions(config, { // [!code hl] chainId: config.state.chainId, // [!code hl] tag: 'pending' // [!code hl] }, // [!code hl] data // [!code hl] )) // [!code hl] } ``` <<< @/snippets/react/app.tsx[app.tsx] <<< @/snippets/react/config.ts[config.ts] ::: ## Prefetching Queries Prefetching a query is the process of fetching the data ahead of time and seeding the cache with the returned data. This is useful for scenarios where you want to fetch data before the user navigates to a page, or fetching data on the server to be reused on client hydration. Read more about **Prefetching Queries** on the [TanStack Query docs.](https://tanstack.com/query/v5/docs/react/guides/prefetching) #### Example: Prefetching in Event Handler ```tsx import { Link } from 'next/link' import { getBlockQueryOptions } from 'wagmi' function App() { const config = useConfig() const chainId = useChainId() // 1. Set up a function to prefetch the block data. // [!code hl] const prefetch = () => // [!code hl] queryClient.prefetchQuery(getBlockQueryOptions(config, { chainId })) // [!code hl] return ( Block details ) } ``` ## SSR It is possible to utilize TanStack Query's SSR strategies with Wagmi Hooks & Query Keys. Check out the [Server Rendering & Hydration](https://tanstack.com/query/v5/docs/react/guides/ssr) & [Advanced Server Rendering](https://tanstack.com/query/v5/docs/react/guides/advanced-ssr) guides. ## Devtools TanStack Query includes dedicated [Devtools](https://tanstack.com/query/latest/docs/framework/react/devtools) that assist in visualizing and debugging your queries, their cache states, and much more. You will have to pass a custom `queryKeyFn` to your `QueryClient` for Devtools to correctly serialize BigInt values for display. Alternatively, You can use the `hashFn` from `@wagmi/core/query`, which already handles this serialization. #### Install ::: code-group ```bash [pnpm] pnpm i @tanstack/react-query-devtools ``` ```bash [npm] npm i @tanstack/react-query-devtools ``` ```bash [yarn] yarn add @tanstack/react-query-devtools ``` ```bash [bun] bun i @tanstack/react-query-devtools ``` ::: #### Usage ```tsx import { QueryClient, QueryClientProvider, } from "@tanstack/react-query"; import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; // [!code hl] import { hashFn } from "@wagmi/core/query"; // [!code hl] const queryClient = new QueryClient({ defaultOptions: { // [!code hl] queries: { // [!code hl] queryKeyHashFn: hashFn, // [!code hl] }, // [!code hl] }, // [!code hl] }); ``` ================================================ FILE: site/react/guides/testing.md ================================================ # Testing ================================================ FILE: site/react/guides/viem.md ================================================ # Viem [Viem](https://viem.sh) is a low-level TypeScript Interface for Ethereum that enables developers to interact with the Ethereum blockchain, including: JSON-RPC API abstractions, Smart Contract interaction, wallet & signing implementations, coding/parsing utilities and more. **Wagmi Core** is essentially a wrapper over **Viem** that provides multi-chain functionality via [Wagmi Config](/react/api/createConfig) and automatic account management via [Connectors](/react/api/connectors). ## Leveraging Viem Actions All of the core [Wagmi Hooks](/react/api/actions) are friendly wrappers around [Viem Actions](https://viem.sh/docs/actions/public/introduction) that inject a multi-chain and connector aware [Wagmi Config](/react/api/createConfig). There may be cases where you might want to dig deeper and utilize Viem Actions directly (maybe a Hook doesn't exist in Wagmi yet). In these cases, you can create your own custom Wagmi Hook by importing Viem Actions directly via `viem/actions` and plugging in a Viem Client returned by the [`useClient` Hook](/react/api/hooks/useClient). The example below demonstrates two different ways to utilize Viem Actions: 1. **Tree-shakable Actions (recommended):** Uses `useClient` (for public actions) and `useConnectorClient` (for wallet actions). 2. **Client Actions:** Uses `usePublicClient` (for public actions) and `useWalletClient` (for wallet actions). ::: tip It is highly recommended to use the **tree-shakable** method to ensure that you are only pulling modules you use, and keep your bundle size low. ::: ::: code-group ```tsx [Tree-shakable Actions] // 1. Import modules. import { useMutation, useQuery } from '@tanstack/react-query' import { http, createConfig, useClient, useConnectorClient } from 'wagmi' import { base, mainnet, optimism, zora } from 'wagmi/chains' import { getLogs, watchAsset } from 'viem/actions' // 2. Set up a Wagmi Config export const config = createConfig({ chains: [base, mainnet, optimism, zora], transports: { [base.id]: http(), [mainnet.id]: http(), [optimism.id]: http(), [zora.id]: http(), }, }) function Example() { // 3. Extract a Viem Client for the current active chain. // [!code hl] const publicClient = useClient({ config }) // [!code hl] // 4. Create a "custom" Query Hook that utilizes the Client. // [!code hl] const { data: logs } = useQuery({ // [!code hl] queryKey: ['logs', publicClient.uid], // [!code hl] queryFn: () => getLogs(publicClient, /* ... */) // [!code hl] }) // [!code hl] // 5. Extract a Viem Client for the current active chain & account. // [!code hl] const { data: walletClient } = useConnectorClient({ config }) // [!code hl] // 6. Create a "custom" Mutation Hook that utilizes the Client. // [!code hl] const { mutate } = useMutation({ // [!code hl] mutationFn: (asset) => watchAsset(walletClient, asset) // [!code hl] }) // [!code hl] return (
{/* ... */}
) } ``` ```tsx [Client Actions] // 1. Import modules. import { useMutation, useQuery } from '@tanstack/react-query' import { http, createConfig, useClient, useConnectorClient } from 'wagmi' import { base, mainnet, optimism, zora } from 'wagmi/chains' // 2. Set up a Wagmi Config export const config = createConfig({ chains: [base, mainnet, optimism, zora], transports: { [base.id]: http(), [mainnet.id]: http(), [optimism.id]: http(), [zora.id]: http(), }, }) function Example() { // 3. Extract a Viem Client for the current active chain. // [!code hl] const publicClient = useClient({ config }) // [!code hl] // 4. Create a "custom" Query Hook that utilizes the Client. // [!code hl] const { data: logs } = useQuery({ // [!code hl] queryKey: ['logs', publicClient.uid], // [!code hl] queryFn: () => publicClient.getLogs(/* ... */) // [!code hl] }) // [!code hl] // 5. Extract a Viem Client for the current active chain & account. // [!code hl] const { data: walletClient } = useConnectorClient({ config }) // [!code hl] // 6. Create a "custom" Mutation Hook that utilizes the Client. // [!code hl] const { mutate } = useMutation({ // [!code hl] mutationFn: (asset) => walletClient.watchAsset(asset) // [!code hl] }) // [!code hl] return (
{/* ... */}
) } ``` ::: ## Private Key & Mnemonic Accounts It is possible to utilize Viem's [Private Key & Mnemonic Accounts](https://viem.sh/docs/accounts/local) with Wagmi by explicitly passing through the account via the `account` argument on Wagmi Actions. ```tsx import { http, createConfig, useSendTransaction } from 'wagmi' import { base, mainnet, optimism, zora } from 'wagmi/chains' import { parseEther } from 'viem' import { privateKeyToAccount } from 'viem/accounts' export const config = createConfig({ chains: [base, mainnet, optimism, zora], transports: { [base.id]: http(), [mainnet.id]: http(), [optimism.id]: http(), [zora.id]: http(), }, }) const account = privateKeyToAccount('0x...') // [!code hl] function Example() { const { data: hash } = useSendTransaction({ account, // [!code hl] to: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', value: parseEther('0.001') }) } ``` ::: info Wagmi currently does not support hoisting Private Key & Mnemonic Accounts to the top-level Wagmi Config – meaning you have to explicitly pass through the account to every Action. If you feel like this is a feature that should be added, please [open a discussion](https://github.com/wevm/wagmi/discussions/new?category=ideas). ::: ================================================ FILE: site/react/guides/write-to-contract.md ================================================ # Write to Contract The [`useWriteContract` Hook](/react/api/hooks/useWriteContract) allows you to mutate data on a smart contract, from a `payable` or `nonpayable` (write) function. These types of functions require gas to be executed, hence a transaction is broadcasted in order to change the state. In the guide below, we will teach you how to implement a "Mint NFT" form that takes in a dynamic argument (token ID) using Wagmi. The example below builds on the [Connect Wallet guide](/react/guides/connect-wallet) and uses the [useWriteContract](/react/api/hooks/useWriteContract) & [useWaitForTransactionReceipt](/react/api/hooks/useWaitForTransactionReceipt) hooks. If you have already completed the [Sending Transactions guide](/react/guides/send-transaction), this guide will look very similar! That's because writing to a contract internally broadcasts & sends a transaction. ## Example Feel free to check out the example before moving on: ## Steps ### 1. Connect Wallet Follow the [Connect Wallet guide](/react/guides/connect-wallet) guide to get this set up. ### 2. Create a new component Create your `MintNFT` component that will contain the Mint NFT logic. ::: code-group ```tsx [mint-nft.tsx] import * as React from 'react' export function MintNFT() { return (
) } ``` ::: ### 3. Add a form handler Next, we will need to add a handler to the form that will send the transaction when the user hits "Mint". This will be a basic handler in this step. ::: code-group ```tsx [mint-nft.tsx] import * as React from 'react' export function MintNFT() { async function submit(e: React.FormEvent) { // [!code ++] e.preventDefault() // [!code ++] const formData = new FormData(e.target as HTMLFormElement) // [!code ++] const tokenId = formData.get('tokenId') as string // [!code ++] } // [!code ++] return (
// [!code --] // [!code ++]
) } ``` ::: ### 4. Hook up the `useWriteContract` Hook Now that we have the form handler, we can hook up the [`useWriteContract` Hook](/react/api/hooks/useWriteContract) to send the transaction. ::: code-group ```tsx [mint-nft.tsx] import * as React from 'react' import { useWriteContract } from 'wagmi' // [!code ++] import { abi } from './abi' // [!code ++] export function MintNFT() { const { data: hash, writeContract } = useWriteContract() // [!code ++] async function submit(e: React.FormEvent) { e.preventDefault() const formData = new FormData(e.target as HTMLFormElement) const tokenId = formData.get('tokenId') as string writeContract({ // [!code ++] address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', // [!code ++] abi, // [!code ++] functionName: 'mint', // [!code ++] args: [BigInt(tokenId)], // [!code ++] }) // [!code ++] } return (
{hash &&
Transaction Hash: {hash}
} // [!code ++]
) } ``` ```ts [abi.ts] export const abi = [ { name: 'mint', type: 'function', stateMutability: 'nonpayable', inputs: [{ internalType: 'uint32', name: 'tokenId', type: 'uint32' }], outputs: [], }, ] as const ``` ::: ### 5. Add loading state (optional) We can optionally add a loading state to the "Mint" button while we are waiting confirmation from the user's wallet. ::: code-group ```tsx [mint-nft.tsx] import * as React from 'react' import { useWriteContract } from 'wagmi' import { abi } from './abi' export function MintNFT() { const { data: hash, isPending, // [!code ++] writeContract } = useWriteContract() async function submit(e: React.FormEvent) { e.preventDefault() const formData = new FormData(e.target as HTMLFormElement) const tokenId = formData.get('tokenId') as string writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi, functionName: 'mint', args: [BigInt(tokenId)], }) } return (
{hash &&
Transaction Hash: {hash}
}
) } ``` ```ts [abi.ts] export const abi = [ { name: 'mint', type: 'function', stateMutability: 'nonpayable', inputs: [{ internalType: 'uint32', name: 'tokenId', type: 'uint32' }], outputs: [], }, ] as const ``` ::: ### 6. Wait for transaction receipt (optional) We can also display the transaction confirmation status to the user by using the [`useWaitForTransactionReceipt` Hook](/react/api/hooks/useWaitForTransactionReceipt). ::: code-group ```tsx [mint-nft.tsx] import * as React from 'react' import { useWaitForTransactionReceipt, // [!code ++] useWriteContract } from 'wagmi' import { abi } from './abi' export function MintNFT() { const { data: hash, isPending, writeContract } = useWriteContract() async function submit(e: React.FormEvent) { e.preventDefault() const formData = new FormData(e.target as HTMLFormElement) const tokenId = formData.get('tokenId') as string writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi, functionName: 'mint', args: [BigInt(tokenId)], }) } const { isLoading: isConfirming, isSuccess: isConfirmed } = // [!code ++] useWaitForTransactionReceipt({ // [!code ++] hash, // [!code ++] }) // [!code ++] return (
{hash &&
Transaction Hash: {hash}
} {isConfirming &&
Waiting for confirmation...
} // [!code ++] {isConfirmed &&
Transaction confirmed.
} // [!code ++]
) } ``` ```ts [abi.ts] export const abi = [ { name: 'mint', type: 'function', stateMutability: 'nonpayable', inputs: [{ internalType: 'uint32', name: 'tokenId', type: 'uint32' }], outputs: [], }, ] as const ``` ::: ### 7. Handle errors (optional) If the user rejects the transaction, or the contract reverts, we can display an error message to the user. ::: code-group ```tsx [mint-nft.tsx] import * as React from 'react' import { type BaseError, // [!code ++] useWaitForTransactionReceipt, useWriteContract } from 'wagmi' import { abi } from './abi' export function MintNFT() { const { data: hash, error, // [!code ++] isPending, writeContract } = useWriteContract() async function submit(e: React.FormEvent) { e.preventDefault() const formData = new FormData(e.target as HTMLFormElement) const tokenId = formData.get('tokenId') as string writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi, functionName: 'mint', args: [BigInt(tokenId)], }) } const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({ hash, }) return (
{hash &&
Transaction Hash: {hash}
} {isConfirming &&
Waiting for confirmation...
} {isConfirmed &&
Transaction confirmed.
} {error && ( // [!code ++]
Error: {(error as BaseError).shortMessage || error.message}
// [!code ++] )} // [!code ++]
) } ``` ```ts [abi.ts] export const abi = [ { name: 'mint', type: 'function', stateMutability: 'nonpayable', inputs: [{ internalType: 'uint32', name: 'tokenId', type: 'uint32' }], outputs: [], }, ] as const ``` ::: ### 8. Wire it up! Finally, we can wire up our Mint NFT component to our application's entrypoint. ::: code-group ```tsx [app.tsx] import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { WagmiProvider } from 'wagmi' import { config } from './config' import { MintNft } from './mint-nft' // [!code ++] const queryClient = new QueryClient() function App() { return ( // [!code ++] ) } ``` ```tsx [mint-nft.tsx] import * as React from 'react' import { type BaseError, useWaitForTransactionReceipt, useWriteContract } from 'wagmi' import { abi } from './abi' export function MintNFT() { const { data: hash, error, isPending, writeContract } = useWriteContract() async function submit(e: React.FormEvent) { e.preventDefault() const formData = new FormData(e.target as HTMLFormElement) const tokenId = formData.get('tokenId') as string writeContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi, functionName: 'mint', args: [BigInt(tokenId)], }) } const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({ hash, }) return (
{hash &&
Transaction Hash: {hash}
} {isConfirming &&
Waiting for confirmation...
} {isConfirmed &&
Transaction confirmed.
} {error && (
Error: {(error as BaseError).shortMessage || error.message}
)}
) } ``` ```ts [abi.ts] export const abi = [ { name: 'mint', type: 'function', stateMutability: 'nonpayable', inputs: [{ internalType: 'uint32', name: 'tokenId', type: 'uint32' }], outputs: [], }, ] as const ``` ```tsx [config.ts] import { http, createConfig } from 'wagmi' import { base, mainnet, optimism } from 'wagmi/chains' import { injected, metaMask, safe, walletConnect } from 'wagmi/connectors' const projectId = '' export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), }, }) ``` ::: [See the Example.](#example) ================================================ FILE: site/react/installation.md ================================================ # Installation Install Wagmi via your package manager, a ` ``` Check out the React docs for info on how to use [React without JSX](https://react.dev/reference/react/createElement#creating-an-element-without-jsx). ================================================ FILE: site/react/typescript.md ================================================ # TypeScript ## Requirements Wagmi is designed to be as type-safe as possible! Things to keep in mind: - Types currently require using TypeScript {{typescriptVersion}}. - [TypeScript doesn't follow semver](https://www.learningtypescript.com/articles/why-typescript-doesnt-follow-strict-semantic-versioning) and often introduces breaking changes in minor releases. - Changes to types in this repository are considered non-breaking and are usually released as patch changes (otherwise every type enhancement would be a major version!). - It is highly recommended that you lock your `wagmi` and `typescript` versions to specific patch releases and upgrade with the expectation that types may be fixed or upgraded between any release. - The non-type-related public API of Wagmi still follows semver very strictly. To ensure everything works correctly, make sure your `tsconfig.json` has [`strict`](https://www.typescriptlang.org/tsconfig#strict) mode set to `true`. ::: code-group ```json [tsconfig.json] { "compilerOptions": { "strict": true } } ``` ::: ## Config Types By default React Context does not work well with type inference. To support strong type-safety across the React Context boundary, there are two options available: - Declaration merging to "register" your `config` globally with TypeScript. - `config` property to pass your `config` directly to hooks. ### Declaration Merging [Declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) allows you to "register" your `config` globally with TypeScript. The `Register` type enables Wagmi to infer types in places that wouldn't normally have access to type info via React Context alone. To set this up, add the following declaration to your project. Below, we co-locate the declaration merging and the `config` set up. ```ts import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' declare module 'wagmi' { // [!code focus] interface Register { // [!code focus] config: typeof config // [!code focus] } // [!code focus] } // [!code focus] export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` Since the `Register` type is global, you only need to add it once in your project. Once set up, you will get strong type-safety across your entire project. For example, query hooks will type `chainId` based on your `config`'s `chains`. ```ts twoslash // @twoslash-cache: {"v":1,"hash":"296ef5d0fbed904e9f4bc9bf96c55b1f47345dcdd993965e6d5420eb1c6583d7","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgAhVhBEBrAHKCAtgCMyAHhGT+7AOa86NMFDi8AwoZO8AvLfvHdpGMyiTWGXqgAdKV4QrUUVAFFaLEUPUjhEXmAgkNTUjy8fP1h+ZkFWNETk4LTS3gzvMF9eMGYNGESAkAi0fDI4EWYwJoBuFLLSiqzpUlZGgjQ0LASAehmYVvbOsAA6CV7+gfTPSurmLHYAVVHx/EnpxDn99hWFtvjltYgZ642S0oBfPvevzd4wpTKAAq7HqiQAjAAmAAMsO+aQMYDQpGYYgSST+aSGVT8MDAcEOYHYJHibAASvAIKwSUVMQNsXsoFAPHB0U1obQYFzuVzwQAWKAAdnBAA4RJCtHzBVAAJwyyEAZlgzC04IVCoArDB+XyeW8tlidsMASobBkaFBEoroSKNXaRfCBr93obMjjeBp8uJOqxWAraS76Ub3V5mfA2SAOZ1weCtLBoRqZYLBVoFQA2BUxtOC6GQkUitMSmCQ5jgwUKpNp6Pg/UGkIMvwm5RmzwWiF8zXp6Hgx1lZ1pfupFbD3j8j0QDy8YcrXu8EnsfgYAASXHwAH5EoxGCIOHjCrZd0jdNOAHwUXhYZgo+o0eKJABqZAXy9XAAUr3UFu0+I4T7xX6QEAaOwsi6FoEBUp4YAnnwAA+0iWDARhgDAUDfB857FGk07oQAumevAiPgzDsGAACSUBmPQeJWIRrjIE0REkfiTS4cgYCaDopBsU07BQKxTh0WARjGAxI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JFTDTEUgCRUiZpzUQHIpaK1yrNKgNk3auTxJcNFidYpuEDoKK0WA7KSRIHMJ/tXAQgENBOKQcBRxQQghMO/lxRgwBCLEVIi00cipq7cCKjeZgSBQDmBlhIMAeB9EfA+EAA==="} // @errors: 2322 import { type Config } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' declare module 'wagmi' { interface Register { config: Config } } // ---cut--- import { useBlockNumber } from 'wagmi' useBlockNumber({ chainId: 123 }) ``` You just saved yourself a runtime error and you didn't even need to pass your `config`. 🎉 ### Hook `config` Property For cases where you have more than one Wagmi `config` or don't want to use the declaration merging approach, you can pass a specific `config` directly to hooks via the `config` property. ```ts import { createConfig, http } from 'wagmi' import { mainnet, optimism } from 'wagmi/chains' export const configA = createConfig({ // [!code focus] chains: [mainnet], // [!code focus] transports: { // [!code focus] [mainnet.id]: http(), // [!code focus] }, // [!code focus] }) // [!code focus] export const configB = createConfig({ // [!code focus] chains: [optimism], // [!code focus] transports: { // [!code focus] [optimism.id]: http(), // [!code focus] }, // [!code focus] }) // [!code focus] ``` As you expect, `chainId` is inferred correctly for each `config`. ```ts twoslash // @twoslash-cache: {"v":1,"hash":"11543ad9699c8fdbef7c0ce7ac938f71b77d113989b5f3a8de83d428479463c3","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgAhVhBEBrAHKCAtgCMyAHhGT+7AOa86NMFDi8AwoZO8AvLfvGKvEfmbswASShm9DCW1gZgRsbIADognt5gcDEAushgmjqkKTHsUMlOHq7RsV4+iSApadpkWSA5ye6yrDBiACLMaMz5WiY+aAB8jFjMpMwaMDSkcAD8iLwAqrIKSmrpZAAKw6PjZHD6ru5xPv4NME2t7cx93LML8ooq6lWkAErjgqRgACrYMLqNzWg2h0+lEwOwNFgIKQ0NJFvcVk9KCAoEoEIgCGg0Fg4IgAPS4gDuzGMGnYADo4PhcaQYMwxLjmFh2LjCBBlHBcTI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6ZGaQjCZCnCXYoibRW2WWW4g5Fajat4van4s6oEm6gSZ6hEh5WZalGSXEpSY1ixI0XKeZPSWuOqaFcFSFeOdMbZpyTxJNtNryQtl5AKStsKe+KKTADtntpKYce1d5eZAqbdkOSqbbi2Sap8n1SFQLhZQaYDsDqDmbqaeaTALDpxFaVADaSjmjg6U6WOUcVlalB6V6T6RTjtVVo7hZZ2XuczuGStbWTzrGUZQ1WycNlOYDd2TxIeUyTLntDmRoMrqroWRuRDQNZOTubDVWQjaFfWRbmRFbiOT9SxuZYVbQADXjZ+D2QpW9WtQORtQHs2YFVDXTrubTbOQzR1QuYninmntZKubHEWeldjeFTTdzWXrzSVBGlXqedGlkheemFec0smiUmUq3o+VUrwDmsWj3o0u+S0i+RtE4EPr+ZWv0oBVdMBQ2jPhMoYdzG+O2hgaYUsoha4HIChbYTAdssKC9IaAbJbMjNCEBG6DvpqOYgIOWsHITKSEHKCKCF/rvowMADofEP4PoQcEfF4SYJcuYtwMneAZqGnRnUcAGqxDnRcrMPhXIIXUiDNMwEgKAOYBBBIGAHgHbGaGaEAA="} // @errors: 2322 import { type Config } from 'wagmi' import { mainnet, optimism } from 'wagmi/chains' declare const configA: Config declare const configB: Config // ---cut--- import { useBlockNumber } from 'wagmi' useBlockNumber({ chainId: 123, config: configA }) useBlockNumber({ chainId: 123, config: configB }) ``` This approach is more explicit, but works well for advanced use-cases, if you don't want to use React Context or declaration merging, etc. ## Const-Assert ABIs & Typed Data Wagmi can infer types based on [ABIs](https://docs.soliditylang.org/en/latest/abi-spec.html#json) and [EIP-712](https://eips.ethereum.org/EIPS/eip-712) Typed Data definitions, powered by [Viem](https://viem.sh) and [ABIType](https://github.com/wevm/abitype). This achieves full end-to-end type-safety from your contracts to your frontend and enlightened developer experience by autocompleting ABI item names, catching misspellings, inferring argument and return types (including overloads), and more. For this to work, you must either [const-assert](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions) ABIs and Typed Data (more info below) or define them inline. For example, `useReadContract`'s `abi` configuration parameter: ```ts const { data } = useReadContract({ abi: […], // <--- defined inline // [!code focus] }) ``` ```ts const abi = […] as const // <--- const assertion // [!code focus] const { data } = useReadContract({ abi }) ``` If type inference isn't working, it's likely you forgot to add a `const` assertion or define the configuration parameter inline. Also, make sure your ABIs, Typed Data definitions, and [TypeScript configuration](#requirements) are valid and set up correctly. ::: tip Unfortunately [TypeScript doesn't support importing JSON `as const` yet](https://github.com/microsoft/TypeScript/issues/32063). Check out the [Wagmi CLI](/cli/getting-started) to help with this! It can automatically fetch ABIs from Etherscan and other block explorers, resolve ABIs from your Foundry/Hardhat projects, generate React Hooks, and more. ::: Anywhere you see the `abi` or `types` configuration property, you can likely use const-asserted or inline ABIs and Typed Data to get type-safety and inference. These properties are also called out in the docs. Here's what [`useReadContract`](/react/api/hooks/useReadContract) looks like with and without a const-asserted `abi` property. ::: code-group ```ts twoslash [Const-Asserted] // @twoslash-cache: {"v":1,"hash":"d7475b91e63cc31608c546a0ebb47f73a765bd7e10587f2f8d3a8df8fdf837c6","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgAlGMygBhSWlLMxAHhGS4aXswBG7XnRpgocXgEETvAD69SiqJNYZpYANaQA7mDIALoUAsJiEmAAcswAtjBm9DCW1qpg6ppoAGLh4pIx8VrG7KEAOiBYgi7ljrzlROwwfuUAfKG6YPqGpADm1ubJVrxpGWI5onlgNr1wRSZlFVUwNU71jc2UYRORBTBtvB387D2JFkNpRycAvMOSl6GyrDBiACLMaMy8NwpKIxqv72YcxKWwi+TiMFCzBmLRajCw0IhNFIcAA/IheABVWQ/FRqf5oAAKiPiyNmxVCQm24PiUJm7TuxweMCeAI+LW4GOx8lcf0yCjQVTAABVsDBgZTcjsIXS+szWWg3uzSmB2LEsBBSAYZDzfvjMpQQG4RAhEAQ0GgsHBEAB6G1+Zg9WLsAB0cHwNpcmRtzCw7BthAg3jgN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U5IMse3gMtdHH85xu48hvjfQBP3xzSJ09yyu5rI/gWQcBgIKjmOBOJjPS5wLggCaPAK41wbgptuXcnkDxHg8qec8l5AQ3lIHeVcvAJOvlY3BT88GuOZtM+BQEe6kNzIfrmqsom8BJekwOLZ0WPiufHOkDzUGg4+aXP53g64uhbh3HuMLngItnk3pVz4/Bbz3kS8+STb49ORsQLBNLRnV08dLgWCCuW65CabtWCKtZoBie9pqAwwA/bhhLAYFsAgWqxF4AAcgdE6dgF2VQqic+VfrvATs3ArmnAkjA7okIxBdqeWQABCNgb5xnXcoZgVZPzPU/LnEQKE0swFggAUSR1WFCcZ8rN34MoSH/AhnNzjCIWCF2KAiWKBiFN+zDmk6MqhyhF3LncSbST+7ck2f0QUxiZAf3aA2CrMofgBOUIoXTPlF4n4jBxklyhfK+UjBwZvlWFHzBPz5WYOxm+KFYL8DyumGAF2QiNO4KziCKpDSkkgogUAAxOiRDwBZEALYWxAA="} const erc721Abi = [ { name: 'balanceOf', type: 'function', stateMutability: 'view', inputs: [{ type: 'address', name: 'owner' }], outputs: [{ type: 'uint256' }], }, { name: 'isApprovedForAll', type: 'function', stateMutability: 'view', inputs: [ { type: 'address', name: 'owner' }, { type: 'address', name: 'operator' }, ], outputs: [{ type: 'bool' }], }, { name: 'getApproved', type: 'function', stateMutability: 'view', inputs: [{ type: 'uint256', name: 'tokenId' }], outputs: [{ type: 'address' }], }, { name: 'ownerOf', type: 'function', stateMutability: 'view', inputs: [{ type: 'uint256', name: 'tokenId' }], outputs: [{ type: 'address' }], }, { name: 'tokenURI', type: 'function', stateMutability: 'pure', inputs: [{ type: 'uint256', name: 'tokenId' }], outputs: [{ type: 'string' }], }, ] as const // ---cut--- import { useReadContract } from 'wagmi' const { data } = useReadContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: erc721Abi, functionName: 'balanceOf', // ^? args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'], // ^? }) data // ^? ``` ```ts twoslash [Not Const-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OHwJMpwQBNHgOcC4lzaVXOuDuW4dzt33IeY8gIzykAvPOXgTz7zdIgs+NJxCzlkJyUBOFgyEVF2rMivAbLXkDk4fSj4OKOpgHxYSs0xLeCLi6CuNcG4qWeBpQebBMrPj8HPJeVlt5nkPhBTPRA4EuUQpIVC1egFASCrzqUxFSAqwthCBw2AeBraagMMAO24YSwGBbAIeusReAAHIHROnYNGlUKpMVyQNfpL4wb8Lh0YK9deG4MTRrClkAAQjYXKcZBnKGYFWZ8UAoDPljiIOCXKYDgWKlWOCcZErRX4MoGt/BCGxREOBaNFBGLFAxE4vhAix2cVGS0y60b/oeXXD5UdSawAbtImsjEyBC3hUijFOKCVkqpXSnFZGeUCrFVKuVSq1Var1UatGkIjluAbqAiqQ0pJgKIFAAMTokQ8AyRAC2FsQA"} declare const erc721Abi: { name: string; type: string; stateMutability: string; inputs: { type: string; name: string; }[]; outputs: { type: string; }[]; }[] // ---cut--- import { useReadContract } from 'wagmi' const { data } = useReadContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: erc721Abi, functionName: 'balanceOf', // ^? args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'], // ^? }) data // ^? ``` :::

You can prevent runtime errors and be more productive by making sure your ABIs and Typed Data definitions are set up appropriately. 🎉 ```ts twoslash // @twoslash-cache: {"v":1,"hash":"0a7ec06948f56913d5c1a0817fa61f890c5a7843c9839243ebabed5019be8a0e","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgAlGMygBhSWlLMxAHhGS4aXswBG7XnRpgocXgEETvAD69SiqJNYZpYANaQA7mDIALoUAsJiEmAAcswAtjBm9DCW1qpg6ppoAGLh4pIx8VrG7KEAOiBYgi7ljrzlROwwfuUAfKG6YPqGpADm1ubJVrxpGWI5onlgNr1wRSZlFVUwNU71jc2UYRORBTBtvB387D2JFkNpRycAvMOSl6GyrDBiACLMaMy8N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YM9HOZhSC+P8YEigZ510DXNZO54h5zUAfUdwQ0pJmBIFAAMTokQ8CKpbC2IAA="} // @errors: 2820 const erc721Abi = [ { name: 'balanceOf', type: 'function', stateMutability: 'view', inputs: [{ type: 'address', name: 'owner' }], outputs: [{ type: 'uint256' }], }, { name: 'isApprovedForAll', type: 'function', stateMutability: 'view', inputs: [ { type: 'address', name: 'owner' }, { type: 'address', name: 'operator' }, ], outputs: [{ type: 'bool' }], }, { name: 'getApproved', type: 'function', stateMutability: 'view', inputs: [{ type: 'uint256', name: 'tokenId' }], outputs: [{ type: 'address' }], }, { name: 'ownerOf', type: 'function', stateMutability: 'view', inputs: [{ type: 'uint256', name: 'tokenId' }], outputs: [{ type: 'address' }], }, { name: 'tokenURI', type: 'function', stateMutability: 'pure', inputs: [{ type: 'uint256', name: 'tokenId' }], outputs: [{ type: 'string' }], }, ] as const // ---cut--- import { useReadContract } from 'wagmi' useReadContract({ abi: erc721Abi, functionName: 'balanecOf', }) ``` ## Configure Internal Types For advanced use-cases, you may want to configure Wagmi's internal types. Most of Wagmi's types relating to ABIs and EIP-712 Typed Data are powered by [ABIType](https://github.com/wevm/abitype). See the [ABIType docs](https://abitype.dev) for more info on how to configure types. ================================================ FILE: site/react/why.md ================================================ # Why Wagmi ## The Problems Building Ethereum applications is hard. Apps need to support connecting wallets, multiple chains, signing messages and data, sending transactions, listening for events and state changes, refreshing stale blockchain data, and much more. This is all on top of solving for app-specific use-cases and providing polished user experiences. The ecosystem is also continuously evolving, meaning you need to adapt to new improvements or get left behind. App developers should not need to worry about connecting tens of different wallets, the intricacies of multi-chain support, typos accidentally sending an order of magnitude more ETH or calling a misspelled contract function, or accidentally spamming their RPC provider, costing thousands in compute units. Wagmi solves all these problems and more — allowing app developers to focus on building high-quality and performant experiences for Ethereum — by focusing on **developer experience**, **performance**, **feature coverage**, and **stability.** ## Developer Experience Wagmi delivers a great developer experience through modular and composable APIs, automatic type safety and inference, and comprehensive documentation. It provides developers with intuitive building blocks to build their Ethereum apps. While Wagmi's APIs might seem more verbose at first, it makes Wagmi's modular building blocks extremely flexible. Easy to move around, change, and remove. It also allows developers to better understand Ethereum concepts as well as understand _what_ and _why_ certain properties are being passed through. Learning how to use Wagmi is a great way to learn how to interact with Ethereum in general. Wagmi also provides [strongly typed APIs](/react/typescript), allowing consumers to get the best possible experience through [autocomplete](https://twitter.com/awkweb/status/1555678944770367493), [type inference](https://twitter.com/jakemoxey/status/1570244174502588417?s=20), as well as static validation. You often just need to provide an ABI and Wagmi can help you autocomplete your way to success, identify type errors before your users do, drill into blockchain errors [at compile and runtimes](/react/guides/error-handling) with surgical precision, and much more. The API documentation is comprehensive and contains usage info for _every_ module in Wagmi. The core team uses a [documentation](https://gist.github.com/zsup/9434452) and [test driven](https://en.wikipedia.org/wiki/Test-driven_development#:~:text=Test%2Ddriven%20development%20(TDD),software%20against%20all%20test%20cases.) development approach to building modules, which leads to predictable and stable APIs. ## Performance Performance is critical for applications on all sizes. Slow page load and interactions can cause users to stop using applications. Wagmi uses and is built by the same team behind [Viem](https://viem.sh), the most performant production-ready Ethereum library. End users should not be required to download a module of over 100kB in order to interact with Ethereum. Wagmi is optimized for tree-shaking and dead-code elimination, allowing apps to minimize bundle size for fast page load times. Data layer performance is also critical. Slow, unnecessary, and manual data fetching can make apps unusable and cost thousands in RPC compute units. Wagmi supports caching, deduplication, persistence, and much more through [TanStack Query](/react/guides/tanstack-query). ## Feature Coverage Wagmi supports the most popular and commonly-used Ethereum features out of the box with 40+ React Hooks for accounts, wallets, contracts, transactions, signing, ENS, and more. Wagmi also supports just about any wallet out there through official [connectors](/react/api/connectors), [EIP-6963 support](/react/api/createConfig#multiinjectedproviderdiscovery), and [extensible API](/dev/creating-connectors). If you need lower-level control, you can always drop down to [Wagmi Core](/core/getting-started) or [Viem](https://viem.sh), which Wagmi uses internally to perform blockchain operations. Wagmi also manages multi-chain support automatically so developers can focus on their applications instead of adding custom code. Finally, Wagmi has a [CLI](/cli/getting-started) to manage ABIs as well as a robust ecosystem of third-party libraries, like [ConnectKit](https://docs.family.co/connectkit), [Dynamic](https://www.dynamic.xyz), [Privy](https://privy.io), and many more, so you can get started quickly without needing to build everything from scratch. ## Stability Stability is a fundamental principle for Wagmi. Many organizations, large and small, rely heavily on Wagmi and expect it to be entirely stable for their users and applications. Wagmi's test suite runs against forked Ethereum nodes to make sure functions work across chains. The test suite also runs type tests against many different versions of peer dependencies, like TypeScript, to ensure compatibility with the latest releases of other popular software. Wagmi follows semver so developers can upgrade between versions with confidence. Starting with Wagmi v2, new functionality will be opt-in with old functionality being deprecated alongside the new features. This means upgrading to the latest major versions will not require immediate changes. Lastly, the core team works full-time on Wagmi and [related projects](https://github.com/wevm), and is constantly improving Wagmi and keeping it up-to-date with industry trends and changes. ================================================ FILE: site/shared/connectors/baseAccount.md ================================================ # baseAccount Connector for the [Base Account SDK](https://github.com/base/account-sdk). ## Import ```ts-vue import { baseAccount } from '{{connectorsPackageName}}' ``` ## Install ::: code-group ```bash-vue [pnpm] pnpm add @base-org/account@{{connectorDependencyVersion}} ``` ```bash-vue [npm] npm install @base-org/account@{{connectorDependencyVersion}} ``` ```bash-vue [yarn] yarn add @base-org/account@{{connectorDependencyVersion}} ``` ```bash-vue [bun] bun add @base-org/account@{{connectorDependencyVersion}} ``` ::: ## Usage ```ts-vue import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { baseAccount } from '{{connectorsPackageName}}' // [!code hl] export const config = createConfig({ chains: [mainnet, sepolia], connectors: [baseAccount()], // [!code hl] transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` :::warning Before going to production, it is highly recommended to set an [`appName`](#appname) and [`appLogoUrl`](#applogourl) for your application that can be displayed upon connection to the wallet. ::: ## Parameters ```ts-vue import { type baseAccountParameters } from '{{connectorsPackageName}}' ``` Check out the [Base Account SDK docs](https://www.base.org/build/base-account) for more info. ### appName `string` Application name. ```ts-vue import { baseAccount } from '{{connectorsPackageName}}' const connector = baseAccount({ appName: 'My Wagmi App', // [!code focus] }) ``` ### appLogoUrl `string | null | undefined` Application logo image URL; favicon is used if unspecified. ```ts-vue import { baseAccount } from '{{connectorsPackageName}}' const connector = baseAccount({ appName: 'My Wagmi App', appLogoUrl: 'https://example.com/myLogoUrl.png', // [!code focus] }) ``` ================================================ FILE: site/shared/connectors/coinbaseWallet.md ================================================ # coinbaseWallet Connector for the [Coinbase Wallet SDK](https://github.com/coinbase/coinbase-wallet-sdk). ## Import ```ts-vue import { coinbaseWallet } from '{{connectorsPackageName}}' ``` ## Install ::: code-group ```bash-vue [pnpm] pnpm add @coinbase/wallet-sdk@{{connectorDependencyVersion}} ``` ```bash-vue [npm] npm install @coinbase/wallet-sdk@{{connectorDependencyVersion}} ``` ```bash-vue [yarn] yarn add @coinbase/wallet-sdk@{{connectorDependencyVersion}} ``` ```bash-vue [bun] bun add @coinbase/wallet-sdk@{{connectorDependencyVersion}} ``` ::: ## Usage ```ts-vue import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { coinbaseWallet } from '{{connectorsPackageName}}' // [!code hl] export const config = createConfig({ chains: [mainnet, sepolia], connectors: [coinbaseWallet()], // [!code hl] transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` :::warning Before going to production, it is highly recommended to set an [`appName`](#appname) and [`appLogoUrl`](#applogourl) for your application that can be displayed upon connection to the wallet. ::: ## Parameters ```ts-vue import { type CoinbaseWalletParameters } from '{{connectorsPackageName}}' ``` Check out the [Coinbase Wallet SDK docs](https://github.com/coinbase/coinbase-wallet-sdk) for more info. ### appName `string` Application name. ```ts-vue import { coinbaseWallet } from '{{connectorsPackageName}}' const connector = coinbaseWallet({ appName: 'My Wagmi App', // [!code focus] }) ``` ### appLogoUrl `string | null | undefined` Application logo image URL; favicon is used if unspecified. ```ts-vue import { coinbaseWallet } from '{{connectorsPackageName}}' const connector = coinbaseWallet({ appName: 'My Wagmi App', appLogoUrl: 'https://example.com/myLogoUrl.png', // [!code focus] }) ``` ### preference Preference for the type of wallet to display. ```ts-vue import { coinbaseWallet } from '{{connectorsPackageName}}' const connector = coinbaseWallet({ appName: 'My Wagmi App', preference: { // [!code focus] options: 'smartWalletOnly' // [!code focus] }, // [!code focus] }) ``` #### attribution `` { auto?: boolean | undefined; dataSuffix?: `0x${string}` | undefined } `` This option only applies to Coinbase Smart Wallet. When a valid data suffix is supplied, it is appended to the `initCode` and `executeBatch` calldata. Coinbase Smart Wallet expects a 16 byte hex string. If the data suffix is not a 16 byte hex string, the Smart Wallet will ignore the property. If auto is true, the Smart Wallet will generate a 16 byte hex string from the apps origin. #### keysUrl `string` - The URL for the keys popup. - By default, `https://keys.coinbase.com/connect` is used for production. Use `https://keys-dev.coinbase.com/connect` for development environments. #### options `"all" | "eoaOnly" | "smartWalletOnly"` Preference for the type of wallet to display. - `'eoaOnly'`: Uses EOA Browser Extension or Mobile Coinbase Wallet. - `'smartWalletOnly'`: Displays Smart Wallet popup. - `'all'` (default): Supports both `'eoaOnly'` and `'smartWalletOnly'` based on context. ================================================ FILE: site/shared/connectors/injected.md ================================================ # injected Connector for [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) Ethereum Providers. ## Import ```ts-vue import { injected } from '{{connectorsPackageName}}' ``` ## Usage ```ts-vue{3,7} import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { injected } from '{{connectorsPackageName}}' export const config = createConfig({ chains: [mainnet, sepolia], connectors: [injected()], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` ## Parameters ```ts-vue import { type InjectedParameters } from '{{connectorsPackageName}}' ``` ### shimDisconnect `boolean | undefined` - MetaMask and other injected providers do not support programmatic disconnect. - This flag simulates the disconnect behavior by keeping track of connection status in storage. See [GitHub issue](https://github.com/MetaMask/metamask-extension/issues/10353) for more info. - Defaults to `true`. ```ts-vue import { injected } from '{{connectorsPackageName}}' const connector = injected({ shimDisconnect: false, // [!code focus] }) ``` ### target `TargetId | (TargetMap[TargetId] & { id: string }) | (() => (TargetMap[TargetId] & { id: string }) | undefined) | undefined` - [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) Ethereum Provider to target. - [EIP-6963](https://eips.ethereum.org/EIPS/eip-6963) supported via `createConfig`'s `multiInjectedProviderDiscovery` property. ```ts-vue import { injected } from '{{connectorsPackageName}}' const connector = injected({ target() { // [!code focus] return { // [!code focus] id: 'windowProvider', // [!code focus] name: 'Window Provider', // [!code focus] provider: window.ethereum, // [!code focus] } // [!code focus] }, // [!code focus] }) ``` ### unstable_shimAsyncInject `boolean | number | undefined` Watches for async provider injection via the `ethereum#initialized` event. When `true`, defaults to `1_000` milliseconds. Otherwise, uses a provided value of milliseconds. ```ts-vue import { injected } from '{{connectorsPackageName}}' const connector = injected({ unstable_shimAsyncInject: 2_000, // [!code focus] }) ``` ================================================ FILE: site/shared/connectors/metaMask.md ================================================ # metaMask Connector for [MetaMask Connect](https://github.com/MetaMask/connect-monorepo). ## Import ```ts-vue import { metaMask } from '{{connectorsPackageName}}' ``` ## Install ::: code-group ```bash-vue [pnpm] pnpm add @metamask/connect-evm@{{connectorDependencyVersion}} ``` ```bash-vue [npm] npm install @metamask/connect-evm@{{connectorDependencyVersion}} ``` ```bash-vue [yarn] yarn add @metamask/connect-evm@{{connectorDependencyVersion}} ``` ```bash-vue [bun] bun add @metamask/connect-evm@{{connectorDependencyVersion}} ``` ::: ## Usage ```ts-vue{3,7} import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { metaMask } from '{{connectorsPackageName}}' export const config = createConfig({ chains: [mainnet, sepolia], connectors: [metaMask()], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` ## Parameters ```ts-vue import { type MetaMaskParameters } from '{{connectorsPackageName}}' ``` Check out the [MetaMask Connect docs](https://docs.metamask.io/wallet/connect/3rd-party-libraries/wagmi/) for more info. A few options are omitted that Wagmi manages internally. ### dapp `DappMetadata | undefined` Metadata is used to fill details for the UX on confirmation screens in MetaMask, including the following fields: - `name`: `string` - The name of the dapp. - `url`: `string` - URL of the dapp (defaults to `window.location.origin`). - `iconUrl`: `string` - URL to the dapp's favicon or icon. Defaults to `{ name: window.location.hostname }`. ```ts-vue import { metaMask } from '{{connectorsPackageName}}' const connector = metaMask({ dapp: { // [!code focus] name: 'My Wagmi App', // [!code focus] url: 'https://example.com', // [!code focus] iconUrl: 'https://example.com/favicon.ico', // [!code focus] } }) ``` ### debug `boolean | undefined` Enables debug mode for the MetaMask SDK. When enabled, provides additional logging and debugging information. ```ts-vue import { metaMask } from '{{connectorsPackageName}}' const connector = metaMask({ debug: true // [!code focus] }) ``` ### connectAndSign `string | undefined` Shortcut to connect and sign a message in a single operation. When provided, the connector will connect to MetaMask and immediately prompt the user to sign the specified message. This parameter is mutually exclusive with `connectWith` - only one can be used at a time. ```ts-vue import { metaMask } from '{{connectorsPackageName}}' const connector = metaMask({ connectAndSign: 'Sign this message to connect', // [!code focus] }) ``` ### connectWith `{ method: string; params: unknown[] } | undefined` Allows connecting with any RPC method. When provided, the connector will connect to MetaMask and immediately call the specified RPC method with the given parameters. This parameter is mutually exclusive with `connectAndSign` - only one can be used at a time. ```ts-vue import { metaMask } from '{{connectorsPackageName}}' const connector = metaMask({ connectWith: { // [!code focus] method: 'eth_requestAccounts', // [!code focus] params: [], // [!code focus] } }) ``` ## Advanced By default, if the EIP-6963 MetaMask injected provider is detected, this connector will replace it. EIP-6963 defines a standard way for dapps to interact with multiple wallets simultaneously by injecting providers into the browser. Wallets that implement this standard can make their presence known to dapps in a consistent and predictable manner. See the [`rdns` property](https://wagmi.sh/dev/creating-connectors#properties) for more information. ================================================ FILE: site/shared/connectors/mock.md ================================================ # mock Connector for mocking Wagmi functionality. ## Import ```ts-vue import { mock } from '{{connectorsPackageName}}' ``` ## Usage ```ts-vue{3,8-14} import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { mock } from '{{connectorsPackageName}}' export const config = createConfig({ chains: [mainnet, sepolia], connectors: [ mock({ accounts: [ '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', '0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC', ], }), ], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` ## Parameters ```ts-vue import { type MockParameters } from '{{connectorsPackageName}}' ``` ### accounts `readonly [Address, ...Address[]]` Accounts to use with the connector. ```ts-vue import { mock } from '{{connectorsPackageName}}' const connector = mock({ accounts: [ // [!code focus] '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', // [!code focus] '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', // [!code focus] '0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC', // [!code focus] '0x90F79bf6EB2c4f870365E785982E1f101E93b906', // [!code focus] '0x15d34aaf54267db7d7c367839aaf71a00a2c6a65', // [!code focus] '0x9965507D1a55bcC2695C58ba16FB37d819B0A4dc', // [!code focus] '0x976EA74026E726554dB657fA54763abd0C3a0aa9', // [!code focus] '0x14dC79964da2C08b23698B3D3cc7Ca32193d9955', // [!code focus] '0x23618e81E3f5cdF7f54C3d65f7FBc0aBf5B21E8f', // [!code focus] '0xa0Ee7A142d267C1f36714E4a8F75612F20a79720', // [!code focus] ], // [!code focus] }) ``` ### features `{ connectError?: boolean | Error | undefined; reconnect?: boolean | undefined; signMessageError?: boolean | Error | undefined; signTypedDataError?: boolean | Error | undefined; switchChainError?: boolean | Error | undefined; } | undefined` Feature flags that change behavior of Wagmi internals. ```ts-vue import { mock } from '{{connectorsPackageName}}' import { UserRejectedRequestError } from 'viem' const connector = mock({ accounts: [ '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266', '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', '0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC', ], features: { // [!code focus] connectError: new UserRejectedRequestError(new Error('Failed to connect.')), // [!code focus] reconnect: false, // [!code focus] }, // [!code focus] }) ``` #### defaultConnected `boolean | undefined` Whether the connector is connected by default. #### connectError `boolean | Error | undefined` Whether to throw an error when `connector.connect` is called. #### reconnect `boolean | undefined` Enables reconnecting to connector. #### signMessageError `boolean | Error | undefined` Whether to throw an error when `'personal_sign'` is called. #### signTypedDataError `boolean | Error | undefined` Whether to throw an error when `'eth_signTypedData_v4'` is called. #### switchChainError `boolean | Error | undefined` Whether to throw an error when `connector.switchChain` is called. ================================================ FILE: site/shared/connectors/porto.md ================================================ # porto Connector for [Porto](https://porto.sh). ## Import ```ts-vue import { porto } from '{{connectorsPackageName}}' ``` ## Install ::: code-group ```bash-vue [pnpm] pnpm add porto@{{connectorDependencyVersion}} ``` ```bash-vue [npm] npm install porto@{{connectorDependencyVersion}} ``` ```bash-vue [yarn] yarn add porto@{{connectorDependencyVersion}} ``` ```bash-vue [bun] bun add porto@{{connectorDependencyVersion}} ``` ::: ## Usage ```ts-vue import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { porto } from '{{connectorsPackageName}}' // [!code hl] export const config = createConfig({ chains: [mainnet, sepolia], connectors: [porto()], // [!code hl] transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` ## Parameters ```ts-vue import { type PortoParameters } from '{{connectorsPackageName}}' ``` See [`Porto.create` Parameters](https://porto.sh/sdk/api/porto/create#parameters) ================================================ FILE: site/shared/connectors/safe.md ================================================ # safe Connector for [Safe Apps SDK](https://github.com/safe-global/safe-apps-sdk). ## Import ```ts-vue import { safe } from '{{connectorsPackageName}}' ``` ## Install ::: code-group ```bash-vue [pnpm] pnpm add @safe-global/safe-apps-provider@{{connectorDependencyVersions?.[0]}} @safe-global/safe-apps-sdk@{{connectorDependencyVersions?.[1]}} ``` ```bash-vue [npm] npm install @safe-global/safe-apps-provider@{{connectorDependencyVersions?.[0]}} @safe-global/safe-apps-sdk@{{connectorDependencyVersions?.[1]}} ``` ```bash-vue [yarn] yarn add @safe-global/safe-apps-provider@{{connectorDependencyVersions?.[0]}} @safe-global/safe-apps-sdk@{{connectorDependencyVersions?.[1]}} ``` ```bash-vue [bun] bun add @safe-global/safe-apps-provider@{{connectorDependencyVersions?.[0]}} @safe-global/safe-apps-sdk@{{connectorDependencyVersions?.[1]}} ``` ::: ## Usage ```ts-vue{3,7} import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { safe } from '{{connectorsPackageName}}' export const config = createConfig({ chains: [mainnet, sepolia], connectors: [safe()], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` ## Parameters ```ts-vue import { type SafeParameters } from '{{connectorsPackageName}}' ``` Check out the [Safe docs](https://github.com/safe-global/safe-apps-sdk/tree/main/packages/safe-apps-sdk) for more info. ### allowedDomains `RegExp[] | undefined` ```ts-vue import { safe } from '{{connectorsPackageName}}' const connector = safe({ allowedDomains: [/app.safe.global$/], // [!code focus] }) ``` ### debug `boolean | undefined` ```ts-vue import { safe } from '{{connectorsPackageName}}' const connector = safe({ debug: true, // [!code focus] }) ``` ### shimDisconnect `boolean | undefined` - This flag simulates disconnect behavior by keeping track of connection status in storage. - Defaults to `false`. ```ts-vue import { safe } from '{{connectorsPackageName}}' const connector = safe({ shimDisconnect: true, // [!code focus] }) ``` ================================================ FILE: site/shared/connectors/walletConnect.md ================================================ # walletConnect Connector for [WalletConnect](https://walletconnect.com). ## Import ```ts-vue import { walletConnect } from '{{connectorsPackageName}}' ``` ## Install ::: code-group ```bash-vue [pnpm] pnpm add @walletconnect/ethereum-provider@{{connectorDependencyVersion}} ``` ```bash-vue [npm] npm install @walletconnect/ethereum-provider@{{connectorDependencyVersion}} ``` ```bash-vue [yarn] yarn add @walletconnect/ethereum-provider@{{connectorDependencyVersion}} ``` ```bash-vue [bun] bun add @walletconnect/ethereum-provider@{{connectorDependencyVersion}} ``` ::: ## Usage ```ts-vue{3,8-10} import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { walletConnect } from '{{connectorsPackageName}}' export const config = createConfig({ chains: [mainnet, sepolia], connectors: [ walletConnect({ projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', }), ], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` ## Parameters ```ts-vue import { type WalletConnectParameters } from '{{connectorsPackageName}}' ``` Check out the [WalletConnect docs](https://github.com/WalletConnect/walletconnect-monorepo/tree/v2.0/providers/ethereum-provider) for more info. A few options are omitted that Wagmi manages internally. ### customStoragePrefix `string | undefined` Custom storage prefix for persisting provider state. ```ts-vue import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ customStoragePrefix: 'wagmi', // [!code focus] projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', }) ``` ### disableProviderPing `boolean | undefined` ```ts-vue import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ disableProviderPing: false, // [!code focus] projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', }) ``` ### isNewChainsStale `boolean | undefined` - If a new chain is added to a previously existing configured connector `chains`, this flag will determine if that chain should be considered as stale. A stale chain is a chain that WalletConnect has yet to establish a relationship with (e.g. the user has not approved or rejected the chain). - Defaults to `true`. ```ts-vue import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ isNewChainsStale: true, // [!code focus] projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', }) ``` ::: details More info Preface: Whereas WalletConnect v1 supported dynamic chain switching, WalletConnect v2 requires the user to pre-approve a set of chains up-front. This comes with consequent UX nuances (see below) when a user tries to switch to a chain that they have not approved. This flag mainly affects the behavior when a wallet does not support dynamic chain authorization with WalletConnect v2. If `true` (default), the new chain will be treated as a stale chain. If the user has yet to establish a relationship (approved/rejected) with this chain in their WalletConnect session, the connector will disconnect upon the dapp auto-connecting, and the user will have to reconnect to the dapp (revalidate the chain) in order to approve the newly added chain. This is the default behavior to avoid an unexpected error upon switching chains which may be a confusing user experience (e.g. the user will not know they have to reconnect unless the dapp handles these types of errors). If `false`, the new chain will be treated as a validated chain. This means that if the user has yet to establish a relationship with the chain in their WalletConnect session, wagmi will successfully auto-connect the user. This comes with the trade-off that the connector will throw an error when attempting to switch to the unapproved chain. This may be useful in cases where a dapp constantly modifies their configured chains, and they do not want to disconnect the user upon auto-connecting. If the user decides to switch to the unapproved chain, it is important that the dapp handles this error and prompts the user to reconnect to the dapp in order to approve the newly added chain. ::: ### metadata `CoreTypes.Metadata | undefined` Metadata related to the app requesting the connection. ```ts-vue import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', metadata: { // [!code focus] name: 'Example', // [!code focus] description: 'Example website', // [!code focus] url: 'https://example.com', // [!code focus] }, // [!code focus] }) ``` ### projectId `string` WalletConnect Cloud project identifier. You can find your `projectId` on your [WalletConnect dashboard](https://cloud.reown.com/sign-in). ```ts-vue import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', // [!code focus] }) ``` ### qrModalOptions `QrModalOptions | undefined` Options for rendering QR modal. ```ts-vue import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', qrModalOptions: { // [!code focus] themeMode: 'dark', // [!code focus] }, // [!code focus] }) ``` ### relayUrl `string | undefined` - WalletConnect relay URL to use. - Defaults to `'wss://relay.walletconnect.com'`. ```ts-vue import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', relayUrl: 'wss://relay.walletconnect.org', // [!code focus] }) ``` ### storageOptions `KeyValueStorageOptions | undefined` ```ts-vue import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', storageOptions: {}, // [!code focus] }) ``` ### showQrModal `boolean | undefined` - Whether to show the QR code modal upon calling `connector.connect()`. - Defaults to `true`. ```ts-vue import { walletConnect } from '{{connectorsPackageName}}' const connector = walletConnect({ projectId: '3fcc6bba6f1de962d911bb5b5c3dba68', showQrModal: true, // [!code focus] }) ``` ::: tip This can be disabled and you can listen for a `'message'` event with payload `{ type: 'display_uri'; data: string }` if you want to render your own QR code. ::: ================================================ FILE: site/shared/create-chain.md ================================================ ## Create Chain Import the `Chain` type from Viem and create a new object that is asserted `as const` and `satisfies` the type. You can also use the `defineChain` function from Viem. ::: code-group ```ts twoslash [as const satisfies Chain] // @twoslash-cache: {"v":1,"hash":"b104f720769e0d28b42cc38edb3952d146e5b9902d8a7bead95767460071c100","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAJMcvAML5m7MAB4AZhFIBbZmhqk4vOjTBRVIsWABishUrKqAPrwCummFPEwovALzDR4g/MXKzl67bD2KXgBjCzg0CDk1ehhNVQAlGCDZKAkw0nEAc0CrAGtIAHcwAD5ecytYP3snXgSk0hS0zOywPIhCkrLfOygS52AAHTBeYd4AI1YIIJyAUVosCdITAH5EXgGhkc3kHJgMVcawDIBdVZ1xACEJqdn52TIAbkHNzYrmC1Y0U9cwS8mZuYWDyeIwAvqUfBVuo8NsMkmA0KRmEE0HAVrwAAqLJTsKQYCTrZ4jba7fYIzInFy6IQQeGI5HggmE57IOAQCykIIwACSUFWYAsclGZApZzA1NpSLQ4PKNihwMJYM6kP8UGhmzBADI1vLnjE4AkMuw0hg0aLxQjJdKuiq1Uy9QBVMDsEgqNgJVmsF2m77mulSpWym06zZyd5odhBNisADM3qpNIt9IDlVVOpBHQhgfstuGADp87wAJy8OR3Xj53M53hSGDwONuWtwaSGTwmK3K+wZmUp6EgwbsORYWRS0WUEBhZikBiIACMABYqKwYhk0PgkABWKhoScZGDTkCjxd2JAABioQVEfrISHnIIo6GwuEQBGI1636jwcLCJd0/k+axBMcJynJA5wADkXZdVyQAB2Lcdz3PAFHEP8xw4fwkAAJnPS9JWvWdozvB8cDwQgXTHGh6DwAQYGCGlvz6QCqGA6cADYFxAJdDmgxBN2oBD9y/BgjwwxBsJAC9Jzw8gxMLIjqEfPAyFIWQgO3EDEBgs9OKgtdEELc9oCfGdo1Y7TbC45g5CfEBxFgWhcxRMd2CgJTSFIABaEyzI8sCYI8wsKI/Z8ABVH14AByYAQQi3goAgeBeEgKU4EUI1cX4fBaLoHBkSqGjItFCLc2BMLBCimLeCNEsjTgTJMtomRWAmfJ6qwFScCndhEqkFTIgKiKitWFzAjAKyYFGtKSCEdlFjAIIMECUgsCCe1SFYBBIJIVg3JU8gRKfcTJKvGTo3XeSaNI199uoYKQBYDguD4ArRWbDxjBUKINC0Sk3BbD7vG7bpqlFdwjC8dssygQIQjCCIvpiH7amSVIyUOZpWnaSGU2qZH6lR9J0Z8THimx7pem1GExiuf5bkWFQ0UZQliT2XgDmOL5dF+a4ATuUgqxeGw3g+TmLhpm5AX5tMyaDKm4UTFE0UxPdw1xfFgyJHZWfZkUfQTP0GQ15nWXZTkeT5AUhVIXX4wlJNMx7I3eEVB25SpzVKaZNQwH1GBDWNesxX1y1kzdr2HSdF1UtYd0IE9MhA99EPXdlr3Qw+CMo1jUWg7t/0U+zNMu2tQuqYrIsSzLCsqxrOsc70Rs3vBttQ5VYuO1TMA+ydQdh1+sA1MnacwO0riVz0vj1N3fdD0448xJwqS8pkudzqOQzYDwAchynNZ+HC0VnerPrIqIbq5AiwZBhyvuhJ/FC92qaLeC4OifZStK4FsRLZ+s7ckFAOoPU7AaTUQQCCEEQA="} // @errors: 1360 import { type Chain } from 'viem' export const mainnet = {} as const satisfies Chain ``` ```ts twoslash [defineChain] // @twoslash-cache: {"v":1,"hash":"51816265e78622b289e1e5f943b76d80bfbe0a867d81b51ec6327613f6e28499","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvWP3ZgYAYXzM5AHn4RSAW2ZoapOLzo0wUQ0pVgAYpp16ycCrxGS4aZ8rlH6MU+c9g6ra6+nAAfGGMIgGIHpbcsQAK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uU9TtOvCmeTviT+BsxoVUQAA7tinP3Tg/TsPAAj3Vogtk+TItUSxtHk7E05OGAPNO7o7AkAodopKIGBOKQWAiIWpCsNDr4wCQrBw/d5AHZsR2QdzhzkIgnZLScOKfbAeCTa0qozeUnThvwZsU0QxtaOTDQNHQU3uE8LyAR8vAALz5x0ASMFT3DdMD8xIKAxhxhIXTXFDIAnCcQA=="} // @errors: 2345 import { defineChain } from 'viem' export const mainnet = defineChain({}) ``` ::: Now, add the missing required properties to the object until the error goes away. ::: code-group ```ts twoslash [as const satisfies Chain] // @twoslash-cache: {"v":1,"hash":"7eb538e5797ec32b451699fd0f71747694cdee2f09698daad95d805d237f68ce","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAJMcvAML5m7MAB4AZhFIBbZmhqk4vOjTBRVIsWABishUrKqAPrwCummFPEwovALzDR4g/MXKzl67bD2KXgBjCzg0CDk1ehhNVQAlGCDZKAkw0nEAc0CrAGtIAHcwAD5ecytYP3snXgSk0hS0zOywPIhCkrLfOygS52AAHTBeYd4AI1YIIJyAUVosCdITAH5EXgGhkc3kHJgMVcawDIBdVZ1xACEJqdn52TIAbkHNzYrmC1Y0U9cwS8mZuYWDyeIwAvqUfBVuo8NsMkmA0KRmEE0HAVrwAAqLJTsKQYCTrZ4jba7fYIzInFy6IQQeGI5HggmE57IOAQCykIIwACSUFWYAsclGZApZzA1NpSLQ4PKNihwMJYM6kP8UGhmzBADI1vLnjE4AkMuw0hg0aLxQjJdKuiq1Uy9QBVMDsEgqNgJVmsF2m77mulSpWym06zZyd5odhBNisADM3qpNIt9IDlVVOpBHQhgfstuGADp87wAJy8OR3Xj53M53hSGDwONuWtwaSGTwmK3K+wZmUp6EgwbsORYWRS0WUEBhZikBiIACMABYqKwYhk0PgkABWKhoScZGDTkCjxd2JAABioQVEfrISHnIIo6GwuEQBGI1636jwcLCJd0/k+2phXhFmYKAaVYDBeHYXleBnKtgNAsBwN4M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iYe73a8CNH54F67RF6nTnRXS3T3SPTPSvTvSfTfS/T/SzFpjHGbBWGuY2Fd4Yk55rTbFD44x4wEwaREykwwDkwHSUzUy0z0yMzMwziszsw3SczMC0mFQb7CzqTb6SwnSbh0k6guGQasn97slYmbSRiSmjCwAnjrivQnSjDRiXR4aiwnQngHQaQaQMxCgHTMC1Y5InSXSGkzjymEiKn2DqRzjRiGaXQnhjGASImyzHFghcCk4fpSjQzhhwC2DwApFUBoTbhICgDqB6irJ4AHIggghAA==="} import { type Chain } from 'viem' export const mainnet = { id: 1, name: 'Ethereum', nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrls: { default: { http: ['https://eth.merkle.io'] }, }, blockExplorers: { default: { name: 'Etherscan', url: 'https://etherscan.io' }, }, contracts: { ensRegistry: { address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', }, ensUniversalResolver: { address: '0xE4Acdd618deED4e6d2f03b9bf62dc6118FC9A4da', blockCreated: 16773775, }, multicall3: { address: '0xca11bde05977b3631167028862be2a173976ca11', blockCreated: 14353601, }, }, } as const satisfies Chain ``` ```ts twoslash [defineChain] // @twoslash-cache: {"v":1,"hash":"9dd120cd705dc697124cfe3fa80116ed4046ca81c57ffb5daa2cfd0b2775f253","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvWP3ZgYAYXzM5AHn4RSAW2ZoapOLzo0wUQ0pVgAYpp16ycCrxGS4aZ8rlH6MU+c9g6ra6+nAAfGGMIgGIHpbcsQAKpDB67PwYqgCCcHDsAOaBFmrCMnIwUGFO0ZYRADpg7FpYmu5l8sVglCBuzKQMiACcVKy++Wj4SACMU1RoffmpeO2KAd0c8kgADFQ1pMxiZEiDAL4U6Ni4iATER3PGeC5gbrw6cvJoscANvL+8AEasCAiADWAFFaFggSkDF8fn8ESlmFBJKwMNIYPxmIJWJ9eN8pAiib8kSiwGjeGBmFoYLE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RWksENgECmS0F4AAHIiB2AYAtBXCGgGg6ACl3AngXgOoPheAABeOw1YSwRgZ6BZCgeEZeVwuWNebw+IwkAVbeIVXeWwxIuWVwpwM+AGJItyfI8GB+aGQ2NIkkZGFtJjP4fTYAXga9ZAVwqzATEdemdDVwlmSo+EM4eEeTAWGEOo34BojFGWJI06MLMAUoizVo/jArEzITCAVw3owkfowkSnA0SWFXXrX7XnVwiRfnU3YXC3abcXG3EsfIl+Kov4WvAxUPZOPBX4A4yxfvI7BPE7ZPc7cfdPa7C8a4qsFQp7U/VZG41UEghJSCH7Z4pgv/Q0Q4lCVgoAsHTgyHCAmHOHGAxHOAhiQE4kYE/PdAnHW4rUW4jYk4bgboGkeYJAUAYwC0CQLoa4ThEAE4E4IAA="} import { defineChain } from 'viem' export const mainnet = defineChain({ id: 1, name: 'Ethereum', nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrls: { default: { http: ['https://eth.merkle.io'] }, }, blockExplorers: { default: { name: 'Etherscan', url: 'https://etherscan.io' }, }, contracts: { ensRegistry: { address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e', }, ensUniversalResolver: { address: '0xE4Acdd618deED4e6d2f03b9bf62dc6118FC9A4da', blockCreated: 16773775, }, multicall3: { address: '0xca11bde05977b3631167028862be2a173976ca11', blockCreated: 14353601, }, }, }) ``` ::: The more properties you add, the better the chain will be to use with Wagmi. Most of these attributes exist within the [`ethereum-lists/chains` repository](https://github.com/ethereum-lists/chains/tree/3fbd4eeac7ce116579634bd042b84e2b1d89886a/_data/chains). - `id`: The chain ID for the network. This can be found by typing the network name into [ChainList](https://chainlist.org). Example: "Ethereum Mainnet" has a Chain ID of `1`. - `name`: Human-readable name for the chain. Example: "Ethereum Mainnet" - `nativeCurrency`: The native currency of the chain. Found from [`ethereum-lists/chains`](https://github.com/ethereum-lists/chains/blob/3fbd4eeac7ce116579634bd042b84e2b1d89886a/_data/chains/eip155-56.json#L20-L24). - `rpcUrls`: At least one public, credible RPC URL. Found from [`ethereum-lists/chains`](https://github.com/ethereum-lists/chains/blob/3fbd4eeac7ce116579634bd042b84e2b1d89886a/_data/chains/eip155-56.json#L4-L18). - `blockExplorers`: A set of block explorers for the chain. Found from [`ethereum-lists/chains`](https://github.com/ethereum-lists/chains/blob/3fbd4eeac7ce116579634bd042b84e2b1d89886a/_data/chains/eip155-56.json#L30-L36). - `contracts`: A set of deployed contracts for the chain. If you are deploying one of the following contracts yourself, make sure it is verified. - `multicall3` is optional, but it's address is most likely `0xca11bde05977b3631167028862be2a173976ca11` – you can find the deployed block number on the block explorer. Check out [`mds1/multicall`](https://github.com/mds1/multicall#multicall3-contract-addresses) for more info. - `ensRegistry` is optional – not all Chains have a ENS Registry. See [ENS Deployments](https://docs.ens.domains/ens-deployments) for more info. - `ensUniversalResolver` is optional – not all Chains have a ENS Universal Resolver. - `sourceId`: Source Chain ID (e.g. the L1 chain). - `testnet`: Whether or not the chain is a testnet. ================================================ FILE: site/shared/createConfig.md ================================================ # createConfig Creates new [`Config`](#config) object. ## Import ```ts-vue import { createConfig } from '{{packageName}}' ``` ## Usage ```ts-vue import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http('https://mainnet.example.com'), [sepolia.id]: http('https://sepolia.example.com'), }, }) ``` ::: tip Integrating a Viem Client Instead of using [`transports`](#transports), it's possible to provide a function that returns a Viem [`Client`](https://viem.sh/docs/clients/custom) via the [`client`](#client) property for more fine-grained control over Wagmi's internal `Client` creation. ```ts-vue {3,7-9} import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { createClient } from 'viem' const config = createConfig({ chains: [mainnet, sepolia], client({ chain }) { return createClient({ chain, transport: http() }) }, }) ``` ::: ## Parameters ```ts-vue import { type CreateConfigParameters } from '{{packageName}}' ``` ### chains `readonly [Chain, ...Chain[]]` - Chains used by the `Config`. - See Chains for more details about built-in chains and the `Chain` type. ```ts-vue import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' const config = createConfig({ chains: [mainnet, sepolia], // [!code focus] transports: { [mainnet.id]: http('https://mainnet.example.com'), [sepolia.id]: http('https://sepolia.example.com'), }, }) ``` ### connectors `CreateConnectorFn[] | undefined` Connectors used by the `Config`. ```ts-vue import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' import { injected } from '{{connectorsPackageName}}' // [!code focus] const config = createConfig({ chains: [mainnet, sepolia], connectors: [injected()], // [!code focus] transports: { [mainnet.id]: http('https://mainnet.example.com'), [sepolia.id]: http('https://sepolia.example.com'), }, }) ``` ### multiInjectedProviderDiscovery `boolean | undefined` - Enables discovery of injected providers via [EIP-6963](https://eips.ethereum.org/EIPS/eip-6963) using the [`mipd`](https://github.com/wevm/mipd) library and converting to injected connectors. - Defaults to `true`. ```ts-vue import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' const config = createConfig({ chains: [mainnet, sepolia], multiInjectedProviderDiscovery: false, // [!code focus] transports: { [mainnet.id]: http('https://mainnet.example.com'), [sepolia.id]: http('https://sepolia.example.com'), }, }) ``` ### ssr `boolean | undefined` Flag to indicate if the config is being used in a server-side rendering environment. Defaults to `false`. ```ts-vue import { createConfig, http } from '{{packageName}}' // [!code focus] import { mainnet, sepolia } from '{{packageName}}/chains' const config = createConfig({ chains: [mainnet, sepolia], ssr: true, // [!code focus] transports: { [mainnet.id]: http('https://mainnet.example.com'), [sepolia.id]: http('https://sepolia.example.com'), }, }) ``` ### storage `Storage | null | undefined` - `Storage` used by the config. Persists `Config`'s [`State`](#state-1) between sessions. - Defaults to `createStorage({ storage: typeof window !== 'undefined' && window.localStorage ? window.localStorage : noopStorage })`. ```ts-vue import { createConfig, createStorage, http } from '{{packageName}}' // [!code focus] import { mainnet, sepolia } from '{{packageName}}/chains' const config = createConfig({ chains: [mainnet, sepolia], storage: createStorage({ storage: window.localStorage }), // [!code focus] transports: { [mainnet.id]: http('https://mainnet.example.com'), [sepolia.id]: http('https://sepolia.example.com'), }, }) ``` ### syncConnectedChain `boolean | undefined` - Keep the [`State['chainId']`](#chainid) in sync with the current connection. - Defaults to `true`. ```ts-vue import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' const config = createConfig({ chains: [mainnet, sepolia], syncConnectedChain: false, // [!code focus] transports: { [mainnet.id]: http('https://mainnet.example.com'), [sepolia.id]: http('https://sepolia.example.com'), }, }) ``` --- ### batch `{ multicall?: boolean | { batchSize?: number | undefined; wait?: number | undefined } | undefined } | { [_ in chains[number]["id"]]?: { multicall?: boolean | { batchSize?: number | undefined; wait?: number | undefined } | undefined } | undefined } | undefined` - Batch settings. See [Viem docs](https://viem.sh/docs/clients/custom#batch-optional) for more info. - Defaults to `{ multicall: true }`. ```ts-vue import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' const config = createConfig({ chains: [mainnet, sepolia], batch: { multicall: true }, // [!code focus] transports: { [mainnet.id]: http('https://mainnet.example.com'), [sepolia.id]: http('https://sepolia.example.com'), }, }) ``` ### cacheTime `number | { [_ in chains[number]['id']]?: number | undefined } | undefined` - Frequency in milliseconds for polling enabled features. See [Viem docs](https://viem.sh/docs/clients/public#cachetime-optional) for more info. - Defaults to [`pollingInterval`](#pollinginterval) or `4_000`. ```ts-vue import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' const config = createConfig({ chains: [mainnet, sepolia], cacheTime: 4_000, // [!code focus] transports: { [mainnet.id]: http('https://mainnet.example.com'), [sepolia.id]: http('https://sepolia.example.com'), }, }) ``` ### pollingInterval `number | { [_ in chains[number]['id']]?: number | undefined } | undefined` - Frequency in milliseconds for polling enabled features. See [Viem docs](https://viem.sh/docs/clients/custom#pollinginterval-optional) for more info. - Defaults to `4_000`. ```ts-vue import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' const config = createConfig({ chains: [mainnet, sepolia], pollingInterval: 4_000, // [!code focus] transports: { [mainnet.id]: http('https://mainnet.example.com'), [sepolia.id]: http('https://sepolia.example.com'), }, }) ``` ### transports `Record` Mapping of [chain IDs](#chains) to `Transport`s. This mapping is used internally when creating chain-aware Viem [`Client`](https://viem.sh/docs/clients/custom) objects. See the Transport docs for more info. ```ts-vue import { createConfig, fallback, http } from '{{packageName}}' // [!code focus] import { mainnet, sepolia } from '{{packageName}}/chains' const config = createConfig({ chains: [mainnet, sepolia], transports: { // [!code focus] [mainnet.id]: fallback([ // [!code focus] http('https://...'), // [!code focus] http('https://...'), // [!code focus] ]), // [!code focus] [sepolia.id]: http('https://...'), // [!code focus] }, // [!code focus] }) ``` --- ### client `(parameters: { chain: chains[number] }) => Client` Function for creating new Viem [`Client`](https://viem.sh/docs/clients/custom) to be used internally. Exposes more control over the internal `Client` creation logic versus using the [`transports`](#transports) property. ```ts-vue import { createClient, http } from 'viem' // [!code focus] import { createConfig } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' const config = createConfig({ chains: [mainnet, sepolia], client({ chain }) { // [!code focus] return createClient({ chain, transport: http('https://...') }) // [!code focus] }, // [!code focus] }) ``` ::: warning When using this option, you likely want to pass `parameters.chain` straight through to [`createClient`](https://viem.sh/docs/clients/custom#createclient) to ensure the Viem `Client` is in sync with any active connections. ::: ## Return Type ```ts-vue import { type Config } from '{{packageName}}' ``` ## Config Object responsible for managing Wagmi state and internals. ```ts-vue import { type Config } from '{{packageName}}' ``` ### chains `readonly [Chain, ...Chain[]]` [`chains`](#chains) passed to `createConfig`. ### connectors `readonly Connector[]` Connectors set up from passing [`connectors`](#connectors) and [`multiInjectedProviderDiscovery`](#multiinjectedproviderdiscovery) to `createConfig`. ### state `State` The `Config` object's internal state. See [`State`](#state-1) for more info. ### storage `Storage | null` [`storage`](#storage) passed to `createConfig`. ### getClient `(parameters?: { chainId?: chainId | chains[number]['id'] | undefined }): Client>` Creates new Viem [`Client`](https://viem.sh/docs/clients/custom) object. ::: code-group ```ts-vue [index.ts] import { config } from './config' const client = config.getClient({ chainId: 1 }) ``` ```ts-vue [config.ts] import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http('https://mainnet.example.com'), [sepolia.id]: http('https://sepolia.example.com'), }, }) ``` ::: ### setState `(value: State | ((state: State) => State)) => void` Updates the `Config` object's internal state. See [`State`](#state-1) for more info. ::: code-group ```ts-vue [index.ts] import { mainnet } from '{{packageName}}/chains' import { config } from './config' config.setState((x) => ({ ...x, chainId: x.current ? x.chainId : mainnet.id, })) ``` ```ts-vue [config.ts] import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http('https://mainnet.example.com'), [sepolia.id]: http('https://sepolia.example.com'), }, }) ``` ::: ::: warning Exercise caution when using this method. It is intended for internal and advanced use-cases only. Manually setting state can cause unexpected behavior. ::: ### subscribe `(selector: (state: State) => state, listener: (selectedState: state, previousSelectedState: state) => void, options?: { emitImmediately?: boolean | undefined; equalityFn?: ((a: state, b: state) => boolean) | undefined } | undefined) => (() => void)` Listens for state changes matching the `selector` function. Returns a function that can be called to unsubscribe the listener. ::: code-group ```ts-vue [index.ts] import { config } from './config' const unsubscribe = config.subscribe( (state) => state.chainId, (chainId) => console.log(`Chain ID changed to ${chainId}`), ) unsubscribe() ``` ```ts-vue [config.ts] import { createConfig, http } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http('https://mainnet.example.com'), [sepolia.id]: http('https://sepolia.example.com'), }, }) ``` ::: ## State ```ts-vue import { type State } from '{{packageName}}' ``` ### chainId `chains[number]['id']` Current chain ID. When `syncConnectedChain` is `true`, `chainId` is kept in sync with the current connection. Defaults to first chain in [`chains`](#chains). ### connections `Map` Mapping of unique connector identifier to [`Connection`](#connection) object. ### current `string | undefined` Unique identifier of the current connection. ### status `'connected' | 'connecting' | 'disconnected' | 'reconnecting'` Current connection status. - `'connecting'` attempting to establish connection. - `'reconnecting'` attempting to re-establish connection to one or more connectors. - `'connected'` at least one connector is connected. - `'disconnected'` no connection to any connector. ## Connection ```ts-vue import { type Connection } from '{{packageName}}' ``` ### accounts `readonly [Address, ...Address[]]` Array of addresses associated with the connection. ### chainId `number` Chain ID associated with the connection. ### connector `Connector` Connector associated with the connection. ================================================ FILE: site/shared/createStorage.md ================================================ # createStorage Creates new [`Storage`](#storage) object. ## Import ```ts-vue import { createStorage } from '{{packageName}}' ``` ## Usage ```ts-vue import { createStorage } from '{{packageName}}' const storage = createStorage({ storage: localStorage }) ``` ## Parameters ```ts-vue import { type CreateStorageParameters } from '{{packageName}}' ``` ### deserialize `((value: string) => T) | undefined` - Function to deserialize data from storage. - Defaults to `deserialize`. ```ts-vue import { createStorage, deserialize } from '{{packageName}}' // [!code focus] const storage = createStorage({ deserialize, // [!code focus] storage: localStorage, }) ``` ::: warning If you use a custom `deserialize` function, make sure it can handle `bigint` and `Map` values. ::: ### key `string | undefined` - Key prefix to use when persisting data. - Defaults to `'wagmi'`. ```ts-vue import { createStorage } from '{{packageName}}' const storage = createStorage({ key: 'my-app', // [!code focus] storage: localStorage, }) ``` ### serialize `((value: T) => string) | undefined` - Function to serialize data for storage. - Defaults to `serialize`. ```ts-vue import { createStorage, serialize } from '{{packageName}}' // [!code focus] const storage = createStorage({ serialize, // [!code focus] storage: localStorage, }) ``` ::: warning If you use a custom `serialize` function, make sure it can handle `bigint` and `Map` values. ::: ### storage `{ getItem(key: string): string | null | undefined | Promise; setItem(key: string, value: string): void | Promise; removeItem(key: string): void | Promise; }` - Storage interface to use for persisting data. - Defaults to `localStorage`. - Supports synchronous and asynchronous storage methods. ```ts-vue import { createStorage } from '{{packageName}}' // Using IndexedDB via https://github.com/jakearchibald/idb-keyval // [!code focus] import { del, get, set } from 'idb-keyval' // [!code focus] const storage = createStorage({ storage: { // [!code focus] async getItem(name) { // [!code focus] return get(name)// [!code focus] }, // [!code focus] async setItem(name, value) { // [!code focus] await set(name, value) // [!code focus] }, // [!code focus] async removeItem(name) { // [!code focus] await del(name) // [!code focus] }, // [!code focus] }, // [!code focus] }) ``` ## Return Type ```ts-vue import { type Storage } from '{{packageName}}' ``` ## Storage Object responsible for persisting Wagmi `State` and other data. ```ts-vue import { type Storage } from '{{packageName}}' ``` ### getItem `getItem(key: string, defaultValue?: value | null | undefined): value | null | Promise` ```ts-vue import { createStorage } from '{{packageName}}' const storage = createStorage({ storage: localStorage }) const recentConnectorId = storage.getItem('recentConnectorId') // [!code focus] ``` ### setItem `setItem(key: string, value: any): void | Promise` ```ts-vue import { createStorage } from '{{packageName}}' const storage = createStorage({ storage: localStorage }) storage.setItem('recentConnectorId', 'foo') // [!code focus] ``` ### removeItem `removeItem(key: string): void | Promise` ```ts-vue import { createStorage } from '{{packageName}}' const storage = createStorage({ storage: localStorage }) storage.removeItem('recentConnectorId') // [!code focus] ``` ================================================ FILE: site/shared/errors.md ================================================ ## BaseError Error class extended by all errors. ```ts-vue import { BaseError } from '{{packageName}}' ``` ## Config ### ConnectorAccountNotFoundError When an account does not exist on the connector or is unable to be used. ```ts-vue import { ConnectorAccountNotFoundError } from '{{packageName}}' ``` ### ConnectorAlreadyConnectedError When a connector is already connected. ```ts-vue import { ConnectorAlreadyConnectedError } from '{{packageName}}' ``` ### ConnectorChainMismatchError When the Wagmi Config is out-of-sync with the connector's active chain ID. This is rare and likely an upstream wallet issue. ```ts-vue import { ConnectorChainMismatchError } from '{{packageName}}' ``` ### ChainNotConfiguredError When a chain is not configured. You likely need to add the chain to `Config['chains']`. ```ts-vue import { ChainNotConfiguredError } from '{{packageName}}' ``` ### ConnectorNotConnectedError When a connector is not connected. ```ts-vue import { ConnectorNotConnectedError } from '{{packageName}}' ``` ### ConnectorNotFoundError When a connector is not found or able to be used. ```ts-vue import { ConnectorNotFoundError } from '{{packageName}}' ``` ### ConnectorUnavailableReconnectingError During the reconnection step, the only connector methods guaranteed to be available are: `id`, `name`, `type`, `uuid`. All other methods are not guaranteed to be available until reconnection completes and connectors are fully restored. This error commonly occurs for connectors that asynchronously inject after reconnection has already started. ```ts-vue import { ConnectorUnavailableReconnectingError } from '{{packageName}}' ``` ## Connector ### ProviderNotFoundError When a connector's provider is not found or able to be used. ```ts-vue import { ProviderNotFoundError } from '{{packageName}}' ``` ### SwitchChainNotSupportedError When switching chains is not supported by connectors. ```ts-vue import { SwitchChainNotSupportedError } from '{{packageName}}' ``` ================================================ FILE: site/shared/faq.md ================================================ ## How do I support the project? Wagmi is an open source software project and free to use. If you enjoy using Wagmi or would like to support Wagmi development, you can: - [Become a sponsor on GitHub](https://github.com/sponsors/wevm) - Send us crypto - Mainnet: 0x4557B18E779944BFE9d78A672452331C186a9f48 - Multichain: 0xd2135CfB216b74109775236E36d4b433F1DF507B - [Become a supporter on Drips](https://www.drips.network/app/projects/github/wevm/wagmi) If you use Wagmi at work, **consider asking your company to sponsor Wagmi**. This may not be easy, but **business sponsorships typically make a much larger impact on the sustainability of OSS projects** than individual donations, so you will help us much more if you succeed. ## Type inference doesn't work - Check that you set up TypeScript correctly with `"strict": true` in your `tsconfig.json` (TypeScript docs) - Check that you const-asserted any ABIs or Typed Data you are using. - Restart your language server or IDE, and check for type errors in your code. ## My wallet doesn't work If you run into issues with a specific wallet, try another before opening up an issue. There are many different wallets and it's likely that the issue is with the wallet itself, not Wagmi. For example, if you are using Wallet X and sending a transaction doesn't work, try Wallet Y and see if it works. ## `BigInt` Serialization Using native `BigInt` with `JSON.stringify` will raise a `TypeError` as [`BigInt` values are not serializable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt#use_within_json). There are two techniques to mitigate this: #### Lossless serialization Lossless serialization means that `BigInt` will be converted to a format that can be deserialized later (e.g. `69420n` → `"#bigint.69420"`). The trade-off is that these values are not human-readable and are not intended to be displayed to the user. Lossless serialization can be achieved with wagmi's `serialize` and `deserialize` utilities. ```tsx import { serialize, deserialize } from 'wagmi' const serialized = serialize({ value: 69420n }) // '{"value":"#bigint.69420"}' const deserialized = deserialize(serialized) // { value: 69420n } ``` #### Lossy serialization Lossy serialization means that the `BigInt` will be converted to a normal display string (e.g. `69420n` → `'69420'`). The trade-off is that you will not be able to deserialize the `BigInt` with `JSON.parse` as it can not distinguish between a normal string and a `BigInt`. This method can be achieved by modifying `JSON.stringify` to include a BigInt `replacer`: ```tsx const replacer = (key, value) => typeof value === 'bigint' ? value.toString() : value JSON.stringify({ value: 69420n }, replacer) // '{"value":"69420"}' ``` ## Is Wagmi production ready? Yes. Wagmi is very stable and is used in production by thousands of organizations, like [Stripe](https://stripe.com), [Shopify](https://shopify.com), [Coinbase](https://coinbase.com), [Uniswap](https://uniswap.org), [ENS](https://ens.domains), [Optimism](https://optimism.com). ## Is Wagmi strict with semver? Yes, Wagmi is very strict with [semantic versioning](https://semver.org) and we will never introduce breaking changes to the runtime API in a minor version bump. For exported types, we try our best to not introduce breaking changes in non-major versions, however, [TypeScript doesn't follow semver](https://www.learningtypescript.com/articles/why-typescript-doesnt-follow-strict-semantic-versioning) and often introduces breaking changes in minor releases that can cause Wagmi type issues. See the TypeScript docs for more information. ## How can I contribute to Wagmi? The Wagmi team accepts all sorts of contributions. Check out the [Contributing](/dev/contributing) guide to get started. If you are interested in adding a new connector to Wagmi, check out the [Creating Connectors](/dev/creating-connectors) guide. ## Anything else you want to know? Please create a new [GitHub Discussion thread](https://github.com/wevm/wagmi). You're also free to suggest changes to this or any other page on the site using the "Suggest changes to this page" button at the bottom of the page. ================================================ FILE: site/shared/getConnection-return-type.md ================================================ ### address `Address | undefined` - Connected address from connector. - Defaults to first address in [`addresses`](#addresses). ### addresses `readonly Address[] | undefined` Connected addresses from connector. ### chain `Chain | undefined` Connected chain from connector. If chain is not configured by config, it will be `undefined`. ### chainId `number | undefined` Connected chain id from connector. ### connector `Connector | undefined` Connected connector. ### isConnecting / isReconnecting / isConnected / isDisconnected `boolean` Boolean variables derived from [`status`](#status). ### status `'connecting' | 'reconnecting' | 'connected' | 'disconnected'` - `'connecting'` attempting to establish connection. - `'reconnecting'` attempting to re-establish connection to one or more connectors. - `'connected'` at least one connector is connected. - `'disconnected'` no connection to any connector. ::: info You can use `status` to narrow the return type. For example, when `status` is `'connected'` properties like `address` are guaranteed to be defined. ```ts twoslash // @twoslash-cache: {"v":1,"hash":"70621ff7ba048810d10cff60e35c82126a2beb12177fb38b972d09b620d6367c","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BjCMONAAmbDBkbQEsWidgHEYaAMIsefQWABK4gK6kwAFWy4qbAIakGiACxUANjDABzNPiQBGAAxU0ei+KbTeAlpRAn+PJEcQRnw9HT4yJEMAXwp0TTxCEnInOgMQAAosUggcfQwASnZdNCU4YQAdECh+OC4ZGigq9gAfdir6zxgmkFb2kFJeD1lLZraO4YFRkB9dfTsAVlNzKxtEADYnFzdEEBKynz8AxCCQsIjyRFsF2PicROJI1Pp3Vg5O2SF2YAqwdn/2DooFBBnByuwAILA0FwADcvwBgOh8Dg8GEgyBLBMGHYyChIJRFHYADpSfiYcgALqU+F/AFnfzCCShfx9JRgWAAM383VpiIZYAAklBhGAlABbABGZD59MmEFITPlpFl/1qUm4XRF7DQpCUMFV7HVk38FmEnJ0JlRhtqABFah9GubLdaEQDaopHabnVaDW7/vtwRNNREerTorNnPMjABmZaWax2IJR1zpL3eUw8uxUM6kcI0S4AJlu1ASuwAjvrSBgfDQXrsuGxOCavj86f8gQSwcJySjDZ2YWj2BioFicXjkWCiaTib2wVSaf7OCywEyV2yOTBuTwoIaBcLRRLpSql46FUqQ2gFTa4BqGt1hLr9Te755vewLb6b/a6pMHx+XT9dsjTgT0TUsH1XWAwNKmCP8w1+CNtCjAxDDjXwVkTK5k22NMWzAQ4syuHNQjzC4kGLSkc2gXBdn4Tl2AydMwGJQN2AAXk49gAHJHW6biijbf5mN+USwDEiTxKkyTJKQkBxXEHQkFANJzDgOQ8DQBBomiIA==="} import { type GetConnectionReturnType } from '@wagmi/core' const connection = {} as GetConnectionReturnType // ---cut--- if (connection.status === 'connected') { connection // ^? } ``` Or when status is `'disconnected'` properties like `address` are guaranteed to be `undefined`: ```ts twoslash // @twoslash-cache: {"v":1,"hash":"03f1cafa2983888b08080373baa176953254622dd97feb972d42875fedc5dd86","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BjCMONAAmbDBkbQEsWidgHEYaAMIsefQWABK4gK6kwAFWy4qbAIakGiACxUANjDABzNPiQBGAAxU0ei+KbTeAlpRAn+PJEcQRnw9HT4yJEMAXwp0TTxCEnInOgMQAAosUggcfQwASnZdNCU4YQAdECh+OC4ZGigq9gAfdir6zxgmkFb2kFJeD1lLZraO4YFRkB9dfTsAVlNzKxtEADYnFzdEEBKynz8AxCCQsIjyRFsF2PicROJI1Pp3Vg5O2SF2YAqwdn/2DooFBBnByuwlGBYAAzfzdADcvwBgOBoLg8GEkJhcKgiL+ALO/kxUJgsJ4uKRBNC/gAklBidjyXjkR80BBSAzSTjmQDalJuF16exoToTOief9aopWf4LMIRWKYBL2HzJrL5aLxZTJXAACK1VndYRoUhKJXa4rOUrgqo1OqTbpVPHRWbOeZGTa+FbWOxBN2udIy7ymOF2KhnUjhGiXABMt2oCV2AEczaQMD4aC9dlw2Jw1V8fvj/kCQfBwViuUyLSW0RiISSyQiLYSwJzGxSi5xqWA6W3uc3Juy+1XO6qBREhQqtaO4NK1ZYNYrlWOGurhZrzTP9fbx41jabN8j9jbqgaHT1na69AZDJ6zJYfVc/dtA/mwIdQ1dw6FIxckHGAF1w2gXBdn4aF2AyIMwAAOmPdgAF4kPYAByO1DSgFCikLf5oN+fCwAIojCJI4jiJdKgAFtxB0JBQDScw4DkPA0AQaJoiAA"} import { type GetConnectionReturnType } from '@wagmi/core' const connection = {} as GetConnectionReturnType // ---cut--- if (connection.status === 'disconnected') { connection // ^? } ``` ::: ================================================ FILE: site/shared/installation.md ================================================ ## Requirements Wagmi is optimized for modern browsers. It is compatible with the latest versions of the following browsers. ::: tip Depending on your environment, you might need to add polyfills. See [Viem Platform Compatibility](https://viem.sh/docs/compatibility) for more info. ::: ## Using Unreleased Commits If you can't wait for a new release to test the latest features, you can either install from the `canary` tag (tracks the [`main`](https://github.com/wevm/wagmi/tree/main) branch). ::: code-group ```bash-vue [pnpm] pnpm add {{packageName}}@canary ``` ```bash-vue [npm] npm install {{packageName}}@canary ``` ```bash-vue [yarn] yarn add {{packageName}}@canary ``` ```bash-vue [bun] bun add {{packageName}}@canary ``` ::: Or clone the [Wagmi repo](https://github.com/wevm/wagmi) to your local machine, build, and link it yourself. ```bash-vue gh repo clone wevm/wagmi cd wagmi pnpm install pnpm build cd packages/{{packageDir}} pnpm link --global ``` Then go to the project where you are using Wagmi and run `pnpm link --global {{packageName}}` (or the package manager that you used to link Wagmi globally). Make sure you installed any [required peer dependencies](#package-manager) and their versions are correct. Finally, pull requests are continuously released via [pkg.pr.new](https://pkg.pr.new) and can be installed using the pull request number or short commit ID. ::: code-group ```bash-vue [pnpm] pnpm add https://pkg.pr.new/{{packageName}}@123 ``` ```bash-vue [npm] npm install https://pkg.pr.new/{{packageName}}@123 ``` ```bash-vue [yarn] yarn add https://pkg.pr.new/{{packageName}}@123 ``` ```bash-vue [bun] bun add https://pkg.pr.new/{{packageName}}@123 ``` ::: ## Security Ethereum-related projects are often targeted in attacks to steal users' assets. Make sure you follow security best-practices for your project. Some quick things to get started. - Pin package versions, upgrade mindfully, and inspect lockfile changes to minimize the risk of [supply-chain attacks](https://nodejs.org/en/guides/security/#supply-chain-attacks). - Use [npm](https://docs.npmjs.com)'s [`min-release-age`](https://docs.npmjs.com/cli/v11/using-npm/config#min-release-age) or [pnpm](https://pnpm.io)'s [`minimumReleaseAge`](https://pnpm.io/settings#minimumreleaseage) and [`trustPolicy`](https://pnpm.io/settings#trustpolicy) to mitigate against supply-chain attacks. - Install the [Socket](https://socket.dev) [GitHub App](https://github.com/apps/socket-security) to help detect and block supply-chain attacks. - Add a [Content Security Policy](https://cheatsheetseries.owasp.org/cheatsheets/Content_Security_Policy_Cheat_Sheet.html) to defend against external scripts running in your app. - Pin [GitHub Action](https://x.com/paulmillr/status/1900948425325031448) versions to commits instead of tags. [Actions Up](https://github.com/azat-io/actions-up) is a good tool for using commits instead of tags. ================================================ FILE: site/shared/migrate-from-v2-to-v3.md ================================================ ## Install Connector Dependencies All connector dependencies are now optional peer dependencies. This means that if you want to use a specific connector, you need to install its required dependencies. For example, if you are using the `porto` connector, you also need to install the `porto` npm package. Required connector dependencies are listed below (along with links to npm, GitHub, [Socket](https://socket.dev), and licenses) and on docs pages under the "Install" section. :::tip Secure your supply-chain Since you are now responsible for managing connector dependencies, take a look at Wagmi's Security Getting Started section to brush up on some best practices. ::: :::tip Building a developer tool on top of Wagmi? If you are developing a library with Wagmi, you should decide if you want to install connector dependencies as part of your library ("batteries-included" approach) or pass the responsibility onto your users (more flexibility and control). ::: ### baseAccount `baseAccount` requires `@base-org/account` ::: code-group ```bash-vue [pnpm] pnpm add @base-org/account@{{packageJson?.peerDependencies?.['@base-org/account']}} ``` ```bash-vue [npm] npm install @base-org/account@{{packageJson?.peerDependencies?.['@base-org/account']}} ``` ```bash-vue [yarn] yarn add @base-org/account@{{packageJson?.peerDependencies?.['@base-org/account']}} ``` ```bash-vue [bun] bun add @base-org/account@{{packageJson?.peerDependencies?.['@base-org/account']}} ``` ::: ### coinbaseWallet `coinbaseWallet` requires `@coinbase/wallet-sdk` ::: code-group ```bash-vue [pnpm] pnpm add @coinbase/wallet-sdk@{{packageJson?.peerDependencies?.['@coinbase/wallet-sdk']}} ``` ```bash-vue [npm] npm install @coinbase/wallet-sdk@{{packageJson?.peerDependencies?.['@coinbase/wallet-sdk']}} ``` ```bash-vue [yarn] yarn add @coinbase/wallet-sdk@{{packageJson?.peerDependencies?.['@coinbase/wallet-sdk']}} ``` ```bash-vue [bun] bun add @coinbase/wallet-sdk@{{packageJson?.peerDependencies?.['@coinbase/wallet-sdk']}} ``` ::: ### metaMask `metaMask` requires `@metamask/sdk` ::: code-group ```bash-vue [pnpm] pnpm add @metamask/sdk@{{packageJson?.peerDependencies?.['@metamask/sdk']}} ``` ```bash-vue [npm] npm install @metamask/sdk@{{packageJson?.peerDependencies?.['@metamask/sdk']}} ``` ```bash-vue [yarn] yarn add @metamask/sdk@{{packageJson?.peerDependencies?.['@metamask/sdk']}} ``` ```bash-vue [bun] bun add @metamask/sdk@{{packageJson?.peerDependencies?.['@metamask/sdk']}} ``` ::: ### porto `porto` requires `porto` ::: code-group ```bash-vue [pnpm] pnpm add porto@{{packageJson?.peerDependencies?.['porto']}} ``` ```bash-vue [npm] npm install porto@{{packageJson?.peerDependencies?.['porto']}} ``` ```bash-vue [yarn] yarn add porto@{{packageJson?.peerDependencies?.['porto']}} ``` ```bash-vue [bun] bun add porto@{{packageJson?.peerDependencies?.['porto']}} ``` ::: ### safe `safe` requires `@safe-global/safe-apps-provider` and `@safe-global/safe-apps-sdk` ::: code-group ```bash-vue [pnpm] pnpm add @safe-global/safe-apps-provider@{{packageJson?.peerDependencies?.['@safe-global/safe-apps-provider']}} @safe-global/safe-apps-sdk@{{packageJson?.peerDependencies?.['@safe-global/safe-apps-sdk']}} ``` ```bash-vue [npm] npm install @safe-global/safe-apps-provider@{{packageJson?.peerDependencies?.['@safe-global/safe-apps-provider']}} @safe-global/safe-apps-sdk@{{packageJson?.peerDependencies?.['@safe-global/safe-apps-sdk']}} ``` ```bash-vue [yarn] yarn add @safe-global/safe-apps-provider@{{packageJson?.peerDependencies?.['@safe-global/safe-apps-provider']}} @safe-global/safe-apps-sdk@{{packageJson?.peerDependencies?.['@safe-global/safe-apps-sdk']}} ``` ```bash-vue [bun] bun add @safe-global/safe-apps-provider@{{packageJson?.peerDependencies?.['@safe-global/safe-apps-provider']}} @safe-global/safe-apps-sdk@{{packageJson?.peerDependencies?.['@safe-global/safe-apps-sdk']}} ``` ::: ### walletConnect `walletConnect` requires `@walletconnect/ethereum-provider` ::: code-group ```bash-vue [pnpm] pnpm add @walletconnect/ethereum-provider@{{packageJson?.peerDependencies?.['@walletconnect/ethereum-provider']}} ``` ```bash-vue [npm] npm install @walletconnect/ethereum-provider@{{packageJson?.peerDependencies?.['@walletconnect/ethereum-provider']}} ``` ```bash-vue [yarn] yarn add @walletconnect/ethereum-provider@{{packageJson?.peerDependencies?.['@walletconnect/ethereum-provider']}} ``` ```bash-vue [bun] bun add @walletconnect/ethereum-provider@{{packageJson?.peerDependencies?.['@walletconnect/ethereum-provider']}} ``` ::: ## Bumped Minimum TypeScript Version The minimum supported TypeScript version is now `5.7.3` instead of `5.0.4`. Older versions of TypeScript should continue to work, but since [TypeScript doesn't follow semver](https://www.learningtypescript.com/articles/why-typescript-doesnt-follow-strict-semantic-versioning) we recommend you update to at least `5.7.3`. This should be relatively simple as there haven't been any breaking changes since `5.0.4`. ## Migrate v2 Deprecations v2 deprecations Review the v2 migration guide for more information. ================================================ FILE: site/shared/mutation-imports.md ================================================ ## TanStack Query ```ts-vue import { type {{typeName}}Data, type {{typeName}}Variables, type {{typeName}}Mutate, type {{typeName}}MutateAsync, {{actionName}}MutationOptions, } from '{{packageName}}/query' ``` ================================================ FILE: site/shared/mutation-options.md ================================================
--- ### mutation TanStack Query parameters. See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/react/reference/useMutation) for more info. ::: info Wagmi does not support passing all TanStack Query parameters TanStack Query parameters, like `mutationFn` and `mutationKey`, are used internally to make Wagmi work and you cannot override them. Check out the [source](https://github.com/wevm/wagmi/blob/main/packages/react/src/utils/query.ts#L30) to see what parameters are not supported. All parameters listed below are supported. ::: #### gcTime `number | Infinity | undefined` - The time in milliseconds that unused/inactive cache data remains in memory. When a mutation's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different cache times are specified, the longest one will be used. - If set to `Infinity`, will disable garbage collection #### meta `Record | undefined` If set, stores additional information on the mutation cache entry that can be used as needed. It will be accessible wherever [`{{mutate}}`](#mutate) is available (e.g. [`onError`](#onerror), [`onSuccess`](#onsuccess) functions). #### networkMode `'online' | 'always' | 'offlineFirst' | undefined` - defaults to `'online'` - see [Network Mode](https://tanstack.com/query/v5/docs/react/guides/network-mode) for more information. #### onError `((error: {{TError}}, variables: {{TVariables}}, context?: context | undefined) => Promise | unknown) | undefined` This function will fire if the mutation encounters an error and will be passed the error. #### onMutate `((variables: {{TVariables}}) => Promise | context | void) | undefined` - This function will fire before the mutation function is fired and is passed the same variables the mutation function would receive - Useful to perform optimistic updates to a resource in hopes that the mutation succeeds - The value returned from this function will be passed to both the `onError` and `onSettled` functions in the event of a mutation failure and can be useful for rolling back optimistic updates. #### onSuccess `((data: {{TData}}, variables: {{TVariables}}, context?: context | undefined) => Promise | unknown) | undefined` This function will fire when the mutation is successful and will be passed the mutation's result. #### onSettled `((data: {{TData}}, error: {{TError}}, variables: {{TVariables}}, context?: context | undefined) => Promise | unknown) | undefined` This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error #### queryClient `QueryClient` Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. #### retry `boolean | number | ((failureCount: number, error: {{TError}}) => boolean) | undefined` - Defaults to `0`. - If `false`, failed mutations will not retry. - If `true`, failed mutations will retry infinitely. - If set to an `number`, e.g. `3`, failed mutations will retry until the failed mutations count meets that number. #### retryDelay `number | ((retryAttempt: number, error: {{TError}}) => number) | undefined` - This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff. - A function like `attempt => attempt * 1000` applies linear backoff. ================================================ FILE: site/shared/mutation-result.md ================================================
--- [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/react/reference/useMutation) ### mutate `(variables: {{TVariables}}, { onSuccess, onSettled, onError }) => void` The mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options. - #### variables `{{TVariables}}` The variables object to pass to the `{{mutate}}` action. - #### onSuccess `(data: {{TData}}, variables: {{TVariables}}, context: TContext) => void` This function will fire when the mutation is successful and will be passed the mutation's result. - #### onError `(error: {{TError}}, variables: {{TVariables}}, context: TContext | undefined) => void` This function will fire if the mutation encounters an error and will be passed the error. - #### onSettled `(data: {{TData}} | undefined, error: {{TError}} | null, variables: {{TVariables}}, context: TContext | undefined) => void` - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error - If you make multiple requests, `onSuccess` will fire only after the latest call you've made. ### mutateAsync `(variables: {{TVariables}}, { onSuccess, onSettled, onError }) => Promise<{{TData}}>` Similar to [`mutate`](#mutate) but returns a promise which can be awaited. ### data `{{TData}} | undefined` - `{{mutate}}` return type - Defaults to `undefined` - The last successfully resolved data for the mutation. ### error `{{TError}} | null` The error object for the mutation, if an error was encountered. ### failureCount `number` - The failure count for the mutation. - Incremented every time the mutation fails. - Reset to `0` when the mutation succeeds. ### failureReason `{{TError}} | null` - The failure reason for the mutation retry. - Reset to `null` when the mutation succeeds. ### isError / isIdle / isPending / isSuccess `boolean` Boolean variables derived from [`status`](#status). ### isPaused `boolean` - will be `true` if the mutation has been `paused`. - see [Network Mode](https://tanstack.com/query/v5/docs/react/guides/network-mode) for more information. ### reset `() => void` A function to clean the mutation internal state (e.g. it resets the mutation to its initial state). ### status `'idle' | 'pending' | 'error' | 'success'` - `'idle'` initial status prior to the mutation function executing. - `'pending'` if the mutation is currently executing. - `'error'` if the last mutation attempt resulted in an error. - `'success'` if the last mutation attempt was successful. ### submittedAt `number` - The timestamp for when the mutation was submitted. - Defaults to `0`. ### variables `{{TVariables}} | undefined` - The variables object passed to [`mutate`](#mutate). - Defaults to `undefined`. ================================================ FILE: site/shared/query-imports.md ================================================ ## TanStack Query ```ts-vue import { type {{typeName}}Data, type {{typeName}}Options, type {{typeName}}QueryFnData, type {{typeName}}QueryKey, {{actionName}}QueryKey, {{actionName}}QueryOptions, } from '{{packageName}}/query' ``` ================================================ FILE: site/shared/query-options.md ================================================
--- ### query TanStack Query parameters. See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/react/reference/useQuery) for more info. ::: info Wagmi does not support passing all TanStack Query parameters TanStack Query parameters, like `queryFn` and `queryKey`, are used internally to make Wagmi work and you cannot override them. Check out the [source](https://github.com/wevm/wagmi/blob/main/packages/react/src/types/properties.ts#L27) to see what parameters are not supported. All parameters listed below are supported. ::: #### enabled `boolean | undefined` - Set this to `false` to disable this query from automatically running. - Can be used for [Dependent Queries](https://tanstack.com/query/v5/docs/react/guides/dependent-queries).
#### gcTime `number | Infinity | undefined` - Defaults to `5 * 60 * 1000` (5 minutes) or `Infinity` during SSR - The time in milliseconds that unused/inactive cache data remains in memory. When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different garbage collection times are specified, the longest one will be used. - If set to `Infinity`, will disable garbage collection
#### initialData `{{TData}} | (() => {{TData}}) | undefined` - If set, this value will be used as the initial data for the query cache (as long as the query hasn't been created or cached yet) - If set to a function, the function will be called **once** during the shared/root query initialization, and be expected to synchronously return the initialData - Initial data is considered stale by default unless a `staleTime` has been set. - `initialData` **is persisted** to the cache #### initialDataUpdatedAt `number | ((() => number | undefined)) | undefined` If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated.
#### initialPageParam `{{TPageParam}}` The initial page parameter to be passed to the query function. #### getPreviousPageParam This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. `(firstPage: {{TData}}, allPages: {{TData}}[], firstPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null` #### getNextPageParam This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of `hasPreviousPage`. `(lastPage: {{TData}}, allPages: {{TData}}[], lastPageParam: {{TPageParam}}, allPageParams: {{TPageParam}}[]) => {{TPageParam}} | undefined | null`
#### meta `Record | undefined` If set, stores additional information on the query cache entry that can be used as needed. It will be accessible wherever the `query` is available, and is also part of the `QueryFunctionContext` provided to the `queryFn`. #### networkMode `online' | 'always' | 'offlineFirst' | undefined` - Defaults to `'online'` - see [Network Mode](https://tanstack.com/query/v5/docs/react/guides/network-mode) for more information. #### notifyOnChangeProps `string[] | 'all' | (() => string[] | 'all') | undefined` - If set, the component will only re-render if any of the listed properties change. - If set to `['data', 'error']` for example, the component will only re-render when the `data` or `error` properties change. - If set to `'all'`, the component will opt-out of smart tracking and re-render whenever a query is updated. - If set to a function, the function will be executed to compute the list of properties. - By default, access to properties will be tracked, and the component will only re-render when one of the tracked properties change. #### placeholderData `{{TData}} | ((previousValue: {{TData}} | undefined; previousQuery: Query | undefined) => {{TData}}) | undefined` - If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `pending` state. - `placeholderData` is **not persisted** to the cache - If you provide a function for `placeholderData`, as a first argument you will receive previously watched query data if available, and the second argument will be the complete previousQuery instance. #### queryClient `QueryClient | undefined` Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. #### refetchInterval `number | false | ((data: {{TData}} | undefined, query: Query) => number | false | undefined) | undefined` - If set to a number, all queries will continuously refetch at this frequency in milliseconds - If set to a function, the function will be executed with the latest data and query to compute a frequency #### refetchIntervalInBackground `boolean | undefined` If set to `true`, queries that are set to continuously refetch with a `refetchInterval` will continue to refetch while their tab/window is in the background #### refetchOnMount `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` - Defaults to `true` - If set to `true`, the query will refetch on mount if the data is stale. - If set to `false`, the query will not refetch on mount. - If set to `'always'`, the query will always refetch on mount. - If set to a function, the function will be executed with the query to compute the value #### refetchOnReconnect `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` - Defaults to `true` - If set to `true`, the query will refetch on reconnect if the data is stale. - If set to `false`, the query will not refetch on reconnect. - If set to `'always'`, the query will always refetch on reconnect. - If set to a function, the function will be executed with the query to compute the value #### refetchOnWindowFocus `boolean | 'always' | ((query: Query) => boolean | 'always') | undefined` - Defaults to `true` - If set to `true`, the query will refetch on window focus if the data is stale. - If set to `false`, the query will not refetch on window focus. - If set to `'always'`, the query will always refetch on window focus. - If set to a function, the function will be executed with the query to compute the value #### retry `boolean | number | ((failureCount: number, error: {{TError}}) => boolean) | undefined` - If `false`, failed queries will not retry by default. - If `true`, failed queries will retry infinitely. - If set to a `number`, e.g. `3`, failed queries will retry until the failed query count meets that number. - Defaults to `3` on the client and `0` on the server #### retryDelay `number | ((retryAttempt: number, error: {{TError}}) => number) | undefined` - This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. - A function like `attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)` applies exponential backoff. - A function like `attempt => attempt * 1000` applies linear backoff. #### retryOnMount `boolean | undefined` If set to `false`, the query will not be retried on mount if it contains an error. Defaults to `true`. #### select `((data: {{TData}}) => unknown) | undefined` This option can be used to transform or select a part of the data returned by the query function. It affects the returned `data` value, but does not affect what gets stored in the query cache.
#### staleTime `number | Infinity | undefined` - Defaults to `0` - The time in milliseconds after data is considered stale. This value only applies to the hook it is defined on. - If set to `Infinity`, the data will never be considered stale
#### structuralSharing `boolean | (((oldData: {{TData}} | undefined, newData: {{TData}}) => {{TData}})) | undefined` - Defaults to `true` - If set to `false`, structural sharing between query results will be disabled. - If set to a function, the old and new data values will be passed through this function, which should combine them into resolved data for the query. This way, you can retain references from the old data to improve performance even when that data contains non-serializable values. ================================================ FILE: site/shared/query-result.md ================================================
--- [TanStack Query query docs](https://tanstack.com/query/v5/docs/react/reference/useQuery) ### data `{{TData}}` - The last successfully resolved data for the query. - Defaults to `undefined`. ### dataUpdatedAt `number` The timestamp for when the query most recently returned the `status` as `'success'`. ### error `null | {{TError}}` - The error object for the query, if an error was thrown. - Defaults to `null` ### errorUpdatedAt `number` The timestamp for when the query most recently returned the `status` as `'error'`. ### errorUpdateCount `number` The sum of all errors. ### failureCount `number` - The failure count for the query. - Incremented every time the query fails. - Reset to `0` when the query succeeds. ### failureReason `null | {{TError}}` - The failure reason for the query retry. - Reset to `null` when the query succeeds.
### fetchNextPage `(options?: FetchNextPageOptions) => Promise>` This function allows you to fetch the next "page" of results. ### fetchPreviousPage `(options?: FetchPreviousPageOptions) => Promise>` This function allows you to fetch the previous "page" of results. ### hasNextPage `boolean` This will be `true` if there is a next page to be fetched (known via the `getNextPageParam` option). ### hasPreviousPage `boolean` This will be `true` if there is a previous page to be fetched (known via the `getPreviousPageParam` option). ### isFetchingNextPage `boolean` Will be `true` while fetching the next page with `fetchNextPage`. ### isFetchingPreviousPage `boolean` Will be `true` while fetching the previous page with `fetchPreviousPage`.
### fetchStatus `'fetching' | 'idle' | 'paused'` - `fetching` Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetches. - `paused` The query wanted to fetch, but has been `paused`. - `idle` The query is not fetching. - See [Network Mode](https://tanstack.com/query/v5/docs/react/guides/network-mode) for more information. ### isError / isPending / isSuccess `boolean` Boolean variables derived from [`status`](#status). ### isFetched `boolean` Will be `true` if the query has been fetched. ### isFetchedAfterMount `boolean` - Will be `true` if the query has been fetched after the component mounted. - This property can be used to not show any previously cached data. ### isFetching / isPaused `boolean` Boolean variables derived from [`fetchStatus`](#fetchstatus). ### isLoading `boolean` - Is `true` whenever the first fetch for a query is in-flight - Is the same as `isFetching && isPending` ### isLoadingError `boolean` Will be `true` if the query failed while fetching for the first time. ### isPlaceholderData `boolean` Will be `true` if the data shown is the placeholder data. ### isRefetchError `boolean` Will be `true` if the query failed while refetching. ### isRefetching `boolean` - Is `true` whenever a background refetch is in-flight, which _does not_ include initial `'pending'`. - Is the same as `isFetching && !isPending` ### isStale `boolean` Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. ### refetch `(options: { cancelRefetch?: boolean | undefined; throwOnError?: boolean | undefined }) => Promise>` - A function to manually refetch the query. - `throwOnError` - When set to `true`, an error will be thrown if the query fails. - When set to `false`, an error will be logged if the query fails. - `cancelRefetch` - When set to `true`, a currently running request will be cancelled before a new request is made. - When set to `false`, no refetch will be made if there is already a request running. - Defaults to `true` ### status `'error' | 'pending' | 'success'` - `pending` if there's no cached data and no query attempt was finished yet. - `error` if the query attempt resulted in an error. The corresponding `error` property has the error received from the attempted fetch - `success` if the query has received a response with no errors and is ready to display its data. The corresponding `data` property on the query is the data received from the successful fetch or if the query's `enabled` property is set to `false` and has not been fetched yet `data` is the first `initialData` supplied to the query on initialization. ================================================ FILE: site/shared/tempo-write-parameters.md ================================================ ### account (optional) - **Type:** `Account | Address` Account that will be used to send the transaction. Defaults to connected Wagmi account. ### feeToken (optional) - **Type:** `Address | bigint` Fee token for the transaction. Can be a TIP-20 token address or ID. ### feePayer (optional) - **Type:** `Account | true` Fee payer for the transaction. Can be a [Viem Account](https://viem.sh/docs/accounts/local/privateKeyToAccount), or `true` if a [Fee Payer Service](https://docs.tempo.xyz/sdk/typescript/server/handler.feePayer) will be used. ### gas (optional) - **Type:** `bigint` Gas limit for the transaction. ### maxFeePerGas (optional) - **Type:** `bigint` Max fee per gas for the transaction. ### maxPriorityFeePerGas (optional) - **Type:** `bigint` Max priority fee per gas for the transaction. ### nonce (optional) - **Type:** `number` Nonce for the transaction. ### nonceKey (optional) - **Type:** `'expiring' | bigint` Nonce key for the transaction. ### validBefore (optional) - **Type:** `number` Unix timestamp before which the transaction must be included. ### validAfter (optional) - **Type:** `number` Unix timestamp after which the transaction can be included. ### throwOnReceiptRevert (optional) - **Type:** `boolean` - **Default:** `true` Whether to throw an error if the transaction receipt indicates a revert. Only applicable to `*Sync` actions. ================================================ FILE: site/shared/transports/custom.md ================================================ # custom The `custom` Transport connects to a JSON-RPC API via custom. Wraps Viem's [`custom` Transport](https://viem.sh/docs/clients/transports/custom). ## Import ```ts-vue import { custom } from '{{packageName}}' ``` ## Usage ```ts-vue import { createConfig, custom // [!code hl] } from '{{packageName}}' import { mainnet } from '{{packageName}}/chains' import { customRpc } from './rpc' export const config = createConfig({ chains: [mainnet], connectors: [injected()], transports: { [mainnet.id]: custom({ // [!code hl] async request({ method, params }) { // [!code hl] const response = await customRpc.request(method, params) // [!code hl] return response // [!code hl] } // [!code hl] }) // [!code hl] }, }) ``` ## Parameters ### provider `{ request({ method: string, params: unknown[] }): Promise }` An [EIP-1193 `request` function](https://eips.ethereum.org/EIPS/eip-1193#request) function. ```ts import { customRpc } from './rpc' const transport = custom({ async request({ method, params }) { // [!code focus:3] const response = await customRpc.request(method, params) return response } }) ``` ### key (optional) `string` A key for the Transport. Defaults to `"custom"`. ```ts const transport = custom( provider, { key: 'windowProvider', // [!code focus] } ) ``` ### name (optional) `string` A name for the Transport. Defaults to `"Ethereum Provider"`. ```ts const transport = custom( provider, { name: 'Window Ethereum Provider', // [!code focus] } ) ``` ### retryCount (optional) `number` The max number of times to retry when a request fails. Defaults to `3`. ```ts const transport = custom(provider, { retryCount: 5, // [!code focus] }) ``` ### retryDelay (optional) `number` The base delay (in ms) between retries. By default, the Transport will use [exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff) (`~~(1 << count) * retryDelay`), which means the time between retries is not constant. ```ts const transport = custom(provider, { retryDelay: 100, // [!code focus] }) ``` ================================================ FILE: site/shared/transports/fallback.md ================================================ # fallback The `fallback` Transport consumes **multiple** Transports. If a Transport request fails, it will fall back to the next one in the list. Wraps Viem's [`fallback` Transport](https://viem.sh/docs/clients/transports/fallback). ## Import ```ts-vue import { fallback } from '{{packageName}}' ``` ## Usage ```ts-vue import { createConfig, fallback, // [!code hl] http, } from '{{packageName}}' import { mainnet } from '{{packageName}}/chains' export const config = createConfig({ chains: [mainnet], connectors: [injected()], transports: { [mainnet.id]: fallback([ // [!code hl] http('https://foo-bar-baz.quiknode.pro/...'), // [!code hl] http('https://mainnet.infura.io/v3/...'), // [!code hl] ]) // [!code hl] }, }) ``` ================================================ FILE: site/shared/transports/http.md ================================================ # http The `http` Transport connects to a JSON-RPC API via HTTP. Wraps Viem's [`http` Transport](https://viem.sh/docs/clients/transports/http). ## Import ```ts-vue import { http } from '{{packageName}}' ``` ## Usage ```ts-vue import { createConfig, http // [!code hl] } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' export const config = createConfig({ chains: [mainnet, sepolia], connectors: [injected()], transports: { [mainnet.id]: http('https://foo-bar-baz.quiknode.pro/...'), // [!code hl] [sepolia.id]: http('https://foo-bar-sep.quiknode.pro/...'), // [!code hl] }, }) ``` ::: warning If no URL is provided, then the transport will fall back to a public RPC URL on the chain. It is highly recommended to provide an authenticated RPC URL to prevent rate-limiting. ::: ### Batch JSON-RPC The `http` Transport supports Batch JSON-RPC. This means that multiple JSON-RPC requests can be sent in a single HTTP request. The Transport will batch up Actions over a given period and execute them in a single Batch JSON-RPC HTTP request. By default, this period is a [zero delay](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop#zero_delays) meaning that the batch request will be executed at the end of the current [JavaScript message queue](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop#queue). Consumers can specify a custom time period `wait` (in ms). You can enable Batch JSON-RPC by setting the `batch` flag to `true`: ```ts const transport = http('https://foo-bar-baz.quiknode.pro/...', { batch: true // [!code hl] }) ``` ## Parameters ### url `string` URL of the JSON-RPC API. Defaults to `chain.rpcUrls.default.http[0]`. ```ts const transport = http('https://foo-bar-baz.quiknode.pro/...') ``` ### batch `boolean | BatchOptions` Toggle to enable Batch JSON-RPC. Defaults to `false` ```ts const transport = http('https://foo-bar-baz.quiknode.pro/...', { batch: true // [!code focus] }) ``` ### batch.batchSize `number` The maximum number of JSON-RPC requests to send in a batch. Defaults to `1_000`. ```ts const transport = http('https://foo-bar-baz.quiknode.pro/...', { batch: { batchSize: 2_000 // [!code focus] } }) ``` ### batch.wait `number` The maximum number of milliseconds to wait before sending a batch. Defaults to `0` ([zero delay](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop#zero_delays)). ```ts const transport = http('https://foo-bar-baz.quiknode.pro/...', { batch: { wait: 16 // [!code focus] } }) ``` ### fetchOptions [`RequestInit`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) [Fetch options](https://developer.mozilla.org/en-US/docs/Web/API/fetch) to pass to the internal `fetch` function. Useful for passing auth headers or cache options. ```ts const transport = http('https://foo-bar-baz.quiknode.pro/...', { fetchOptions: { // [!code focus:5] headers: { 'Authorization': 'Bearer ...' } } }) ``` ### key `string` A key for the Transport. Defaults to `"http"`. ```ts const transport = http('https://foo-bar-baz.quiknode.pro/...', { key: 'alchemy', // [!code focus] }) ``` ### name `string` A name for the Transport. Defaults to `"HTTP JSON-RPC"`. ```ts const transport = http('https://foo-bar-baz.quiknode.pro/...', { name: 'Alchemy HTTP Provider', // [!code focus] }) ``` ### retryCount `number` The max number of times to retry when a request fails. Defaults to `3`. ```ts const transport = http('https://foo-bar-baz.quiknode.pro/...', { retryCount: 5, // [!code focus] }) ``` ### retryDelay `number` The base delay (in ms) between retries. By default, the Transport will use [exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff) (`~~(1 << count) * retryDelay`), which means the time between retries is not constant. ```ts const transport = http('https://foo-bar-baz.quiknode.pro/...', { retryDelay: 100, // [!code focus] }) ``` ### timeout `number` The timeout for requests. Defaults to `10_000`. ```ts const transport = http('https://foo-bar-baz.quiknode.pro/...', { timeout: 60_000, // [!code focus] }) ``` ================================================ FILE: site/shared/transports/unstable_connector.md ================================================ # unstable_connector The `unstable_connector` Transport connects to a JSON-RPC API via the provided Connector. For example, if the provided Connector is `injected` and the end-user uses MetaMask, then outgoing JSON-RPC requests will be sent via the MetaMask EIP-1193 Provider (`window.ethereum`). ## Import ```ts-vue import { unstable_connector } from '{{packageName}}' ``` ## Usage ```ts-vue import { createConfig, fallback, unstable_connector, // [!code hl] } from '{{packageName}}' import { mainnet } from '{{packageName}}/chains' export const config = createConfig({ chains: [mainnet], connectors: [injected()], transports: { [mainnet.id]: fallback([ unstable_connector(injected), // [!code hl] http('https://foo-bar-baz.quiknode.pro/...') ]) }, }) ``` ::: warning It is **highly recommended** to use the `unstable_connector` Transport inside of a `fallback` Transport. This ensures that if the Connector request fails, the Transport will fall back to a different Transport in the fallback set. Some common cases for a Connector request to fail are: - Chain ID mismatches, - Connector RPC not supporting the requested method and/or only supporting a subset of methods for connected accounts, - Rate-limiting of Connector RPC. ::: ## Parameters ### connector `Connector` The Connector to use for the Transport. ```ts import { unstable_connector } from 'wagmi' import { safe } from 'wagmi/connectors' const transport = unstable_connector(safe) // [!code focus] ``` ### key (optional) `string` A key for the Transport. Defaults to `"connector"`. ```ts import { unstable_connector } from 'wagmi' import { injected } from 'wagmi/connectors' const transport = unstable_connector(injected, { key: 'injected', // [!code focus] }) ``` ### name (optional) `string` A name for the Transport. Defaults to `"Connector"`. ```ts import { unstable_connector } from 'wagmi' import { injected } from 'wagmi/connectors' const transport = unstable_connector(injected, { name: 'Injected', // [!code focus] }) ``` ### retryCount (optional) `number` The max number of times to retry when a request fails. Defaults to `3`. ```ts import { unstable_connector } from 'wagmi' import { injected } from 'wagmi/connectors' const transport = unstable_connector(injected, { retryCount: 5, // [!code focus] }) ``` ### retryDelay (optional) `number` The base delay (in ms) between retries. By default, the Transport will use [exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff) (`~~(1 << count) * retryDelay`), which means the time between retries is not constant. ```ts import { unstable_connector } from 'wagmi' import { injected } from 'wagmi/connectors' const transport = unstable_connector(injected, { retryDelay: 100, // [!code focus] }) ``` ================================================ FILE: site/shared/transports/webSocket.md ================================================ # webSocket The `webSocket` Transport connects to a JSON-RPC API via a WebSocket. Wraps Viem's [`webSocket` Transport](https://viem.sh/docs/clients/transports/websocket). ## Import ```ts-vue import { webSocket } from '{{packageName}}' ``` ## Usage ```ts-vue import { createConfig, webSocket // [!code hl] } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' export const config = createConfig({ chains: [mainnet, sepolia], connectors: [injected()], transports: { [mainnet.id]: webSocket('wss://foo-bar-baz.quiknode.pro/...'), // [!code hl] [sepolia.id]: webSocket('wss://foo-bar-sep.quicknode.pro/...'), // [!code hl] }, }) ``` ::: warning If no URL is provided, then the transport will fall back to a public RPC URL on the chain. It is highly recommended to provide an authenticated RPC URL to prevent rate-limiting. ::: ## Parameters ### url `string` URL of the JSON-RPC API. ```ts const transport = webSocket('wss://foo-bar-baz.quiknode.pro/...') ``` ### key (optional) `string` A key for the Transport. Defaults to `"webSocket"`. ```ts const transport = webSocket('wss://foo-bar-baz.quiknode.pro/...', { key: 'alchemy', // [!code focus] }) ``` ### name (optional) `string` A name for the Transport. Defaults to `"WebSocket JSON-RPC"`. ```ts const transport = webSocket('wss://foo-bar-baz.quiknode.pro/...', { name: 'Alchemy WebSocket Provider', // [!code focus] }) ``` ### retryCount (optional) `number` The max number of times to retry when a request fails. Defaults to `3`. ```ts const transport = webSocket('wss://foo-bar-baz.quiknode.pro/...', { retryCount: 5, // [!code focus] }) ``` ### retryDelay (optional) `number` The base delay (in ms) between retries. By default, the Transport will use [exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff) (`~~(1 << count) * retryDelay`), which means the time between retries is not constant. ```ts const transport = webSocket('wss://foo-bar-baz.quiknode.pro/...', { retryDelay: 100, // [!code focus] }) ``` ### timeout (optional) `number` The timeout for async WebSocket requests. Defaults to `10_000`. ```ts const transport = webSocket('wss://foo-bar-baz.quiknode.pro/...', { timeout: 60_000, // [!code focus] }) ``` ================================================ FILE: site/shared/utilities/cookieToInitialState.md ================================================ # cookieToInitialState Helper to convert a cookie string into [initial state](/react/api/WagmiProvider#initialstate). ## Import ```ts-vue import { cookieToInitialState } from '{{packageName}}' ``` ## Usage ::: code-group ```ts-vue [server.ts] import { cookieToInitialState } from '{{packageName}}' import config from './config' function handler(req: Request) { const initialState = cookieToInitialState(config, req.headers.cookie) // ... } ``` ```ts-vue [config.ts] import { createConfig, http, cookieStorage, createStorage } from '{{packageName}}' import { mainnet, sepolia } from '{{packageName}}/chains' export const config = createConfig({ chains: [mainnet, sepolia], ssr: true, storage: createStorage({ storage: cookieStorage, }), transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` ::: ## Parameters ### config `Config` Wagmi Config ### cookie `string | null | undefined` The cookie string. ## Return Type `State` Initial state. ================================================ FILE: site/shared/utilities/deserialize.md ================================================ # deserialize Deserialize function that supports `bigint` and `Map`. ## Import ```ts-vue import { deserialize } from '{{packageName}}' ``` ## Usage ```ts-vue import { deserialize } from '{{packageName}}' const result = deserialize('{"foo":"wagmi","bar":{"__type":"bigint","value":"123"}}') ``` ## Parameters ### value `string` The string to deserialize. ### reviver `(key: string, value: any) => any` A custom reviver function for handling standard values. ## Return Type `unknown` Parsed value. ================================================ FILE: site/shared/utilities/serialize.md ================================================ # serialize Serialize function that supports `bigint` and `Map`. ## Import ```ts-vue import { serialize } from '{{packageName}}' ``` ## Usage ```ts-vue import { serialize } from '{{packageName}}' const result = serialize({ foo: 'wagmi', bar: 123n }) ``` ## Parameters ### value `any` The value to stringify. ### replacer `(key: string, value: any) => any` A custom replacer function for handling standard values. ### indent `number | null | undefined` The number of spaces to indent the output by. ### circularReplacer A custom replacer function for handling circular values. ## Return Type `string` Stringified value. ================================================ FILE: site/snippets/abi-event.ts ================================================ export const abi = [ { type: 'event', name: 'Approval', inputs: [ { indexed: true, name: 'owner', type: 'address' }, { indexed: true, name: 'spender', type: 'address' }, { indexed: false, name: 'value', type: 'uint256' }, ], }, { type: 'event', name: 'Transfer', inputs: [ { indexed: true, name: 'from', type: 'address' }, { indexed: true, name: 'to', type: 'address' }, { indexed: false, name: 'value', type: 'uint256' }, ], }, ] as const ================================================ FILE: site/snippets/abi-infinite-read.ts ================================================ export const abi = [ { inputs: [{ internalType: 'uint256', name: 'tokenId', type: 'uint256' }], name: 'getChest', outputs: [{ internalType: 'string', name: '', type: 'string' }], stateMutability: 'view', type: 'function', }, { inputs: [{ internalType: 'uint256', name: 'tokenId', type: 'uint256' }], name: 'getFoot', outputs: [{ internalType: 'string', name: '', type: 'string' }], stateMutability: 'view', type: 'function', }, { inputs: [{ internalType: 'uint256', name: 'tokenId', type: 'uint256' }], name: 'getHand', outputs: [{ internalType: 'string', name: '', type: 'string' }], stateMutability: 'view', type: 'function', }, ] as const ================================================ FILE: site/snippets/abi-read.ts ================================================ export const abi = [ { type: 'function', name: 'balanceOf', stateMutability: 'view', inputs: [{ name: 'account', type: 'address' }], outputs: [{ type: 'uint256' }], }, { type: 'function', name: 'totalSupply', stateMutability: 'view', inputs: [], outputs: [{ name: 'supply', type: 'uint256' }], }, ] as const ================================================ FILE: site/snippets/abi-write.ts ================================================ export const abi = [ { type: 'function', name: 'approve', stateMutability: 'nonpayable', inputs: [ { name: 'spender', type: 'address' }, { name: 'amount', type: 'uint256' }, ], outputs: [{ type: 'bool' }], }, { type: 'function', name: 'transferFrom', stateMutability: 'nonpayable', inputs: [ { name: 'sender', type: 'address' }, { name: 'recipient', type: 'address' }, { name: 'amount', type: 'uint256' }, ], outputs: [{ type: 'bool' }], }, ] as const ================================================ FILE: site/snippets/core/config-chain-properties.ts ================================================ import { createConfig, http } from '@wagmi/core' import { base, celo, mainnet } from '@wagmi/core/chains' export const config = createConfig({ chains: [base, celo, mainnet], transports: { [base.id]: http(), [celo.id]: http(), [mainnet.id]: http(), }, }) ================================================ FILE: site/snippets/core/config-tempo.ts ================================================ import { createConfig, http } from '@wagmi/core' import { tempoTestnet } from '@wagmi/core/chains' import { KeyManager, webAuthn } from '@wagmi/core/tempo' export const config = createConfig({ connectors: [ webAuthn({ keyManager: KeyManager.localStorage(), }), ], chains: [tempoTestnet], multiInjectedProviderDiscovery: false, transports: { [tempoTestnet.id]: http(), }, }) ================================================ FILE: site/snippets/core/config.ts ================================================ import { createConfig, http } from '@wagmi/core' import { mainnet, sepolia } from '@wagmi/core/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ================================================ FILE: site/snippets/react/app.tsx ================================================ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import * as React from 'react' import { WagmiProvider } from 'wagmi' import { config } from './config' export const queryClient = new QueryClient() export function App() { return ( {/** ... */} ) } ================================================ FILE: site/snippets/react/config-chain-properties.ts ================================================ import { createConfig, http } from 'wagmi' import { base, celo, mainnet } from 'wagmi/chains' export const config = createConfig({ chains: [base, celo, mainnet], transports: { [base.id]: http(), [celo.id]: http(), [mainnet.id]: http(), }, }) declare module 'wagmi' { interface Register { config: typeof config } } ================================================ FILE: site/snippets/react/config-tempo.ts ================================================ import { createConfig, http } from 'wagmi' import { tempoTestnet } from 'wagmi/chains' import { KeyManager, webAuthn } from 'wagmi/tempo' export const config = createConfig({ connectors: [ webAuthn({ keyManager: KeyManager.localStorage(), }), ], chains: [tempoTestnet], multiInjectedProviderDiscovery: false, transports: { [tempoTestnet.id]: http(), }, }) ================================================ FILE: site/snippets/react/config.ts ================================================ import { createConfig, http } from 'wagmi' import { mainnet, sepolia } from 'wagmi/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ================================================ FILE: site/snippets/solid/config.ts ================================================ import { createConfig, http } from '@wagmi/solid' import { mainnet, sepolia } from '@wagmi/solid/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ================================================ FILE: site/snippets/typedData.ts ================================================ import type { TypedData } from 'viem' export const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const satisfies TypedData ================================================ FILE: site/snippets/vue/App.vue ================================================ ================================================ FILE: site/snippets/vue/config-chain-properties.ts ================================================ import { createConfig, http } from '@wagmi/vue' import { base, celo, mainnet } from '@wagmi/vue/chains' export const config = createConfig({ chains: [base, celo, mainnet], transports: { [base.id]: http(), [celo.id]: http(), [mainnet.id]: http(), }, }) declare module '@wagmi/vue' { interface Register { config: typeof config } } ================================================ FILE: site/snippets/vue/config.ts ================================================ import { createConfig, http } from '@wagmi/vue' import { mainnet, sepolia } from '@wagmi/vue/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ================================================ FILE: site/snippets/vue/main.ts ================================================ import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query' import { WagmiPlugin } from '@wagmi/vue' import { createApp } from 'vue' import App from './App.vue' import { config } from './config' export const queryClient = new QueryClient() createApp(App) .use(WagmiPlugin, { config }) .use(VueQueryPlugin, { queryClient }) .mount('#app') ================================================ FILE: site/solid/api/WagmiProvider.md ================================================ # WagmiProvider Solid Context Provider for Wagmi. ## Import ```ts import { WagmiProvider } from '@wagmi/solid' ``` ## Usage ```tsx import { WagmiProvider } from '@wagmi/solid' import { config } from './config' function App() { return ( {/** ... */} ) } ``` ## Parameters ```ts import { type WagmiProviderProps } from '@wagmi/solid' ``` ### config [`Config`](/solid/api/createConfig#config) object to inject with context. ```tsx import { WagmiProvider } from '@wagmi/solid' import { config } from './config' function App() { return ( {/** ... */} ) } ``` ### initialState `State | undefined` - Initial state to hydrate into the [Wagmi Config](/solid/api/createConfig). Useful for SSR. ```tsx import { WagmiProvider } from '@wagmi/solid' import { config } from './config' function App() { return ( {/** ... */} ) } ``` ### reconnectOnMount `boolean | undefined` - Whether or not to reconnect previously connected [connectors](/solid/api/createConfig#connectors) on mount. - Defaults to `true`. ```tsx import { WagmiProvider } from '@wagmi/solid' import { config } from './config' function App() { return ( {/** ... */} ) } ``` ## Context ```ts import { type WagmiContext } from '@wagmi/solid' ``` ================================================ FILE: site/solid/api/actions.md ================================================ # Actions `@wagmi/solid` exports all of the actions from `@wagmi/core`. These actions can be used for lower-level control or when you need to interact with Wagmi outside of Solid components. ## Import ```ts import { getBalance, sendTransaction } from '@wagmi/solid/actions' ``` ## Usage ```ts import { getBalance } from '@wagmi/solid/actions' import { config } from './config' const balance = await getBalance(config, { address: '0x...', }) ``` ## Available Actions See the [`@wagmi/core` Actions docs](/core/api/actions) for the full list of available actions and their documentation. ## When to Use Actions vs Primitives **Use Primitives when:** - You need reactive data in your Solid components - You want automatic caching and refetching - You're building UI that displays blockchain data **Use Actions when:** - You need imperative control over when data is fetched - You're working outside of Solid components - You need to chain multiple operations together - You're building utilities or helper functions ## Example: Using Actions with Primitives ```tsx import { useConnection } from '@wagmi/solid' import { signMessage } from '@wagmi/solid/actions' import { config } from './config' function SignMessage() { const connection = useConnection() const handleSign = async () => { if (!connection.address) return const signature = await signMessage(config, { message: 'Hello, World!', }) console.log('Signature:', signature) } return ( ) } ``` ================================================ FILE: site/solid/api/chains.md ================================================ # Chains Viem `Chain` objects. More info at the [Viem docs](https://viem.sh/docs/chains/introduction). ## Import Import via the `'@wagmi/solid/chains'` entrypoint (proxies all chains from `'viem/chains'`). ```ts import { mainnet } from '@wagmi/solid/chains' ``` ## Available Chains Chain definitions as of `viem@{{viemVersion}}`. For `viem@latest`, visit the [Viem repo](https://github.com/wevm/viem/blob/main/src/chains/index.ts). ================================================ FILE: site/solid/api/connectors/baseAccount.md ================================================ --- title: baseAccount --- ================================================ FILE: site/solid/api/connectors/injected.md ================================================ --- title: injected --- ================================================ FILE: site/solid/api/connectors/metaMask.md ================================================ --- title: metaMask --- ================================================ FILE: site/solid/api/connectors/mock.md ================================================ --- title: mock --- ================================================ FILE: site/solid/api/connectors/porto.md ================================================ --- title: porto --- ================================================ FILE: site/solid/api/connectors/safe.md ================================================ --- title: safe --- ================================================ FILE: site/solid/api/connectors/walletConnect.md ================================================ --- title: walletConnect --- ================================================ FILE: site/solid/api/connectors.md ================================================ # Connectors Connectors for popular wallet providers and protocols. ## Import Import via the `'@wagmi/solid/connectors'` entrypoint. ```ts import { injected } from '@wagmi/solid/connectors' ``` ## Available Connectors ::: tip Some connectors require third-party packages. See the "Install" section on each connector's page for more info on license, version, and more. ::: ================================================ FILE: site/solid/api/createConfig.md ================================================ --- title: createConfig --- ================================================ FILE: site/solid/api/createStorage.md ================================================ --- title: createStorage --- ================================================ FILE: site/solid/api/errors.md ================================================ # Errors `@wagmi/solid` exports error types that can be used for type-safe error handling. ## Import ```ts import { BaseError, ChainNotConfiguredError, ConnectorNotFoundError, // ... } from '@wagmi/solid' ``` ## Base Error All Wagmi errors extend from `BaseError`: ```ts import { BaseError } from '@wagmi/solid' try { // Wagmi operation } catch (error) { if (error instanceof BaseError) { console.error('Wagmi error:', error.message) console.error('Details:', error.details) } } ``` ## Available Errors ### ChainNotConfiguredError Thrown when trying to use a chain that isn't configured in your Wagmi config. ```ts import { ChainNotConfiguredError } from '@wagmi/solid' try { // Operation with unconfigured chain } catch (error) { if (error instanceof ChainNotConfiguredError) { console.error('Chain not configured:', error.message) } } ``` ### ConnectorNotFoundError Thrown when trying to use a connector that doesn't exist or isn't available. ```ts import { ConnectorNotFoundError } from '@wagmi/solid' try { // Connect operation } catch (error) { if (error instanceof ConnectorNotFoundError) { console.error('Wallet not installed') } } ``` ### ConnectorAlreadyConnectedError Thrown when trying to connect with a connector that's already connected. ```ts import { ConnectorAlreadyConnectedError } from '@wagmi/solid' try { // Connect operation } catch (error) { if (error instanceof ConnectorAlreadyConnectedError) { console.error('Already connected') } } ``` ### ProviderNotFoundError Thrown when the connector's provider is not found. ```ts import { ProviderNotFoundError } from '@wagmi/solid' try { // Provider operation } catch (error) { if (error instanceof ProviderNotFoundError) { console.error('Provider not found') } } ``` ### SwitchChainNotSupportedError Thrown when the connector doesn't support programmatic chain switching. ```ts import { SwitchChainNotSupportedError } from '@wagmi/solid' try { // Switch chain operation } catch (error) { if (error instanceof SwitchChainNotSupportedError) { console.error('Chain switching not supported') } } ``` ## More Errors See the [`@wagmi/core` Errors docs](/core/api/errors) for the full list of available error types. ================================================ FILE: site/solid/api/primitives/useBalance.md ================================================ --- title: useBalance description: Primitive for fetching native currency balance. --- # useBalance Primitive for fetching native currency balance. ## Import ```ts import { useBalance } from '@wagmi/solid' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useBalance } from '@wagmi/solid' function App() { const balance = useBalance(() => ({ address: '0x4557B18E779944BFE9d78A672452331C186a9f48', })) } ``` <<< @/snippets/solid/config.ts[config.ts] ::: ## Parameters ```ts import { useBalance } from '@wagmi/solid' useBalance.Parameters useBalance.SolidParameters ``` Parameters are passed as a getter function to maintain Solid reactivity. ```ts useBalance(() => ({ address: '0x...', // other parameters... })) ``` ### address `Address | undefined` Address to get balance for. [`enabled`](#enabled) set to `false` if `address` is `undefined`. ### blockNumber `bigint | undefined` Block number to get balance at. ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get balance at. ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ### config `Config | undefined` [`Config`](/solid/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/solid/api/WagmiProvider). ### scopeKey `string | undefined` Scopes the cache to a given context. Primitives that have identical context will share the same cache. ## Return Type ```ts import { useBalance } from '@wagmi/solid' useBalance.ReturnType ``` ## Action - [`getBalance`](/core/api/actions/getBalance) ================================================ FILE: site/solid/api/primitives/useBlockNumber.md ================================================ --- title: useBlockNumber description: Primitive for fetching the current block number. --- # useBlockNumber Primitive for fetching the current block number. ## Import ```ts import { useBlockNumber } from '@wagmi/solid' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useBlockNumber } from '@wagmi/solid' function App() { const blockNumber = useBlockNumber() } ``` <<< @/snippets/solid/config.ts[config.ts] ::: ## Parameters ```ts import { useBlockNumber } from '@wagmi/solid' useBlockNumber.Parameters useBlockNumber.SolidParameters ``` Parameters are passed as a getter function to maintain Solid reactivity. ```ts useBlockNumber(() => ({ chainId: 1, // other parameters... })) ``` ### cacheTime `number | undefined` Time in milliseconds that cached block number will remain in memory. ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ### config `Config | undefined` [`Config`](/solid/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/solid/api/WagmiProvider). ### scopeKey `string | undefined` Scopes the cache to a given context. Primitives that have identical context will share the same cache. ## Return Type ```ts import { useBlockNumber } from '@wagmi/solid' useBlockNumber.ReturnType ``` ## Action - [`getBlockNumber`](/core/api/actions/getBlockNumber) ================================================ FILE: site/solid/api/primitives/useChainId.md ================================================ --- title: useChainId description: Primitive for getting current chain ID. --- # useChainId Primitive for getting current chain ID. ## Import ```ts import { useChainId } from '@wagmi/solid' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useChainId } from '@wagmi/solid' function App() { const chainId = useChainId() return

Chain ID: {chainId()}

} ``` <<< @/snippets/solid/config.ts[config.ts] ::: ## Parameters ```ts import { useChainId } from '@wagmi/solid' useChainId.Parameters useChainId.SolidParameters ``` Parameters are passed as a getter function to maintain Solid reactivity. ```ts useChainId(() => ({ config, })) ``` ### config `Config | undefined` [`Config`](/solid/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/solid/api/WagmiProvider). ## Return Type ```ts import { useChainId } from '@wagmi/solid' useChainId.ReturnType ``` `Accessor` Returns an accessor containing the current chain ID from the config state. ::: info Only returns chain IDs for chains configured via `createConfig`'s [`chains`](/solid/api/createConfig#chains) parameter. If the active [connection](/solid/api/createConfig#connection) [`chainId`](/solid/api/createConfig#chainid-1) is not from a chain included in your Wagmi `Config`, `useChainId` will return the last configured chain ID. ::: ## Action - [`getChainId`](/core/api/actions/getChainId) - [`watchChainId`](/core/api/actions/watchChainId) ================================================ FILE: site/solid/api/primitives/useChains.md ================================================ --- title: useChains description: Primitive for getting configured chains. --- # useChains Primitive for getting configured chains. ## Import ```ts import { useChains } from '@wagmi/solid' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useChains } from '@wagmi/solid' import { For } from 'solid-js' function App() { const chains = useChains() return (
    {(chain) =>
  • {chain.name}
  • }
) } ``` <<< @/snippets/solid/config.ts[config.ts] ::: ## Parameters ```ts import { useChains } from '@wagmi/solid' useChains.Parameters useChains.SolidParameters ``` Parameters are passed as a getter function to maintain Solid reactivity. ```ts useChains(() => ({ config, })) ``` ### config `Config | undefined` [`Config`](/solid/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/solid/api/WagmiProvider). ## Return Type ```ts import { useChains } from '@wagmi/solid' useChains.ReturnType ``` `Accessor` Returns an accessor containing the configured chains. ## Action - [`getChains`](/core/api/actions/getChains) ================================================ FILE: site/solid/api/primitives/useClient.md ================================================ --- title: useClient description: Primitive for getting Viem Client. --- # useClient Primitive for getting [Viem Client](https://viem.sh/docs/clients/intro) instance. ## Import ```ts import { useClient } from '@wagmi/solid' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useClient } from '@wagmi/solid' function App() { const client = useClient() } ``` <<< @/snippets/solid/config.ts[config.ts] ::: ## Parameters ```ts import { useClient } from '@wagmi/solid' useClient.Parameters useClient.SolidParameters ``` Parameters are passed as a getter function to maintain Solid reactivity. ```ts useClient(() => ({ chainId: 1, })) ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when getting the client. ### config `Config | undefined` [`Config`](/solid/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/solid/api/WagmiProvider). ## Return Type ```ts import { useClient } from '@wagmi/solid' useClient.ReturnType ``` `Accessor` Returns an accessor containing the Viem Client instance, or `undefined` if not available. ## Action - [`getClient`](/core/api/actions/getClient) ================================================ FILE: site/solid/api/primitives/useConfig.md ================================================ --- title: useConfig description: Primitive for getting Wagmi Config. --- # useConfig Primitive for getting the current Wagmi [`Config`](/solid/api/createConfig#config). ## Import ```ts import { useConfig } from '@wagmi/solid' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useConfig } from '@wagmi/solid' function App() { const config = useConfig() } ``` <<< @/snippets/solid/config.ts[config.ts] ::: ## Parameters ```ts import { useConfig } from '@wagmi/solid' useConfig.Parameters useConfig.SolidParameters ``` Parameters are passed as a getter function to maintain Solid reactivity. ```ts useConfig(() => ({ config: customConfig, })) ``` ### config `Config | undefined` [`Config`](/solid/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/solid/api/WagmiProvider). ## Return Type ```ts import { useConfig } from '@wagmi/solid' useConfig.ReturnType ``` `Accessor` Returns an accessor containing the Wagmi Config. ================================================ FILE: site/solid/api/primitives/useConnect.md ================================================ --- title: useConnect description: Primitive for connecting accounts with connectors. --- # useConnect Primitive for connecting accounts with [connectors](/solid/api/connectors). ## Import ```ts import { useConnect } from '@wagmi/solid' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useConnect } from '@wagmi/solid' import { injected } from '@wagmi/solid/connectors' function App() { const connect = useConnect() return ( ) } ``` <<< @/snippets/solid/config.ts[config.ts] ::: ## Parameters ```ts import { useConnect } from '@wagmi/solid' useConnect.Parameters useConnect.SolidParameters ``` Parameters are passed as a getter function to maintain Solid reactivity. ```ts useConnect(() => ({ config, // mutation options... })) ``` ### config `Config | undefined` [`Config`](/solid/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/solid/api/WagmiProvider). ## Return Type ```ts import { useConnect } from '@wagmi/solid' useConnect.ReturnType ``` ::: tip Not all connectors support connecting directly to a `chainId` (e.g. they don't support programmatic chain switching). In those cases, the connector will connect to whatever chain the connector's provider (e.g. wallet) is connected to. ::: ## Action - [`connect`](/core/api/actions/connect) ================================================ FILE: site/solid/api/primitives/useConnection.md ================================================ --- title: useConnection description: Primitive for getting current connection. --- # useConnection Primitive for getting current connection. ## Import ```ts import { useConnection } from '@wagmi/solid' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useConnection } from '@wagmi/solid' import { Show } from 'solid-js' function App() { const connection = useConnection() return ( Not connected

}>

Address: {connection.address}

Chain ID: {connection.chainId}

) } ``` <<< @/snippets/solid/config.ts[config.ts] ::: ## Parameters ```ts import { useConnection } from '@wagmi/solid' useConnection.Parameters useConnection.SolidParameters ``` Parameters are passed as a getter function to maintain Solid reactivity. ```ts useConnection(() => ({ config, })) ``` ### config `Config | undefined` [`Config`](/solid/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/solid/api/WagmiProvider). ## Return Type ```ts import { useConnection } from '@wagmi/solid' useConnection.ReturnType ``` ### address `Address | undefined` The connected account address. ### addresses `readonly Address[] | undefined` All connected account addresses. ### chain `Chain | undefined` The connected chain. ### chainId `number | undefined` The connected chain ID. ### connector `Connector | undefined` The active connector. ### isConnected `boolean` Whether an account is connected. ### isConnecting `boolean` Whether a connection is in progress. ### isDisconnected `boolean` Whether the account is disconnected. ### isReconnecting `boolean` Whether a reconnection is in progress. ### status `'connected' | 'connecting' | 'disconnected' | 'reconnecting'` The current connection status. ## Action - [`getConnection`](/core/api/actions/getConnection) ================================================ FILE: site/solid/api/primitives/useConnectionEffect.md ================================================ --- title: useConnectionEffect description: Primitive for reacting to connection state changes. --- # useConnectionEffect Primitive for reacting to connection state changes. ## Import ```ts import { useConnectionEffect } from '@wagmi/solid' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useConnectionEffect } from '@wagmi/solid' function App() { useConnectionEffect(() => ({ onConnect(data) { console.log('Connected!', data) }, onDisconnect() { console.log('Disconnected!') }, })) return
...
} ``` <<< @/snippets/solid/config.ts[config.ts] ::: ## Parameters ```ts import { useConnectionEffect } from '@wagmi/solid' useConnectionEffect.Parameters useConnectionEffect.SolidParameters ``` Parameters are passed as a getter function to maintain Solid reactivity. ```ts useConnectionEffect(() => ({ onConnect(data) { /* ... */ }, onDisconnect() { /* ... */ }, })) ``` ### onConnect `((data: { address: Address; addresses: readonly Address[]; chain: Chain | undefined; chainId: number; connector: Connector; isReconnected: boolean }) => void) | undefined` Callback that is called when accounts are connected. ### onDisconnect `(() => void) | undefined` Callback that is called when no more accounts are connected. ### config `Config | undefined` [`Config`](/solid/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/solid/api/WagmiProvider). ## Return Type ```ts import { useConnectionEffect } from '@wagmi/solid' useConnectionEffect.ReturnType ``` `void` ## Action - [`watchConnection`](/core/api/actions/watchConnection) ================================================ FILE: site/solid/api/primitives/useConnections.md ================================================ --- title: useConnections description: Primitive for getting all active connections. --- # useConnections Primitive for getting all active connections. ## Import ```ts import { useConnections } from '@wagmi/solid' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useConnections } from '@wagmi/solid' import { For } from 'solid-js' function App() { const connections = useConnections() return (
    {(connection) => (
  • {connection.connector.name}: {connection.accounts[0]}
  • )}
) } ``` <<< @/snippets/solid/config.ts[config.ts] ::: ## Parameters ```ts import { useConnections } from '@wagmi/solid' useConnections.Parameters useConnections.SolidParameters ``` Parameters are passed as a getter function to maintain Solid reactivity. ```ts useConnections(() => ({ config, })) ``` ### config `Config | undefined` [`Config`](/solid/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/solid/api/WagmiProvider). ## Return Type ```ts import { useConnections } from '@wagmi/solid' useConnections.ReturnType ``` `Accessor` Returns an accessor containing all active connections. Each connection includes: - `accounts`: Connected account addresses - `chainId`: Connected chain ID - `connector`: The connector instance ## Action - [`getConnections`](/core/api/actions/getConnections) ================================================ FILE: site/solid/api/primitives/useConnectorClient.md ================================================ --- title: useConnectorClient description: Primitive for getting Viem Wallet Client from the active connector. --- # useConnectorClient Primitive for getting a [Viem Wallet Client](https://viem.sh/docs/clients/wallet) from the active connector. ## Import ```ts import { useConnectorClient } from '@wagmi/solid' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useConnectorClient } from '@wagmi/solid' function App() { const client = useConnectorClient() // client() returns the Wallet Client when connected } ``` <<< @/snippets/solid/config.ts[config.ts] ::: ## Parameters ```ts import { useConnectorClient } from '@wagmi/solid' useConnectorClient.Parameters useConnectorClient.SolidParameters ``` Parameters are passed as a getter function to maintain Solid reactivity. ```ts useConnectorClient(() => ({ chainId: 1, connector: myConnector, })) ``` ### account `Address | undefined` Account to use for the client. ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use for the client. ### config `Config | undefined` [`Config`](/solid/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/solid/api/WagmiProvider). ### connector `Connector | undefined` Connector to get the client for. Defaults to the active connector. ## Return Type ```ts import { useConnectorClient } from '@wagmi/solid' useConnectorClient.ReturnType ``` ## Action - [`getConnectorClient`](/core/api/actions/getConnectorClient) ================================================ FILE: site/solid/api/primitives/useConnectors.md ================================================ --- title: useConnectors description: Primitive for getting configured connectors. --- # useConnectors Primitive for getting configured connectors. ## Import ```ts import { useConnectors } from '@wagmi/solid' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useConnect, useConnectors } from '@wagmi/solid' import { For } from 'solid-js' function App() { const connectors = useConnectors() const connect = useConnect() return (
    {(connector) => (
  • )}
) } ``` ```ts [config.ts] import { http, createConfig } from '@wagmi/solid' import { mainnet, sepolia } from '@wagmi/solid/chains' import { injected, walletConnect } from '@wagmi/solid/connectors' export const config = createConfig({ chains: [mainnet, sepolia], connectors: [injected(), walletConnect({ projectId: '...' })], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` ::: ## Parameters ```ts import { useConnectors } from '@wagmi/solid' useConnectors.Parameters useConnectors.SolidParameters ``` Parameters are passed as a getter function to maintain Solid reactivity. ```ts useConnectors(() => ({ config, })) ``` ### config `Config | undefined` [`Config`](/solid/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/solid/api/WagmiProvider). ## Return Type ```ts import { useConnectors } from '@wagmi/solid' useConnectors.ReturnType ``` `Accessor` Returns an accessor containing all configured connectors. ## Action - [`getConnectors`](/core/api/actions/getConnectors) ================================================ FILE: site/solid/api/primitives/useDisconnect.md ================================================ --- title: useDisconnect description: Primitive for disconnecting connections. --- # useDisconnect Primitive for disconnecting connections. ## Import ```ts import { useDisconnect } from '@wagmi/solid' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useDisconnect } from '@wagmi/solid' function App() { const disconnect = useDisconnect() return ( ) } ``` <<< @/snippets/solid/config.ts[config.ts] ::: ## Parameters ```ts import { useDisconnect } from '@wagmi/solid' useDisconnect.Parameters useDisconnect.SolidParameters ``` Parameters are passed as a getter function to maintain Solid reactivity. ```ts useDisconnect(() => ({ config, // mutation options... })) ``` ### config `Config | undefined` [`Config`](/solid/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/solid/api/WagmiProvider). ## Return Type ```ts import { useDisconnect } from '@wagmi/solid' useDisconnect.ReturnType ``` ## Action - [`disconnect`](/core/api/actions/disconnect) ================================================ FILE: site/solid/api/primitives/useReconnect.md ================================================ --- title: useReconnect description: Primitive for reconnecting to previously connected connectors. --- # useReconnect Primitive for reconnecting to previously connected connectors. ## Import ```ts import { useReconnect } from '@wagmi/solid' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useReconnect } from '@wagmi/solid' function App() { const reconnect = useReconnect() return ( ) } ``` <<< @/snippets/solid/config.ts[config.ts] ::: ## Parameters ```ts import { useReconnect } from '@wagmi/solid' useReconnect.Parameters useReconnect.SolidParameters ``` Parameters are passed as a getter function to maintain Solid reactivity. ```ts useReconnect(() => ({ config, // mutation options... })) ``` ### config `Config | undefined` [`Config`](/solid/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/solid/api/WagmiProvider). ## Return Type ```ts import { useReconnect } from '@wagmi/solid' useReconnect.ReturnType ``` ## Action - [`reconnect`](/core/api/actions/reconnect) ================================================ FILE: site/solid/api/primitives/useSwitchChain.md ================================================ --- title: useSwitchChain description: Primitive for switching chains. --- # useSwitchChain Primitive for switching chains. ## Import ```ts import { useSwitchChain } from '@wagmi/solid' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useSwitchChain } from '@wagmi/solid' import { mainnet, sepolia } from '@wagmi/solid/chains' import { For } from 'solid-js' function App() { const switchChain = useSwitchChain() return (
{(chain) => ( )}
) } ``` <<< @/snippets/solid/config.ts[config.ts] ::: ## Parameters ```ts import { useSwitchChain } from '@wagmi/solid' useSwitchChain.Parameters useSwitchChain.SolidParameters ``` Parameters are passed as a getter function to maintain Solid reactivity. ```ts useSwitchChain(() => ({ config, // mutation options... })) ``` ### config `Config | undefined` [`Config`](/solid/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/solid/api/WagmiProvider). ## Return Type ```ts import { useSwitchChain } from '@wagmi/solid' useSwitchChain.ReturnType ``` ## Action - [`switchChain`](/core/api/actions/switchChain) ================================================ FILE: site/solid/api/primitives/useSwitchConnection.md ================================================ --- title: useSwitchConnection description: Primitive for switching between connections. --- # useSwitchConnection Primitive for switching between connections when multiple wallets are connected. ## Import ```ts import { useSwitchConnection } from '@wagmi/solid' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useConnections, useSwitchConnection } from '@wagmi/solid' import { For } from 'solid-js' function App() { const connections = useConnections() const switchConnection = useSwitchConnection() return (
{(connection) => ( )}
) } ``` <<< @/snippets/solid/config.ts[config.ts] ::: ## Parameters ```ts import { useSwitchConnection } from '@wagmi/solid' useSwitchConnection.Parameters useSwitchConnection.SolidParameters ``` Parameters are passed as a getter function to maintain Solid reactivity. ```ts useSwitchConnection(() => ({ config, // mutation options... })) ``` ### config `Config | undefined` [`Config`](/solid/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/solid/api/WagmiProvider). ## Return Type ```ts import { useSwitchConnection } from '@wagmi/solid' useSwitchConnection.ReturnType ``` ## Action - [`switchConnection`](/core/api/actions/switchConnection) ================================================ FILE: site/solid/api/primitives/useWatchBlockNumber.md ================================================ --- title: useWatchBlockNumber description: Primitive for watching block number changes. --- # useWatchBlockNumber Primitive for watching block number changes. ## Import ```ts import { useWatchBlockNumber } from '@wagmi/solid' ``` ## Usage ::: code-group ```tsx [index.tsx] import { useWatchBlockNumber } from '@wagmi/solid' import { createSignal } from 'solid-js' function App() { const [blockNumber, setBlockNumber] = createSignal() useWatchBlockNumber(() => ({ onBlockNumber(blockNumber) { setBlockNumber(blockNumber) }, })) return

Block number: {blockNumber()?.toString()}

} ``` <<< @/snippets/solid/config.ts[config.ts] ::: ## Parameters ```ts import { useWatchBlockNumber } from '@wagmi/solid' useWatchBlockNumber.Parameters useWatchBlockNumber.SolidParameters ``` Parameters are passed as a getter function to maintain Solid reactivity. ```ts useWatchBlockNumber(() => ({ onBlockNumber(blockNumber) { // Handle new block number }, })) ``` ### onBlockNumber `(blockNumber: bigint, prevBlockNumber: bigint | undefined) => void` Callback function called when the block number changes. ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when watching. ### config `Config | undefined` [`Config`](/solid/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/solid/api/WagmiProvider). ### emitMissed `boolean | undefined` Whether or not to emit missed block numbers to the callback. Defaults to `false`. Missed block numbers may occur in instances where internet connection is lost, or the block time is lesser than the polling interval of the client. ### emitOnBegin `boolean | undefined` Whether or not to emit the current block number when the watcher starts. Defaults to `false`. ### enabled `boolean | undefined` Whether or not to enable the watcher. Defaults to `true`. ### onError `((error: Error) => void) | undefined` Error handler called when an error occurs. ### poll `boolean | undefined` Whether or not to use polling. Defaults to the transport's `pollingInterval`. ### pollingInterval `number | undefined` Polling frequency (in ms). Defaults to the transport's `pollingInterval`. ### syncConnectedChain `boolean | undefined` Whether or not to sync the chain with the connected chain. Defaults to `true`. ## Return Type ```ts import { useWatchBlockNumber } from '@wagmi/solid' useWatchBlockNumber.ReturnType ``` `void` ## Action - [`watchBlockNumber`](/core/api/actions/watchBlockNumber) ================================================ FILE: site/solid/api/primitives.md ================================================ # Primitives Solid Primitives for accounts, wallets, contracts, transactions, signing, and more. ## Import ```ts import { useConnection } from '@wagmi/solid' ``` ## Reactive Parameters In Solid, primitive parameters are passed as getter functions (accessors) to maintain reactivity. This is different from React where parameters are passed directly as objects. ```ts // Solid style useBlockNumber(() => ({ chainId: 1 })) ``` ## Available Primitives ================================================ FILE: site/solid/api/transports/custom.md ================================================ --- title: custom --- ================================================ FILE: site/solid/api/transports/fallback.md ================================================ --- title: fallback --- ================================================ FILE: site/solid/api/transports/http.md ================================================ --- title: http --- ================================================ FILE: site/solid/api/transports/webSocket.md ================================================ --- title: webSocket --- ================================================ FILE: site/solid/api/transports.md ================================================ # Transports [`createConfig`](/solid/api/createConfig) can be instantiated with a set of Transports for each chain. A Transport is the intermediary layer that is responsible for executing outgoing JSON-RPC requests to the RPC Provider (e.g. Alchemy, Infura, etc). ## Import ```ts import { http } from '@wagmi/solid' ``` ## Built-In Transports Available via the `'@wagmi/solid'` entrypoint. ================================================ FILE: site/solid/getting-started.md ================================================ # Getting Started ## Overview `@wagmi/solid` is a collection of Solid primitives for Ethereum. You can learn more about the rationale behind the project in the [Why Wagmi](/solid/why) section. ## Manual Installation To manually add `@wagmi/solid` to your project, install the required packages. ::: code-group ```bash-vue [pnpm] pnpm add @wagmi/solid viem@{{viemVersion}} @tanstack/solid-query ``` ```bash-vue [npm] npm install @wagmi/solid viem@{{viemVersion}} @tanstack/solid-query ``` ```bash-vue [yarn] yarn add @wagmi/solid viem@{{viemVersion}} @tanstack/solid-query ``` ```bash-vue [bun] bun add @wagmi/solid viem@{{viemVersion}} @tanstack/solid-query ``` ::: - [Viem](https://viem.sh) is a TypeScript interface for Ethereum that performs blockchain operations. - [TanStack Query](https://tanstack.com/query/v5) is an async state manager that handles requests, caching, and more. - [TypeScript](/solid/typescript) is optional, but highly recommended. Learn more about [TypeScript support](/solid/typescript). ### Create Config Create and export a new Wagmi config using `createConfig`. ::: code-group ```ts [config.ts] import { http, createConfig } from '@wagmi/solid' import { mainnet, sepolia } from '@wagmi/solid/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` ::: In this example, Wagmi is configured to use the Mainnet and Sepolia chains, and `injected` connector. Check out the [`createConfig` docs](/solid/api/createConfig) for more configuration options. ::: details TypeScript Tip If you are using TypeScript, you can "register" the Wagmi config or use the hook `config` property to get strong type-safety across Solid Context in places that wouldn't normally have type info. ::: code-group ```ts twoslash [register config] // @twoslash-cache: {"v":1,"hash":"5a265a7585bba6cc64f83e9dd43093d209786bd39bd0106c74836c3c3bff74f8","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgAhVhBEBrAHKCAtgCMyAHhGT+7AOa86NMFDi8AwoZO8AvLfvHdpGMyiTWGXqgAdKV4QrUUVAFFaLEUPUjhEXmAgkNTUjy8fP1h+ZkFWNETk4L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nYjgtVEMqIogjyh8AIIigkgAALkLATUIcAzpBBBCIFLRcRbi46MDUrpKeRZIKjdzcDcD4GIQ7hXjFSg5QD5BNKYF9TYF1Z8R5IazcakC8bFSmZ1Lq7S6JCNKTrS79AfBk5NQ3jMBICgDmA6wSBgB4DOIfAfBAA="} // @errors: 2345 import { type Config } from '@wagmi/solid' import { mainnet, sepolia } from '@wagmi/solid/chains' declare const config: Config // ---cut--- import { useBlockNumber } from '@wagmi/solid' useBlockNumber(() => ({ chainId: 123 })) declare module '@wagmi/solid' { interface Register { config: typeof config } } ``` ```ts twoslash [hook config property] // @twoslash-cache: {"v":1,"hash":"f81e0bbbae23a2914d38755afa1fcae7b27d59df3ac778f5d55a5f0a3952daf7","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgAhVhBEBrAHKCAtgCMyAHhGT+7AOa86NMFDi8AwoZO8AvLfvGKvEfmbswASShm9DCW1gZgRsbIADognt5gcDEAushgmjqkKTHsUMlOHq7RsV4+iSApadpkWSA5ye6yrDBiACLMaMz5WiY+aAB8jFjMpMwaMDSkcAD8iNKyCkpq6WQAdAAKw6PjZHD6ru5xPv4NME2t7cx93LMy8ooq6lWkKwBK44KkYAAq2DC6jc00G0On0omAWBwuHwwFs4EMRDA5ndFo8MmD2BosBBSGgkQsHstyFQoEoEIgCGg0Fg4IgAPS0gDuzGMGnYKzg+FpcAgHCgtOYWHYtMIEGUcFpt3xSyelBAcA6OKQAE4qE0wMY0PgkABGAAsVAVxnGeEl92lGVlHDAuEQAAYqHERmIyMqAL4UdC/PCEEhE6jmJhsTg8PFm1F6OzhEy6UgwZgksCsDC8VBg3jp3haM0AUVoWEUscms2AaYzZdj8ckSd4sH4zEErDQxdLZdbvArCerMLGsxi2c1OxEzDAMQA3C22xmO1Xkx9WL2KVSafTxvhB8OVhIxxPJ+2453kwL2ABVUjz3gxfCU6l0/mClar9dgTcQO/sbd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oe4TInIOeTsL5GCklPRemG96qSfp+pRUDdw1GMyDbAK6CGc6gVfplkgYy/6XaICisBjWeAwgRAgwbaDJs4NiW4idh0nsg6MxxMPbWiqX4CAwWXAAAkyFkQpBYLrBGCYHhIZpoMYNU2u/g6liQOAR103BuCyh2swJAoBzBYQkGAPA4dXSuiAA==="} // @errors: 2345 import { type Config } from '@wagmi/solid' import { mainnet, sepolia } from '@wagmi/solid/chains' declare const config: Config // ---cut--- import { useBlockNumber } from '@wagmi/solid' useBlockNumber(() => ({ chainId: 123, config })) ``` By registering or using the hook `config` property, `useBlockNumber`'s `chainId` is strongly typed to only allow Mainnet and Sepolia IDs. Learn more by reading the [TypeScript docs](/solid/typescript#config-types). ::: ### Wrap App in Context Provider Wrap your app in the `WagmiProvider` Solid Context Provider and pass the `config` you created earlier to the `config` property. ::: code-group ```tsx [App.tsx] import { WagmiProvider } from '@wagmi/solid' import { config } from './config' function App() { return ( {/** ... */} ) } ``` ```ts [config.ts] import { http, createConfig } from '@wagmi/solid' import { mainnet, sepolia } from '@wagmi/solid/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` ::: Check out the [`WagmiProvider` docs](/solid/api/WagmiProvider) to learn more about Solid Context in Wagmi. ### Setup TanStack Query Inside the `WagmiProvider`, wrap your app in a TanStack Query Solid Context Provider, e.g. `QueryClientProvider`, and pass a new `QueryClient` instance to the `client` property. ::: code-group ```tsx [App.tsx] import { QueryClient, QueryClientProvider } from '@tanstack/solid-query' import { WagmiProvider } from '@wagmi/solid' import { config } from './config' const queryClient = new QueryClient() function App() { return ( {/** ... */} ) } ``` ```ts [config.ts] import { http, createConfig } from '@wagmi/solid' import { mainnet, sepolia } from '@wagmi/solid/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` ::: Check out the [TanStack Query docs](https://tanstack.com/query/latest/docs/framework/solid/overview) to learn about the library, APIs, and more. ### Use Wagmi Now that everything is set up, every component inside the Wagmi and TanStack Query Providers can use Wagmi Solid Primitives. ::: code-group ```tsx [Profile.tsx] import { useConnection } from '@wagmi/solid' export function Profile() { const connection = useConnection() return (

Address: {connection.address}

Status: {connection.status}

) } ``` ```tsx [App.tsx] import { QueryClient, QueryClientProvider } from '@tanstack/solid-query' import { WagmiProvider } from '@wagmi/solid' import { config } from './config' import { Profile } from './Profile' const queryClient = new QueryClient() function App() { return ( ) } ``` ```ts [config.ts] import { http, createConfig } from '@wagmi/solid' import { mainnet, sepolia } from '@wagmi/solid/chains' export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` ::: ## Next Steps For more information on what to do next, check out the following topics. - [**TypeScript**](/solid/typescript) Learn how to get the most out of Wagmi's type-safety and inference for an enlightened developer experience. - [**Connect Wallet**](/solid/guides/connect-wallet) Learn how to enable wallets to connect to and disconnect from your apps and display information about connected accounts. - [**Solid Primitives**](/solid/api/primitives) Browse the collection of Solid Primitives and learn how to use them. - [**Viem**](/solid/guides/viem) Learn about Viem and how it works with Wagmi. ================================================ FILE: site/solid/guides/connect-wallet.md ================================================ # Connect Wallet This guide covers how to connect and disconnect wallets using `@wagmi/solid`. ## Overview Connecting a wallet allows your app to interact with the user's Ethereum accounts. Wagmi provides primitives to handle the entire connection flow. ## Connecting Use the `useConnect` primitive to connect a wallet: ```tsx import { useConnect } from '@wagmi/solid' import { injected } from '@wagmi/solid/connectors' function Connect() { const connect = useConnect() return ( ) } ``` ## Displaying Available Connectors Use the `useConnectors` primitive to get a list of configured connectors: ```tsx import { useConnect, useConnectors } from '@wagmi/solid' import { For } from 'solid-js' function Connect() { const connect = useConnect() const connectors = useConnectors() return (
{(connector) => ( )}
) } ``` ## Checking Connection Status Use the `useConnection` primitive to check if a wallet is connected: ```tsx import { useConnection } from '@wagmi/solid' import { Show } from 'solid-js' function ConnectionStatus() { const connection = useConnection() return ( Not connected

} >

Connected to {connection.address}

) } ``` ## Disconnecting Use the `useDisconnect` primitive to disconnect: ```tsx import { useDisconnect } from '@wagmi/solid' function Disconnect() { const disconnect = useDisconnect() return ( ) } ``` ## Complete Example Here's a complete example combining all the pieces: ```tsx import { useConnect, useConnection, useConnectors, useDisconnect } from '@wagmi/solid' import { For, Show } from 'solid-js' function WalletConnection() { const connection = useConnection() const connectors = useConnectors() const connect = useConnect() const disconnect = useDisconnect() return (

Connect your wallet:

{(connector) => ( )} {connect.isError &&

Error: {connect.error?.message}

}
} >

Connected: {connection.address}

Chain ID: {connection.chainId}

) } ``` ## Connection Effects Use `useConnectionEffect` to react to connection state changes: ```tsx import { useConnectionEffect } from '@wagmi/solid' function ConnectionLogger() { useConnectionEffect(() => ({ onConnect(data) { console.log('Connected!', data) }, onDisconnect() { console.log('Disconnected!') }, })) return null } ``` ## Next Steps - [useConnect](/solid/api/primitives/useConnect) - Learn more about the connect primitive - [useDisconnect](/solid/api/primitives/useDisconnect) - Learn more about the disconnect primitive - [useConnection](/solid/api/primitives/useConnection) - Learn more about connection state ================================================ FILE: site/solid/guides/error-handling.md ================================================ # Error Handling `@wagmi/solid` provides comprehensive error handling through typed errors and TanStack Query's error states. ## Query Errors When using query primitives, errors are available through the `error` property: ```tsx import { useBalance } from '@wagmi/solid' function Balance() { const balance = useBalance(() => ({ address: '0x...', })) return (
{balance.isError && (

Error: {balance.error?.message}

)} {balance.isSuccess && (

Balance: {balance.data?.formatted}

)}
) } ``` ## Mutation Errors For mutation primitives like `useConnect` or `useDisconnect`, you can handle errors similarly: ```tsx import { useConnect } from '@wagmi/solid' import { injected } from '@wagmi/solid/connectors' function Connect() { const connect = useConnect() const handleConnect = () => { connect.mutate( { connector: injected() }, { onError(error) { console.error('Failed to connect:', error.message) }, } ) } return (
{connect.isError &&

Error: {connect.error?.message}

}
) } ``` ## Error Types Wagmi exports specific error types that you can use for more granular error handling: ```tsx import { useConnect, ConnectorNotFoundError } from '@wagmi/solid' function Connect() { const connect = useConnect() const handleConnect = () => { connect.mutate( { connector: injected() }, { onError(error) { if (error instanceof ConnectorNotFoundError) { console.error('Wallet not installed') } else { console.error('Unknown error:', error.message) } }, } ) } // ... } ``` ## Common Errors ### ConnectorNotFoundError Thrown when trying to use a connector that isn't available (e.g., MetaMask not installed). ### ChainNotConfiguredError Thrown when trying to use a chain that isn't configured in your Wagmi config. ### ConnectorAlreadyConnectedError Thrown when trying to connect with a connector that's already connected. ## Further Reading - [Wagmi Errors](/solid/api/errors) - [TanStack Query Error Handling](https://tanstack.com/query/latest/docs/framework/solid/guides/queries#error-handling) ================================================ FILE: site/solid/guides/tanstack-query.md ================================================ # TanStack Query [TanStack Query](https://tanstack.com/query/latest) is a powerful asynchronous state management library for Solid. It provides features like caching, deduplication, background refetching, and more. ## Overview `@wagmi/solid` uses TanStack Query under the hood to handle data fetching, caching, and state management. This means you get all the benefits of TanStack Query while using Wagmi primitives. ## Setup To use `@wagmi/solid`, you need to wrap your app with both `WagmiProvider` and `QueryClientProvider`: ```tsx import { QueryClient, QueryClientProvider } from '@tanstack/solid-query' import { WagmiProvider } from '@wagmi/solid' import { config } from './config' const queryClient = new QueryClient() function App() { return ( {/* Your app */} ) } ``` ## Query States When using Wagmi query primitives like `useBalance` or `useBlockNumber`, you have access to TanStack Query's state properties: ```tsx import { useBalance } from '@wagmi/solid' function Balance() { const balance = useBalance(() => ({ address: '0x...', })) return (
{balance.isPending &&

Loading...

} {balance.isError &&

Error: {balance.error?.message}

} {balance.isSuccess &&

Balance: {balance.data?.formatted}

}
) } ``` ## Query Options Wagmi primitives accept TanStack Query options through the `query` parameter: ```tsx import { useBalance } from '@wagmi/solid' function Balance() { const balance = useBalance(() => ({ address: '0x...', query: { enabled: true, refetchInterval: 5000, // Refetch every 5 seconds staleTime: 1000, // Consider data stale after 1 second }, })) // ... } ``` ## Further Reading For more information about TanStack Query, check out: - [TanStack Query Solid Documentation](https://tanstack.com/query/latest/docs/framework/solid/overview) - [Query Basics](https://tanstack.com/query/latest/docs/framework/solid/guides/queries) - [Mutations](https://tanstack.com/query/latest/docs/framework/solid/guides/mutations) ================================================ FILE: site/solid/guides/viem.md ================================================ # Viem [Viem](https://viem.sh) is a TypeScript interface for Ethereum that provides low-level primitives for interacting with Ethereum. `@wagmi/solid` is built on top of Viem. ## Overview Wagmi uses Viem internally to perform blockchain operations like sending transactions, reading from contracts, and more. You can also use Viem directly alongside Wagmi when you need lower-level control. ## Using Viem with Wagmi ### Getting the Viem Client You can get a Viem Public Client or Wallet Client using Wagmi primitives: ```tsx import { useClient, useConnectorClient } from '@wagmi/solid' function Example() { // Get a Public Client for read operations const publicClient = useClient() // Get a Wallet Client for write operations (requires connected account) const walletClient = useConnectorClient() // Use the clients... } ``` ### Using Viem Actions Directly Once you have a client, you can use Viem actions directly: ```tsx import { useClient } from '@wagmi/solid' import { getBlockNumber } from 'viem/actions' import { createEffect } from 'solid-js' function Example() { const client = useClient() createEffect(async () => { const clientValue = client() if (clientValue) { const blockNumber = await getBlockNumber(clientValue) console.log('Block number:', blockNumber) } }) // ... } ``` ## Viem Concepts ### Public Client vs Wallet Client - **Public Client**: Used for read-only operations (e.g., getting block numbers, reading contract state) - **Wallet Client**: Used for write operations that require signing (e.g., sending transactions, signing messages) ### Transports Wagmi uses Viem's transport system to communicate with Ethereum nodes. Common transports include: - `http`: HTTP JSON-RPC transport - `webSocket`: WebSocket transport for real-time updates - `fallback`: Fallback transport for reliability ## Further Reading For more information about Viem, check out: - [Viem Documentation](https://viem.sh) - [Viem Actions](https://viem.sh/docs/actions/public/introduction) - [Viem Clients](https://viem.sh/docs/clients/intro) ================================================ FILE: site/solid/installation.md ================================================ # Installation Install `@wagmi/solid` via your package manager. ## Package Manager Install the required packages. ::: code-group ```bash-vue [pnpm] pnpm add @wagmi/solid viem@{{viemVersion}} @tanstack/solid-query ``` ```bash-vue [npm] npm install @wagmi/solid viem@{{viemVersion}} @tanstack/solid-query ``` ```bash-vue [yarn] yarn add @wagmi/solid viem@{{viemVersion}} @tanstack/solid-query ``` ```bash-vue [bun] bun add @wagmi/solid viem@{{viemVersion}} @tanstack/solid-query ``` ::: - [Viem](https://viem.sh) is a TypeScript interface for Ethereum that performs blockchain operations. - [TanStack Query](https://tanstack.com/query/v5) is an async state manager that handles requests, caching, and more. - [TypeScript](/solid/typescript) is optional, but highly recommended. Learn more about [TypeScript support](/solid/typescript). ================================================ FILE: site/solid/typescript.md ================================================ # TypeScript ## Requirements `@wagmi/solid` is designed to be as type-safe as possible! Things to keep in mind: - Types currently require using TypeScript {{typescriptVersion}}. - [TypeScript doesn't follow semver](https://www.learningtypescript.com/articles/why-typescript-doesnt-follow-strict-semantic-versioning) and often introduces breaking changes in minor releases. - Changes to types in this repository are considered non-breaking and are usually released as patch changes (otherwise every type enhancement would be a major version!). - It is highly recommended that you lock your `@wagmi/solid` and `typescript` versions to specific patch releases and upgrade with the expectation that types may be fixed or upgraded between any release. - The non-type-related public API of Wagmi still follows semver very strictly. To ensure everything works correctly, make sure your `tsconfig.json` has [`strict`](https://www.typescriptlang.org/tsconfig#strict) mode set to `true`. ::: code-group ```json [tsconfig.json] { "compilerOptions": { "strict": true } } ``` ::: ## Config Types By default Solid Context does not work well with type inference. To support strong type-safety across the Solid Context boundary, there are two options available: - Declaration merging to "register" your `config` globally with TypeScript. - `config` property to pass your `config` directly to primitives. ### Declaration Merging [Declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) allows you to "register" your `config` globally with TypeScript. The `Register` type enables Wagmi to infer types in places that wouldn't normally have access to type info via Solid Context alone. To set this up, add the following declaration to your project. Below, we co-locate the declaration merging and the `config` set up. ```ts import { http, createConfig } from '@wagmi/solid' import { mainnet, sepolia } from '@wagmi/solid/chains' declare module '@wagmi/solid' { // [!code focus] interface Register { // [!code focus] config: typeof config // [!code focus] } // [!code focus] } // [!code focus] export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` Since the `Register` type is global, you only need to add it once in your project. Once set up, you will get strong type-safety across your entire project. For example, query primitives will type `chainId` based on your `config`'s `chains`. ```ts twoslash // @twoslash-cache: {"v":1,"hash":"27f72e6eb6261410d5ea826717da884abdb710c1600590e05d55d49a8093f14a","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgAhVhBEBrAHKCAtgCMyAHhGT+7AOa86NMFDi8AwoZO8AvLfvHdpGMyiTWGXqgAdKV4QrUUVAFFaLEUPUjhEXmAgkNTUjy8fP1h+ZkFWNETk4LTS3gzvMF9eMGYNGESAkAi0fDI4EWYwJoBuFLLSiqzpUlZGgjQ0LASAehmYVvbOsAA6CV7+gfTPSurmLHYAVVHx/EnpxDn99hWFtvjltYgZ642S0oBfPvevzd4wpTKAAq7HqiQAjAAmAAMsO+aQMYDQpGYYgSST+aSGVT8MDAcEOYHYJHibAASvAIKwSUVMQNsXsoFAPHB0U1obQYFzuVzwQAWKAAdnBAA4RJCtHzBVAAJwyyEAZlgzC04IVCoArDB+XyeW8tlidsMASobBkaFBEoroSKNXaRfCBr93obMjjeBp8uJOqxWAraS76Ub3V5mfA2SAOZ1weCtLBoRqZYLBVoFQA2BUxtOC6GQkUitMSmCQ5jgwUKpNp6Pg/UGkIMvwm5RmzwWiF8zXp6Hgx1lZ1pfupFbD3j8j0QDy8YcrXu8EnsfgYAASXHwAH5EoxGCIOHjCrZd0jdNOAHwUXhYZgo+o0eKJABqZAXy9XAAUr3UFu0+I4T7xX6QEAaOwsi6FoEBUp4YAnnwAA+0iWDARhgDAUDfB857FGk07oQAumevAiPgzDsGAACSUBmPQeJWIRrjIE0REkfiTS4cgYCaDopBsU07BQKxTh0WARjGAxIBMaRcCsexnFkDxIB8ax56yKwMBiAAIswaDMIJWgmKRaAnowl7Xl+8QbtIsgKIC6jaGQKzvqZt5wPorjnhJ5FQMpMCqRpWnMDBiQyPI4RqLJpArBSaCCKQYBAtgMC6CpaloJp2knkELAcFwfC1PUcCXiIM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KgVge/K+MBpwJJWP0GwbBWC8DKcYWo0VJweBJVIJp1gElpI8lk+WCpckfHyV0Si1LCKojaPciyHFlposQshW+6TmIUQsm/eC38v4xj5dfFCaECUGBwAAaRgBgCya1IV7WlUhG+cqACOggyCqsSAAGQgrIAA8sBBeABFA1pAMDmqwOISQLk/4GXPAAcQWItK6pAIikDUfFHAv99JInPOjZA04X5031Ya5VGAmjvyaLG+1AAxBZf5L78p1bkxEIkLIQxEiC9+ryPlThHFmmVgrepoCIhZE+qkuglpHJCMtfdK0YuHMyycpEDA4K0uwSp2L3hAjaLEhK1homJNpVAbtxVe1AUvOISp/wFjdS5BStoshx04DgMOsoQbmlQgVPkwpkASmsnKSqVSsSalNMSWKj+byNTfy1QK2dKwbowBIKwNxAaJw3UkQYmRH4XrkEQG8xRTSvrEHEdQIJ7VjKARwBtDAfAZ2ivfhKl9UqO3vqapojaSBhS6J4cRgRYSzrtRnYBu6wHxKyNVq9Qxz9HomLsTg6qwzRGIN5R8AQSLEkAAFyHAWoRwWdQQgg8aWlxLcKTeCMBpRkzy2SFTd24NwJqN5mBIFAOYHWEgwB4GcR8D4QA==="} // @errors: 2345 import { type Config } from '@wagmi/solid' import { mainnet, sepolia } from '@wagmi/solid/chains' declare module '@wagmi/solid' { interface Register { config: Config } } // ---cut--- import { useBlockNumber } from '@wagmi/solid' useBlockNumber(() => ({ chainId: 123 })) ``` ### Primitive `config` Property For cases where you have more than one Wagmi `config` or don't want to use the declaration merging approach, you can pass a specific `config` directly to primitives via the `config` property. ```ts import { http, createConfig } from '@wagmi/solid' import { mainnet, optimism } from '@wagmi/solid/chains' export const configA = createConfig({ // [!code focus] chains: [mainnet], // [!code focus] transports: { // [!code focus] [mainnet.id]: http(), // [!code focus] }, // [!code focus] }) // [!code focus] export const configB = createConfig({ // [!code focus] chains: [optimism], // [!code focus] transports: { // [!code focus] [optimism.id]: http(), // [!code focus] }, // [!code focus] }) // [!code focus] ``` As you expect, `chainId` is inferred correctly for each `config`. ```ts twoslash // @twoslash-cache: {"v":1,"hash":"6db931da3d5d995c7840071ad1e449e536b2569da9cadac7a5f1a18cd2f5e66d","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgAhVhBEBrAHKCAtgCMyAHhGT+7AOa86NMFDi8AwoZO8AvLfvGKvEfmbswASShm9DCW1gZgRsbIADognt5gcDEAushgmjqkKTHsUMlOHq7RsV4+iSApadpkWSA5ye6yrDBiACLMaMz5WiY+aAB8jFjMpMwaMDSkcAD8iNKyCkpq6WQAdAAKw6PjZHD6ru5xPv4NME2t7cx93LMy8ooq6lWkKwBK44KkYAAq2DC6jc00G0On0omAWBwuHwwFs4EMRDA5ndFo8MmD2BosBBSGgkQsHstyFQoEoEIgCGg0Fg4IgAPS0gDuzGMGnYKzg+FpcAgHCgtOYWHYtMIEGUcFpt3xSyelBAcA6OKQAE4qE0wMY0PgkABGAAsVAVxnGeEl92lGVlHDAuEQAAYqHERmIyMqAL4UdC/PCEEhE6jmJhsTg8PFm1F6OzhEy6UgwZgksCsDC8VBg3jp3haM0AUVoWEUscms2AaYzZdj8ckSd4sH4zEErDQxdLZdbvArCerMLGsxi2c1OxEzDAMQA3C22xmO1Xkx9WL2KVSafTxvhB8OVhIxxPJ+2453kwL2ABVUjz3gxfCU6l0/mClar9dgTcQO/sbdSSeu8ef9PfidZosXwYjAszagATLaUE/mWYRoE6aA0rwJa/q206JsmwRwMeYDsL6cBsG83KsL6zaobu6HVvGUCxnASExLatAwMxLHMXqUAAOzagAHCI4FaLqHFQEqSrgQAzLAzBaNqYliQArDAeq6qxH67uW+4zpmZo2BWNBQLM4m2txckmdxMFfuZbaUcmGgNuIQ6sKwYlkWpU4aRhvDUbR9EgIxQ7atqWiwLaclKhxHFaGJABsYkBVFHG2uB3HcVF/EwOBzDahxYlhVF/naqprl7pWHmASoOlxnpYG6vJ0W2tqlmtv+qHNWWKztbweq8Bo2KIu1KyN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cSI6HPBmYnc6n0fkYOZqeMdMbkgKKKJKKsSsaihseqPsYgkcZgGaINNcbVeaebaRMVJGP8e2fVM7dmI3dzf9eic2O2N2J5ISaSZgFOOklSagHSZuLuOydyeCfvcGd7mKdKd+J4IzbgM6eBdBbBYhMabiN9d4FabNC9eqeWIWaeaw7xLknOd4dYJJNGY0CpJpKmYBZ9c3b9Yw7I/I/BPrcTbWZ5NID5IFLVNQ5CJmTzcec4+hLOchd46fb8YCaE6I/Q+3fE4k/Bdedw+o/AjNItImd+fwWmffdE/9cw844hY0/yYzF9O5v9wRfiv2qksjJSqLPOp63jMrIGxeSQRGzTPGyZtJZmypasSvNpaL02yztcDkBZd9oXTr2BjthvOfJbNxGLnXKeBvgEAQTzgAAE+zWQhzeRc4wQwRUuMgZo4FGBKqjhXdxIDgUK6qE4b5uBuBiu+Z2zSAyukyKuo6qvELaua5Zg7tjA5BGvuBZQdpmAkBQBzAsIJAwA8BfZXRXQgA=="} // @errors: 2345 import { type Config } from '@wagmi/solid' import { mainnet, optimism } from '@wagmi/solid/chains' declare const configA: Config declare const configB: Config // ---cut--- import { useBlockNumber } from '@wagmi/solid' useBlockNumber(() => ({ chainId: 123, config: configA })) useBlockNumber(() => ({ chainId: 123, config: configB })) ``` This approach is more explicit, but works well for advanced use-cases, if you don't want to use Solid Context or declaration merging, etc. ## Reactive Parameters In Solid, primitive parameters are passed as getter functions (accessors) to maintain reactivity. This is different from React where parameters are passed directly as objects. ```ts // React style (NOT used in @wagmi/solid) useBlockNumber({ chainId: 1 }) // Solid style (used in @wagmi/solid) useBlockNumber(() => ({ chainId: 1 })) ``` This allows Wagmi to react to changes in your parameters automatically when using Solid's reactive primitives like `createSignal`. ```ts import { createSignal } from 'solid-js' import { useBlockNumber } from '@wagmi/solid' const [chainId, setChainId] = createSignal(1) // Block number will automatically update when chainId changes useBlockNumber(() => ({ chainId: chainId() })) ``` ## Configure Internal Types For advanced use-cases, you may want to configure Wagmi's internal types. Most of Wagmi's types relating to ABIs and EIP-712 Typed Data are powered by [ABIType](https://github.com/wevm/abitype). See the [ABIType docs](https://abitype.dev) for more info on how to configure types. ================================================ FILE: site/solid/why.md ================================================ # Why Wagmi Please see the [React "Why Wagmi"](/react/why) page for more information on the rationale behind the Wagmi project. The same principles apply to `@wagmi/solid`. ## Why Solid? [Solid](https://www.solidjs.com/) is a declarative JavaScript library for building user interfaces. It compiles templates to real DOM nodes and updates them with fine-grained reactions. Solid combines the best ideas from React, Vue, and Svelte while providing excellent performance and a small bundle size. `@wagmi/solid` brings the same great developer experience from Wagmi to Solid applications, allowing you to build Ethereum applications with Solid's reactive primitives. ================================================ FILE: site/tempo/actions/amm.burn.md ================================================ # `amm.burn` Burns liquidity tokens and receives the underlying token pair. [Learn more about the Fee AMM](https://docs.tempo.xyz/protocol/fees/spec-fee-amm) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"15a04714fe58dc0283f87db9029cec245122d1b5c43e71becacad49ab6778a83","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScAGYArmD8gmCcWJJwMACqYIxocEFEobEwiJxipBZKFJywvCyhcCVgscwARmQRJS2MShZoADrZrOxcqaTpWTmmUBC8CAYAsrFyAljm8JzipWjlypykMFj76WASxskQ0RucTa1knC0YVz0kyXRsliecF/fhMJwAjNZOEFAW8hIo0BEAHQDAYAWk4ABEZg1OPg0GgsA0APTYoiMGDMKFwfDY6azbGxATmATwbGjcbZXKUajiJRzZDIEB0cSsBQslhsDicYApNKZJlwTiuGKkCDMTgAcnxhMVsLADIlkyCioALAAmayKqrSCIDXGcA3Wa0221gEAAXQdom0+l1mjMihUakQgK0kl0gU1E2Z8gsVn+dgcpCcNHIiGk7k8ODwhBI5H89DwITCkU4vBMXALYGi3RK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LDTBxATCrAsh+uRx6LLWamzUxBjycKxEwtj/TNBXR9zcFAaB2kh1QChwYGh5LfeBD9+i+FaievhximpoBhxCR4oGRxR5RyItBd0kVPBa4GEgWLAEwCLmPJdMILKjPHPNXJfCPEr1KiqjKlPHKsytr1UhnJvAbzPFCD+dWEqsUqKIraLaIsLOT6LEBvTFUF4lwDKFvDjIguIMgir2gjdIki7LwLgqUvgmrJsrMrankIqICFCPeBqp82IkLBIoqIGgaCGmGhGlGjGnGgmkmimmmhmtmrmvmoWsWmWi0LwkLBujj2whwuL03/qjX1TC71T6wun/euOs383/8K38ooKytRgXz4R3zhF/TA0Bqvb8QgBJAuU6taPwL+37I/hKR/dVUMLRT9egTJAiyNYuIEgKAAECL0kI2ggK4K4EAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { config } from './config' const { amountUserToken, amountValidatorToken, receipt } = await Actions.amm.burnSync(config, { liquidity: parseUnits('10.5', 18), to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', userToken: '0x20c0000000000000000000000000000000000000', validatorToken: '0x20c0000000000000000000000000000000000001', }) console.log('Received user tokens:', amountUserToken) // @log: Received user tokens: 5250000000000000000n console.log('Received validator tokens:', amountValidatorToken) // @log: Received validator tokens: 5250000000000000000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `amm.burn` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' import { parseUnits } from 'viem' const hash = await Actions.amm.burn(config, { liquidity: parseUnits('10.5', 18), to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', userToken: '0x20c0000000000000000000000000000000000000', validatorToken: '0x20c0000000000000000000000000000000000001', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args: { amountUserToken, amountValidatorToken } } = viem_Actions.amm.burn.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Amount of user tokens received */ amountUserToken: bigint /** Amount of validator tokens received */ amountValidatorToken: bigint /** Amount of liquidity tokens burned */ liquidity: bigint /** Transaction receipt */ receipt: TransactionReceipt /** Address that initiated the burn */ sender: Address /** Address that received the underlying tokens */ to: Address /** Address of the user token */ userToken: Address /** Address of the validator token */ validatorToken: Address } ``` ## Parameters ### liquidity - **Type:** `bigint` Amount of LP tokens to burn. ### to - **Type:** `Address` Address to send tokens to. ### userToken - **Type:** `Address | bigint` Address or ID of the user token. ### validatorToken - **Type:** `Address | bigint` Address or ID of the validator token. ## Viem - [`amm.burn`](https://viem.sh/tempo/actions/amm.burn) ================================================ FILE: site/tempo/actions/amm.getLiquidityBalance.md ================================================ # `amm.getLiquidityBalance` Gets the liquidity balance for an address in a specific pool. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"685594825d16d8c180f2d81984cf6bf8e0a654c6d4ca8ae78262e8340a1d1fb4","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinABGoeJgvDCpK8kWDKLa+uqytcqqGi06enhrchtbXRZWAMwDjs6jjRPUXtO+c2oASYrHYXCMgmEpXKUjGAFZ5HULogato2ngISYnj1EG8QPYPiMkAAmYk/TBTAwzPxAhYGfJgzjiZjMaFHPrWPEKc4NPFom4GZms+TPJB4glDT5i6zkv5UgGlGh0kAJACum2MYE4bQAMowA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qqXoVuxynofhaSa4uQSQKYXA/SeS2aNsLAkgli6hugjSTINOucpokInquR4Qt4JBYgpoMOkGl83YUiLA1OkgoyxKXeCQQQLwEQu6VKBBoGYA6g/yx63QqosKoxH6AWVBoxLwx2+wCQwYLwfKaK40QQ+qrQMRTaIagGfaSR10xy3RIEl274IGiE5SeBVK+6dKR6gKwKoKbKDBnKN6FEFxGxGKFxVxaAfxP0rQkQkqNuIEdupOF4YS6UcIPubBueBEkJaAqQQm5GnoiJq+QBXeN0iJqQCIEWjy6m9ucJeGCJuKYSiALe6JgBMu8mqQOJnAeJHGoqNeiBBukGc664VyXxfxNxlKGE9xh6JYjKzxrK4Kbx163KXxD66Kvx7AoG/xcpiEgJOgIsv6bigGwGipmok8EgKBKAf4PCVopQRA1gwYvQZp1g1gnByc+g/W6cKsusoCwhZgpSYhxcHMg2SC/wKCtI7QiUM0VoOwewYSbI08LwACiIPIlwTpmsAZU4ZgooYw7pBsLwxs+8eAuppQ5OeAvGoZsILwjQICQCNgqCBgm044licZ2wnAZMcIlp9ZDZjZ9Z68IoOIvQfBEhHMMoRMMQsAIIMsYky0wgEkbE4mnEFEFkEAQk0EokByI5UkBEwYrBWQykRJywVZ6UC04gWUxYq0605ZjMO0Voe0HonAFU50ec10g0tA6glQxIUA4ZaQvAjQjQqZaQ1gcIdp/84gLwKwg2lQlQZovA0gMA6gcI0gcICQ1gKwUGKwKwo03kK87c15xI1gvATZGFmFWFGFCFHUXU18UCyFt0tAqF6F2F5FFFlpvQCFj0kGLO8JB5NYccgZLeVZ40pQEM4gSAoAAQigPCQgGZCArgrgQAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const balance = await Actions.amm.getLiquidityBalance(config, { address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', userToken: '0x20c0000000000000000000000000000000000000', validatorToken: '0x20c0000000000000000000000000000000000001', }) console.log('Liquidity balance:', balance) // @log: Liquidity balance: 10500000000000000000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `bigint` Liquidity balance. ## Parameters ### address - **Type:** `Address` Address to check balance for. ### poolId (optional) - **Type:** `Hex` Pool ID. ### userToken (optional) - **Type:** `Address | bigint` User token. ### validatorToken (optional) - **Type:** `Address | bigint` Validator token. ## Viem - [`amm.getLiquidityBalance`](https://viem.sh/tempo/actions/amm.getLiquidityBalance) ================================================ FILE: site/tempo/actions/amm.getPool.md ================================================ # `amm.getPool` Gets the reserves for a liquidity pool. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"7dda7bb1ad17e8af2b2215af2a34e1eccb912d3acf16ffbd8338a2da0631fe20","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinGwQcqnAuZzbnKTwZCQAqnBkACoQANaKqQBGyRZoANxbO3snpCQAaqGMUOJo7HOVzAt3uYCeL22AIkcgAygBXLBYOQYUFKB7PMCuUrlKSIdSyWrKVRISotHR6PCrORdCxWADMA0czlGjQm1C8018c2oASYrHYXCMgmEOO0+mkACZ5HUSfjyW08MKTLSeohGSB7MyRn1xh4OVMDDM/LyFgZ8oLOOJmMwxRU+tZbET6kgNdpFQZrbb5HTXUyhiykJL1OzMIafLNSjQzSAEvCwPwRZw2gAFCBrAA8GUSyQAfEEOslUtmshQVo5mHoyHBUsrhAA6L311PpuT1lMVqukOBZ4pKXMRVIp0gQZiME4ZzZgHa7fYfGDHM6Xa6cO7o8GYmdvA4wb7mP4A0hAldrjGQzjQ0IIpEot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GRM2ROSbRJyNoH0CTR/jEkVzDJEwFXA0MGILAH5BMxzIbUYQKpGsgCRQMWkSSJFAgDGR8UoIvji6PUiCR6wX+LIK5CT7UhGo4gZqEKCdEfQmwaMOQL1Fpj9QXgocatitFoCShrAvAU0bmLzHWANo5UFtgiJXAZisxOY/MZWN8a9BCxW0I3kMMEjOMqB5bUbN7mpAOYIR3rRQCFiO57p4RcEZsTQLbGYRB2lbLON2I257p9RoMQ0TG2HFrB6wUozkSFlKCPRxASAUAAEEUAfwhApjBAK4FcBAA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const pool = await Actions.amm.getPool(config, { userToken: '0x20c0000000000000000000000000000000000000', validatorToken: '0x20c0000000000000000000000000000000000001', }) console.log('User token reserve:', pool.reserveUserToken) // @log: User token reserve: 1000000000000000000000n console.log('Validator token reserve:', pool.reserveValidatorToken) // @log: Validator token reserve: 1000000000000000000000n console.log('Total supply:', pool.totalSupply) // @log: Total supply: 1000000000000000000000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = { /** Reserve of user token */ reserveUserToken: bigint /** Reserve of validator token */ reserveValidatorToken: bigint /** Total supply of LP tokens */ totalSupply: bigint } ``` ## Parameters ### userToken - **Type:** `Address | bigint` Address or ID of the user token. ### validatorToken - **Type:** `Address | bigint` Address or ID of the validator token. ## Viem - [`amm.getPool`](https://viem.sh/tempo/actions/amm.getPool) ================================================ FILE: site/tempo/actions/amm.mint.md ================================================ # `amm.mint` Mints liquidity tokens by providing a token pair. [Learn more about the Fee AMM](https://docs.tempo.xyz/protocol/fees/spec-fee-amm) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"8c8d9e3a10d7fc7ac97a66b8da388430eb2e46abfa5de1aeb9fd7c017dfd2448","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAn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FAACEUEYyEDwGZFcFcCAA"} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { config } from './config' const { liquidity, receipt } = await Actions.amm.mintSync(config, { to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', userTokenAddress: '0x20c0000000000000000000000000000000000000', validatorTokenAddress: '0x20c0000000000000000000000000000000000001', validatorTokenAmount: parseUnits('100', 6), }) console.log('Liquidity minted:', liquidity) // @log: Liquidity minted: 100000000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `amm.mint` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' import { parseUnits } from 'viem' const hash = await Actions.amm.mint(config, { to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', userTokenAddress: '0x20c0000000000000000000000000000000000000', validatorTokenAddress: '0x20c0000000000000000000000000000000000001', validatorTokenAmount: parseUnits('100', 6), }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args: { liquidity } } = viem_Actions.amm.mint.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Amount of user tokens provided */ amountUserToken: bigint /** Amount of validator tokens provided */ amountValidatorToken: bigint /** Amount of liquidity tokens minted */ liquidity: bigint /** Transaction receipt */ receipt: TransactionReceipt /** Address that initiated the mint */ sender: Address /** Address of the user token */ userToken: Address /** Address of the validator token */ validatorToken: Address } ``` ## Parameters ### to - **Type:** `Address` Address to mint the liquidity tokens to. ### userTokenAddress - **Type:** `Address | bigint` User token address. ### validatorTokenAddress - **Type:** `Address | bigint` Validator token address. ### validatorTokenAmount - **Type:** `bigint` Amount of validator tokens to provide. ## Viem - [`amm.mint`](https://viem.sh/tempo/actions/amm.mint) ================================================ FILE: site/tempo/actions/amm.rebalanceSwap.md ================================================ # `amm.rebalanceSwap` Performs a rebalance swap between user and validator tokens. [Learn more about the Fee AMM](https://docs.tempo.xyz/protocol/fees/spec-fee-amm) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"e399d67fb11f22f03c5401507bb51f3428c3c4c6a5e925ed4f4bc4e8e55c065a","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScAGYArmD8gmCcWJJwMACqYIxocEFEobEwiJxipBZKFJywvCyhcCVgscwARmQRJS2MShZoADrZrOxcqaTpWTmmUBC8CAYAsrFyAljm8JzipWjlypykMFj76WASxskQ0RucTa1knC0YVz0kyXRsliecF/fhMJwAjNZOEFAW8hIo0BEAHQDAYAWk4ABEZg1OPg0GgsA0APTYoiMGDMKFwfDY6azbGxATmATwbGjcbZXKUajiJRzZDIEB0cSsBQslhsDicYApNKZJlwTiuGKkCDMTgAcnxhMVsLADIlkyCioALAAmayKqrSCIDXGcA3Wa0221gEAAXQdom0+l1mjMihUakQgK0kl0gU1E2Z8gsVn+dgcpCcNHIiGk7k8ODwhBI5H89DwITCkU4vBMXALYGi3RKAGEhKWlANBcN81XuiyxJJ9AAOSOe5SqJAANn9Oj0eGL1ZZ5ksSH1UccznjiY81C8qd8GeoAWHhY2zAg8TQAEkwJ1ur1m66kP9/gBWeRenuINsDwN4Xk7k4HsfhpC66cx2dINtJouKYGGmfhrlmBjFmIewwLwMCMFgaAlAAKjGwixkkABKsHwYhLLknMICoeI6GJEIMFwQhaBQqerbnvq15dt6GiPkOBj7JReFhhOiDfiA9gznG54AQumDAT46YsjQEEgHWwpGEkpgtlIvq6gAzDe3Y+h62hPgYCkmB+PF8QJv5CYgam9oBYneK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r2OvKPBAOgkqiqmqhqlqjqnqgakapeCamahataravao6s6m6h6jghtJWt/N9BgkOqOvnTmhnZ2i9CutncHYOtYBmgXdXbaP8DgnglGUuZVdwLjZ8BYIgFSkbbvCyGwuIEgKAAEIoMBkIOTQgK4K4EAA=="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { config } from './config' const { amountIn, receipt } = await Actions.amm.rebalanceSwapSync(config, { amountOut: parseUnits('10.5', 6), to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', userToken: '0x20c0000000000000000000000000000000000000', validatorToken: '0x20c0000000000000000000000000000000000001', }) console.log('Amount in:', amountIn) // @log: 10605000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `amm.rebalanceSwap` action and wait for inclusion manually: ```ts import { Actions } from 'wagmi/tempo' import { Actions as viem_Actions } from 'viem/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' import { parseUnits } from 'viem' const hash = await Actions.amm.rebalanceSwap(config, { amountOut: parseUnits('10.5', 6), to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', userToken: '0x20c0000000000000000000000000000000000000', validatorToken: '0x20c0000000000000000000000000000000000001', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args: { amountIn } } = viem_Actions.amm.rebalanceSwap.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Amount of tokens required for the swap */ amountIn: bigint /** Amount of output tokens received */ amountOut: bigint /** Transaction receipt */ receipt: TransactionReceipt /** Address that initiated the swap */ swapper: Address /** Address of the user token */ userToken: Address /** Address of the validator token */ validatorToken: Address } ``` ## Parameters ### amountOut - **Type:** `bigint` Amount of user token to receive. ### to - **Type:** `Address` Address to send the user token to. ### userToken - **Type:** `Address | bigint` Address or ID of the user token. ### validatorToken - **Type:** `Address | bigint` Address or ID of the validator token. ## Viem - [`amm.rebalanceSwap`](https://viem.sh/tempo/actions/amm.rebalanceSwap) ================================================ FILE: site/tempo/actions/amm.watchBurn.md ================================================ # `amm.watchBurn` Watches for liquidity burn events on the Fee AMM. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"88643edeaab8a1c3858658b1397de9291730cd2a4ec09f2bcb6ee2f76ce6d305","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinACuYADu4mj2qQDqW/YZYGhD/ACiJMcASnorpGAAKl6l5VKI6rK1yqoaLTp6eDWm22ankFisAGYBo5nKNGhNqM8DDM/NQAkxWOwuEZBMIXtp9AAOT4Kb4NGraNp4HEmLrgpBQkD2GEjPrwjyIqbI3xzNELAz5LGccTMZj4ioyGqk+oMv5UgwisVgnqIRnM06sxAAJkqCMwXJ8s1KNH5IASa34uM4wPsACE7mAADxHLIAPiCHWSqRdyQonCwjmYejIcFSNOEADpFRGbfh7fcIwAFQPB0hwZ3FJSuiJ7A74I4nYYXRRoG5oB1PHC5MAi+AB3gwa15+NgUpQCC8BAGfYg+CcBLsTjmACOK0YUEYmE4ACMHZwYJc0HAI8bxEou8hkCA6CKsApSgADI9L3KCwrAaKkGBbGA+pR+/BoNBYTiufukCDMTgAcgAApslGYRgAHoYivb9T0xc9OBoTFX3fT8f3/NcgNA9gYFAhwLDgCC8igrgL3DOB4ISD8vz/ADULAjDYLYXDciWOJM04ABeS9rxoO8gmAXJOGiLDhFSZBaIgB54DQSw0AAXQoX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h8qAk3rCr3riogSQkyqkownQZwlakIlBTAaDjgaNgWDwlwa4EbhbjW4NilBEDWARi9B2nWDWBCEWw3xYLyEPyII4x4CoLKhWDulfyKG9A+y/x+yqF8iAIhxkBhxBQqS5zRx9I/YcJlwdzpxVyXy1zTKrytxJntxk5pnbx1xLwrwjwlw5lnypndwZm9z9xDxkAlkHzyJbw9xzzHCLzmDLyrRZnrzjyNlHwZm7xZSYANmTwFmqynwpldzpmuAwJsiEjiH3RPzIKvxBRyEKGahag4Ihl4JGhqEGA05Ah5gBSiyOESxQAznajWBSiYzkhekGAHkgjvy9D3wBmajWCuAXQxCwAYgIyEROTCAkRkS94oQgQiS4QWrRT3JKAAWITfgRh8FZD0TokQy2SxgOREQuT7KczDKej3gRymQuzc6lR8zhR4Uzyc5kbsysmInlTmTja1apQ3ikB2arQvixiVy5D3n2BGSlCDTiBICgABCKCSJCB4BLggCuCuBAA"} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.amm.watchBurn(config, { onBurn(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `() => void` Returns a function to unsubscribe from the event. ## Parameters ### onBurn - **Type:** `function` ```ts declare function onBurn(args: Args, log: Log): void type Args = { /** Amount of user token received */ amountUserToken: bigint /** Amount of validator token received */ amountValidatorToken: bigint /** Amount of LP tokens burned */ liquidity: bigint /** Address that removed liquidity */ sender: Address /** Address that received the tokens */ to: Address /** Address of the user token */ userToken: Address /** Address of the validator token */ validatorToken: Address } ``` Callback to invoke when liquidity is removed. ### args (optional) - **Type:** `object` ```ts type Args = { /** Filter by sender address */ sender?: Address | Address[] | null /** Filter by user token address */ userToken?: Address | Address[] | null /** Filter by validator token address */ validatorToken?: Address | Address[] | null } ``` Filter events by indexed parameters. ### userToken (optional) - **Type:** `Address | bigint` Address or ID of the user token to filter events. ### validatorToken (optional) - **Type:** `Address | bigint` Address or ID of the validator token to filter events. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `function` ```ts declare function onError(error: Error): void ``` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Enable polling mode. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`amm.watchBurn`](https://viem.sh/tempo/actions/amm.watchBurn) ================================================ FILE: site/tempo/actions/amm.watchMint.md ================================================ # `amm.watchMint` Watches for liquidity mint events on the Fee AMM. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"3e678dc18ce9b1b0888b0e3f1b0a2e9e066a3d862bdcaf011c8c115c0b244c46","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinACuYADu4mj2qQDqW/YZYGhD/ACiJMcASnorpGAAKl6l5VKI6rK1yqoaLTp6eDWm22ankFisAGYBo5nKNGhNqM8DDM/NQAkxWOwuEZBMIXtp9AAOT4Kb4NGraNp4HEmLrgpBQkD2GEjPrwjyIqbI3xzNELAz5LGccTMZj4ioyGqk+oMv5UgwisVgnqIRnM06sxAAJkqCMwXJ8s1KNH5IASa34uM4wPsAFkLGgADxHLIAPiCHWSqRdyQonCwjmYejIcFSNOEADpFRGbfh7ccIwAFQPB0hwZ3FJSuiJ7A74I4nYYXRRoG5oO6PLy5MAi+AB3gwa15+MMKhQCC8BAGfYg+CcBLsTjmACOK0YUEYmE4zAdnBglzQcAjxvESi7yGQIDoIqwClKAAND4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F1E5HbJPj5GxpLjHLFEdKlH74VHDJVE5pTK1HsANr1E/FbCNH+QVqDg1qNh1r/HzRmz2zD4oCbhI4NilBEDWARi9AonWDWDn7myxxdwv6JyNyYx4CtzKhWC4nZxv69Dex5y+xf58hFzBxkChz+Tlx2jsyczD5Ym1yNCEg343TJzNxpzRzElICkkdyahag9xUl9xGjf4GCLZAh5i+RCzoGixQA1xIBajWBShozkgEkGDykggZy9AJxkmajWCuCnQxCwAYiwx4T2TCCETESm5ITDKCRYSni4TJJPyvh7QkQRjH5Qw0QE6gxWSxi2T4SOTBJszHBuRQweTSTOxoB+RrjcwhQRTSTcR7ZTosz5TChAnFQmR2ZSZJTXikCoaLTPixiPy5D6n2D6SlC9TiBICgABCKCXxCB4CLggCuCuBAA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.amm.watchMint(config, { onMint(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = () => void ``` Returns a function to unsubscribe from the event. ## Parameters ### onMint - **Type:** ```ts declare function onMint(args: Args, log: Log): void type Args = { /** Amount of LP tokens minted */ liquidity: bigint /** Address that added liquidity */ sender: Address /** User token details */ userToken: { /** Address of the user token */ address: Address /** Amount of user token added */ amount: bigint } /** Validator token details */ validatorToken: { /** Address of the validator token */ address: Address /** Amount of validator token added */ amount: bigint } } ``` Callback to invoke when liquidity is added. ### sender (optional) - **Type:** `Address | bigint` Address or ID of the sender to filter events. ### userToken (optional) - **Type:** `Address | bigint` Address or ID of the user token to filter events. ### validatorToken (optional) - **Type:** `Address | bigint` Address or ID of the validator token to filter events. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `(error: Error) => void` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Enable polling mode for watching events. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`amm.watchMint`](https://viem.sh/tempo/actions/amm.watchMint) ================================================ FILE: site/tempo/actions/amm.watchRebalanceSwap.md ================================================ # `amm.watchRebalanceSwap` Watches for rebalance swap events on the Fee AMM. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"91e718ca006a23e8682b0ebc2f91d672ae05dd36421745b488980a673c12e660","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinACuYADu4mj2qQDqW/YZYGhD/ACiJMcASnorpGAAKl6l5VKI6rK1yqoaLTp6eDWm22ankFisAGYBo5nKNGhNqM8DDM/NQAkxWOwuEZBMIXtp9AAOT4Kb4NGraNp4HEmLrgpBQkD2GEjPrwjyIqbI3xzNELAz5LGccTMZj4ioyGqk+oMv5UgwisVgnqIRnM06sxAAJkqCMwXJ8s1KNH5IASa34uM4wPsNwARqFxGBeDAAMqbLAAHiOWQAfEEOslUj7khROFhHMw9GQ4KkacIAHSKhM2/D2x3Ot0ehMABUj0dIcG9xSUvoiewO+COJ2GF0UaBuaDujy8uTAIvgEZd1sr6bkTpd7vEWFKUAgvAQBn2IPgnAS7E4pBgDv7mc4cA9nBglzQcATxvESknyGQIDoIqwClKAANb7vcoLCsBokutjAQ0ow/g0GgsJxXHOpAQMwnAAOQAAKbEozCMAA9DES6gQ+mJPpwNCYv+gHAWBkGHjB8HsDA8EOBYcBIXkKFcM+8ZwJhCRASBEFQfhCFEehbDkbkSxxCWnAALwvjAb4fkEwC5Jw0QkcI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Ez4jlX8H469PcAVAEh9UVZ9SVOCSEz9clGE2DOEjUhE5KUDBcSDC6CweEhDHA48U8K3F0UoIgawBMXoG06wawIQz2O+dQRkdBBoTBN+QIHBZUKweQ/BTUXoBOQBaGZONQtOCaAsLOZKPSFuRZUgbuRQKefuWeeuJuFuN7DuXaeM4uRMvhPuGeOuIeNM0edcD0SePM6eUnIs3eKbA+ZeNec+LeY4GswHOs4+U+Rs1RHeRqZBf+ZoCQ7+EOBUZKOQ2ORQrUQOZQmGZmVOHqJ/IESsRKdWRw7WJ0/QLUCcv2MkSQrBQIBckEL+XoYmBQzUawVwB6GIWADEHGaiXyYQOiBiHvPCOCOSciG1HKXGZIB87CUCBMXgrITiR/ZYfcxpASGifyU5UWcOAWcKTGSKDSMOEKeBJKI8WWDKHOEsznYTYWbvRE+qJycbOrZWN8UgezXaP8VMQeXIEC/AWyUoSacQJAUAAIRQPRIQPAXcEAVwVwIAA"} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.amm.watchRebalanceSwap(config, { onRebalanceSwap(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = () => void ``` Returns a function to unsubscribe from the event. ## Parameters ### onRebalanceSwap - **Type:** `function` ```ts declare function onRebalanceSwap(args: Args, log: Log): void type Args = { /** Address of the user token */ userToken: Address /** Address of the validator token */ validatorToken: Address /** Address of the swapper */ swapper: Address /** Amount of validator token swapped in */ amountIn: bigint /** Amount of user token received */ amountOut: bigint } ``` Callback to invoke when a rebalance swap occurs. ### userToken (optional) - **Type:** `Address | bigint` Address or ID of the user token to filter events. ### validatorToken (optional) - **Type:** `Address | bigint` Address or ID of the validator token to filter events. ### args (optional) - **Type:** `object` ```ts type Args = { /** Filter by user token address */ userToken?: Address | Address[] | null /** Filter by validator token address */ validatorToken?: Address | Address[] | null /** Filter by swapper address */ swapper?: Address | Address[] | null } ``` Filter parameters for the event. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `function` ```ts declare function onError(error: Error): void ``` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Whether to use polling. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`amm.watchRebalanceSwap`](https://viem.sh/tempo/actions/amm.watchRebalanceSwap) ================================================ FILE: site/tempo/actions/dex.buy.md ================================================ # `dex.buy` Buys a specific amount of tokens from the Stablecoin DEX orderbook. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"514f8188da5f3aadb6f821b1369361f48b3a9b8e33f46d5689339bc21bc9aed7","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScAGYArmD8gmCcWJJwMACqYIxocEFEobEwiJxipBZKFJywvCyhcCVgscwARmQRJS2MShZoADrZrOxcqaTpWTmmUBC8CAYAsrFyAljm8JzipWjlypykMFj76WASxskQ0RucTa1knC0YVz0kyXRsliecF/fhMJwAjNZOEFAW8hIo0BEAHQDAYAWk4ABEZg1OPg0GgsA0APTYoiMGDMKFwfDY6azbGxATmATwbGjcbZXKUajiJRzZDIEB0cSsBQslhsDicYApNKZJlwTiuGKkCDMTgAcnxhMVsLADIlkyCioALAAmayKqrSCIDXGcA3Wa0221gEAAXQdom0+l1mjMihUakQgK0kl0gU1E2Z8gsVn+dgcpCcNHIiGk7k8ODwhBI5H89DwITCkU4vBMXALYGi3RKAGEhKWlANBcN81XuiyxJJ9AAOSOe5SqJAANn9Oj0eGL1ZZ5ksSH1UccznjiY81C8qd8GeoAWHhb2MF4MEYWDQJQAK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Wq3EeqsKw7JqhmDvZ89qkNcqgnd7Hq9gVffqwa2fZ6RfP4ZfaGlpIQbGVkDcrkXfHcFkIgawKEf4Am60b8h9RSXsKcKlH0JSYCvACLMCzsDdFhNhZMNFNtYxAwS4nBD8I8TBS6aqUqXqWYPACqT6S6EqD8dGstVhOdQC0Cd9SCK8D8emv9FhCiGC3ddm4ILFQ9btd6SqJIAACXCHwBKFJl7kBOONcHflYqFoMCNpJHtWTIM15rOGnV0mkFcVloAnloMD1tFrOHtrUB/XAsZp0X+FcHwQLFgCYCTVFBCm1g5gVCQMNgez9jVljruTiQTt1iTvTSKRpkkW6FTT1ihHfJtjeUuNFC5v3HZjLgri4HjrCjoAiiim6kbhtmbjDh8TQFPUzRvmtHvkfkPmPgZXPi7kzqOW3msDvj3gPg9k/SJR7j7iHRvVXrHX+CXiKk/VPSXv7jXv3oBX1CXhfjrLmsNMVBFqwVMJJEQHvmrs/D9qwUDpYpAFgXECQFAACBWiSCXQQFcFcCAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { config } from './config' const { receipt } = await Actions.dex.buySync(config, { amountOut: parseUnits('100', 6), maxAmountIn: parseUnits('105', 6), tokenIn: '0x20c0000000000000000000000000000000000001', tokenOut: '0x20c0000000000000000000000000000000000002', }) console.log('Transaction hash:', receipt.transactionHash) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `dex.buy` action and wait for inclusion manually: ```ts import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' import { parseUnits } from 'viem' const hash = await Actions.dex.buy(config, { amountOut: parseUnits('100', 6), maxAmountIn: parseUnits('105', 6), tokenIn: '0x20c0000000000000000000000000000000000001', tokenOut: '0x20c0000000000000000000000000000000000002', }) const receipt = await waitForTransactionReceipt(config, { hash }) ``` ## Return Type ```ts type ReturnType = { /** Transaction receipt */ receipt: TransactionReceipt } ``` ## Parameters ### amountOut - **Type:** `bigint` Amount of tokenOut to buy. ### maxAmountIn - **Type:** `bigint` Maximum amount of tokenIn to spend. ### tokenIn - **Type:** `Address` Address of the token to spend. ### tokenOut - **Type:** `Address` Address of the token to buy. ## Viem - [`dex.buy`](https://viem.sh/tempo/actions/dex.buy) ================================================ FILE: site/tempo/actions/dex.cancel.md ================================================ # `dex.cancel` Cancels an order from the Stablecoin DEX orderbook. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"8e63dbc2614d60dc2105888794c30ac7532f2a92ed7af97887d3f5dd42573f7c","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinOywpACSUKkARskWDKLa+gAc/bXKqhotOnp4q2SbXRZWAMwDjs6jxxPUXtO+c2oAUWsU4pBgvBgjCwaFSABUhsJhoIwAAlCFQmGlKAQXgIAwI8RI/gosEY6FoAB0pXKUjGtnO9Su1FatwM4MhFKePUQbxA9g+Iz66h+mCmBhmfiBCwM+XYXCMKNMtP0vWsx3kdUuiBq2jaeEVJm5r3eQ0+SBeAFZRX8JQDSjQZSA5YVYLQaUc+r1moztXy9WyQG7jRbTcMXIhKi8beKfLMHcCDAkAK5gElCaJEyFyADKGDTAB4MolkgA+IIdZKpYtZCicLCOZh6MhwVKG4SUt2U3hZmC5/O8SkABUbzdIcCLxSUpYiqSHpAgzEYcBgBeAuU4m5WpDWmx2ezAaAA3ButxzMbDOITicY0eSYSewK5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FHr67JRplFxo9KVHsCFrVGfHMS1E6CuyaRYJ5qJA/G3hmQsgWRIBWRlBST94gBEDWCUi9BInWDWD76Bx0i9DqBaxagND+gX54CSLX7NwRjJyTDtzP7SiX6tH1z7jnyHgejly9DSA1Bhzajn43B1w7gPANzyDPDMi36WxWiP4GASBKClAnaEndqMl0gozWA+hskNAMiOx4CgQQwKDyQIwurbapCozoxmyyD8iDB35IAP6qwxCwBMAAqZTAy3hNR5QIRHpFSJRLQ1TuQ2mky5QtSOmUjb5ZC9QtHLCeT1x1jnj/xhT/SAwKggxcxgxgQmzQyeywyni0nIxowYwvSGbzEbrdpbpqnZgakoQyrrA6krH1yGalDMziBICgABCKD7xCB4CcQgCuCuBAA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { orderId, receipt } = await Actions.dex.cancelSync(config, { orderId: 123n, }) console.log('Cancelled order ID:', orderId) // @log: Cancelled order ID: 123n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `dex.cancel` action and wait for inclusion manually: ```ts import { Actions } from 'wagmi/tempo' import { Actions as viem_Actions } from 'viem/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.dex.cancel(config, { orderId: 123n, }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args: { orderId } } = viem_Actions.dex.cancel.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** ID of the cancelled order */ orderId: bigint /** Transaction receipt */ receipt: TransactionReceipt } ``` ## Parameters ### orderId - **Type:** `bigint` ID of the order to cancel. ## Viem - [`dex.cancel`](https://viem.sh/tempo/actions/dex.cancel) ================================================ FILE: site/tempo/actions/dex.createPair.md ================================================ # `dex.createPair` Creates a new trading pair on the Stablecoin DEX. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"898ef8c60c928fbbc1b3ecd918cdf0c00d4ac080a78268a8148b45b02b060db9","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinADWMBipAAbWtAAkwGKkFkqum6XlUogAHP21yqpIAMwtOnp4axhdFlbPIPaOzlGVwm1C8018c2oAUWsU4ACNwjAtjt9odjqdztp9Fdmnd6khKi82ngEXBcPJvk8BgCRn1HiDMFMDDM/FCFgYllwAI4AVwgNGRewOaCOygxoixMgATPI6g9EABWIlvAy8/nksyUxC/f5DQF9cYeUFMnyzUo0dl/WGkGC8GCMLBoVIAFSGwmGgjAACVbfbHaUoBBeAgDK7xO7+J7ODa7Q60AA6TEVGSyPHymraYkGGN+hgUnra6l62mIKWNBlg5kQ83Qgz5dhcIye0wXfS9Xo1BT3BoZ1oqwyRkxfAs6wbDFyISqVCsmlmQi2BeuFWC0JOXXpSpVphq/TP9lfDn5F8ejBVSmfeOc1y0JHlgQdgaI28Q0AAK4kYpAAyhh7wAeDJEmSAA+IIOmSVJAKyChOCwRxmD0Mg4FSJsTHjFd414Z83w/b9f14eN3yGBCRjgADiiUYCIlSV9SAgZhGDJP9gFyTg2NWdZBVREV0U2ABuVj2NJJFOG2IU0TFfjBLYtUBVElFhVFE4pMfdiczjF03TgD0hB9WNHQEsBXGA3IwHEBC4Dgu0nxgF8YHfT8f3vAMgxDEA0mw+BOHEThLAAd04EVxCgY5YNwzghEC/AYE4AARABRAANeNclyAA5dUXXwRjOByny4Hw/A6MgHk4G8h8opfTg/I/NAyoSdgopioKI2MR80AgXI4Riixe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WdtSKNfJSaSDKL0sqISqatqJydS5RqaKeNaMdlKdv66KaThF6Oqc9FqbDEfWYxRpirGaZjNWmV7DpisW2Y9Nti/TOCIMz6ZgARm0xU4uxSmYtxom9xLyoUzP6vEmmqzZFus2EoylRKt7bdkqX6qHNjmsJM5maWJbbQrmePDErCEpIPNE6v5F5j81JLkk7mnzYXhCx4F/NgugLQxsCx4HvNsS4LbksIKhbmYAWVdOFkJwRamIkWhLNACi1IGbN0Wd7eTtQNVJ4sTmBLbUowMNKNQkMPUBaktSEAWkJAtDG0htTtD0tHSvQZ0tYBL7SFSwVwX4JX0LDcsswZgeTOQgb5bxAyurLRgWUZiyQRI0rRSLxHjJy1fByrRUNXxiEhDNWMhYEGPBiCwAmAzqaGDwGdikxEYGmFGMDGFh4xLohQtOCUPJjfR4wohLIPTAHrXQPgMEYSDBBiEwRO4XAN6HbAdhOw2oLsDCFhFsg4RHI+EH2MzD9iCRYEwcWgKHF4CYIVhqwlYb0GjgmxVs7nQkp7EjKIAJ8HwVbDZ2+gAAhRELsjWDu0J8wkY4eIIUwABFPkDsg6hXCDhXQ54TAEX4gASI4gJAKAACCKBjEQgPAHVBACuBXAQAA"} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { key, base, quote, receipt } = await Actions.dex.createPairSync(config, { base: '0x20c0000000000000000000000000000000000001', }) console.log('Pair key:', key) console.log('Base token:', base) console.log('Quote token:', quote) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `dex.createPair` action and wait for inclusion manually: ```ts import { Actions } from 'wagmi/tempo' import { Actions as viem_Actions } from 'viem/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.dex.createPair(config, { base: '0x20c0000000000000000000000000000000000001', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args: { base, quote } } = viem_Actions.dex.createPair.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Key of the trading pair */ key: Hex /** Address of the base token */ base: Address /** Address of the quote token */ quote: Address /** Transaction receipt */ receipt: TransactionReceipt } ``` ## Parameters ### base - **Type:** `Address` Address of the base token for the pair. The quote token is determined by the base token's quote token. ## Viem - [`dex.createPair`](https://viem.sh/tempo/actions/dex.createPair) ================================================ FILE: site/tempo/actions/dex.getBalance.md ================================================ # `dex.getBalance` Gets a user's token balance on the Stablecoin DEX. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"2cbcd8f2e4514b44f515cfd59cdc515095e16ac4e7309dcfa2a7dbd7df793943","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinABGoeJgvDCpK8kWDKLa+uqytcqqGi06enhrchtbXRZWAMwDjs6jjRPUXtO+c2oASYrHYXCMgmEpXKUjGAFZ5HULogato2ngISYnj1EG8QPYPiMkAAmYk/TBTAwzPxAhYGfJgziwWjQo59ax4hTnBp4tE3AzM7Gvd5DT5IF7Wcl/KkA0o0OkgBIAV02xjAnDaACF1psYAAeDKJZIAPiCHWSqUNWQonCwjmYejIcFSmOEADpmW6tTqtm6AAr2x2kOAG4pKY0RVJ+0gQZiMOD611wD10L16bX3XVugBKeiVpDAADVQkqYMbcmBxA64Hathr0z7cFQoBBeAgDABxPRwTjiThKhOkADkPbQEAA1opVo3OEJOKoYJwACIAUQAGm65eIlO3kMgQHQq1gFKUAAbntBwXIMwrAaKkGDiGhW5I2/BoNB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EQBAEZDzAANS9CzizA6pc4RCGJ1J4CaGjgsqnifZoAcxQayoA7dB2qcCWw3ICDHihI6BKgOh8qgbuq2iSqVw2i4lQpGjBhcBzRVzhAtIkwsCSAEp46hLWoOK9jayeSQiAbslqovKDFiCeSR5CDrIlhPKvJgqbIFpFqiEJBBAvARAhb7q9HVZgDqCto6BdoWBKjDoGl5a2wTEGkvDB77AJBugvDPozpFRBAbStCUlCyMbsJCl2h6w5osqFqR5yBuiVbVZoD6rdH7phbHqnomkxZXq9pzGJYPohkulzohnhlPjZloD1StCRBeK9ZwFXgIG/RFCRTIFwh4HLEvFDhmKpBnYzY2hmL5FuH6wNmcAIgfblqyFln7Z1kNkqGtmuFompCdndlba9n6EAG+JgBLzua6Snjpm5lRl7qfixkRbxntqJk9p5kpn3pYTplpazpZnsARm5n5k6DfSVYKJAqJDnk1btISCNEoD7jBy6ilBEDWC5S5TWDWBrGRKbFwjEixLIi8j7F4DDZHFpL3RQy4zXE0iEyLBOQrS6g7B7DJJAUkjqCgU7HIh7GDK3CNgwUnGEj3TEjwWXHSiIxKClAT5QW6qsidKUX9D4UNC2C0iBCrhrjOSrSpAHT/lCVCUjLyDPCnRkUTL3SSg7QxCwAgggxkTeQmAURoTXaYQQQSQQBEQ3ikSZp1Q/iUQARDhuhLFZDMT9lcBoWuS9geReRqi+SpiXS6hBT/TqzaRJLCwxS0DqCVDEhQAvBwhpC8CNCNAvCVBpDWBwj67SDEhwjiAvArBQyVCVCai8DSAwDqBwjSBwgJDWArArgrArAFTaTDLpS0CZS8DCXVU1W1V1U1X5RWR2ThG1mHZDg8V8XoUqHWUwBFSlDdTiBICgABCKDBxCB4CXggCuCuBAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const balance = await Actions.dex.getBalance(config, { account: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000001', }) console.log('DEX balance:', balance) // @log: DEX balance: 1000000000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = bigint ``` ## Parameters ### account - **Type:** `Address` Address of the account. ### token - **Type:** `Address` Address of the token. ## Viem - [`dex.getBalance`](https://viem.sh/tempo/actions/dex.getBalance) ================================================ FILE: site/tempo/actions/dex.getBuyQuote.md ================================================ # `dex.getBuyQuote` Gets the quote for buying a specific amount of tokens. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"a420bc920b6563e021956e1161cf4176a0594ca6d74434e3e2fa2b7a9993a741","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScAGYArmD8gmCcWJJwMACqYIxocEFEobEwiJxipBZKFJywvCyhcCVgscwARmQRJS2MShZoADrZrOxcqaTpWTmmUBC8CAYAsrFyAljm8JzipWjlypykMFj76WASxskQ0RucTa1knC0YVz0kyXRsliecF/fhMJwAjNZOEFAW8hIo0BEAHQDAYAWk4ABEZg1OPg0GgsA0APTYoiMGDMKFwfDY6azbGxATmATwbGjcbZXKUajiJRzZDIEB0cSsBQslhsDicYApNKZJlwTiuGKkCDMTgAcnxhMVsLADIlkyCioALAAmayKqrSCIDXGcA3Wa0221gEAAXQdom0+l1mjMihUakQgK0kl0gU1E2Z8gsVn+dgcpCcNHIiGk7k8ODwhBI5H89DwITCkU4vBMXALYGi3RKAGEhKWlANBcN81XuiyxJJ9AAOSOe5SqJAANn9Oj0eGL1ZZ5ksSH1UccznjiY81C8qd8GeoAWHhY2zAg8TQAEkwJ1ur1m66kP9/gBmeRenuINsDwN4Xk7k4HsfhpC66cx2d9pOLimBhpn4a5ZgYdbCkYSSmC2Ui+pethdt6GiPkOBjQSYH4Tog34gPY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SKAXI6QpSyAsqWU5U6Gr2uIPQqgsQLQUI5a72uG8mUm2IQ2KWeIKmNG5gLQqMvRj6EQjozoPy68okdKt4PowKAYoKtqECfoiyhEZ81g8KCC/KBgQQ2W0AUQ8xVRieyeAA/CUFelUEnKgmcKEPXLyKiFesgA6CFEQBAJLMCAANT/BfDpjjp178k3IEIGBwnNSTxrQy6oanodoFa3RzImbGIrBmoBjNAQhSi8B2b6rhBHpVDOadoer6RjBcCOaLy9b6rlCY6kCPA6m6B8YbDcF15QDpJCA/o5mDqlA0liA5Bf5CCSr5S9osBcFuonqCZC7RBBCXgRAvYxJvaY5gDqD4ZfbjixA0Zjmw7J7yZjmXgaa9DRBQiXhQgsZyBqxBAzwxm+RaEbD5ahCJapCtrgYwZrRf5yBQgY6HRTrkkSZvZSafaEa1Q/akZoDKYA5qYozXmbk6bsbXl3loAgVwgBiRBhI+EbS07y7CCvwkLEznwxG9FVGKgFi7glBq5c5VAYUnAwmaHwl4VxycA8LvLW5Ui25yp9E6jEWIDGgNi7gEW+klB0WkVWGBly6ZzqinYXZXnUi3nsCY5oAPniaYiSYfaxSybvmKZkb/aqZA6pJcEAW6bAVCWHRgUQWI7dSo5/Do7qVnDfK5KLQDIWDlQshEDWBQj/DWXWgCm0JICXj6iML0qOWgIGCM4ylIQcrCRthKl8qbJgK4x9z+w4JaKcJCnwSXi6iinAL3juUgAhX2iQrnjeVLLQKITwq5IsiyF4CeUOUXyxVjITIySGDEKfAjxjwlBuyIR2gylThylCQKmuCCkFiwBMDlLQwxS1IKja7IzYiMyQydWigzI9VKgJJDVfx7SBRjWKhQg8nVhNKsFJW6ziD6xcAxRxS0AJRoBJRmyFGFxWxcwcJOwtLaiKhuwMWeyKxCz7KhWBzBzWC8A9IvWvVvXvXWD/CpzUwsrYIPUhwfWA1A02j6ipzpyvGVFK6KhEJjQFajyjz0VVBJVqwsiNziBICgABCzRJB4DMiuCuBAA"} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { config } from './config' const amountIn = await Actions.dex.getBuyQuote(config, { amountOut: parseUnits('100', 6), tokenIn: '0x20c0000000000000000000000000000000000001', tokenOut: '0x20c0000000000000000000000000000000000002', }) console.log('Amount needed:', amountIn) // @log: Amount needed: 100300000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = bigint ``` Returns the amount of `tokenIn` needed to buy the specified `amountOut` of `tokenOut`. ## Parameters ### amountOut - **Type:** `bigint` Amount of tokenOut to buy. ### tokenIn - **Type:** `Address` Address of the token to spend. ### tokenOut - **Type:** `Address` Address of the token to buy. ## Viem - [`dex.getBuyQuote`](https://viem.sh/tempo/actions/dex.getBuyQuote) ================================================ FILE: site/tempo/actions/dex.getOrder.md ================================================ # `dex.getOrder` Gets an order's details from the Stablecoin DEX orderbook. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"1b4c194e1433ff47798203a8d893230e07a7bba99b163b51514c7b0d01dbdc5f","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinOywpKnAuZzbK6RrAJJQqQBGyRZoANxbO8ziANZkqQAG1rQAJMBipBZKrk9XYB2nGOEAgdwA0jAMM9Xh8vj8/gCgYw4AAhRhHYGghTiMBInYCXh3VJgACuzGOZHx23EzAgpLAaBOZ0Z1M4pBgtwsP2ZSnObKwHKIvP5122lnoItZYs4KIAYuYsCdsTBcWyEoqACqMIkk8mU0gA1ylcpSRDqWS1ZSqJAAVhaOj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Y4eGoESETmlkaZBDK0JEKcg2tpBDr1jEAyFwDVLaGjtPuLu2mUYyKkJuv2pePUX0jzorqkK0akPaEYqgY+q2hLtxF0dxC0fSIyJnrzmekUOUd0c9n0WAL9JAqalRAEQIEETkWgOEZMjZFEe6ghIsnET6uUmPgGtsmkfsu0pkdmqZBsXkToNLCETAhmhYBsbGInIbJXigCpD9pRKUEQNYM+L0ICdYNYPPknGaL0LaMmKvt2L2EbIEG2tvgXPzFOIfjOCLDWOLCbFDp+JNM1E9J+C9MCCyJcDKLcA8I7i8O8J8CNAiP8DKDJBCFCDCNSe1r8PSfiXvOiN7CqGqDKISMSH1vqFSDKLSGMUyMSb7KSZyRyE1jyJKaKJyYKNxlKNKUCBKBKT7IqciHAAqBlsqO3HyZyRqBltqLqEKRSCKWAMaOCUvuoCvnrA0EzNnIEFJEiSbIMHzKMB6AfpMN4BIEoKUKtngIibaX0BOMWLrBnEgLYGGJXMHBTAJEJBsBxHSDMZwL0CCVmVmZ9KPPcI8M5K8G/s+CMVyRiKkCNIRK/m/nZHnJaLvl6TGa4HTDELABGCrBlGdMIFlBFHutFF5J1BAClAZOlP4uDPZNlM5M+FPlkKVAHssFJIdOIMdKdLmghG+JzLdGDA9NcF7K9O9J9JtDpv0azoMQmfxFTMmaWVJDpqUCjOIEgKAAEIoIvEIHgLpCAK4K4EAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const order = await Actions.dex.getOrder(config, { orderId: 123n, }) console.log('Order details:', order) // @log: Order details: { amount: 100000000n, maker: '0x...', isBid: true, ... } ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = { /** Original order amount */ amount: bigint /** Orderbook key (identifies the trading pair) */ bookKey: Hex /** Tick to flip to when fully filled (for flip orders). For bid flips: must be > tick. For ask flips: must be < tick */ flipTick: number /** Whether this is a bid (true) or ask (false) order */ isBid: boolean /** Whether this is a flip order */ isFlip: boolean /** Address of the user who placed this order */ maker: Address /** Next order ID in the doubly linked list (0 if tail) */ next: bigint /** The order ID */ orderId: bigint /** Previous order ID in the doubly linked list (0 if head) */ prev: bigint /** Remaining amount to be filled */ remaining: bigint /** Price tick */ tick: number } ``` Returns the complete order details including the maker's address, order amounts, price tick, linked list pointers, and flip order information. ## Parameters ### orderId - **Type:** `bigint` Order ID to query. ## Viem - [`dex.getOrder`](https://viem.sh/tempo/actions/dex.getOrder) ================================================ FILE: site/tempo/actions/dex.getSellQuote.md ================================================ # `dex.getSellQuote` Gets the quote for selling a specific amount of tokens. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"e72885ed736301b0d1aa5f428258ba248ff06fde799d2fc7fe974306d5b6b9c7","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScAGYArmD8gmCcWJJwMACqYIxocEFEobEwiJxipBZKFJywvCyhcCVgscwARmQRJS2MShZoADrZrOxcqaTpWTmmUBC8CAYAsrFyAljm8JzipWjlypykMFj76WASxskQ0RucTa1knC0YVz0kyXRsliecF/fhMJwAjNZOEFAW8hIo0BEAHQDAYAWk4ABEZg1OPg0GgsA0APTYoiMGDMKFwfDY6azbGxATmATwbGjcbZXKUajiJRzZDIEB0cSsBQslhsDicYApNKZJlwTiuGKkCDMTgAcnxhMVsLADIlkyCioALAAmayKqrSCIDXGcA3Wa0221gEAAXQdom0+l1mjMihUakQgK0kl0gU1E2Z8gsVn+dgcpCcNHIiGk7k8ODwhBI5H89DwITCkU4vBMXALYGi3RKAGEhKWlANBcN81XuiyxJJ9AAOSOe5SqJAANn9Oj0eGL1ZZ5ksSH1UccznjiY81C8qd8GeoAWHhY2zAg8TQAHkqZ1ur1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048tKVVfRq1kIAwLILc4gSAoAAQi0SQeAzIrgrgQAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { config } from './config' const amountOut = await Actions.dex.getSellQuote(config, { amountIn: parseUnits('100', 6), tokenIn: '0x20c0000000000000000000000000000000000001', tokenOut: '0x20c0000000000000000000000000000000000002', }) console.log('Amount received:', amountOut) // @log: Amount received: 99700000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = bigint ``` Returns the amount of `tokenOut` received for selling the specified `amountIn` of `tokenIn`. ## Parameters ### amountIn - **Type:** `bigint` Amount of tokenIn to sell. ### tokenIn - **Type:** `Address` Address of the token to sell. ### tokenOut - **Type:** `Address` Address of the token to receive. ## Viem - [`dex.getSellQuote`](https://viem.sh/tempo/actions/dex.getSellQuote) ================================================ FILE: site/tempo/actions/dex.getTickLevel.md ================================================ # `dex.getTickLevel` Gets the tick level information at a specific tick on the Stablecoin DEX orderbook. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"3fba3acc82c4f344f1ecc51d048f896383905db7488d943734d6cdae1b8b032a","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogLGwcnAAqjLwA1pQgYpL6ACyaZooqaoiJWpK6gRHRseaWSACMdg6kTjTkiNLunjh4hCTk/vR4ABTi5uJwAJScvCZcQ2AAZoxKiJwAwkITSgA6YMHsI/OTsfFSiAAcZanKqkgAbNk6enijC4UWVgBM5Y7ONXUe1F5Nvq3UAVfDnAUJDk01y+SiABkYMCAHQAJT0AFdSGAAGrdRG4UTafQlEoAZnkaWOiAArOdcnggTA5LdipknpUXqd6h9G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CVZmPUqkQ9Q02wemNUJmc+OeBFNVI0SQ58UEPcOsFqUBWGRcTEEVDUaQW0cKqVPeKkFqGK40pmMUeFAwCQJQWIKEqKhq4Kh0awOWbeJAWKm+K1YpdKzgPCRGIfaYEoMAE3cQSNfisa1uCQOQCERgTudKGqDAEa9JNajaH8VwQ0smRVJmLUXGIYWAJecWPCUcHScSJ3KSexFKMyMxQSABc6vSRid1FKa6k0ZSHCAaiWSYR6hiRiGERUhYRxNKtGeycQaqWqDSSsasKmA8NqIWDqCKEOfqQaYada9GjGzGrGzaCaCKcuWaJJb+MJVJDaBpSadFTFI6E6HbIqC/EPeY2XbSdK1Y58C/WIAGcQJAUAAIRQXlIQPATCEAVwVwIAA"} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { Tick } from 'viem/tempo' import { config } from './config' const level = await Actions.dex.getTickLevel(config, { base: '0x20c0000000000000000000000000000000000001', tick: Tick.fromPrice('1.001'), isBid: true, }) console.log('Tick level:', level) // @log: Tick level: { head: 1n, tail: 5n, totalLiquidity: 1000000000n } ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = { /** Order ID of the first order at this tick (0 if empty) */ head: bigint /** Order ID of the last order at this tick (0 if empty) */ tail: bigint /** Total liquidity available at this tick level */ totalLiquidity: bigint } ``` Returns the price level information including the order IDs for the head and tail of the FIFO queue at this price level, and the total liquidity available. ## Parameters ### base - **Type:** `Address` Address of the base token. ### isBid - **Type:** `boolean` Whether to query the bid side (`true`) or ask side (`false`). ### tick - **Type:** `number` Price tick to query. Can be created using `Tick.fromPrice()`. ## Viem - [`dex.getTickLevel`](https://viem.sh/tempo/actions/dex.getTickLevel) ================================================ FILE: site/tempo/actions/dex.place.md ================================================ # `dex.place` Places a limit order on the Stablecoin DEX orderbook. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"ae78873af261e30e0a9ea1adc6baa89b8d91d755de180f0299788136db141068","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScAGYArmD8gmCcWJJwMACqYIxocEFEobEwiJxipBZKFJywvCyhcCVgscwARmQRJS2MShZoADrZrOxcqaTpWTmmUBC8CAYAsrFyAljm8JzipWjlypykMFj76WASxskQ0RucTa1knC0YVz0kyXRsliecF/fhMJwAjNZOEFAW8hIo0BEAHQDAYAWk4ABEZg1OPg0GgsA0APTYoiMGDMKFwfDY6azbGxATmATwbGjcbZXKUajiJRzZDIEB0cSsBQslhsDicYApNKZJlwTiuGKkCDMTgAcnxhMVsLADIlkyCioALAAmayKqrSCIDXGcA3Wa0221gEAAXQdom0+l1mjMihUakQgK0kl0gU1E2Z8gsVn+dgcpCcNHIiGk7k8ODwhBI5H89CYQ2FABVGLwANYssSSfQADkjnuUqiQuv9Oj0eHzRZZ5ksSH1UccznjiY81C8qd8GeoATwITCkU4vBMXFnYGi3RKAGEhEulANBcMZ+vuiXXUh/v8AKzyL21xAANgbgbwC43bfDSAAzN2Y723APMCmDGm/GOWYGAuYhfKQsCkAAklAnTdL0B5lkeuqyNW3oaLeTYGOwEHQU+HaIGeID2D2cZIOWSaDr+PjpiyNBAURc57DAvAwIwWBoCUuYxsIsZJAASsxrHsSy5JzCAXHiDxiRCExLFsWgUIIVIvonuW541j6HraHeBj7HJwlhvhhHER+pG+uoFE/t4/6jnRgTbsKRhJKYpbKf86g3qhl5aQGmGGNJwh4VYxnRrGLiIC+J6WUOf4jrR44GA5XCwLQSn6P85b1l5PpvqyjaBClQVICFJHhbqL7RVRNnxfRcQJGcKRyE4MAAMoYAkAA8a6Lt0AB8QQPsunDdRuVSjLyehkKiTkmFCKVQqszVtQkUIAAqOMwk1jF1e5KL1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1ee6e8m1EdezgRe6Uo/PEmxdUIo0or6dOzO0gbOu2lAzENAgu12u/Yu9opuzo7oiuy+wYuurOhu3+pulu2Y72RYv4ZY/+pIYuVkFVcuHYliFkIgBRHTARa6wHSKE7T1V8FtMwG416962HeMbtBHZ7UteiLpTWaCWCM5Q7CKdQKsR6ssrB8hqAXB0beMfUKKJ7AwZVFkfcvANPahl8csWwG5YRmbEAWo8CO4SCREEoN6l8a7MwZ8X0LKfBpAb6vJWcWAbMQZUUGaYQRjU+Veb/SDXeCtHVP1C9Y+JjUVUxnRiTIsAxg1UVNjW+RFYUFuJ+Kx0+KEc6npE1LpUUJhqoZJdiPuChKhLgPRuheaRaFiSpVhHpdhF6B5bhMUMYLUXIfha0K1YRHBNRMRexwsFdaRJzaLWLVRK6dRFbJUdbTbPbephplzPJyp77RUP7CxKxIhW8weiRiCTgaRjeqoJhwhFkEJcQJAUAAIRQVnIQLNBAVwVwIAA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { Tick } from 'viem/tempo' import { config } from './config' const { orderId, receipt } = await Actions.dex.placeSync(config, { amount: parseUnits('100', 6), tick: Tick.fromPrice('0.99'), token: '0x20c0000000000000000000000000000000000001', type: 'buy', }) console.log('Order ID:', orderId) // @log: Order ID: 123n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `dex.place` action and wait for inclusion manually: ```ts import { Actions } from 'wagmi/tempo' import { Actions as viem_Actions } from 'viem/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' import { parseUnits } from 'viem' import { Tick } from 'viem/tempo' const hash = await Actions.dex.place(config, { amount: parseUnits('100', 6), tick: Tick.fromPrice('0.99'), token: '0x20c0000000000000000000000000000000000001', type: 'buy', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args: { orderId } } = viem_Actions.dex.place.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** ID of the placed order */ orderId: bigint /** Address of the order maker */ maker: Address /** Address of the base token */ token: Address /** Amount of tokens in the order */ amount: bigint /** Whether this is a buy order */ isBid: boolean /** Price tick for the order */ tick: number /** Transaction receipt */ receipt: TransactionReceipt } ``` ## Parameters ### amount - **Type:** `bigint` Amount of tokens to place in the order. ### tick - **Type:** `number` Price tick for the order. Use `Tick.fromPrice()` to convert from a price string. ### token - **Type:** `Address` Address of the base token. ### type - **Type:** `OrderType` Order type - `'buy'` to buy the token, `'sell'` to sell it. ## Viem - [`dex.place`](https://viem.sh/tempo/actions/dex.place) ================================================ FILE: site/tempo/actions/dex.placeFlip.md ================================================ # `dex.placeFlip` Places a flip order that automatically flips to the opposite side when filled. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"e9b109959543a4af97fa80fd74ff57c367fad28063d8fae2ea79374624391edb","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScAGYArmD8gmCcWJJwMACqYIxocEFEobEwiJxipBZKFJywvCyhcCVgscwARmQRJS2MShZoADrZrOxcqaTpWTmmUBC8CAYAsrFyAljm8JzipWjlypykMFj76WASxskQ0RucTa1knC0YVz0kyXRsliecF/fhMJwAjNZOEFAW8hIo0BEAHQDAYAWk4ABEZg1OPg0GgsA0APTYoiMGDMKFwfDY6azbGxATmATwbGjcbZXKUajiJRzZDIEB0cSsBQslhsDicYApNKZJlwTiuGKkCDMTgAcnxhMVsLADIlkyCioALAAmayKqrSCIDXGcA3Wa0221gEAAXQdom0+l1mjMihUakQgK0kl0gU1E2Z8gsVn+dgcpCcNHIiGk7k8ODwhBI5H89CYQ2FAB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i8Yw5u5xADNO565mR25+FEoB5tymEySzJdUecpcgGNpjp/802bp/k3p0B4UgZo8oZk8tAKU888ZskiFm8uZzp02RZ1FlZj8mypuIufFpIPuVkV3LkcCliFkIgXxazXRG/S7CKaQDFXdV8NggY3BkncKMnZHfgkg75RibCMgaCWCJFFA3Uf4DBitHyfKPAUVqCKAHlrgklPq5tQNFkKGvAblllg0QiFgmwFdEAdZI2aQyCREEoXUbde0Z7U8Xlgh1wKZWcWAbMB5UUBaYQfTABB+Mk9jD+NdKNFNVOAPABZ1QNj19df3WNJUZ1YPNgSNnTR5boH1uNKEeB65JNS5UUJV6CKoPSIWTeERMRLgL1qRZaVZeRDaRRQpFRL6fFDRMUMYLUXIHRa0DNAxIJDmLmXtaNuvXPTzArexQJUhPtxPQd8LLbUd4JRGMJKAmAxApd5d60BxbthOBJJUWg1JdJPhPow5s1pVjcq1jNPNqAXhFkRpcQJAUAAIRQWwoQPAZkVwVwIAA=="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { Tick } from 'viem/tempo' import { config } from './config' const { orderId, receipt } = await Actions.dex.placeFlipSync(config, { amount: parseUnits('100', 6), flipTick: Tick.fromPrice('1.01'), tick: Tick.fromPrice('0.99'), token: '0x20c0000000000000000000000000000000000001', type: 'buy', }) console.log('Flip order ID:', orderId) // @log: Flip order ID: 456n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `dex.placeFlip` action and wait for inclusion manually: ```ts import { Actions } from 'wagmi/tempo' import { Actions as viem_Actions } from 'viem/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' import { parseUnits } from 'viem' import { Tick } from 'viem/tempo' const hash = await Actions.dex.placeFlip(config, { amount: parseUnits('100', 6), flipTick: Tick.fromPrice('1.01'), tick: Tick.fromPrice('0.99'), token: '0x20c0000000000000000000000000000000000001', type: 'buy', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args: { orderId } } = viem_Actions.dex.placeFlip.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** ID of the placed flip order */ orderId: bigint /** Address of the order maker */ maker: Address /** Address of the base token */ token: Address /** Amount of tokens in the order */ amount: bigint /** Whether this is a buy order */ isBid: boolean /** Price tick for the order */ tick: number /** Target tick to flip to when order is filled */ flipTick: number /** Transaction receipt */ receipt: TransactionReceipt } ``` ## Parameters ### amount - **Type:** `bigint` Amount of tokens to place in the order. ### flipTick - **Type:** `number` Target tick to flip to when order is filled. Must be greater than `tick` for buy orders, less than `tick` for sell orders. ### tick - **Type:** `number` Price tick for the order. Use `Tick.fromPrice()` to convert from a price string. ### token - **Type:** `Address` Address of the base token. ### type - **Type:** `'buy' | 'sell'` Order type - `'buy'` to buy the token, `'sell'` to sell it. ## Viem - [`dex.placeFlip`](https://viem.sh/tempo/actions/dex.placeFlip) ================================================ FILE: site/tempo/actions/dex.sell.md ================================================ # `dex.sell` Sells a specific amount of tokens on the Stablecoin DEX orderbook. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"997af5c0532953dd4e2e196ac8b932f9108ab9fe48dbcca2fc81f6d18ce19b1e","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScAGYArmD8gmCcWJJwMACqYIxocEFEobEwiJxipBZKFJywvCyhcCVgscwARmQRJS2MShZoADrZrOxcqaTpWTmmUBC8CAYAsrFyAljm8JzipWjlypykMFj76WASxskQ0RucTa1knC0YVz0kyXRsliecF/fhMJwAjNZOEFAW8hIo0BEAHQDAYAWk4ABEZg1OPg0GgsA0APTYoiMGD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wOiCCDIniyPKWRb3STAHUBOw73HFiEexCtn1kP2RCrIje16GiChDImH2+3ziCH5wkqShRI2BN1MvkvSBBi8tJgaLkChA3xugy0Ct9Rbzb1WnR2DW7zQBxz73x1e3KvSt+3KqqrQD6rhADEiA9XJPJhv0LmEGEVmgeP/DFI9If0VALFmhKEQI/yqCWvdWtLELzIbGWs4EAl414vIOiwWo2oPBXjOonO2pRJKDOpKAOtUK20VQpILjLwry6r6pqsRzqtxAavCrO2aoZh71fI6pDQqtJx+16vYE3wGqGsX2elXz+HX2huaSEGxlZBjXxkPx3BZCIGsBPhPmtF/OfUUl7FpUXUUmXTwFiwgs7CCWRTYV3XRTAxEluJwQ/CPEwUuhqjKj6lmDwEqk+kulKg/HRrLVYQXXfVAipoMHZpgjMAbUgoA20hYQolgoMUxUPW7XMSiHeiqiSAAAlwh8AShSZ95QTzjXB352L+aDAjaSR7VUzTMuazhZ1dIl4gLIVSEa0V0XbDbjbaaoKdF/hXB8ECxYAmAk1RRQptYOYFQ0DDZXs/Y1Yo7BV7lY7dZ4701CkaZJFuhU146oRPybY3lbjRQ5auAZQy4K4uAY7wo6BIp64EhG4bZm4w4fEO4u40754+5rQV414R4LACUp4Z5u7e5F5l5B5h4N5+011d5r1eB70l6J1/gn5ipv1R6b5R1l6d7bR9Qn4X4Gz5rTTFRBasELCSREAV4K6oQ9ahazh7b8A2KQBYFxAkBQAAgVokgv0EBXBXAgA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { config } from './config' const { receipt } = await Actions.dex.sellSync(config, { amountIn: parseUnits('100', 6), minAmountOut: parseUnits('95', 6), tokenIn: '0x20c0000000000000000000000000000000000001', tokenOut: '0x20c0000000000000000000000000000000000002', }) console.log('Transaction hash:', receipt.transactionHash) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `dex.sell` action and wait for inclusion manually: ```ts import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' import { parseUnits } from 'viem' const hash = await Actions.dex.sell(config, { amountIn: parseUnits('100', 6), minAmountOut: parseUnits('95', 6), tokenIn: '0x20c0000000000000000000000000000000000001', tokenOut: '0x20c0000000000000000000000000000000000002', }) const receipt = await waitForTransactionReceipt(config, { hash }) ``` ## Return Type ```ts type ReturnType = { /** Transaction receipt */ receipt: TransactionReceipt } ``` ## Parameters ### amountIn - **Type:** `bigint` Amount of tokenIn to sell. ### minAmountOut - **Type:** `bigint` Minimum amount of tokenOut to receive. ### tokenIn - **Type:** `Address` Address of the token to sell. ### tokenOut - **Type:** `Address` Address of the token to receive. ## Viem - [`dex.sell`](https://viem.sh/tempo/actions/dex.sell) ================================================ FILE: site/tempo/actions/dex.watchFlipOrderPlaced.md ================================================ # `dex.watchFlipOrderPlaced` Watches for flip order placed events on the Stablecoin DEX. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"546bd06c6d922c9812fee931dd4652721a211f4c197b95a0862ff50f70b8b057","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinACuYADu4mj2qQDqW/YZYGhD/ACiJMcASnorpGAAKl6l5VKI6rK1yqoaLTp6eDWm22ankFisAGYBo5nKNGhNqM8DDM/NQAkxWOwuEZBMIXtp9AAOT4Kb4NGraNp4HEmLrgpBQkD2GEjPrwjyIqbI3xzNELAz5LGcWC0fEVGQ1Un1B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VmVgAPypD3IYDhiJiBFxZPShAnSvq+FgAYDIAmRVicBuzuQ7YADUvQ64swFUvWuhVAHK3sh+dSr0X4hmFKUa0yoW3Q/ynAAAsmYgIB+OVjoEAk2MeCGg8gOJGOMp6OGJMtMueLkEkCWFwBGpiuEFOirCwJINkp4boCcpkjer1lAFMriDxoMTMQsp9GIFMtDkIIoqECsIuH4nLsonigSupgkEEBCBEOBnqmIRPGAOoCyrBt0CsEKjccRmVgoTcRCKDkPAkImBCE6lhnIOdkEMDK0A0d0rHDRjem0ZGkcdDnIImBRgxpsiIXqpBkajBmytkRajymgEhjaihvanCf8dhnCYiVsGSbiUNNlkxmAMJnAA3kUFfNFCgiXtoRJjEFfKkOZgpuGByccJQTPg7oyccKkFYXVr5mfuruyZfCKQNMKcqtPrkakHydfJwGKQZhKUZrSSHvAR+gOPikSRScibqrBGidBudKaliQhlashnanhESc6jKqSfRuSS6ZSaVORiuNRgOBYBSbiHeC0FwSgC+JHv2KUEQNYImL0FGdYNYHoWzOKBzOoJKCYaLLwngPwmCEqFYZXLjKMJzKQtMOQk4U3PtMWG3KVHZGPBuGQL3DfIPMcGAhPFPHvAvEvCcEfCfGPNvIoK2QfB2avOvGPN2DKaqbfPfGPM/K/P3O/AoPcmAgIH/AAkAiAmAgkHaJAkuTAiufAkFGwvDgjFKJgmYXgLglmVYDmQQjYZqCgoWdyBInyOYYgUCDWMVC7HEe7BOAmW8FzMYbnO8CeQYC+SCGXL0AjFeeqCQuDDELABiMzNxLFMIJRIDIJMJHhHpBAOxPGnVGistHxAJGhImFoVkJJAgcsMBUsgpDxPFLQIlAwkbAVHmBlAzFlBZEXCOIxeOCVI+BbFVB3JvB3uJqPqhPrHKVSSNP5ONPASpg7GBKQAli9HBGmEfLkBRfgL5KUAdOIEgKAAEIoHYkIHgEeCAK4K4EAA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.dex.watchFlipOrderPlaced(config, { onFlipOrderPlaced(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = () => void ``` Returns a function to unsubscribe from the event. ## Parameters ### onFlipOrderPlaced - **Type:** `function` ```ts declare function onFlipOrderPlaced(args: Args, log: Log): void type Args = { /** ID of the placed order */ orderId: bigint /** Address that placed the order */ maker: Address /** Address of the base token */ token: Address /** Amount of tokens in the order */ amount: bigint /** Whether this is a buy order */ isBid: boolean /** Price tick for the order */ tick: number /** Target tick to flip to when filled */ flipTick: number } ``` Callback to invoke when a flip order is placed. ### args (optional) - **Type:** `object` ```ts type Args = { /** Filter by order ID */ orderId?: bigint | bigint[] | null /** Filter by maker address */ maker?: Address | Address[] | null /** Filter by token address */ token?: Address | Address[] | null } ``` Filter parameters for the event subscription. ### maker (optional) - **Type:** `Address` Address of the maker to filter events. ### token (optional) - **Type:** `Address` Address of the token to filter events. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `(error: Error) => void` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Whether to use polling. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`dex.watchFlipOrderPlaced`](https://viem.sh/tempo/actions/dex.watchFlipOrderPlaced) ================================================ FILE: site/tempo/actions/dex.watchOrderCancelled.md ================================================ # `dex.watchOrderCancelled` Watches for order cancelled events on the Stablecoin DEX. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"1aec0eda0f46341180a0b333aee616ad8d50c79358e60da62345f78224a573d1","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvog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UxKFcgKz7BPJSgtpxAkBQAAhFBCEhA8BdwQBXBXAgA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.dex.watchOrderCancelled(config, { onOrderCancelled(args, log) { console.log('Order cancelled:', args.orderId) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = () => void ``` Returns a function to unsubscribe from the event. ## Parameters ### onOrderCancelled - **Type:** `function` ```ts declare function onOrderCancelled(args: Args, log: Log): void type Args = { /** ID of the cancelled order */ orderId: bigint } ``` Callback to invoke when an order is cancelled. ### args (optional) - **Type:** `object` ```ts type Args = { /** Order ID to filter events */ orderId?: bigint | bigint[] | null } ``` Filter options for the event. ### orderId (optional) - **Type:** `bigint` Order ID to filter events. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `function` ```ts declare function onError(error: Error): void ``` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Enable polling mode. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`dex.watchOrderCancelled`](https://viem.sh/tempo/actions/dex.watchOrderCancelled) ================================================ FILE: site/tempo/actions/dex.watchOrderFilled.md ================================================ # `dex.watchOrderFilled` Watches for order filled events on the Stablecoin DEX. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"31f40edcd3e0cb0dd5299ece3d0406a3ef9a70aba1beaad5bca49c399a7dd538","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQ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DiknJzGvOqNqNvEjNnPvILBKtAFEB7k4kJiJgAPypBewYDBixgkHUZHShArRxoEFgAYDICaSlicBGw2TeYADUvQc4sw2UumgBVASy5s8+yS94v6QyxKpiRG3QmSnAAAsn/AILeKJjoCsOGKohEluASqGL0hmMGMYqYjuLkEkPmFwDEs0uEFSsLCwJIKwjgboH4kwqGrplACYriGusYXYVYpdGICYlVkIOfKECsFOOAohAYqah0l0rxgkEEBCBEAWp8lfpOmAOoHMmWt0CsDsvET2iJi/vERCCVohgkLGBCLCs2nIKFkEM9K0EobWFKqOqGhoUSqEVVnILGIOpOmgM4hfp8kWr8qWgsnwcCmsmgNWuCrWlCo0UUS2o0S0VsFMYMU1BxjOtvo+OzldjEGsFwKJJzKLv/keqsccKkCBlesGLsWgLPjxvnqkMcakHAcksIbho4mblBJcf7scacfPhcTcnsZwNcbJgMjhosfePwomt2J0mMTMe0R8kBF0SWutACn0ZWqCjWpCshGMXCmcpMROtMRibMRlAOoJmRGOjMdOrvueAfhYF2KUEQNYLGL0NSdYNYEASHNXI0CSDTA0IvP8MvDlLAfAXDL0FvJMLvAaKgXnPNHmEXBlCPDaGPEHBXKYCAX0ISBqNTGSEgI3EvHgC3GCEqHAazCyHDBqNzEgbzHvHyNAdjL5EmGlAbIwcbFAFPBvBqOAayb8EDByYCH5CCEnL0BHO3OvDYK4O9DELABiMTAxEFMIHhI9GxBxMhMpBADRK+PRA0sNMxKxNBLGH/lkHxBzuaUCP5KJIxCFLQGFKPAnK6DFATHFLpPHJFHVOlGeGrLlIVLpLJJ9kenLP7nMS1C5O1GAEZjrN+KQLRidMBEmPArkHmSCE5KUAtOIEgKAAEIoOAkIHgOuCAK4K4EAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.dex.watchOrderFilled(config, { onOrderFilled(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = () => void ``` Returns a function to unsubscribe from the event. ## Parameters ### onOrderFilled - **Type:** `function` ```ts declare function onOrderFilled(args: Args, log: Log): void type Args = { /** ID of the filled order */ orderId: bigint /** Address that placed the order */ maker: Address /** Amount of tokens filled */ amountFilled: bigint /** Whether the order was partially filled */ partialFill: boolean } ``` Callback to invoke when an order is filled. ### maker (optional) - **Type:** `Address` Address of the maker to filter events. ### orderId (optional) - **Type:** `bigint` Order ID to filter events. ### taker (optional) - **Type:** `Address` Address of the taker to filter events. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `function` ```ts declare function onError(error: Error): void ``` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Whether to use polling. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`dex.watchOrderFilled`](https://viem.sh/tempo/actions/dex.watchOrderFilled) ================================================ FILE: site/tempo/actions/dex.watchOrderPlaced.md ================================================ # `dex.watchOrderPlaced` Watches for order placed events on the Stablecoin DEX. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"2279834665a0cfd3fb844984d371abd87f4fb79413544bf125a15d46b41d1004","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinACuYADu4mj2qQDqW/YZYGhD/ACiJMcASnorpGAAKl6l5VKI6rK1yqoaLTp6eDWm22ankFisAGYBo5nKNGhNqM8DDM/NQAkxWOwuEZBMIXtp9AAOT4Kb4NGraNp4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hYAGAyAWkxYnAJstkcsAA1L0LOLMDlPlrwVQDipbP3kkmdA+MJjCravUuZt0McpwAALISICB3iRY6APzVibgWrbhWqhjVKujBi1L1K7i5BJC5hcBrK/LhAuoiwsCSD+IaG6ATK+Jzr5ZQB1K4h4b5FVEtJXRiB1JXZCDMKhArCTiKJITGKmLcqcYJBBAQgRCXpCpkFtxgDqAYr3rdArBkpTGgYRYMFTEQgnYNwJCxgQhqo/pyCjZBAvStBxH5LexwZzopE2pAoPhXZyCxhQZIa9IkFCrXpip3pYqeEyoEpoAvoKpvrKq3G7G/q3EPFbCgk/HNS+YoZgCkZwBx5FAbyBRcxB7cFUYxAbypCSZMbBjonHAQFV5y4InHCpBSEJb6Yj5s5onrzEmNREnsqV7eGpC4mbycCklCbkkiYwlG635bqdjAqAnglPGCrASvG3obSSqfFPpyqvpKooSAnqoMogmIZgnKkQmZSQYziwadgWDgm4ihzAxYEoBXjm4dilBEDWCxi9CWnWDWB8FhzvyNAki0wNC4L/D4K5SSHSHwy9BkKTCUIGiKEFwLQ5glyZRlzjyzhVw1zby7wtxtwdwzx9wDwnALxLwtyTyKCJlzwpnDyjwtwtjUkskxnHCXwBxwBHzRmnwKA+ylkCA3x3wPxPwvxoJ9CEgag0xkhIC/x4J4AAJghKhSFswsjwwag8xyF8xUJ8jiH35AiljpRGw2GmwDj2n6CkLCHOm/DAxumAj+Qggpy9BRzALEI2CuAfQxCwAYgkyMTBTCD4RPTsScQoQqQQC0RvgMRfIjQsRsQwSxhcFZD8R37LCzkgiBRMShS0DhSILKypSxSEzxR6SJxRTpjyyH6VRRDFRySUnF7QSly0mQmtSuQdS35sZ6w/ikBOanQgRJgLy5DAX2DOSlCLTiBICgABCKCKJCB4AbggCuCuBAA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.dex.watchOrderPlaced(config, { onOrderPlaced(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = () => void ``` Returns a function to unsubscribe from the event. ## Parameters ### onOrderPlaced - **Type:** `function` ```ts declare function onOrderPlaced(args: Args, log: Log): void type Args = { /** ID of the placed order */ orderId: bigint /** Address that placed the order */ maker: Address /** Address of the base token */ token: Address /** Amount of tokens in the order */ amount: bigint /** Whether this is a buy order */ isBid: boolean /** Price tick for the order */ tick: number } ``` Callback to invoke when an order is placed. ### args (optional) - **Type:** `object` ```ts type Args = { /** Filter by order ID */ orderId?: bigint | bigint[] | null /** Filter by maker address */ maker?: Address | Address[] | null /** Filter by token address */ token?: Address | Address[] | null } ``` Filter parameters for the watch subscription. ### maker (optional) - **Type:** `Address` Address of the maker to filter events. ### token (optional) - **Type:** `Address` Address of the token to filter events. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `(error: Error) => void` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Enable polling mode. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`dex.watchOrderPlaced`](https://viem.sh/tempo/actions/dex.watchOrderPlaced) ================================================ FILE: site/tempo/actions/dex.withdraw.md ================================================ # `dex.withdraw` Withdraws tokens from the Stablecoin DEX to your wallet. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"023ba6e6ceee483261ba554408e01773012c9493ad2b5216c866b9cc71fec07f","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScAGYArmD8gmCcWJJwMACqYIxocEFEobEwiJxipBZKFJywvCyhcCVgscwARmQRJS2MShZoADrZrOxcqaTpWTmmUBC8CA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ueSLNdhSTeQshcfebRo+XRcDC+W+QDr7sTMjE+UkPTKyFsszIjjuCyEQNYPvPvNaAyd8mSr2B6JSiBEpDSngL2jyUyjpHQsmD4uyqKQYHgVBLVEeNnHDM1LVNkveA1LDPbJAtXqSpONIBSsBDRBybIrZR+MZexJCjpBRKysKcwqZMEEimQCimAo1EkAABLhD4AlCcxbxsEYHKCuAwkgCyoGBpUkjVIHSvTQzJVCDeXz62K6UArUp0S0oOX2wlVqAMoJgmU0KySuAoIFiwBMCHK2yRRSgyj6wKji7GxkaJzWxDWiiZJnJjVOyXLpICyCLdDnITVQg0n+xXJ4GijBX7jSydygxcAjUDy0BDzxQkLJTjz+yTyZzOKmLHKMjaiKgLwPK9i1yZx0obzYrWC8CEpA3A02j/CHxgCuBNya4jopFuUQIOAkiIAPKHWfiVXuVnBtXWkgDfziBICgABBLRJB4DMiuCuBAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { config } from './config' const { receipt } = await Actions.dex.withdrawSync(config, { amount: parseUnits('100', 6), token: '0x20c0000000000000000000000000000000000001', }) console.log('Transaction hash:', receipt.transactionHash) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `dex.withdraw` action and wait for inclusion manually: ```ts import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' import { parseUnits } from 'viem' const hash = await Actions.dex.withdraw(config, { amount: parseUnits('100', 6), token: '0x20c0000000000000000000000000000000000001', }) const receipt = await waitForTransactionReceipt(config, { hash }) ``` ## Return Type ```ts type ReturnType = { /** Transaction receipt */ receipt: TransactionReceipt } ``` ## Parameters ### amount - **Type:** `bigint` Amount of tokens to withdraw. ### token - **Type:** `Address` Address of the token to withdraw. ## Viem - [`dex.withdraw`](https://viem.sh/tempo/actions/dex.withdraw) ================================================ FILE: site/tempo/actions/faucet.fund.md ================================================ # `faucet.fund` Funds an account with an initial amount of tokens on Tempo's testnet. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"2a334c0a8b0b464e60d225d6b8c383a129c837283be2bd8d4d6de2830fe35d4e","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinA5w+PCpCQCuYFAAdABKelukYABqoVu4otr66rK1yqpIzdStetPh66bdVgDMA0czlGjQm1C8018c2oASYrHYXCMgmEpXKUjGlXkdWeiBq2jaeCRJi6Fn+gKGwKQACZemDMFMDDM/DCFgZ8gjOAlxFteB8bhU+tYqVing1XviPgYuTy+WZSUgASB7ECRtTxh5wQyfLNSjRWSBtmB+MjOTsoAAeDKJZIAPiCHWSqStWQonCwjmYejIcFSwFynAD0QcFgAklAAPypMBbZgAIzInAAPpwzTAkpYoABuf2BpwxHZoVJ8fNgLjJ7hQKCkeBwbNgVwRVIABVIEGYjDgMHNROEe2lvLQfbNh2OpwuciuNtyYHEnrg7t5pt2pSgEF4CAMADEzXBOOIwHveCWuAB3RiqPcHiznxihPfMCAFzgQBKcTtcNAQADWiiCkVyQicAAKjA8IAOS7jQYiWIOuriEoG7IMgIB0LOWAKKUAAG2FoHAuTsoUwDRNW4g0M6ySuvgaBoFgnCuJyrbMJwYEAAInvB7YAPQxNWYH4fChGcDQ8J0QxbbMWxHGMNx7AwNxwbCHxeQCVwRE9ru9EJIxEnsUoXE8XJwlsEpuRLHExRKJwAC8xEwKRMDkUoQR+geQbiBYPqcMgR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PJP3B+kFMKnhJ9A7WpNi1KEgXECQFAACEUEOyEHRIQFcFcCAA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const hashes = await Actions.faucet.fund(config, { account: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef', }) console.log('Transaction hashes:', hashes) // @log: Transaction hashes: ['0x...', '0x...'] ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Synchronous Usage Use `fundSync` to wait for the transactions to be included on a block before returning: ```ts twoslash // @twoslash-cache: {"v":1,"hash":"4cb3e4d43afd1edf434898c4fbf7dd960d22cef1a4ff558f529b06bca056f27f","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogvCZcpDC8MIxYaHCInABmAK5gUADKGGC8AHQASnqJpGAAauJyibii2voALACs8ooqaogAHFqSuoFhEVExlGYWVgBMdg6kTjTkiABs7p44eIQk5P70TKzsXEaCwv1ikvrTI2aNqhrtOnp42yb95pZIx/aOzlNDAMxz1F6LvivUAXWbA4CXEiQiDEqBw0thOyjOMwunTw8TBELug0eoxekyQ7wAjF9MAsDEs/AC1gYkpljGAEsk0hleAAeADCQnijCUAD4ABTBMCcpRxdmCrkUThYRzMPRkWKcYAAHTpnFVzwsAEkoAB+OJgRLMABGZE4AB9OAyYJzLFAANzK1WqpzBZJoOJ8F1gLjm7hQKBhOBwe0q1UCGUQRJoXWcfVGk3my3WmBQM0WlJWwZ25WuACUcQACqQIMxGHAYMybsIsqjwXpqwz0plcvlCiUyjBucqwOIZXApRF6SlG7x+lAILwEAYAGIMuCccR050Rr2cADujFU87pFg3jFK8+Yy64EHinDLXDQEAA1opeXAc8qhJwACowDYAcjnNDEljQWU4eRoAU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hFY2ODbwRBxm0EDhAB+OQgePDkHyGFqDeLWP6FazwHuLOKQHxGkEhNOGaFhGozwDyB6GQlCiolLxfWEQNGNCV04HxA+DAFXzX3Yj6hPlwVpPpLIDiGZPeFZM4DX3/FcGil7xxieIjiQGsDFLsDESBH0iokrBMgUm4g7RUmsnCkcgiOEFCFql+IanECai2CMhMGrDRDrH+OHB6jFCUD6nimDi9DiHfFGjWnmkWnWndOWgWlmg9L9I2i2gqnyJRwTXfHJLqliBpwRJiAqn6FenECQFAACEUF2yEDwD6FcFcCAA=="} import type { Config } from 'wagmi' export const config = {} as Config // ---cut--- import { Actions } from 'wagmi/tempo' const receipts = await Actions.faucet.fundSync(config, { account: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef', }) console.log('Receipts:', receipts) // @log: Receipts: [{ blockNumber: 123n, ... }, { blockNumber: 123n, ... }] ``` ## Return Type ### fund ```ts type ReturnType = readonly Hash[] ``` Returns an array of transaction hashes for the funding transactions. ### fundSync ```ts type ReturnType = readonly TransactionReceipt[] ``` Returns an array of transaction receipts after the transactions are confirmed. ## Parameters ### account - **Type:** `Account | Address` Account to fund with testnet tokens. ### timeout (fundSync only) - **Type:** `number` - **Default:** `10000` Timeout in milliseconds to wait for transaction confirmation. ## Viem - [`faucet.fund`](https://viem.sh/tempo/actions/faucet.fund) ================================================ FILE: site/tempo/actions/fee.getUserToken.md ================================================ # `fee.getUserToken` Gets the user's default fee token preference. [Learn more about fees](https://docs.tempo.xyz/protocol/fees) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"5479b50dafab06e9b134224ed428649f20a0a0eb27d506ae6e901fff4d3d8fab","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJw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CvC1KLAgyVIawTSVwcoj4Nc7UGwVwWaGIWADED6IibyYQBCMiJCSrVCECcSCAPCK8QiOVCqUiciacM4dIrIBiG05YF8rgdidycQTyHgZinqGMLacsEKZ6KWSyNxSM2KWgdQSoNkKACENKNIXgRoRoCESoNIdKAnaQNkNKcQCEJ+InSoSoAAIV4GkBgHUDSmkDSgSGsCfhsyfifiylYRyhDIxTaOnFgvO0dCjIDGkpylKFanECQFAACEUA9iEDwHPBAFcFcCAA=="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const result = await Actions.fee.getUserToken(config, { account: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', }) console.log('Fee token:', result) // @log: Fee token: { address: '0x20c0000000000000000000000000000000000000', id: 0n } ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = { /** Address of the fee token */ address: Address /** ID of the fee token */ id: bigint } | null ``` Returns `null` if the user has not set a default fee token. ## Parameters ### account - **Type:** `Address` Account address. ## Viem - [`fee.getUserToken`](https://viem.sh/tempo/actions/fee.getUserToken) ================================================ FILE: site/tempo/actions/fee.setUserToken.md ================================================ # `fee.setUserToken` Sets the user's default fee token preference. [Learn more about fees](https://docs.tempo.xyz/protocol/fees) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"f0b0a406d4ab0b85a6a931aef7b66a18557d4e63a6f5cf4303ff3b1ade02ff54","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk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tNg7t0ApJwAALInSbDnytC6ghjYZfLzg/JBg8IWIBj/ICLvi5BJC5hcCNhxLhC8qJwsCSCIK/6EY6IGrYRQBQAkSQFvKiGcTiHHQMRiAkQxZCDjyhC6jHyvwLYfzJKpJB4JBBB/AKLj6rKT4lpgDqCVI6D1IWC6gdKOGZp/7BqOF/AxqzoJBRh/AXIJpyBmZBBgrMGsGkQKrYSLZcEmiWLmExZyAxjsAlpoBaJ2F2Q+qbLbKuFBohq9ThrHJRo9KpGhGJqpHFr4S1FhqtCRD3Ltp6QY5TYxD6inScAgzk7bo9p9odH8ypBHpjoBiDFTKy616pDjGpD1x2KkGfqqLi4zEQxFCdHV5y5zozHdFA4LFd7g6o6pjcicApKVH1HZErK5GT75EBqFF7INIlFb4nLRqVGXLDI1EZF1GfENE6BWwiS4KFqJDfFlo96qTqSnxRKlBEDWBRi9CwnAxH5uzXB/T1y1yigNyBByJ341AKhhwgjP7qiv4sjtCHQczLiPKsyNabicwVzuxjY1zSy+xX64iBBkkXA/Caw4mDB4kkh/AEnGzMhxx4AJxJxkCYBpyUlHAAAS4Q+AE4HYXYNEM4sM+BS8eAMpcAAiEACQlEiEo0BwbMtJyJfwXsaJfQqJ1+gQ+pa4bMGpagHJVgXJFI4clQvQ/JEgSgpQM2eAWJSJ+gVIYM3sIoSANcQpBgewY0NpjWPGmpqQbYvQVIfwlQIMjQ6gNw0g1g4gDEvAf4CZSZKZaZGZWZOZwkeZyZqZ6ZmZ2ZuZiZ5ZhZVZJZCQd+GIuJHcT+osMQsAcIzsGUbMWUEULk56MUPSXUEAKURk6ULsyQ4UOUkUX4UYe+dspUmOywJkbJXAjkZ0F0iIfZt0CkysF4asBor0ds70I0YE30OcvAJcN5t5hcvQEMO0ZmixMi4uEZBp0ZDgsZqx65UY1pOEdpZmpQxM4gSAoAAQigp8QgeApEIArgrgQAA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { receipt } = await Actions.fee.setUserTokenSync(config, { token: '0x20c0000000000000000000000000000000000001', }) console.log('Transaction hash:', receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `fee.setUserToken` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.fee.setUserToken(config, { token: '0x20c0000000000000000000000000000000000001', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args } = viem_Actions.fee.setUserToken.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Address of the user */ user: Address /** Address of the token set */ token: Address /** Transaction receipt */ receipt: TransactionReceipt } ``` ## Parameters ### token - **Type:** `Address | bigint` Address or ID of the TIP-20 token to use for fees. ## Viem - [`fee.setUserToken`](https://viem.sh/tempo/actions/fee.setUserToken) ================================================ FILE: site/tempo/actions/fee.watchSetUserToken.md ================================================ # `fee.watchSetUserToken` Watches for user token set events on the Fee Manager. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"466d1d7e9b6e662521a4dfa3841e61d192d4a41ddd5d17120f2190e4200b7515","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinACuYADu4mj2qUFRALwAfJxEEIxQpeVSiOqytcqqGi06enhrm9t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A1L0AuLMPFA5ggTrEAngInqohoteFRlAkyvgDdvnt0OUpuHAgIJeBmjoCsAGEYtEOkvSn6PYtkj6KoZyrkEkBmFwFkvwj4i6pzCwJIEIrQboNEk4WPg5lAE4kiFeo4d4h4rtAIHNGtO/KECsP2GgrBOQkamMhMqBgkEEL8BEE2mCp/jumAOoDsh2t0CsFcjkfOspocjkb8J1jJgkGGL8FimOnIGVEEC6q0IYZdDqhupmuYRaDkhouMv1nIBGNulsIEu/mCi2lCu2nsgct2vAL2pAQOuigMfUeOgMSuqQDumgOsZsW1KVISvereI+j0o5DEGsFwAJNvOrtnq+mBKcbOKkGhn+j6HcWgNvt7qTkUGcakHgWbFRjRhlDcS8UVM8V8rOG8fIakECZwD8XBnpuntVNIqWnpNeMsdsSMRkWMX+BMW2pNLCjMccnMX2iiosfBMsdii8mscMVsVSbsaLMuoOOutWBYGiWtG7EfLfigKeLzlWKUEQNYGGL0AKdYNYIge7CgeoN7D3IfP3CfAlLgfgSDL0PKDfFDKQWzHgEnONCnN4qLOnDpJnNnBYnXEXDUo3M3FXKOM2LXAXCaSXE3BXDZFvCgWiBHBgcPFgQYIPP9FYHgZHJSHTPKNvCqWqEyOqQYL9u8L2PmPxIWIIU6QqPKOgVKTcB6SAJGZ8GfA9AqXTNYK4DdDELALCFjDRO5MIFhCdExCxPBPJBABRGyslH0q1PRIxOBGGLAVkFxMccjE5NGK5LRJ5OUkrHGALM2IFKjMFCpEHGvJFHoCLEePLIlMlFXH4jcWnDHqVCpNZK3GVIFqrO+KQDxqOP+NGI3LkOmfYHsKUENOIEgKAAEIoGgkIHgHOCAK4K4EAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.fee.watchSetUserToken(config, { onUserTokenSet(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `() => void` Returns a function to unsubscribe from the event. ## Parameters ### onUserTokenSet - **Type:** `function` ```ts declare function onUserTokenSet(args: Args, log: Log): void type Args = { /** Address of the user */ user: Address /** Address of the new fee token */ token: Address } ``` Callback to invoke when a user token is set. ### args (optional) - **Type:** `object` ```ts type Args = { /** Address of the user to filter by */ user?: Address | Address[] | null /** Address of the token to filter by */ token?: Address | Address[] | null } ``` Optional filters for the event. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `function` ```ts declare function onError(error: Error): void ``` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Enable polling mode. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`fee.watchSetUserToken`](https://viem.sh/tempo/actions/fee.watchSetUserToken) ================================================ FILE: site/tempo/actions/index.md ================================================ # Overview | Action | Description | |--------|-------------| | **AMM Actions** | | | [`amm.burn`](/tempo/actions/amm.burn) | Burns liquidity tokens and receives the underlying token pair | | [`amm.getLiquidityBalance`](/tempo/actions/amm.getLiquidityBalance) | Gets the liquidity balance for an address in a specific pool | | [`amm.getPool`](/tempo/actions/amm.getPool) | Gets the reserves for a liquidity pool | | [`amm.mint`](/tempo/actions/amm.mint) | Mints liquidity tokens by providing a token pair | | [`amm.rebalanceSwap`](/tempo/actions/amm.rebalanceSwap) | Performs a rebalance swap between user and validator tokens | | [`amm.watchBurn`](/tempo/actions/amm.watchBurn) | Watches for liquidity burn events | | [`amm.watchMint`](/tempo/actions/amm.watchMint) | Watches for liquidity mint events | | [`amm.watchRebalanceSwap`](/tempo/actions/amm.watchRebalanceSwap) | Watches for rebalance swap events | | **Faucet Actions** | | | [`faucet.fund`](/tempo/actions/faucet.fund) | Funds an account with testnet tokens | | **Fee Actions** | | | [`fee.getUserToken`](/tempo/actions/fee.getUserToken) | Gets the user's default fee token preference | | [`fee.setUserToken`](/tempo/actions/fee.setUserToken) | Sets the user's default fee token preference | | [`fee.watchSetUserToken`](/tempo/actions/fee.watchSetUserToken) | Watches for user token set events | | **Nonce Actions** | | | [`nonce.getNonce`](/tempo/actions/nonce.getNonce) | Gets the nonce for an account and nonce key | | [`nonce.watchNonceIncremented`](/tempo/actions/nonce.watchNonceIncremented) | Watches for nonce incremented events | | **Policy Actions** | | | [`policy.create`](#TODO) | Creates a new transfer policy for token access control | | [`policy.getData`](#TODO) | Gets the data for a transfer policy, including its type and admin address | | [`policy.isAuthorized`](#TODO) | Checks if an address is authorized by a transfer policy | | [`policy.modifyBlacklist`](#TODO) | Modifies the blacklist for a blacklist-type transfer policy | | [`policy.modifyWhitelist`](#TODO) | Modifies the whitelist for a whitelist-type transfer policy | | [`policy.setAdmin`](#TODO) | Sets the admin for a transfer policy | | [`policy.watchAdminUpdated`](#TODO) | Watches for policy admin update events | | [`policy.watchBlacklistUpdated`](#TODO) | Watches for blacklist update events | | [`policy.watchCreate`](#TODO) | Watches for policy creation events | | [`policy.watchWhitelistUpdated`](#TODO) | Watches for whitelist update events | | **Reward Actions** | | | [`reward.claim`](/tempo/actions/reward.claim) | Claims accumulated rewards for the caller | | [`reward.getUserRewardInfo`](/tempo/actions/reward.getUserRewardInfo) | Gets reward information for a specific account | | [`reward.setRecipient`](/tempo/actions/reward.setRecipient) | Sets or changes the reward recipient for a token holder | | [`reward.distribute`](/tempo/actions/reward.distribute) | Distributes tokens to opted-in holders | | [`reward.watchRewardRecipientSet`](/tempo/actions/reward.watchRewardRecipientSet) | Watches for reward recipient set events | | [`reward.watchRewardDistributed`](/tempo/actions/reward.watchRewardDistributed) | Watches for reward distributed events | | **Stablecoin DEX Actions** | | | [`dex.buy`](/tempo/actions/dex.buy) | Buys a specific amount of tokens from the Stablecoin DEX orderbook | | [`dex.cancel`](/tempo/actions/dex.cancel) | Cancels an order from the orderbook | | [`dex.createPair`](/tempo/actions/dex.createPair) | Creates a new trading pair on the DEX | | [`dex.getBalance`](/tempo/actions/dex.getBalance) | Gets a user's token balance on the Stablecoin DEX | | [`dex.getBuyQuote`](/tempo/actions/dex.getBuyQuote) | Gets the quote for buying a specific amount of tokens | | [`dex.getOrder`](/tempo/actions/dex.getOrder) | Gets an order's details from the orderbook | | [`dex.getTickLevel`](/tempo/actions/dex.getTickLevel) | Gets the price level information at a specific tick | | [`dex.getSellQuote`](/tempo/actions/dex.getSellQuote) | Gets the quote for selling a specific amount of tokens | | [`dex.place`](/tempo/actions/dex.place) | Places a limit order on the orderbook | | [`dex.placeFlip`](/tempo/actions/dex.placeFlip) | Places a flip order that automatically flips when filled | | [`dex.sell`](/tempo/actions/dex.sell) | Sells a specific amount of tokens from the Stablecoin DEX orderbook | | [`dex.watchFlipOrderPlaced`](/tempo/actions/dex.watchFlipOrderPlaced) | Watches for flip order placed events | | [`dex.watchOrderCancelled`](/tempo/actions/dex.watchOrderCancelled) | Watches for order cancelled events | | [`dex.watchOrderFilled`](/tempo/actions/dex.watchOrderFilled) | Watches for order filled events | | [`dex.watchOrderPlaced`](/tempo/actions/dex.watchOrderPlaced) | Watches for order placed events | | [`dex.withdraw`](/tempo/actions/dex.withdraw) | Withdraws tokens from the DEX to the caller's wallet | | **Token Actions** | | | [`token.approve`](/tempo/actions/token.approve) | Approves a spender to transfer TIP-20 tokens on behalf of the caller | | [`token.burn`](/tempo/actions/token.burn) | Burns TIP-20 tokens from the caller's balance | | [`token.burnBlocked`](/tempo/actions/token.burnBlocked) | Burns TIP-20 tokens from a blocked address | | [`token.changeTransferPolicy`](/tempo/actions/token.changeTransferPolicy) | Changes the transfer policy for a TIP-20 token | | [`token.create`](/tempo/actions/token.create) | Creates a new TIP-20 token and assigns the admin role to the calling account | | [`token.getAllowance`](/tempo/actions/token.getAllowance) | Gets the amount of tokens that a spender is approved to transfer on behalf of an owner | | [`token.getBalance`](/tempo/actions/token.getBalance) | Gets the token balance of an address | | [`token.getMetadata`](/tempo/actions/token.getMetadata) | Gets the metadata for a TIP-20 token, including name, symbol, decimals, currency, and total supply | | [`token.grantRoles`](/tempo/actions/token.grantRoles) | Grants one or more roles to an address | | [`token.mint`](/tempo/actions/token.mint) | Mints new TIP-20 tokens to a recipient | | [`token.pause`](/tempo/actions/token.pause) | Pauses a TIP-20 token, preventing all transfers | | [`token.renounceRoles`](/tempo/actions/token.renounceRoles) | Renounces one or more roles from the caller's address | | [`token.revokeRoles`](/tempo/actions/token.revokeRoles) | Revokes one or more roles from an address | | [`token.setRoleAdmin`](/tempo/actions/token.setRoleAdmin) | Sets the admin role for another role | | [`token.setSupplyCap`](/tempo/actions/token.setSupplyCap) | Sets the supply cap for a TIP-20 token | | [`token.transfer`](/tempo/actions/token.transfer) | Transfers TIP-20 tokens from the caller to a recipient | | [`token.unpause`](/tempo/actions/token.unpause) | Unpauses a TIP-20 token, allowing transfers to resume | | [`token.watchAdminRole`](/tempo/actions/token.watchAdminRole) | Watches for role admin update events | | [`token.watchApprove`](/tempo/actions/token.watchApprove) | Watches for token approval events | | [`token.watchBurn`](/tempo/actions/token.watchBurn) | Watches for token burn events | | [`token.watchCreate`](/tempo/actions/token.watchCreate) | Watches for new token creation events | | [`token.watchMint`](/tempo/actions/token.watchMint) | Watches for token mint events | | [`token.watchRole`](/tempo/actions/token.watchRole) | Watches for role membership update events | | [`token.watchTransfer`](/tempo/actions/token.watchTransfer) | Watches for token transfer events | ================================================ FILE: site/tempo/actions/nonce.getNonce.md ================================================ # `nonce.getNonce` Gets the nonce for an account and nonce key. This is useful for managing multiple nonce lanes for parallel transaction submission. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"95821029487d78766a2dcd7ccfe1331d8bf3d401ae5c2d46c01fcfe2b5f0f262","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQg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jO8mwp+t0KmJwAALLzwCCbjao6CKh2goaPJ6LWjhCxhi6oEcq5BJABhcCvJ8JVqAwsCSCRy366BKITg6osZQAWQf4CyMHhBrw95iAWQVbwL8YFhnwsDjZXzhKDIsE4wJBBBPARDupTId55pgDqC5I6DFIWCKg1LaFJpYZFLaFPC+a7AJAuhPAuhRp6ZBB/KtBEEKqEpZo6o2iqxBIKHbhBZyAuhJx5poDiJt5TKepzILL6H+olJrIbIhrbIIT+H2EHLtL+FBEXgZHrKtCRBSwNq7hNrQ7LAKzw7nBY5z5c5vgKypA7r9pWgKxZ4O5FAQyXDmJIFoAroyKVHVHy4NGnoq457NE4ypCtGLqPoJKV4ywWpdiDLJFZGhGTL3gRHepRH5IxGrJlKT6ho7LJFRptLpG5qZGHHZE6DbRJxIJITZpZEFoLg14oCrj/Z0ggBEDWAui9BvHWDWCL69QMiiiXTaxDQCgb54Btrb7VwigSiH5SgrRkh/SLDB7ahbA7BGxL64i4j5w6wNDsj6xlzahgkgC75vR4i4iWwGASBKClBbYgmiKQh9S9a4gAmFy2DkiBA+wbCcCVC4hgCVy9DMmEnmwEg9QxCwBAgnQ4RWQmB4QESHrwR/h8QQAYTfKcAngpRSkwRvguiz5ZCURFGNbajw5mTiAWSYyqg2RJjVjagOT7ROTCSGxoAeReTqCclQBPDnBpC8CNCNBPCVBpDWDnBabSDoniBPCbBiiVCVAABCvA0gMA6g5w0g5wCQ1gmwRamwmwfkwk5coU4UukemnRra66b4bJiA8uPIempQRU4gSAoAAQig68QgeA+4IArgrgQAA"} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const nonce = await Actions.nonce.getNonce(config, { account: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', nonceKey: 1n, }) console.log('Nonce:', nonce) // @log: Nonce: 42n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = bigint ``` The current nonce value for the given account and nonce key. ## Parameters ### account - **Type:** `Address` Account address to get the nonce for. ### nonceKey - **Type:** `bigint` Nonce key (must be > 0, key 0 is reserved for protocol nonces). ## Viem - [`nonce.getNonce`](https://viem.sh/tempo/actions/nonce.getNonce) ================================================ FILE: site/tempo/actions/nonce.watchNonceIncremented.md ================================================ # `nonce.watchNonceIncremented` Watches for nonce incremented events. This event is emitted whenever a transaction is executed using a specific nonce key. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"d6c088363c7a29ffdad7dc923554c75831017d0aa12ea1177d8bb4c8f55ce3f0","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinACuYADu4mj2qUFRALwAfJxEEIxQpeVSiOqytcqqGi06enhrm9tq8hZWAMwDjmco0aE2oXmmvjm1ACTFY7C4RkEwku2n0AA47goHg0ato2nhESYuj8kP8QPZASM+iCPGCpgYZn5oQsDPl4ZxIGBeLhRKiZDUsfUkABWZ74gyc7nEnqIMkUoZApAAJkqoMw9J8s1KNBZIASa34SM4H3sADkhNyAJJc0gwZiKGhQAA8GUSyUOQQ6yVSrqyFE4WEc9pGcFShOEADpJTAIyb8OauTBrbxbfawI6IwAFIN6MhwF3FJSHCK7A7HU7nXJgcT2uCB7nGrZmi1Jm12h0wC5UKAQXgIAwAdSb+HgnAS7A5Lc4FhT7fTnc4MBI6bgEe14iU/eQyBAsCwtt4W07pQAKvhGHAxwbjGBOA5LwAjGCKTh7g9HqABiBiAC03DkChKKQEAALLQGQWwQBGnCWlw6yMABnBPpwqa+J+FicOIV5oCstonH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IFt4pQ4lkmcCiiFxxHWbMbEnUkHRUk8rpi0lRH+yclMk26slEHUQpLHqlyfECDfGIn/Hiq8RAlvqrjypglkoQl/qqpAaySwngZsoInsDYZIkGlbAol+zIYTjoalyYbGk3gNxMykEoA7hu5ShUBEDWARi9AenWDWCSGNwyFoiMy0wUJdx4A0LfAyjqH0Kjy9BWzaHCyahMj2wGFoJzyYR+yLwvyYS8CCmbw7x7wPKHzHzPwNbRjXy3xIRfxPznxvwfwVkmLfzlREIyHSCgJBlICgJUIQJ+xqEjz8xazMIJl2ziwqHLDvDDili+Tlg+FNnKi/DyHYiKGdlvB1SfBQJUy9nmyCxkwxCwCwgqxWRNTCAaR4zaS6SyQxRmRMSWSAovS2T2QiQRiiFZAeRYmjkrkDJ+TWQtSJhtSBw4J1w9TPT9TxQ9ydS4IhwhARx1pJwLTnwi4KYLwj7HSlQlTnQnSdbxxHikClYOJ8RxiHy5BjmfB7ClDBjiBICgABCKC6JCB4D0QgCuCuBAA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.nonce.watchNonceIncremented(config, { onNonceIncremented(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `() => void` Returns a function to unsubscribe from the event. ## Parameters ### onNonceIncremented - **Type:** `function` ```ts declare function onNonceIncremented(args: Args, log: Log): void type Args = { /** Address of the account */ account: Address /** Nonce key that was incremented */ nonceKey: bigint /** New nonce value after increment */ newNonce: bigint } ``` Callback to invoke when a nonce is incremented. ### args (optional) - **Type:** `object` ```ts type Args = { /** Address of the account to filter by */ account?: Address | Address[] | null /** Nonce key to filter by */ nonceKey?: bigint | bigint[] | null } ``` Optional filters for the event. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `function` ```ts declare function onError(error: Error): void ``` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Enable polling mode. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`nonce.watchNonceIncremented`](https://viem.sh/tempo/actions/nonce.watchNonceIncremented) ================================================ FILE: site/tempo/actions/policy.create.md ================================================ # `policy.create` Creates a new transfer policy for token access control. [Learn more about transfer policies](https://docs.tempo.xyz/protocol/tip403/overview) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"e0c93d427169d0944a1d8b51a79fe35242cf5f9a3229dd7529118fcdd9ec4d11","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinGzmvBgAklCpAEbJFgyi2voAHP21yqpIJy06enirjOtbXRZWAMwDjs6jJxPUXmmvjm1ACi1iKwgawwABUvKkwABXZg7PxlY4yc4KS4NXq2aite4GR7rOFTeRvJCfED2b4jPp/DwAqYGGZomgLAxLLikGC8GCMLBoVIwobCYaCMAAJT5AqFpXKUkQeOp2PqGlubTwvP5gsOZkpiGptKGPyp1n+mBZPlmpQ5gXy7C4RklpkV+l6ACYsXUrogatotQYXSZXj0jV9TfTEJVGZNvGyQfamKwnZDoQqMcrPbILuqmpqiSASRgwx9I8MXIgAKyNS2A1nAu1ggwJRFgfiS6K88Q0ADKGA7AB4MolkgA+IIdZKpUdZCgrRzMPRkOCpEPCAB0Jc3vB7/cHvE3AAUlyvSHAR8UlOOIqlj6QIMxGHAYEPgLlOF/009NttOHsSgHAA3J+36IlgUC9mQqQAAbWLQAAkwBiKQFhKK4sGgWA34/qS8KcEi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BNwZNewAVoTupyN/VA0kTaN6MYYmNI1WMjUmSiSrUmTWS0BJS9ZWhIhM09NaoDMstlgYh2xWZOBqwB9ssgtVSQ5UhQtbMFxdS0BCCgCY8ig1TUhqxH8Msm8nkdT7U9Tf9jTTTpDUhjSrSbTU0oDNDYI6Z0NeIuVRTJT2SvVOSLDuTqNeSQ01UBSPCo02NRSuNLUJT2BZMpS0zewZSdBIh+pesHpApJT5NtCSoypMkGVSgiBrBNxegazrBrAAijh653hE544GhqQ25AgXlojYie5M44xmQh4TFkwuQIQSwthdh9gQ4FEqRPQdE1Q/QdFOyHg+ZngoAezOF9E6wkjrQJAlBSgLc8BuymylR3h3h5zm4Ej+EDBjxVy2kNhPdUhegwBojjQ+zowLRI4YhYAUxq5MYuZZdLp1obopZtojVIYIBjpGozp3osg1prohphpNwfCPoXplSYLxyH8lIyRX1spGIuA+o2YOZnRuZeZoQBZ+IDwOwRYPoxYwJmEF54BwYwIvxho15KgN4t4d494D4j4T4z4L4r4b575H5n5X535P4f4dgFYWKRpQFwFIF1BoFYF4EoBEFkFUF0FMFsFcF8FCFiETgZLgZEZkZJYpFZZN0jKlY68XcgtbzoQCNHzf9MKQdSgF1xAkBQAAhFBMkhA8BHIQBXBXAgA"} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { policyId, policyType, receipt } = await Actions.policy.createSync(config, { addresses: [ '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', '0x70997970C51812dc3A010C7d01b50e0d17dc79C8', ], type: 'whitelist', }) console.log('Policy ID:', policyId) // @log: Policy ID: 1n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `policy.create` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.policy.create(config, { addresses: [ '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', '0x70997970C51812dc3A010C7d01b50e0d17dc79C8', ], type: 'whitelist', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args: { policyId } } = viem_Actions.policy.create.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** ID of the created policy */ policyId: bigint /** Type of the policy (0 = whitelist, 1 = blacklist) */ policyType: number /** Transaction receipt */ receipt: TransactionReceipt /** Address that created the policy */ updater: Address } ``` ## Parameters ### type - **Type:** `'whitelist' | 'blacklist'` Type of policy to create. A `whitelist` policy only allows listed addresses, while a `blacklist` policy allows all except listed addresses. ### addresses (optional) - **Type:** `Address[]` Optional array of addresses to initialize the policy with. ## Viem - [`policy.create`](https://viem.sh/tempo/actions/policy.create) ================================================ FILE: site/tempo/actions/policy.getData.md ================================================ # `policy.getData` Gets the data for a transfer policy, including its type and admin address. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"7be8148a546f6e73e327ea871b234bea4c43f38a349d04fbe07fd29b5c985e9a","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinOJQzBapAAbWtAAkwGKkFkqum6VQELwIBtxrFitQUKTwcAB0peVSiAAc/bXKqiQAFYWjo9HhVuswF0LFYAMwDRzOUbfCbULzTXxzagBRaxTiYHCpAAKEHMvAwABUMVQLlc8KTyRgCV53qJtPpvt95HVAYhKqC2nhCbh5LCkAiQPYkSM+kC0SLMbNSjQFgZ8uwuEZBMI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z1Cc0sEcEikjAjzbumWmIjiaW01LJ5iLpFjCyi0nsyqj2zaiuzCzcm+yCmSjyz2jxK0AymdBUYDV+i/x9UUmTUq63cpiBFZj5jFjehljx7PohpliZ6/pJQgSDBd6zBxQfhkG0xTisxziOYG8DAwtbwI0WpqQpgN9QJGQHwWQcAFZnmXm3m+R9ZPmgWkGDZUwjZAW4YkIt6dcd7/4AwvgtMC9Z6bBLiDB4XYIIWuJUMaBzAxAy8Hn/moZnR3oYhYAmBOkJIeBGooJGJDJWJi1FIzJApNIiIBXFoDI5I2JXg08sgbILLiJz7k0vAZJnJxA6oGoh83gno2o0BAJxBOpMZuprxtZUhehRpchSpga1as06XmRIQNgki3WwBxoBm4iXXEWbqkiRRxpSh9pxAkBQAAhFB44hBhQEBXBXAgA=="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { admin, type } = await Actions.policy.getData(config, { policyId: 1n, }) console.log('Policy admin:', admin) // @log: Policy admin: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb console.log('Policy type:', type) // @log: Policy type: whitelist ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = { /** Address of the policy admin */ admin: Address /** Type of policy */ type: PolicyType } ``` ## Parameters ### policyId - **Type:** `bigint` ID of the policy to query. ## Viem - [`policy.getData`](https://viem.sh/tempo/actions/policy.getData) ================================================ FILE: site/tempo/actions/policy.isAuthorized.md ================================================ # `policy.isAuthorized` Checks if an address is authorized by a transfer policy. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"d89a8bdb355ed397122134203ceb623b3e34be73a444f2615bf50197c0945485","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMV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Ebnpbd/ZKgwAflSLIr0pUwm7zRKEMa3YO2yOQDpTMnAiAQC7iJgA1L0AFsxKESMx8XYBYDB48kNHxB00BG4dksEL1uglFOAABZVuAQe8EVHQdYX0DdaIdZAcPsSWfYL0WAo5XIJIZMLgURYhI5duFgSQQ8CDKDdhThUVUWKAUKO/X5Kg8IWDRvMQUKZzIQfOVseAWDFgDrBeRxZxYDBIIIQECII1JpWvGNMAdQMJC1bodYVJFQ/1KDaJFQwEWzJ2BIYMQEMZN1OQSqIINaVoLAzlHuaFVgggrZJDJxZzOQYMKNGNNAGhavJpE1Npc1CJKJa1PpPvQZR1VCdw8w91dwrwv8eI21VoSIWZT7R8b7JrGIY0f7TgdUaHEfI/WCLIyBVIadOtL0YotAQ3OPJnVISo1IE6JDKA49chQo+ogXSo6ojbDdOo0pEo3I87ZovPR8F+JVAcNwgQDwxI3wxpUCAIs1YsTpEI2JMIgZB1YZaI8ZfJOI9gbwxItqZI4NdgJuSiMxRIuNAvS8a8PuE0XAKgIgawYMXoJ4nEcff2SfJ4VWCUBoSkcOG6UtJffWNfEUDfGELfdkTGUGQcHaa0I4E4M4C4CffQJJS6NWWfafdGCOW6SsXcB6MwJ6RAZfPGA2QEawUEgwCQJQUoabPAAEpEukdUNGNEyUXECmPAClfyYcfYVIdRNsXWbEIEt6Mk/aGIWAREGGZicKYQViYiBdMiVCVSeiD8JiKxVqCCNiGCWCYMYfLIASH7KEu6LkzhIKEKMKTLYsVKCsIcXEqABKcGJKAyRmQqYqdQD6KADUNIXgRoRoQESoNIawdUaTaQJ4dUcQQEQ4EUSoSoAAIV4GkBgHUHVGkHVASGsEOATUOEOHKgMjtkyl6BylyC8jdwKLHVgg5O2nugOAF0NJtMqlKHBXECQFAACEUD7iEDwFfBAFcFcCAA=="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const isAuthorized = await Actions.policy.isAuthorized(config, { user: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', policyId: 1n, }) console.log('Is authorized:', isAuthorized) // @log: Is authorized: true ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = boolean ``` ## Parameters ### policyId - **Type:** `bigint` Policy ID. ### user - **Type:** `Address` User address to check. ## Viem - [`policy.isAuthorized`](https://viem.sh/tempo/actions/policy.isAuthorized) ================================================ FILE: site/tempo/actions/policy.modifyBlacklist.md ================================================ # `policy.modifyBlacklist` Modifies the blacklist for a blacklist-type transfer policy. Requires policy admin role. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"6c776f607178f89d5334ea2398757c8b3ee4db029caff53ec164954928f7b409","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinKQwvDCMWGipACpDwsOCYABKaxtbpeVSiAAc/bXKqhotOnp4q+ubDPIWVgDMA0czlGNwm1C8018c2oASYrHYXCMR1MV300lkD3qz2orTeBiRJi6vyQAJA9iBIyQACZGmDMFMDDM/DCFgZ8gjOGxzLwMJdtPpetYagpHg1mjjXoEuYweUSeohSeShsCSZU6RDGVDSjRWSAEgBXMD8I6cZjQRgJDAAITkTgA1uYxABlDBGgA8GUSyQAfEEOslUp6shROY5mHoyHBUgThAA6aU82NmqAW6223gOxjO128WMABTDEdIcA9xSU3oiqTzpAgzCzMDdwFynBbnIg3IwAEkoKkAEbJCxoADczdb+qwUHEI1SAANrLQACTAMSkCxKVwzkdgVucJwxQ3bThzxfLtCr5Qbrc71YrmU0HucXsQdswcRgK+tj7nQ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qDKn8Qxs1jhn8X8KRoOAkLGH8P6mqq9kELnq0IMZOoOtZPseMemgChSljnILGFxlOPct8SlKhg6k6kCdhrhqdARl6sRgqoSUiRqoSSSWgBydLK0JEBGrJiFGXprvuC7NXhvG3vZkpipsKYeG5jpiGNKTAQFpwakNKakHQl1tFrZuXnFqvqqXfgqRwXASqbqi7GqYno0SXmDKBhBjOCyRyWSdahSWoVSZhjSa6iKvSeYd6iRiyRRuquyewNxpyYGVONyToAXFZAhBxokCGQLu5C0FISgL5L4niqUEQNYLGL0JmdYNYPYTXP/PApUBiKQg0KSOAngMcl4fQj3KCEwhqJnMyCPIsBDF+F8LsFbCpEBN+EItSCvC4YHG4ZKO8GcF8FWWSIMMoiSH8P4ZqIEU2bnBwlwtPB1gcMjAABLhD4CzjzhLjK7riCzVHWJ4AblwCrIQAJDyQsS3TWwC49nwI3BUj9kNC9B0JSKtzXkqQnlqA/DyjeETlwKpwzk4hKClAu4VnKZ3knzFkBwNCSLzm2Idk2wOCnmpDzi9BUj1wbyNDqA3DSDWDiC9i8CwAJDoWYXYW4X4WEXEWkWVBYU4V4UEVEWWQ0V0UUWMXEXQK9D3A+HJx+GewxCwBwiVwDTIxDQNSjTeYtQKpHQQA9QRT9RVzJD1QjTZQ5SxjWElyzTakKWtk5LpRwwIyIiiXxjtjEzowphIQUQxy4ySwEyjiQLzypA5TLyrzrxbw7x7yVAHxHwnxnwXxXw3x3wPxPwvxvyfzfzMyjjUKpC9DkyjiyK8L3ipBcw8zAyvaxZXKr6/irkC4zYoV366WHYfnrmbmvalDqziBICgABCKC+JCB4DSQgCuCuBAA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { receipt } = await Actions.policy.modifyBlacklistSync(config, { address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', policyId: 1n, restricted: true, }) console.log('Transaction hash:', receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `policy.modifyBlacklist` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.policy.modifyBlacklist(config, { address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', policyId: 1n, restricted: true, }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args } = viem_Actions.policy.modifyBlacklist.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Address that was added/removed from blacklist */ account: Address /** ID of the policy */ policyId: bigint /** Transaction receipt */ receipt: TransactionReceipt /** Whether the address is restricted */ restricted: boolean /** Address that modified the blacklist */ updater: Address } ``` ## Parameters ### address - **Type:** `Address` Target account address to add or remove from the blacklist. ### policyId - **Type:** `bigint` ID of the blacklist policy to modify. ### restricted - **Type:** `boolean` Whether the address should be restricted (`true`) or unrestricted (`false`). ## Viem - [`policy.modifyBlacklist`](https://viem.sh/tempo/actions/policy.modifyBlacklist) ================================================ FILE: site/tempo/actions/policy.modifyWhitelist.md ================================================ # `policy.modifyWhitelist` Modifies the whitelist for a whitelist-type transfer policy. Requires policy admin role. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"952192056f8028f108ce757f5c41d5167a39f17553d4a449338c09baaef8c103","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlk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YA4Qa5+o7ZBo6oRoPMmpCojoIBuowo+pa5khaphpMosoYwjCshZpFTJLuzao4YEZEQ+LUY2xMZkwkIqJcYswCZy4iZhxYEl5Ugso14N4t5d595D5Khj5T5z5L5r5b574n4X434P4v5f5/5WZzLGEiFpzeY2ZlERFehKZgZ7tIsHl59ILjyTQHBYLT9uyYwjyhJHz7tShNZxAkBQAAhFBgkhA8BgoQBXBXAgA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { receipt } = await Actions.policy.modifyWhitelistSync(config, { address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', allowed: true, policyId: 1n, }) console.log('Transaction hash:', receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `policy.modifyWhitelist` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.policy.modifyWhitelist(config, { address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', allowed: true, policyId: 1n, }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args } = viem_Actions.policy.modifyWhitelist.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Address that was added/removed from whitelist */ account: Address /** Whether the address is allowed */ allowed: boolean /** ID of the policy */ policyId: bigint /** Transaction receipt */ receipt: TransactionReceipt /** Address that modified the whitelist */ updater: Address } ``` ## Parameters ### address - **Type:** `Address` Target account address to add or remove from the whitelist. ### allowed - **Type:** `boolean` Whether the address should be allowed (`true`) or disallowed (`false`). ### policyId - **Type:** `bigint` ID of the whitelist policy to modify. ## Viem - [`policy.modifyWhitelist`](https://viem.sh/tempo/actions/policy.modifyWhitelist) ================================================ FILE: site/tempo/actions/policy.setAdmin.md ================================================ # `policy.setAdmin` Sets the admin for a transfer policy. Requires current policy admin role. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"983f569302010026098cc5bbf73d68463318d1076985854dbfdfd589c471fed0","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinKQwvDCMWGipACpDwsOCYABKaxtbpeVSiAAc/bXKqhotOnp4q+ubDPIWVgDMA0czlGNwm1C8018c2oASYrHYXCMR1MV300lkD3qz2orTeBiRJi6vyQAJA9iBIyQACZGmDMFMDDM/DCFgZ8gjOGxzLwMJdtPpetYagpHg1mjjXoEuYweUSeohSeShsCSZU6RDGVDSjRWSAEgBXMD8I6cOB6bhQZgWADKGCNAB4MolkgA+IIdZKpJ1ZCicxzMPRkOCpAnCAB00p5YbNaAtVrAtqNYYACv7A6Q4I7ikoXRFUsnSBArWb7cBcpwK5yINyMABJKCpABGyQsaAA3OXK/qsFBxCNUgADay0AAkwDEpAsSlcA47YErnHElosg+HY4nU5nc4XH3O204e3EB2NQlOny2c9cLtyYHEAbgWCcMFN5uXCbtvFKUAgvAQBmtehwJwqjPku8acAk7CLlWNZhrkuQAHIQDQuz4IwQHodBcAfvghaQPqQGHEIwEOFwADu4iMGgQGQaQJHPmg+xwER85oBAuSNs+Fi8HI+qwFAnDEeInCNnIP4ANYiTAtHPqsaD6qQeTKNBqwPiYMBhtq4hKH+yDICAdB3lgCilAOZnUbk7KFMA0SrH2MDeskvr4GgaBYJwrgQY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zRyggAIaiWzMipyLBXS7hfC7B8yvRnh7j3z6C/I/wmlMG4iBCukXA/DygcFKjcEkh/B8GagCEshpykJZwXzAQelfYAAS4Q+Aq4o444jEm4aM1h6CeAmZcAYSEACQJEmEc0x4X2Pp1ITcDBq8vQ/p5pgQNZzEr0pZagYZVgEZXBu8pssZOISgpQtOeAlpBp1w/sxpK8KsxpTpBgh4tZJoDgZZqQw4asdcMcjQ6gNw0g1g4gjYvAsACQW5lQO5e5B5R5J50k55l5+5h5x5p595u5j5N5p5W8go1pPBrgMsMQsAcInsy0L0X2xUiUPkTGqUIKw0EAuUsqIFeMCUpUSUvkYY5BLsdUBuywNkIZXAnkD0T0iIr0zM70n0sYb4P0f0LsAMnYecqQvkxcpc5clc1ctc9cjczcrc7cnc3cfcA8Q8I8Y8E808jYiMnYn8qQvQEMp09W2JyScey5nZX2q+65JeeFYYHZLE3Z9WpQNM4gSAoAAQignCQgeA1EIArgrgQAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { receipt } = await Actions.policy.setAdminSync(config, { admin: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', policyId: 1n, }) console.log('Transaction hash:', receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `policy.setAdmin` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.policy.setAdmin(config, { admin: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', policyId: 1n, }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args } = viem_Actions.policy.setAdmin.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Address of the new admin */ admin: Address /** ID of the policy */ policyId: bigint /** Transaction receipt */ receipt: TransactionReceipt /** Address that updated the admin */ updater: Address } ``` ## Parameters ### admin - **Type:** `Address` Address to set as the new policy admin. ### policyId - **Type:** `bigint` ID of the policy to update. ## Viem - [`policy.setAdmin`](https://viem.sh/tempo/actions/policy.setAdmin) ================================================ FILE: site/tempo/actions/policy.watchAdminUpdated.md ================================================ # `policy.watchAdminUpdated` Watches for policy admin update events on the TIP403 Registry. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"00763990b98b4efbcf9bd7321d9ba2c95d1dae5db8d2d85db9dc52b8f2ca0034","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinACuYADu4mj2qQDqW/YZYGhD/ACiJMcASnorpGAAKl6l5VKI6rK1yqoaLTp6eDWm22ankFisAGYBo5nKNGhNqM8DDM/NQAkxWOwuEZBMIXtp9AAOT4Kb4NGraNp4HEmLrgpBQkD2GEjPrwjyIqbI3xzNELAz5LGcNjmXgYfEVGQ1Un1JDNaitAEGEWMMV0nqIRnM06sxAAJkqCMwXJ8s1KNH5IASa34uM4wPs3CgzAsAFUsFAtjAoAAeI5ZAB8QQ6yVS/uSFGFjmYejIcFSNOEADoVWKkw78E6XWB3Z6aFAkwAFaOx0hwP3FJQBiJ7A74I4nYYXRRoG5oO6PLy5MDiGNwLBOGD2utZt0er1QUpQCC8BAGfYg+CcBLsYUQUUYTjiZ0WVbjmicGCXNBwJPm8RKOfIZAgOi9rAKUoAAxfJ9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sJbpwF/C7shiXjBECccKkKxrhpGNCWgO/lnqRoiakL/Eco4XJvkkxmiZXoicibYakGiaCXLliX8U+LYmOkOOcs8e8ScWSiBOcVuqeHStcfusykeuynCs8Reqim8ewD+h8YKVsF8VlC+quB+kOF+iKZdJHAqFASgDeBrkgqUEQNYEmL0JqdYNYHQVHJvOoHHCwQ0AAvvAYMAmCBqNwTnHwb0PnALJjEXMIaXGtKWJXFlMZF3HXI3KkC3DwscFPCluHGlEvv3EPCPCcMvKvF3LPBYPPOGUjivJPL1B/H0ISNKGDA0HvOwQfFlFwaArqHqF/AIVjCLCXEyD5ECHWBlGbHoZbJOPqfoAzMwZmb8AqDmQYFWSCJnL0LYDwSyKjNYK4P9DELABiFTAxEFMIMxKxFXiRHCspDRB+PRHslNOBB9GxEmFQeTHxGbkTL5BmAFIxCFBuBFM/GrC1HFOTAlLpGnGOJeZ1NrPlNXNPGHihoUjBMrJXt8d1O5G1nlkbD3HptdKBBmMvLkF2fYE5KUOtOIEgKAAEIoKwkIHgCeCAK4K4EAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.policy.watchAdminUpdated(config, { onAdminUpdated(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `() => void` Returns a function to unsubscribe from the event. ## Parameters ### onAdminUpdated - **Type:** `function` ```ts declare function onAdminUpdated(args: Args, log: Log): void type Args = { /** ID of the policy */ policyId: bigint /** Address that updated the admin */ updater: Address /** Address of the admin */ admin: Address } ``` Callback to invoke when a policy admin is updated. ### args (optional) - **Type:** `object` ```ts type Args = { /** Filter by policy ID */ policyId?: bigint | bigint[] | null /** Filter by updater address */ updater?: Address | Address[] | null /** Filter by admin address */ admin?: Address | Address[] | null } ``` Optional filter arguments for the event. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `function` ```ts declare function onError(error: Error): void ``` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Enable polling mode. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`policy.watchAdminUpdated`](https://viem.sh/tempo/actions/policy.watchAdminUpdated) ================================================ FILE: site/tempo/actions/policy.watchBlacklistUpdated.md ================================================ # `policy.watchBlacklistUpdated` Watches for blacklist update events on the TIP403 Registry. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"9b1d65086b67741e13cb6c063a4e3c7d1060b98061ad9be94ac501be7904f5a6","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinACuYADu4mj2qQDqW/YZYGhD/ACiJMcASnorpGAAKl6l5VKI6rK1yqoaLTp6eDWm22ankFisAGYBo5nKNGhNqM8DDM/NQAkxWOwuEZBMIXtp9AAOT4Kb4NGraNp4HEmLrgpBQkD2GEjPrwjyIqbI3xzNELAz5LGcNjmXgYfEVGQ1Un1JDNaitAEGEWMMV0nqIRnM06sxAAJkqCMwXJ8s1KNH5IASa34uM4wPsACE5E4ANbmMQAVSwUC2MCgAB4jlkAHxBDrJVLB5IUYWOZh6MhwVI04QAOhVYrTDvwzrdHrQ3t9NCgaYACvHE6Q4EHikoQxE9gd8EcTsMLoo0Dc0HdHl5cmBxAm4FgnDB7c287x3YwvT6/VBSlAILwEAZ9iD4JwEuxOAAjF3Tgurec0TgwS5oOBp83iJRr5DIEB0IdYBSlAAGX6vuUFhWA0SkDAfrRkosb4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LQCWgGgC1QzAHIzgDTyKE3ginFmj2EMkw3mOFSBkxY1jFxLQAQKbzVzRLxM4CUOSyM1n15xxJZTxMH2JNJMCNSGJNSGpJE1pLEyRKtzf03XHEBTBJhI+P5Sgm+NvWvHFX+KlTxVhL4LfUVTBNVTpUhMQ2hI1NhPhO3F3Fg3HAsBhJQ0IIfCfHtzoVKCIGsDTF6BtOsGsDEOTkfkJD1AzllE1D+FzjMAqkUOUIrg5irmASJlrk0Ibl2irBbhKmshHk7h7lSH13UWOCPjsi6lSnP0nhnjnhOH3kPhHnXkZK3gER3izIXgPmXhHlPmzPPnjKvgUBvjvlQT6GkCUK+HdPfkVE/hKl9LLhZDxj1HFjUOJjlnrkFg/yBGbCKmdmcLdgxjBhTj1AhGkNflkNwQMHHJBG/l6FsB7LFlGGsFcFBhiFgAxGZg4iimEG4l4iH2omwm0hYgdVqg+UWlgj+j4jTCEKyDEnf2WHXJaVkk4hijigSngVjjRgXHSgZkylMnziPFtnRmKnvAtkqjblXjz2o26SQj1kH3hKGn8im3K3tjHlcyemghzH3lyF/PwC8lKD2nECQFAACEUAUSEDwCvBAFcFcCAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.policy.watchBlacklistUpdated(config, { onBlacklistUpdated(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `() => void` Returns a function to unsubscribe from the event. ## Parameters ### onBlacklistUpdated - **Type:** `function` ```ts declare function onBlacklistUpdated(args: Args, log: Log): void type Args = { /** Address of the account */ account: Address /** ID of the policy */ policyId: bigint /** Whether the account is restricted */ restricted: boolean /** Address that updated the blacklist */ updater: Address } ``` Callback to invoke when a blacklist is updated. ### args (optional) - **Type:** `object` ```ts type Args = { /** Filter by policy ID */ policyId?: bigint | bigint[] | null /** Filter by updater address */ updater?: Address | Address[] | null /** Filter by account address */ account?: Address | Address[] | null } ``` Optional filter arguments to narrow the events being watched. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `function` ```ts declare function onError(error: Error): void ``` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Enable polling mode. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`policy.watchBlacklistUpdated`](https://viem.sh/tempo/actions/policy.watchBlacklistUpdated) ================================================ FILE: site/tempo/actions/policy.watchCreate.md ================================================ # `policy.watchCreate` Watches for policy creation events on the TIP403 Registry. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"4175566a55e750e5214e1ba28bd900a36c6ad75d45fe9a2ac4e16980d28c414b","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinACuYADu4mj2qQDqW/YZYGhD/ACiJMcASnorpGAAKl6l5VKI6rK1yqoaLTp6eDWm22ankFisAGYBo5nKNGhNqM8DDM/NQAkxWOwuEZBMIXtp9AAOT4Kb4NGraNp4HEmLrgpBQkD2GEjPrwjyIqbI3xzNELAz5LGcNjmXgYfEVGQ1Un1JDNaitAEGEWMMV0nqIRnM06sxAAJkqCMwXJ8s1KNH5IASa34uM4wMOpBgWxgAB4jlkAHxBDrJVIe5IUYWOZh6MhwVI04QAOhVYujDvwaSdLujAAUQ2HSHB3cUlJ6InsDkmhCdhhdFGgbmg7o8vLkwOJQ3AsE4YPbi8nnTRSlAILwEAZ9iD4JwEuxhRBRRhoinjGBODBLmg4NHz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qXJoCDqYrDo4qTGdFTqTEzFbBHGbGlSyZHoP4njy7/YxBrBcBsTey65e7oa3HHCpBYaAZBivFoCt4kaqGpDfGpC+yGyaFMYhIvH/JvEp7fG/HB7kaAmcDAmGYMay7KJlrtgzJ7EnHzFQrPhLFdqrhIprH9ropDrYogR7EEqfKHF7rHG0mnFRRroThbrtgWAnGHpP5bg7hC4fylBEDWDRi9CCnWDWDoEuz9yNAkiPQNCMhjx4BXw/RWAkEzxRxuwUHxzPyMxDRZhpxRQZzNw2xuR5ypAFyELHBNweYrAVxVw1x1yvIWlqStztxcxdwwA9wHx9CEh6iexnyjyKjjxRTEHkyzzRzezqnLyakGD/ZAjFgRSKxiEqwhzin6B6h6g4HSl4FykGAxkgiTy9Anwqm6jWCuBXQxCwAYhoyEROTCAkRkSp4oQgTCS4QXgETDJtRvjHTkTRjIFZD0QK5wy2SJgOREQuTTgeQ7xeQ+TIx+SySBxuTBwCw15ZRRApS8Rw7obpwp5nHlQmRVQy7k6yxVxCZ0IviJhEK5A5n2BGSlDDTiBICgABCKBYJCB4ArggCuCuBAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.policy.watchCreate(config, { onPolicyCreated(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `() => void` Returns a function to unsubscribe from the event. ## Parameters ### onPolicyCreated - **Type:** `function` ```ts declare function onPolicyCreated(args: Args, log: Log): void type Args = { /** ID of the created policy */ policyId: bigint /** Type of policy */ type: PolicyType /** Address that created the policy */ updater: Address } ``` Callback to invoke when a policy is created. ### args (optional) - **Type:** `object` ```ts type Args = { /** Filter by policy ID */ policyId?: bigint | bigint[] | null /** Filter by updater address */ updater?: Address | Address[] | null } ``` Optional filter arguments to narrow which events to watch. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `function` ```ts declare function onError(error: Error): void ``` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Enable polling mode. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`policy.watchCreate`](https://viem.sh/tempo/actions/policy.watchCreate) ================================================ FILE: site/tempo/actions/policy.watchWhitelistUpdated.md ================================================ # `policy.watchWhitelistUpdated` Watches for whitelist update events on the TIP403 Registry. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"e8df301eda13d3e824a0f6ebe0befaea3f9f427a3290ede59f525defedbfdb9e","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinACuYADu4mj2qQDqW/YZYGhD/ACiJMcASnorpGAAKl6l5VKI6rK1yqoaLTp6eDWm22ankFisAGYBo5nKNGhNqM8DDM/NQAkxWOwuEZBMIXtp9AAOT4Kb4NGraNp4HEmLrgpBQkD2GEjPrwjyIqbI3xzNELAz5LGcNjmXgYfEVGQ1Un1JDNaitAEGEWMMV0nqIRnM06sxAAJkqCMwXJ8s1KNH5IASa34uM4wPsu3wjBo5jEAFUsFAtjAoAAeI5ZAB8QQ6yVSgeSFGFjmYejIcFSNOEADoVWKUw78E6XTA3WhPd6aFAUwAFWPx0hwAPFJRBiJ7A74I4nYYXRRoG5oO6PLy5MDiONwLBOGD2ps512MD1en1QUpQCC8BAGfYg+CcBLse3OqfLFazmicGCXNBwFPm8RKFfIZAgOiDrAKUoAAzfZ9ygsKwGipBgPsjJRo3wNA0CwThXE3UgIGYTgA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uxhiakLIZ8gEfpm0uiYyscF1LiVSWgPiT4akESZwCSbFrph7iEmumOH8kCWCS8TymBO8VeueCKt8eKtimgI+tKs+nKkCUqtSqCewHBuCUqVsJCYVGBtuFBmODBqqbdBeC0LgSgHeLbtQqUEQNYCmL0FadYNYIIUzJKKNnqKnLKJqH8FnGYKVDIXIbqKzIofjFLDXMEFtJWI3IVOZEPG3J3KkD3CoscAfFZAeLlCfuPFPDPCcLvPvEPKvHSZvGmWTnvIvNmVRqfF3M9BfAoFfDfCgg9rIV8K6a/IqO/IVN6cXCyFjHqMLP6VXCoQYDTkCE2PlLbHYQ7POA6W8HqBCGIc/BIVggYAOSCJ/L0LYG2ZjKMNYK4MDDELABiPTCxGFMIOxJxP3uROhOpAxF+MxK8nNJBD9FxCmLwVkEJN7uTIFFmCFKxBFFFDFLArrPAslLNGlIZDnHuIlHHAVNeMbGVM3MvNnmRh0nBFrH3lCf1N5ONrVpbCPHZvdOBFmLvLkAufYG5KUNtOIEgKAAEIoLIkIHgGeCAK4K4EAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.policy.watchWhitelistUpdated(config, { onWhitelistUpdated(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `() => void` Returns a function to unsubscribe from the event. ## Parameters ### onWhitelistUpdated - **Type:** `function` ```ts declare function onWhitelistUpdated(args: Args, log: Log): void type Args = { /** Address of the account */ account: Address /** Whether the account is allowed */ allowed: boolean /** ID of the policy */ policyId: bigint /** Address that updated the whitelist */ updater: Address } ``` Callback to invoke when a whitelist is updated. ### args (optional) - **Type:** `object` ```ts type Args = { /** Filter by policy ID */ policyId?: bigint | bigint[] | null /** Filter by updater address */ updater?: Address | Address[] | null /** Filter by account address */ account?: Address | Address[] | null } ``` Optional filter arguments for the watch. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `function` ```ts declare function onError(error: Error): void ``` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Enable polling mode. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`policy.watchWhitelistUpdated`](https://viem.sh/tempo/actions/policy.watchWhitelistUpdated) ================================================ FILE: site/tempo/actions/reward.claim.md ================================================ # `reward.claim` Claims accumulated rewards for the caller. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"63fa687fe50fa183122469b6de0ff02764948fafd9737817ff79121a442b3050","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinKQwvDCMWGipACpDwsOCYABKaxtbpVAQvAgGO/gwnGj7cIdCK2ebDKLa+gAc/VqylUGhaOj0eFW6y+XQsVgAzANHM5Rn8JtQvNNfHNqAEmKx2FwjEdTOUpGNZED6qDqK0IQZiSZYT1EIiQPZkSMkAAmRrozBTAwzPy4hYGfKEj4Ad0kUFKZP0vWsNQUwIazVp4MCqxlpDl8jhSDZHKGKKNlX5mKF2NKNDFIASAFcwPwjtE5OIWABlDAugA8GUSyQAfEEOslUoGshROFhHMw9GQ4KlGcIAHQ62Vp3ge72+3hpgAK8cTpDgAeKSmDEVShdIEGYjDgMD9Oc9zB9LrTpzQjtIYAAaqFHTBg7kwOIE3A4+t3e3O7xLtdbiA0rnmHBOE5eI7mI6PTQoNLZZuEuwtx9eJtGIouOIwEeZYw0Kfz+HSMxxMYwGnbeIlLcyDICAdCTlgCil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gKkJBA1Dlt5unK4MNKcd7AYDCXALfBAAkKXLnJcTdN+HcZMfCMTDMX0H4ZqBTNQJCd+FiWoAaCyHnoMAXkgBDACbSEoKUCFngIsRMfoNyEzJ9GqEgLYMCT7HSW6A4NiakA1L0H5pUAzI0OoH8NINYOIInLwLAAkAqWScqaqeqZqdqTALqYqQaWqRqVqTqXqUqSqZacaTqXrJSPnobEXs9DELAPiDjOJLdJJOxDJLmtxDYlZBAMJPBGJLjMkGxNJERMRGmLHujCpLNqjJwIhLsVsGxOlJlDwH6blPlIVPOPmCVOjGVC5ELLVCRBLM1LLLWXWdYH1LkHFIFh9nYXsNdIcVTrKXDhmY9ISYcQyQNKUJtOIEgKAAEIoLHEIHgC+CAK4K4EAA=="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { receipt } = await Actions.reward.claimSync(config, { token: '0x20c0000000000000000000000000000000000000', }) console.log('Transaction hash:', receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `reward.claim` action and wait for inclusion manually: ```ts import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.reward.claim(config, { token: '0x20c0000000000000000000000000000000000000', }) const receipt = await waitForTransactionReceipt(config, { hash }) ``` ## Return Type ```ts type ReturnType = { /** Transaction receipt */ receipt: TransactionReceipt } ``` ## Parameters ### token - **Type:** `Address` Address of the TIP-20 token. ## Viem - [`reward.claim`](https://viem.sh/tempo/actions/reward.claim) ================================================ FILE: site/tempo/actions/reward.distribute.md ================================================ # `reward.distribute` Distributes tokens to opted-in holders. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"h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EVZc6gwYgVQX+Qg6qRM8AAa3BwauG+GYu0QQQHEW61J88tJSsYA6gjGQOPYsQvGi5GOxp9yi5HEQmYw0Q/wHE8OtmcgG8QQkWbYGZcekgR2PBqQo6mG45X+cg/wxOlEx6c5xytJ7J70hm64IOFsYO/Jlm1y3BJ5dmL575aA0FwIbYkQLmTOesLOvhwg1ii4sRt4URipfRnO6Yz8Qxke5Q+FVwcJmh7ahQJFOk94n6kZPSIhquYoVFiAIxVFZFYZlFn4hQNFOepGPS6CMo92T2SEL5b57AJOn52m35tGAOf5QOAFoOaAZmEOFm0OolCOEmUF4llEsF8FOOcsBORERO2lpOBJGsbkFgmkbIRA1g/wTodleoYpKKkp0g4kfKSA6KgqBgHOmSzoqpVUGivioEZKq0+iBckSOkXSq4wZVkBgbCEVNMv0Z4k0EpHll+MpvE2KgQEVvlWK4qxKmimp1I5YVAbBeAPlzlHlTovKuUSArosqhg6SUSnAr87KhoIqU0/o/Y+V6prg4i6YsAyUfSic6UuwgowcQKYcgmrcEAccvsCc/S3oy241qckozAc1w1hcZYgKooYo/wQpRcoKBc3IEV5QQkZA5QPC2k9sJcj8R8r0JUZ840UA30LMV8/09Mt8Rc5Qw86+TVOkuKOQYorVGoICo8wqkCzKrKbVMNBoyCK8G89uVRnO3A/1LF5QEVG8bIYM4gSAoAAQ3MSQQqCArgrgQAA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { parseEther } from 'viem' import { config } from './config' const { amount, funder, receipt } = await Actions.reward.distributeSync(config, { amount: parseEther('1000'), token: '0x20c0000000000000000000000000000000000000', }) console.log('Amount:', amount) // @log: Amount: 1000000000000000000000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `reward.distribute` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { parseEther } from 'viem' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.reward.distribute(config, { amount: parseEther('1000'), token: '0x20c0000000000000000000000000000000000000', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args: { funder, amount } } = viem_Actions.reward.distribute.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Total amount distributed */ amount: bigint /** Address that funded the distribution */ funder: Address /** Transaction receipt */ receipt: TransactionReceipt } ``` ## Parameters ### amount - **Type:** `bigint` The amount of tokens to distribute. Must be greater than 0. ### token - **Type:** `Address` Address of the TIP-20 token. ## Viem - [`reward.distribute`](https://viem.sh/tempo/actions/reward.distribute) ================================================ FILE: site/tempo/actions/reward.getUserRewardInfo.md ================================================ # `reward.getUserRewardInfo` Gets reward information for a specific account. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"2817cf8eb4e4b47b5f84b40187d076c43f7a53bee576d8d38d3d92985fa42e8f","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinKQwAO6SUABCoeJgvDCpAEbJFgyi2voAHP21yqp9AMwtOnp4qxuk27v7uPIWVmeIHsjmcoyuE2oXmmvjm1ACi1iK3WmwACmQACoQADWimOpzA5zKlxkzTu9T6lRebXeKK+6NIWNxYC6AKQQJBQzBSAATI9IZgpgYZn54QsDEsuB9NgAlGC8RhYRiKNCpAAG1loABJgGJSBYlK41aVylJEL1ejz5HUHuaAKzUt4GaVfOUKpUq1k9RAcwbDFw+8YeKFCnyzUo0cUgfLsLh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EWgNBk8FdiGCfK6DSmywcOJiBhg10FkBIA9owLmZYjKQOInsFhAjjUirmvA0uAGHvICCjIQgx8CILab9g7QaYFgTYGfa9MsId4Y9HYhpF7k7QVwawGYkaDSB+yio5UeYjVH5NVBXAipr6EnL8Dk4MQWAEwFqqpRz4i4ESIFFqjZQ8seUETLNDKhOQLRGsGqHVFCjvhMmWQNqJ3wtFbsfgBwaOFuHZHMhgxsoZcheUyg9R1o4gb6L9CtGYQtwOENAHhHzggw9wYMLqBDHWh4x/4q5YmLQFGbjNJm0zWZvM0WY8hlmqzdZps22a7N9mhzY5qc3OZHAZY+0KGNSKJjwxEYygvsf2IxjtjxoT0IxoYJfyyCBmK5VUAGQbBnkpxcsaHqllkHcod2abRct8HkEJxdhPpWQSvD0R4gZxbIqkcyDlilBTY4gJAKAACCKAakQgPAPZBACuBXAQAA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { rewardBalance, rewardPerToken, rewardRecipient } = await Actions.reward.getUserRewardInfo(config, { account: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) console.log('Reward recipient:', rewardRecipient) // @log: Reward recipient: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb console.log('Reward balance:', rewardBalance) // @log: Reward balance: 1000000000000000000n console.log('Reward per token:', rewardPerToken) // @log: Reward per token: 385802469135802469135n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = { /** Accumulated reward balance claimable by the account */ rewardBalance: bigint /** Reward per token checkpoint for the account */ rewardPerToken: bigint /** Current reward recipient address (zero address if opted out) */ rewardRecipient: Address } ``` ## Parameters ### account - **Type:** `Address` Address of the account to get reward info for. ### token - **Type:** `Address` Address of the TIP-20 token. ## Viem - [`reward.getUserRewardInfo`](https://viem.sh/tempo/actions/reward.getUserRewardInfo) ================================================ FILE: site/tempo/actions/reward.setRecipient.md ================================================ # `reward.setRecipient` Sets or changes the reward recipient for a token holder. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"fbddd9bb5f6273cdad3f5a5527a9ec016a6ae4f6251d0c70ea8374e2f635bb69","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinIRysKSpAAbWtAAkwGKkFkqum6VQELwIBgAq+DCcaBAA1oorEGtknOJQUKTwcE4AHdCJw4HpHvdGKROP8gZIoLCYLxGFhGIoGKJtPoABz9WrKVRIZrUVp6aYfdZdCxWADMA0czlGOIm1C8FNmpRoCwMSy4/14MFRaFSNyGwmGgjAACVkUKsJiQBcrng7g80OK4JKhEjBcLSuUpIgcbICfUNC0dOSDAL5YrunSGUMmX1GqzMFMDDM/NQAotYrrUeiwCLONs9gcNcdTudLtcQGqkfDSIiBUGMd9fv84ICggAvMgQTN/AGcCxQRi8cQ0QEQBUAWggAFc0BEDdiZDj5HUiWNLW08Gm0RjqT1EPSQPZGSMkAAmACs7vZXt8c19PJA+XYXCMUtMhv0vV6XbNvZq2gHBl3JlHjsng2GLkQlUXHjZnp8nPmgS3hThCPbCo+lnEkFEJBoSQva0QH/FNbyQCcp2dGdEHnWklw/b0125QIEibMB+ClME9FlFFhxDABlDACIAHgyRJkgAPiCDpklSeisgoTgsEcZg9DIOBUmvYQADpYKgETwTQUj00o6jeBEgAFXj+NIOA6OKJRGIiVJFNICBmEYcEaKkmTyLQKiCJE2U0CbUgwAANVCJsYEY3IwHEPi4B4wViOk5FZIs+TYxVAwKL0WsYSnZR4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0HoyVH/N4yi382S2Esy3tbrbZbNgcyPC8z/W2ziyg26nNSqadSurWnI2CymbmyypWzx32zapuaYQjMHh+a2z+zcnByygLBBRRzxzJzPZrAumFnxxegahXEVyBn5mzAaRFEILKjjRtE6jsIGigYVFQxwxzzX6TgzhrzQoExD0EpH3ixsxcwCx9I/3SxyxKwS0z0Gwx0SXcjxxyFlmL21zBx5Zfz5Bz2+xL3NE3QYLPEaoZmtC5mEU/yEJKglyFEbADyDAzJNZUgiESEyEKEqEaE6EGFsdmF5xWF2FOFuFeF+FBFhFRFxFz4jx/nRhb414YhYAmBFq9oeAJ5XpjpZpytzp5N0Z7puoZPK4jp3oTo5oRJ0iQYAY02ZPjzSAuIp4FQzPkOMwpoRYxZZOLMe5xJJISIrO5ICJlYQZVZCZH245aPSFyFKFqFaF6FGE2OOOOEuEeE+EBEhERExEbZc4OYvFfPLFk5bF0v0vEv84/GoWf9NnHyEyRotnSB8c9af8qO8FEzH38dShW5xAkBQAAhFAOkhBPEEBXBXAgA=="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { holder, receipt, recipient } = await Actions.reward.setRecipientSync(config, { recipient: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) console.log('Holder:', holder) // @log: Holder: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 console.log('Recipient:', recipient) // @log: Recipient: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Opt Out of Rewards Set `recipient` to the zero address to opt out from rewards distribution: ```ts twoslash // @twoslash-cache: {"v":1,"hash":"352385a25dd040388468da70eb96fdefa557efcc59a10ea4590405622b87794e","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcV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kM9xIANvT4i8RJvIunwGCEYSRHRtHbRK1ogd8dGdKI8Oo70/R7PUSDo3C7TWhcBNE4MwwuIToKU4SPizLTZLBFgjo4BwGBRHWabeqk2QgFF00m6bZujYbwIVH0A0YpCQtjEcmMIt5DYS1YiOYtLpOIANCveMS7w0KrQTqxAmuYFEPUdmABtG7QQ0jebyem5bPPW6joIDUjUJIDFTvwtQvVgO7ee3CTOK+64sMxLAXzHrhrnCFBhFvu+JGIUJmFHmBXPJC3MHvqqSH0VRMbOTwTf3dWUBaimOM+tSAX0UFsm6z5aD9bQKc72bc0hdHfUfoNw272f437+ZpQXeISCgAEihwGseBjiAriuEAA"} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' await Actions.reward.setRecipientSync(config, { recipient: '0x0000000000000000000000000000000000000000', token: '0x20c0000000000000000000000000000000000000', }) ``` ### Delegate Rewards Set `recipient` to another address to delegate your rewards to them: ```ts twoslash // @twoslash-cache: {"v":1,"hash":"47f5abecdba9b37d942876b7098a742d3423c65e8a06c57e478266e3647d4535","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70TKzsXEaCwqXlUojqsrXKqhotOnp4qyZdFlYAzAOOzqONE9Re075z1AGLBVykMADukigG20+gAHDUFPsGs1qK0TgZfgDSED5JckDcQPY7iM+pUnpgpgYZn4PgsDAkAK5gfhrThwPQAJRgvEYWEYijQAGUMNSADwZRLJAB8QQ6yVSAqyFE4WEczD0ZDgqTOwgAdIjAar6WgmSy2RzudTVQAFOUK0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QFgOsHNMA5lSgXXEEgUAARFBwDWHgMcIBXCuCAA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' await Actions.reward.setRecipientSync(config, { recipient: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC', token: '0x20c0000000000000000000000000000000000000', }) ``` ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `reward.setRecipient` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.reward.setRecipient(config, { recipient: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args: { holder, recipient } } = viem_Actions.reward.setRecipient.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Token holder address who set their reward recipient */ holder: Address /** Transaction receipt */ receipt: TransactionReceipt /** Reward recipient address (zero address indicates opt-out) */ recipient: Address } ``` ::: tip Rewards are automatically distributed to the current recipient before changing. This happens during any balance-changing operation (transfers, mints, burns). ::: ## Parameters ### recipient - **Type:** `Address` The reward recipient address. Use zero address to opt out of rewards. ### token - **Type:** `Address` The TIP20 token address. ## Viem - [`reward.setRecipient`](https://viem.sh/tempo/actions/reward.setRecipient) ================================================ FILE: site/tempo/actions/reward.watchRewardDistributed.md ================================================ # `reward.watchRewardDistributed` Watches for reward distributed events. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"468089c03999f8f886d48f18ae80edff227a04649f0e95be6e2f75637d974e5d","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJ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JuJEI+JMJNImIfxWJ7kLpoIkYeI0w2CsgRJHcdybyQQwp2Ioo1RYowF3YW4/RUphZ0pjIm4CwIEUp1pfYBowzvJlIBkiMJ5VpwTNoGp+y8pEJCpipSoap2KOL2L6ptpBtqsQ5AJSAbMspIJcx5FchEL7APJShXpxAkBQAAhFAJEhA8ALwQBXBXAgA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.reward.watchRewardDistributed(config, { onRewardDistributed(args, log) { console.log('args:', args) }, token: '0x20c0000000000000000000000000000000000000', }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `() => void` Returns a function to unsubscribe from the event. ## Parameters ### onRewardDistributed - **Type:** `function` ```ts declare function onRewardDistributed(args: Args, log: Log): void type Args = { /** Total amount distributed */ amount: bigint /** Address that funded the distribution */ funder: Address } ``` Callback to invoke when a reward is distributed. ### token - **Type:** `Address` Address of the TIP-20 token to watch. ### args (optional) - **Type:** `object` ```ts type Args = { /** Filter by funder address */ funder?: Address | Address[] } ``` Optional filters to narrow down events by funder address. ## Viem - [`reward.watchRewardDistributed`](https://viem.sh/tempo/actions/reward.watchRewardDistributed) ================================================ FILE: site/tempo/actions/reward.watchRewardRecipientSet.md ================================================ # `reward.watchRewardRecipientSet` Watches for reward recipient set events when token holders change their reward recipient. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"7c5c4a80757b69fb0cc9e78c15e065ab4f7f1e8dca7ffc4ca8ae3da467de30df","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHN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uzL7TRRCjTKSs7kbzxrSwlbQNTDl5SISFTFSlQ1TcU8XcX1Q7RDbVYRyASkA2ZZSQQ5jXy5APn2AeSlBvTiBICgABCKBm5CB4AXggCuCuBAA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.reward.watchRewardRecipientSet(config, { onRewardRecipientSet(args, log) { console.log('args:', args) }, token: '0x20c0000000000000000000000000000000000000', }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `() => void` Returns a function to unsubscribe from the event. ## Parameters ### onRewardRecipientSet - **Type:** `function` ```ts declare function onRewardRecipientSet(args: Args, log: Log): void type Args = { /** Token holder address who set their reward recipient */ holder: Address /** New reward recipient address (zero address indicates opt-out) */ recipient: Address } ``` Callback to invoke when a reward recipient is set. ### token - **Type:** `Address` Address of the TIP-20 token to watch. ### args (optional) - **Type:** `object` ```ts type Args = { /** Filter events by holder address */ holder?: Address /** Filter events by recipient address */ recipient?: Address } ``` Optional filters for the event. ## Viem - [`reward.watchRewardRecipientSet`](https://viem.sh/tempo/actions/reward.watchRewardRecipientSet) ================================================ FILE: site/tempo/actions/token.approve.md ================================================ # `token.approve` Approves a spender to transfer TIP-20 tokens on behalf of the caller. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"ac90d56fef4b8b0bb0fdd99d1f3d9e38719b2c463becd75cdc590e023c1e0813","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScAGYArmD8gmCcWJJwMACqYIxocEFEobEwiJxipBZKFJywvCyhcCVgscwARmQRJS2MShZoADrZrOxcqaTpWTmmUBC8CAYAs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hhZiFVvLrVvhcrqrs1urm1lrgJfRb1gJcJWgGpXCAGJENCMHubKHtvMIDoktBEf+DsbCZ8TqAWL/JwFXonlUFZScHqUuaiA5ctIBL3tlpCckZHoqK5YgEiq5U5WyQ2NZe5Tfs5v0LaX0VvLzgLvxdSEJewM7mgKJRVuJbLtVlJQFjJQ7GrtGe1nFkpfrqlqpUlXTBpVpdbizPbn8I7mVWcDrKyF8gbN7juCyEQNYFCP8F1daMmQmmmfqDYjaj6JRGmngGRgWcSm6oZKhJ6kokyoWhuIZW+NtEeP9FQgdNtN0veLtFzNTCtR+I1amUZP+MmlYnarmTQjBBSnBFNS4jShRNkuZAWr6gYH4v6mykEhQntEkAABLhD4DNStQdT+FKA9TbV4D/UkgbJ8l/rrXUwWppnmJZk+gAQ5nCKDx7VnBQ1qCpJ3WcRyIKRPVNUsi5HjVl6I1GTqBDVxJIC2CLUGC7VUIMkkglCtT/D6jGT/i9jqBtjSDWDiAtC8CwDRAc1c08180C1C0i1i26jc28382C3C1yyy3y2S1K0i2TVTjsT3WGQKIcIFiwBMCAoZxRTZwewKj16Fxxa9xpwm2ihkrm25yW3XJ22GK2x5Tgp5xQjxk1wwqhGihXVcAygHxHxcBm3nxaRXy3TiL3R3w1wPzfx9rWWO06iAhQj/hIq9jLwDSOrcpKj8qCrCqiriqSrSqyryqKrKqqoapao6p6oGrGqmpfwbSxRgCvytThqxrd0922gt0gJbzeXwmKhM37UOCs1IpB0xTw3Y0A2bwsi4LiBICgABBQxJB4DMiuCuBAA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { config } from './config' const { receipt } = await Actions.token.approveSync(config, { amount: parseUnits('10.5', 6), spender: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) console.log('Transaction hash:', receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.approve` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.token.approve(config, { amount: parseUnits('10.5', 6), spender: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args } = viem_Actions.token.approve.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Address of the token owner */ owner: Address /** Address of the spender */ spender: Address /** Amount of tokens approved */ amount: bigint /** Transaction receipt */ receipt: TransactionReceipt } ``` ## Parameters ### amount - **Type:** `bigint` Amount of tokens to approve. ### spender - **Type:** `Address` Address of the spender. ### token - **Type:** `Address | bigint` Address or ID of the TIP-20 token. ## Viem - [`token.approve`](https://viem.sh/tempo/actions/token.approve) ================================================ FILE: site/tempo/actions/token.burn.md ================================================ # `token.burn` Burns TIP-20 tokens from the caller's balance. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"e5eb311ca3488bbee0e7931eefae4e3f14d1d9b3f00dad2aa580098254b3ae39","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScAGYArmD8gmCcWJJwMACqYIxocEFEobEwiJxipBZKFJywvCyhcCVgscwARmQRJS2MShZoADrZrOxcqaTpWTmmUBC8CAYAsrFyAljm8JzipWjlypykMFj76WASxskQ0RucTa1knC0YVz0kyXRsliecF/fhMJwAjNZOEFA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skyC/IqQQSAqaTMR8m6S8Jfm/w9RHhfyozDQ9SYqTjSA4piTvhII8LdR/iGUJjGU4LYRUpaQ0r8kGAyJygQqKIHQOX2wAAS4Q+ARUJU5UKBSg1UUSsweACVJIWS4MX0Kc38ZwLl9+0g7JTyb4T4Xl0ksVZwOVagJi7J5KKkwkwVrISgLIzBeABl6lOlWiuiPotgtKwqtVmSDgJIJQJU/w+oakrC6gbY0g1g4gLQvAsA0Q01s1vY81i1y1q1FMG1uoc1C1S1K1a1B1R1O1p1FMflD4AV8YeCkCBYsATASytsvkUojsmyxseGCc1sr1ooHyH1csWyqoYSQsDC3QGyzsioUIpJAcuyWBooPl+4sszcrcXA71XcskQUIUi0vAA8AcQ89URiLUgNOogIUIj4xyvYZcycRK888K1giKaKLNrNNoK8YA1c2xAFuOOofUA0hk41SVxyyNaA/ko1Qg9VNcLI984gSAoAAQigyqQgeAzIrgrgQAA=="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { config } from './config' const { receipt } = await Actions.token.burnSync(config, { amount: parseUnits('10.5', 6), token: '0x20c0000000000000000000000000000000000000', }) console.log('Transaction hash:', receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.burn` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.token.burn(config, { amount: parseUnits('10.5', 6), token: '0x20c0000000000000000000000000000000000000', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args } = viem_Actions.token.burn.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Amount of tokens burned */ amount: bigint /** Address tokens were burned from */ from: Address /** Transaction receipt */ receipt: TransactionReceipt } ``` ## Parameters ### amount - **Type:** `bigint` Amount of tokens to burn. ### memo (optional) - **Type:** `Hex` Memo to include in the transfer. ### token - **Type:** `Address | bigint` Address or ID of the TIP-20 token. ## Viem - [`token.burn`](https://viem.sh/tempo/actions/token.burn) ================================================ FILE: site/tempo/actions/token.burnBlocked.md ================================================ # `token.burnBlocked` Burns TIP-20 tokens from a blocked address. Requires the `BURN_BLOCKED` role. [Learn more about token roles](https://docs.tempo.xyz/protocol/tip403/spec) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"4c6f4c6c8a9a3012b0d32258ab141ad46f5a27fb53da72d2d92aecbf86789fa0","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScAGYArmD8gmCcWJJwMACqYIxocEFEobEwiJxipBZKFJywvCyhcCVgscwARmQRJS2MShZoADrZrOxcqaTpWTmmUBC8CAYAsrFyAljm8JzipWjlypykMFj76WASxskQ0RucTa1knC0YVz0kyXRsliecF/fhMJwAjNZOEFAW8hIo0BEAHQDAYAWk4ABEZg1OPg0GgsA0APTYoiMGDMKFwfDY6azbGxATmATwbGjcbZXKUajiJRzZDIEB0cSsBQslhsDicYApNKZJlwTiuGKkCDMTgAcnxhMVsLADIlkyCioALAAmayKqrSCIDXGcA3Wa0221gEAAXQdom0+l1mjMihUakQgK0kl0gU1E2Z8gsVn+dgcpCcNHIiGk7k8ODwhBI5H89DwITCkU4vBMXALYGi3RKAGEhKWlANBcN81XuiyxJJ9AAOSOe5SqJAANn9Oj0eGL1ZZ5ksSH1UccznjiY81C8qd8GeoAWHhb2MF4MEYWDQJQAKjHhLGkgAlbe7/c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Qa1BAlMz9VOEFI7qDBTkWQUi8BhquqjJ1BergIfQsyCUDANrKY38SQSgup/h9RjJDF1A2xpBrBxAWheBYBogmaWbew2aOauaebOZ+bdRWb2bObubebxbJbhaZbOYRqfVrr4xuEiECxYAmBbkA4EopQQ4Xk3Z/MS4/YdbRQkV9bDZXlVRilVZZFuhnkw5FQoRwzk4PlvDRQzquAZRx5J4uA9akog154GEzoLoEg15k4N5D5q1zKLadRAQoR/w/lewu5RoyVr5aAaV9Q6UGUmUWU2UOUuUeU+UBUhURUxUJUpUZV5UWgD5L4g0M6HU3Vm6W7bQ6775B4oiTKabUEHB6a/kvakpkazhUaB4WQIFxAkBQAAhFBm0hA8BmRXBXAgA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { config } from './config' const { receipt } = await Actions.token.burnBlockedSync(config, { amount: parseUnits('10.5', 6), from: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) console.log('Transaction hash:', receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.burnBlocked` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.token.burnBlocked(config, { amount: parseUnits('10.5', 6), from: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args } = viem_Actions.token.burnBlocked.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Amount of tokens burned */ amount: bigint /** Address tokens were burned from */ from: Address /** Transaction receipt */ receipt: TransactionReceipt } ``` ## Parameters ### amount - **Type:** `bigint` Amount of tokens to burn. ### from - **Type:** `Address` Address to burn tokens from. ### token - **Type:** `Address | bigint` Address or ID of the TIP-20 token. ## Viem - [`token.burnBlocked`](https://viem.sh/tempo/actions/token.burnBlocked) ================================================ FILE: site/tempo/actions/token.changeTransferPolicy.md ================================================ # `token.changeTransferPolicy` Changes the transfer policy for a TIP-20 token. Requires the default admin role. [Learn more about transfer policies](https://docs.tempo.xyz/protocol/tip403/spec) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"782fbb9e3637fb97aaa75c17e78a39fa8f7ff7754db53d7b3ab76722d9c43fad","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinKQwvDCMWGipACpDwsOCYABKaxtbpeVSiAAc/bXKqhotOnp4q+ubDPIWVgDMA0czlGNwm1C8018c2oASYrHYXCMR1MV300lkD3qz2orTeBiRJi6vyQAJA9iBIyQACZGmDMFMDDM/DCFgZ8gjOGgIABrRSXbT6XrWGoKR4NACsLzaeC5vLARJ6iFJ5KGwJJlTpEMZUNKNFZIASAFcwPwjtEHMoYHtxMIEmQAAoQcy8DAAZQwJoAPBlEskAHxBDrJVI+rIUThYRzMPRkOCpAnCAB0ssUifJluttodTsYLvdJsT9qjMdIcG9xSUfoiqXtpAgzEYcBgnuAuU47c4hqwUHEI1SAANrLQACTAMSkCxKVz9gDcbY7lgA7o7nRgAJJQVIAI2SFjQc7AHZWZy+u32cEOQlOny2B9cftyYHE0bgkf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ElGKVo3oyiS9yBMTx+L+MDzbyBIeLZzBLAApnenLSrX7D2KOIWMhSWO/xWK7TWORTOU2MHQxR2MeT2InQ+UOPYG3WOLpN7FOJ0BDjEiUQ3USEZLOzshaHvxQBcjwX6VKCIGsETF6DFO3mQITnbm+3uFNnTlJBwOtmCQILHndlBDIPpBLh1BnkWE+mVlPAImkhBhOBPAuGlOuCpHFEvnlKwJvgMANPNLMGJFuDVILj+D+Ffl9mZHLjwErmrjIEXgVgOBNIAAlwh8ABwhxRxPtlBpwoFwI8Bwy4BXEIAEg4JGJdoQyztT59AaRLYr4O57TqBjSztky1AfhFRCDBhiCkBKhegvSJAlBSgMc8AVSLS8y7hU4xQkAu5fSDBvwZIHAUzUghxeh0DKhrT1AbhpBrBxAtxeBYAEhxy/hJzGhpzZz5zFyDIVy1yNy5yFylzdypyZyDztyEgR4hQ3SSDXB9YYhYA4RY4jpgYzsOoypEpcMqpHl1oIAmoeVnzGZSoupyokpEx4CI5hpZdlhApHSuA4p/pAZEQTSxZl5IZUc7ZYYAJ4ZEYI5kZ5xB51xNxOBiZcZUZFB0YN5rAt4j4aLaL94cYXostwTAkvdByTSh8RzE9YLkxSyjhyystSh+ZxAkBQAAhFA8EhAZQEBXBXAgA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { receipt } = await Actions.token.changeTransferPolicySync(config, { policyId: 1n, token: '0x20c0000000000000000000000000000000000000', }) console.log('Transaction hash:', receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.changeTransferPolicy` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.token.changeTransferPolicy(config, { policyId: 1n, token: '0x20c0000000000000000000000000000000000000', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args } = viem_Actions.token.changeTransferPolicy.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** ID of the new transfer policy */ newPolicyId: bigint /** Transaction receipt */ receipt: TransactionReceipt /** Address that updated the policy */ updater: Address } ``` ## Parameters ### policyId - **Type:** `bigint` New transfer policy ID. ### token - **Type:** `Address | bigint` Address or ID of the TIP-20 token. ## Viem - [`token.changeTransferPolicy`](https://viem.sh/tempo/actions/token.changeTransferPolicy) ================================================ FILE: site/tempo/actions/token.create.md ================================================ # `token.create` Creates a new TIP-20 token, and assigns the admin role to the calling account. [Learn more](https://docs.tempo.xyz/protocol/tip20/overview) ## Usage Use the `token.create` action on the Wagmi `config` to create and deploy a new TIP-20 token. ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"bac950d77bf219845f78904458b22c83c87e562f6ef3fc715d1a2f1ce5643b37","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinOJQzBapAAbWtAAkwGKkFkqum6XlUogAHP21yqpIAKwtOnp4q+tgXRZWAMwDjmcoyuE2oXmmvjm1ACi1inFIMF4MEYWDQqQAKkNhMNBGAAEqI5Go0pQCC8BAGTHibH8XHwwkotAAOnO2n0Vyu8jqD0QNW0bTwCKRjO+PUQ/xA9kBIz6j1BmCmBhmfmhCwMSy4aAgAGtFFsdvtDsdTqyKjIagp7g1ntRWm8DFrdV95D8kBKpUMg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C4Bti2B7UtmdRa4VtbyGPB8ljzLInlTaH5V2p+HvbfQ22h/FsnCFHI9t2G0AgdguyMLDku2o7YgVOTxHrtICUvPIQtmXIjkJ2IAwkZOzX4OFB4IcHdkWzhElsrhRXE9u10x53VYRe7N8giK/LIiAKC0ZrDtBdpu0hA4FEFhsx9pIgf2iFZCoAgA4YVWKRCfDvhQeIQtQWZgFxDYLPDkdgQ6Q+8O0FopOhRIZ0cSEmGw5uhHgsSWFp821GHgLRBYKwX0BSFwcxwIDewSzEcFFI8AkHW0eKEaA4VMwNgVZCAEjBdxUglQEjtYJqSpC7Bn8GILACYCoZqY8cKKCLAZjix3sLMYmCbD5iQxMxk8emGLCxjYwmQRxLIPLGv7QwnEMEEKIyFBxOhWx+YemNHFjiNgE4u8JOKAlwjpxlYmcISGhxxh+CAhoicRJImkSyJ5EiiZRKonURaIdEeiAxEYhMTmJYwvcViMEhbhtxsYncHuKXFaa5xq4hcDIKwGapHidxfSdSAMirhpAbxfsfuHQ1pZ3ZEWyLedIu3bFgAncfPbGN4I2AmEnE/498QtmjE/i6orop3KUDXjiAkAoAAIIoE+RCA8As0EAK4FcBAA=="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { admin, receipt, token, tokenId } = await Actions.token.createSync(config, { admin: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', currency: 'USD', name: 'My Company USD', symbol: 'CUSD', }) console.log('Address:', token) // @log: Address: 0x20c0000000000000000000000000000000000004 console.log('Admin:', admin) // @log: Admin: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb console.log('ID:', tokenId) // @log: ID: 4n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.create` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.token.create(config, { admin: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', currency: 'USD', name: 'My Company USD', symbol: 'CUSD', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args: { token, tokenId } } = viem_Actions.token.create.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Address of the admin that was granted the admin role */ admin: Address /** Currency code of the token */ currency: string /** Name of the token */ name: string /** Address of the quote token */ quoteToken: Address /** Transaction receipt */ receipt: TransactionReceipt /** Symbol of the token */ symbol: string /** Address of the deployed TIP-20 token */ token: Address /** ID of the deployed TIP-20 token */ tokenId: bigint } ``` ## Parameters ### admin - **Type:** `Address` Admin address for the token. ### currency - **Type:** `string` Currency code for the token. ### name - **Type:** `string` Name of the token. ### quoteToken (optional) - **Type:** `Address | bigint` Quote token address or ID. ### symbol - **Type:** `string` Symbol of the token. ## Viem - [`token.create`](https://viem.sh/tempo/actions/token.create) ================================================ FILE: site/tempo/actions/token.getAllowance.md ================================================ # `token.getAllowance` Gets the amount of tokens that a spender is approved to transfer on behalf of an owner. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"39248a39ac64c814f65ae5d23e0ffb2fb9d2135d90759bdd100c74ba402498d5","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinKFyEADu4mC8MKkARskWDKLa+uqytcqqMi06enirG1s7XRZWAMwDjs6jjRPUXmmvjm1ACTFY7C4RkEwlK5SkYxqCiuDRq2jaeGhJleP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0JEzkJgZEqEEOGEx6okEABEVGVMraJU345E/4AEAYjx90DEg5ywbFLa7E4gDkTk+orky4HkaAelNkPk90IsSkdiZ5YUtA6glQJIUA7wPIaQvAjQjQ7wlQaQvIio0g6y4g7wew+06lAAQrwNIDAOoDyNIDyAkNYHsHNnsHsGlEpEUhkfleoIntIOcNNWkJDPtL0MVbwO8NwNYKwmkOoFABtXsBsjANYFAL0NtbwOcGkPtGNfxG5ElLQAuLwMZQ9Y9U9c9S9Q9WNaZGUROTuelexY4TFTsBlKUI1OIEgKAAEIoM7EIHgBeCAK4K4EAA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const allowance = await Actions.token.getAllowance(config, { account: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', spender: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8', token: '0x20c0000000000000000000000000000000000000', }) console.log('Allowance:', allowance) // @log: Allowance: 10500000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = bigint // Allowance amount ``` ## Parameters ### account - **Type:** `Address` Account address. ### spender - **Type:** `Address` Address of the spender. ### token - **Type:** `Address | bigint` Address or ID of the TIP20 token. ## Viem - [`token.getAllowance`](https://viem.sh/tempo/actions/token.getAllowance) ================================================ FILE: site/tempo/actions/token.getBalance.md ================================================ # `token.getBalance` Gets the token balance of an address. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"be2aaf71065dae41e98187e9334b07b0203145c233743016fbab053ac04a5f67","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZ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ENDELACCNdBRJ5CYFRDRBNthFBDJBACRGevjC6nlH+NRBhEBD6M0VkKxGGcsO+S2C5G5B5DqN5LOH5GgNhcaIFGdJzJpIYhTFFDFOoJUMSFAC8HCGkLwI0I0C8JUGkNYHCJotIMSHCOIC8CsGkpUJUPqLwNIDAOoHCNIHCAkNYCsNFisCsAlIpC4sBDFFOLwARVFdFTFbFXFVFcFWAElLWWJfynGUpVsIgMwRJTALzqUEXOIEgKAAEIoGbEILBQgK4K4EAA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const balance = await Actions.token.getBalance(config, { account: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) console.log('Balance:', balance) // @log: Balance: 10500000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = bigint // Balance amount ``` ## Parameters ### account - **Type:** `Address` Account address. ### token - **Type:** `Address | bigint` Address or ID of the TIP20 token. ## Viem - [`token.getBalance`](https://viem.sh/tempo/actions/token.getBalance) ================================================ FILE: site/tempo/actions/token.getMetadata.md ================================================ # `token.getMetadata` Gets the metadata for a TIP-20 token, including name, symbol, decimals, currency, and total supply. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"17796bba722c896e3ea092096ebfba46eb5bcfc91851eb26e942755800833739","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinMx64lDiEqnAuZx70QCupKSKvBipYqQWSg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sGzkIfLDSAAD0ZKQ8AcPFsq5QOuq1ZAZkVPg5d4AGYYruglCHKg1gG8n8rV0gRwQSUU9GwfPbBkQjoRsI2EdfCSGPwuwqRa4FrgxBYA7YdeFjFNhDR7oeMZ6AZlhg/QeYEANGA9QA6hTcYUMF6ORFkJZAKYwg+sfrENjIMTYFONlNZ27hVwJAdsJeA7EFgWwXYiIcaLwHCP9GBjgx/o57HVgo7FNcFJA+cEXz1i+C8Kn2JZPUymdkV+naYzbHIhoH5j8yl6Nwv3qrGe45EeqJsfE0a6NVexlowxHVWcgjjim/w78hsNTG8IMx6wxRx9ilBK4SAUAAEEUAB4hAeAXaCAFcCuAgAA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const metadata = await Actions.token.getMetadata(config, { token: '0x20c0000000000000000000000000000000000000', }) console.log('Currency:', metadata.currency) // @log: Currency: USD console.log('Decimals:', metadata.decimals) // @log: Decimals: 18 console.log('Name:', metadata.name) // @log: Name: United States Dollar console.log('Symbol:', metadata.symbol) // @log: Symbol: USD console.log('Total Supply:', metadata.totalSupply) // @log: Total Supply: 1000000000000000000000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = { currency: string decimals: number name: string paused?: boolean quoteToken?: Address supplyCap?: bigint symbol: string totalSupply: bigint transferPolicyId?: bigint } ``` ## Parameters ### token - **Type:** `Address | bigint` Address or ID of the TIP-20 token. ## Viem - [`token.getMetadata`](https://viem.sh/tempo/actions/token.getMetadata) ================================================ FILE: site/tempo/actions/token.grantRoles.md ================================================ # `token.grantRoles` Grants a role to an address. Requires the admin role for the role being granted. [Learn more about token roles](https://docs.tempo.xyz/protocol/tip403/spec) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"5e8451097f9633d21d3a3cdfc8f44501a3bb693043aa17e5311b84bfc53aca06","data":"N4Igdg9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iCjrkihigqi4SpDai6j6gExnxNn6B/CJiYLdhmKOiUS9mzwThCKJHljJGOIGBUKAI0Lbynaqjqh3k6gKB6ioLui9BtmjyphflBjhC4S/mxHjhlx/CDmkJ4ASBKClAR54A9kvnugGofkNCWggUgC4TMSAToqpACguhRFWC9D3D9nxGuDJwxCwBMAHQ1R0yq4nRLQ9QpZrTmogwQB7TVSzRGyLRnTLS9RfieFtz3Rd7LC1RhxfAPiTluSdRUw0xRghzuxKT/gsTATsycxtzcysiPywzIDyxHxKwqzSygICy0CQJIJ+X+UIIiwQz0LeXMKsLsKcLcK8L8KCLCKiLiKSIyJyIKJKIqJqKaKahBVgCEy27n7WmMUswsV/6GXIDWBGi8aYXqjqylAOziBICgABCKCpJCBEUICuCuBAA=="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { receipt, value } = await Actions.token.grantRolesSync(config, { roles: ['issuer'], token: '0x20c0000000000000000000000000000000000000', to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', }) console.log('Role granted:', value[0].hasRole) // @log: Role granted: true ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.grantRoles` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.token.grantRoles(config, { roles: ['issuer'], token: '0x20c0000000000000000000000000000000000000', to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', }) const receipt = await waitForTransactionReceipt(config, { hash }) const events = viem_Actions.token.grantRoles.extractEvents(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Transaction receipt */ receipt: TransactionReceipt /** Array of role membership update events */ value: readonly { /** Role identifier */ role: Hex /** Address that received the role */ account: Address /** Address that granted the role */ sender: Address /** Whether the role was granted (true) or revoked (false) */ hasRole: boolean }[] } ``` ## Parameters ### roles - **Type:** `("defaultAdmin" | "pause" | "unpause" | "issuer" | "burnBlocked")[]` Roles to grant. ### token - **Type:** `Address | bigint` Address or ID of the TIP20 token. ### to - **Type:** `Address` Address to grant the role to. ## Viem - [`token.grantRoles`](https://viem.sh/tempo/actions/token.grantRoles) ================================================ FILE: site/tempo/actions/token.hasRole.md ================================================ # `token.hasRole` Checks if an address has a specific role for a TIP-20 token. [Learn more about token roles](https://docs.tempo.xyz/protocol/tip403/spec) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"85a38813b3282ff4bd2875a74fa06ec2d675d0c901545edfa0dbfa76002d3c25","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinA5wAEoQCqkARhCbMOJgpeVSiOqytcqqGi06etPhGwpdFlYAzAOOzqONE9Re018c2oASYrHYXCMgmEx20+mkAFZ5HVrmdbm08FCTC8eogPiB7F8RkgAEwkv6YKYGGZ+EELAz5CGcNAQADWilhFT61nxCiuDSR1Fa9wMLPZR3kryQ+MJQ2+0usFIB1KBpRo9JACQArmB+NCVo99gAeDKJZIAPiCHWSqVNWQonCwjmYejIcFSWOEADoxYovasnjAvQAFZ2u0hwE3FJTmiKpYOkCDMRhwGBGz1wH1sv0B/ZetZ6LWkMAANVCWpg5tyYHELrgTt4MAN632pSgEF4CAMaXwMF4rLgnEYCU4h1HvBiOq4q1HnHrfeHjF4nETCk4CXYs4AKgBJYMk6zM7NgL1q8RKLvIZAgOi1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AK4K4EAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const hasRole = await Actions.token.hasRole(config, { account: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', role: 'issuer', token: '0x20c0000000000000000000000000000000000011', }) console.log('Has issuer role:', hasRole) // @log: Has issuer role: true ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type ```ts type ReturnType = boolean // Whether the account has the role ``` ## Parameters ### account - **Type:** `Address` Address to check for the role. ### role - **Type:** `"defaultAdmin" | "pause" | "unpause" | "issuer" | "burnBlocked"` Role to check. ### token - **Type:** `Address | bigint` Address or ID of the TIP-20 token. ## Viem - [`token.hasRole`](https://viem.sh/tempo/actions/token.hasRole) ================================================ FILE: site/tempo/actions/token.mint.md ================================================ # `token.mint` Mints new TIP-20 tokens to a recipient. Requires the `ISSUER` role. [Learn more about roles](https://docs.tempo.xyz/protocol/tip20/spec#role-based-access-control) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"46f1c80e43ab006ecc429ac40c2ea48df2c7b1c8e47b608bc34a4be0659f09aa","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScAGYArmD8gmCcWJJwMACqYIxocEFEobEwiJxipBZKFJywvCyhcCVgscwARmQRJS2MShZoADrZrOxcqaTpWTmmUBC8CAYAsrFyAljm8JzipWjlypykMFj76WASxskQ0RucTa1knC0YVz0kyXRsliecF/fhMJwAjNZOEFAW8hIo0BEAHQDAYAWk4ABEZg1OPg0GgsA0APTYoiMGDMKFwfDY6azbGxATmATwbGjcbZXKUajiJRzZDIEB0cSsBQslhsDicYApNKZJlwTiuGKkCDMT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P+G0TYTfBwgFUCE/Q9P+UwT+QgntXwRsRlTdI9g6j/CPA/hhgGk6k5XtN1FyqdPwgQW4RqpvHQSKu9JomwWwklS0mlWdQMGkTlAhQURynqstgAAlwh8B8pCoSoVClAKoolZg8AFqSQsk/pno45P4zhmrVJHweUxJmFOrpJZqzgdq1BeqXkbVsFhJhrWQlAWRnC8ACr0rVItEjUkAvSxqQBupepDIHASQShCp/h9Q1IWF1A2xpBrBxAWheBYBohobYbex4bEbkbUb8YMbdQ4aEakaUa0aCaiacbSb8ZCrobirfTXBwECxYAmAllzYfIpQZQtZNldYDMo5TZWbRQPkObxYFQtlVQwluZ6FugNlRaoQLSvZdktDRRuquAZRa564uB2a/JzU25go5pO4vZu4R4hdRKhadRAQoRHxjlewC5Y4IA55aAEV9QkUUU0UMVdQsUcU8UCUiUSUyVKVqVaV6VGUWU2Vh4Z5zUHa1UdUY7Y7bRw6l4CSFihKQajrMlwalrjkVa/Ibqkg7qy4WQb5xAkBQAAg9okg8BmRXBXAgA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { config } from './config' const { receipt } = await Actions.token.mintSync(config, { amount: parseUnits('10.5', 6), to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) console.log('Transaction hash:', receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.mint` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.token.mint(config, { amount: parseUnits('10.5', 6), to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args } = viem_Actions.token.mint.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Amount of tokens minted */ amount: bigint /** Transaction receipt */ receipt: TransactionReceipt /** Address tokens were minted to */ to: Address } ``` ## Parameters ### amount - **Type:** `bigint` Amount of tokens to mint. ### memo (optional) - **Type:** `Hex` Memo to include in the mint. ### to - **Type:** `Address` Address to mint tokens to. ### token - **Type:** `Address | bigint` Address or ID of the TIP-20 token. ## Viem - [`token.mint`](https://viem.sh/tempo/actions/token.mint) ================================================ FILE: site/tempo/actions/token.pause.md ================================================ # `token.pause` Pauses a TIP-20 token, preventing all transfers. Requires the `PAUSE` role. [Learn more about token roles](https://docs.tempo.xyz/protocol/tip403/spec) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"a6393fccb27fa70eaa319de7e39d7a619889bb2d3f5ab63be266ef0351e444c4","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinIxwAAriAK5wMFCpAEYQEAriYKXlUogAHP21yqpIVy06ekzrWztQXRZWAMwDjmcoyuE2oXmmvjm1ACi1inFIMF4MEYWDQqQAKkNhMNBGAAEqI5Go87afTSW4Ke4NGraNp4BFIlEMeQ/JD/ED2QEjPogjxgqYGGZ+aELAz5dhcIy40wXfS9ayyO71DTPOkGKUmb49RDszlDIFsxqgzACnyzUo0UUgcWFNAQADWihJFT6vRqlOViAArKrXgY7Y6ziztbrBsMXIhKpV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p6QZHaNFoilGPbnqXpCIs5tGIC/RFFNGc6p7c6jR9EdE6JdEg6vbA46r6oaRJFpEhGDJhHN4REOpRHTK5KxHuoLJeqVJJFrINKpHsAprpGnHGSZE6AawCTQKJqJAXH5YyRl4KRKRfZIilBEDWBti9A/Gxwz4mwuhlzyhL5UjOy2wvCBDcJFzb5hily8gH4QhH4ijtBwirCvifAHBHAnBBg8xAl/h/hPA5wNBEn5yBDolZhfCb4qgchwmyx/hGieyxi2xKClDdZ4DQmAmXD8xEmCwNC2Aol4BMrXiYkUSHhFyKg76lzyzcwxCwBMCpT6QXT5aZThQ5RrrRSVLdTJR6RBSaxZBhTZSORORtgT46wlQFHLAGQUlqK1h0z3y2QnRnSSiXT4zXRix3SQyPQDRhzORRzWAxwpxBnBmJy/SbRqbdEzo1pzrClix7ADE2mfBqalAjjiBICgABCKCLxCB4BEQgCuCuBAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { isPaused, receipt } = await Actions.token.pauseSync(config, { token: '0x20c0000000000000000000000000000000000000', }) console.log('Is paused:', isPaused) // @log: Is paused: true ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.pause` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.token.pause(config, { token: '0x20c0000000000000000000000000000000000000', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args } = viem_Actions.token.pause.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Whether the token is paused */ isPaused: boolean /** Transaction receipt */ receipt: TransactionReceipt /** Address that paused the token */ updater: Address } ``` ## Parameters ### token - **Type:** `Address | bigint` Address or ID of the TIP-20 token. ## Viem - [`token.pause`](https://viem.sh/tempo/actions/token.pause) ================================================ FILE: site/tempo/actions/token.renounceRoles.md ================================================ # `token.renounceRoles` Renounces one or more roles from the caller's address. [Learn more about token roles](https://docs.tempo.xyz/protocol/tip403/spec) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"30d2bdf2635250f6359f0da611ced8b75cdd1e915d48aa5fa8de4385cdfaa662","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinKQwvDCMWGipACpDwsOCYABKaxtbpeVSiAAc/bXKqhotOnp4q+ubDPIWVgDMA0czlGNwm1C8018c2oAUWsU4RFCAFcYKlVuIoEI5BhOMBcpwCSsIApUgADay0AAkwDEpAsSlcpIA3PjCU4YkiwNtOOSqTS0HTlIyWWBCZw4IpYKQyRTqbT6cLWQSHHBjsTUZwAEYQdXiMAi1zIAC6l20+mktge9SQAFYXm08Ii5Ciur8kACQPYgSM+uowZgpgYZn4YQsDPl2FwjEdTFd9L1rM0rU9EDVtA6DNGTK6eogPV6hsD3X9/RCg1DSjQwyAI4U0BAANaKU0VPq9SryOopu3UVpvAz1ptgHP/QGFn2ISq9UuBnyzSuwgwJTn8I4rRQQFcwNUKOAAZQwYF4AB4MolkgA+IIdZKpM9ZCicLCOZh6MhwVJZ4QAOkHim/qyQFuO7wAeR7fgACi+b6kHAp7FEoF4RKkEGkBAzCMBKx6AZuR7buq+6Hrw36nGgSKkGAABqyIwBeuRgOIr5wM+6zrkBeEgYRR6lJivAIAYpzsescCcOIRIKJwCTsKJnA7AAkhBABM1icH+YDfrkuQAHIQDQu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0BPlJ+mBJ0EbjckCWA0SCVJh1yhaBQJQGKikTwlKCIGsG/F6HNIgU4N7lbAJyTDQRTA9EwUCAaVEJngnFBCITLDnBDFrjhEdydBRDRG+kxDAGxERkBklnVBlD5DxwZGZCRnZHpJjLlAFAVATMjPFElHex5FlH5EFHjJFDFBVBAlSG1F1H1GJlPhtOuEUkaCvi7AaAwWzkdBojdOfm9FLgGykJ9JrkXGCF/n/i3lpxDKxAwG4FM3EAwGPB2AvHqUbNSDAGiMCmhDcIMAAHE9Aq1PIHSikIAEhLVJAhgMAVU5s1EZIlzmAVyIpLBlNkhx0VE/I1UDIlA/ZlgWMlpO0Y5EpfhwoLAelRJJyTykECFGh7TGykAkxnS8Bdz2zxCJxB4eyJAlBSh+cYLCMQLPt1An5YKbAyEBICI2JcJ1goBUhegp4Ex3TS5JDE4YhYAmAzUFozoVpLo1pJNNpcVwYIBDo6oFoDYWKroBpvxWDW4noHdlgGoQ4vhHxAzPIepaZ6Yowg5XY1IAINwOZdwuYeZW4+ZWQd4N9ZZD4FYlYJYdEhwhZQFrBwF4EbLbKYFxYVZidc9G9OIiKtxSK29ZL5z05VZSg7ZxAkBQAAhFApEhA8AXIQBXBXAgA"} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { receipt, value } = await Actions.token.renounceRolesSync(config, { roles: ['issuer'], token: '0x20c0000000000000000000000000000000000000', }) console.log('Roles renounced:', value.length) // @log: Roles renounced: 1 ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.renounceRoles` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.token.renounceRoles(config, { roles: ['issuer'], token: '0x20c0000000000000000000000000000000000000', }) const receipt = await waitForTransactionReceipt(config, { hash }) const events = viem_Actions.token.renounceRoles.extractEvents(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Transaction receipt */ receipt: TransactionReceipt /** Array of role membership update events */ value: readonly { /** Address that renounced the role */ account: Address /** Whether the role was granted (true) or revoked (false) */ hasRole: boolean /** Role identifier */ role: Hex /** Address that initiated the change */ sender: Address }[] } ``` ## Parameters ### roles - **Type:** `("defaultAdmin" | "pause" | "unpause" | "issuer" | "burnBlocked")[]` Roles to renounce. ### token - **Type:** `Address | bigint` Address or ID of the TIP-20 token. ## Viem - [`token.renounceRoles`](https://viem.sh/tempo/actions/token.renounceRoles) ================================================ FILE: site/tempo/actions/token.revokeRoles.md ================================================ # `token.revokeRoles` Revokes one or more roles from an address. Requires the admin role for each role being revoked. [Learn more about token roles](https://docs.tempo.xyz/protocol/tip403/spec) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"4331bbb216753b0e0d034449438e7597cb718b5c0bcc79635d29f21308e5a7b9","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinKQwvDCMWGipACpDwsOCYABKaxtbpeVSiAAc/bXKqhotOnp4q+ubDPIWVgDMA0czlGNwm1C8018c2oAUWsU4RFCAFcYKlVuIoEI5BhOMBcpwCSsIApUgADay0AAkwDEpAsSlcpIA3PjCU4YkiwNtOOSqTS0HTlIyWWBCZw4IpYKQyRTqbT6cLWQSHHBjsTUZwAEYQdXiMAi1zIAC6l20+mktge9SQAFYXm08Ii5Ciur8kACQPYgSM+uowZgpg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IrIwirGrLLPzP1MotYKorostStVoiNWAETPbpfraXhA5U2E5QAX+VhVnJrKUE7OIEgKAAEIoBkkIHgE5CAK4K4EAA"} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { receipt, value } = await Actions.token.revokeRolesSync(config, { from: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', roles: ['issuer'], token: '0x20c0000000000000000000000000000000000000', }) console.log('Roles revoked:', value.length) // @log: Roles revoked: 1 ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.revokeRoles` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.token.revokeRoles(config, { from: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', roles: ['issuer'], token: '0x20c0000000000000000000000000000000000000', }) const receipt = await waitForTransactionReceipt(config, { hash }) const events = viem_Actions.token.revokeRoles.extractEvents(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Transaction receipt */ receipt: TransactionReceipt /** Array of role membership update events */ value: readonly { /** Role identifier */ role: Hex /** Address that had role revoked */ account: Address /** Address that revoked the role */ sender: Address /** Whether the role was granted (true) or revoked (false) */ hasRole: boolean }[] } ``` ## Parameters ### from - **Type:** `Address` Address to revoke the role from. ### roles - **Type:** `("defaultAdmin" | "pause" | "unpause" | "issuer" | "burnBlocked")[]` Roles to revoke. ### token - **Type:** `Address | bigint` Address or ID of the TIP-20 token. ## Viem - [`token.revokeRoles`](https://viem.sh/tempo/actions/token.revokeRoles) ================================================ FILE: site/tempo/actions/token.setRoleAdmin.md ================================================ # `token.setRoleAdmin` Sets the admin role for another role. Requires the current admin role for the target role. [Learn more about token roles](https://docs.tempo.xyz/protocol/tip403/spec) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"d9c54665ca890ceb4e883643fe63cb29f5ad11e7649208e7a46fe48ce88991c9","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinKQwvDCMWGipACpDwsOCYABKaxtbpeVSiAAc/bXKqhotOnp4q+ubDPIWVgDMA0czlGNwm1C8018c2oASYrHYXCMR1MV300lkD3qz2orTeBiRJi6vyQAJA9iBIyQACZGmDMFMDDM/DCFgZ8gjOGgIABrRSXbT6XrWGoKR4NACsLzaeC5vLARJ6iFJ5KGwJJlTpEMZUNKNFZIASAFcwPwjpw4HpjhAFNwoMwLABlDAmgA8GUSyQAfEEOslUu6shROFhHMw9GQ4KkCcIAHSyxQxi1oK02u2O528GMABVD4dIcDdxSUnoiqSzpAg9otLqTKZgtvtYCdJpjpzQhtIYAAaqFDTBPbkwOIw3AQ+tzZbrfW002M6UoBBeAgDA69HBOfgYJxxDOVlPOAl2NvzTheIwkrw9wpOBZjzsAJJZqnWTk8hO5XIAOQgNF2+EY64AcecAZvgFaQIa66HEIG7iFwADu4iMGg66HqQG5bmg+xwNBYCvrkABGW4WLwciGrAUCcDB4icARciLtytEwGhW6rO2nYWEox6rKOJgwDGuriEoy7IMgIB0MOWAKKUAAGckobk7KFMA0SrHBMABskQb4GgaBYJwrgHhWzCcAA5AAAohSj2gA9DEqymYp8LKZyMDwgZRmVmZllCbZ9kwHZDgWHAjl5M5XAqdG66GQkxneVZfnsAFNDwqFuRLHERacAAvKpMDqZpShBMAuScNEQXCKkyApWwA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2YIbuXuROBmJmL7AACXCHwFSBkjujp1h04lcChksMwQMFzLgGCQgASA3CAkcyzKOELiNJuBFBDL6GXnDIMCbJwmZmrLUB+EVDYNXmbkqF6ETIkCUFKAZzwGtP9JJGsFNIYJsD4IMD2EZn7K+zCxrNSDul6AR0qHFEaHUHfmsHEAIl4EzkPL+GPNPPPMvOvOYlvPvLPOkAvKvJvKPJPPfM/OfISAbl6HuHYM1h1iFhiFgDhHtkimZmik8hMkY18gBRqggFCiUgigdmSA8lii8lMhjDIKtjSj+OWBUndK2A8lWnWkRDgp2jlH2mTEVhnGOlOitnOl+hnFTlMkzmzmWjzlBhemQTMhHjIAEuPkUBunPmsEvkflkrkrvlBnBh3xj3z1Mk3ObJggcD3JL3IrQDjC9IHLzLq1KHxnECQFAACEUE4SEBlAQFcFcCAA=="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { receipt } = await Actions.token.setRoleAdminSync(config, { adminRole: 'defaultAdmin', role: 'issuer', token: '0x20c0000000000000000000000000000000000000', }) console.log('Transaction hash:', receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.setRoleAdmin` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.token.setRoleAdmin(config, { adminRole: 'defaultAdmin', role: 'issuer', token: '0x20c0000000000000000000000000000000000000', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args } = viem_Actions.token.setRoleAdmin.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** New admin role identifier */ newAdminRole: Hex /** Transaction receipt */ receipt: TransactionReceipt /** Role identifier that had its admin updated */ role: Hex /** Address that updated the role admin */ sender: Address } ``` ## Parameters ### adminRole - **Type:** `"defaultAdmin" | "pause" | "unpause" | "issuer" | "burnBlocked"` New admin role. ### role - **Type:** `"defaultAdmin" | "pause" | "unpause" | "issuer" | "burnBlocked"` Role to set admin for. ### token - **Type:** `Address | bigint` Address or ID of the TIP20 token. ## Viem - [`token.setRoleAdmin`](https://viem.sh/tempo/actions/token.setRoleAdmin) ================================================ FILE: site/tempo/actions/token.setSupplyCap.md ================================================ # `token.setSupplyCap` Sets the supply cap for a TIP-20 token. Requires the default admin role. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"3425b57e63dd869d50e97fa72c6063375687c2cec9e58782eaf2d9e3f31e96b3","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScAGYArmD8gmCcWJJwMACqYIxocEFEobEwiJxipBZKFJywvCyhcCVgscwARmQRJS2MShZoADrZrOxcqaTpWTmmUBC8CAYAsrFyAljm8JzipWjlypykMFj76WASxskQ0RucTa1knC0YVz0kyXRsliecF/fhMJwAjNZOEFAW8hIo0BEAHQDAYAWk4ABEZg1OPg0GgsA0APTYoiMGDMKFwfDY6azbGxATmATwbGjcbZXKUajiJRzZDIEB0cSsBQslhsDicYApNKZJlwTiuGKkCDMTgAcnxhMVsLADIlkyCioALAAmayKqrSCIDXGcA3Wa0221gEAAXQdom0+l1mjMihUakQgK0kl0gU1E2Z8gsVn+dgcpCcNHIiGk7k8ODwhBI5H89DwITCkU4vBMXALYGi3RKAGEhKWlANBcN81XuiyxJJ9AAOSOe5SqJAANn9Oj0eGL1ZZ5ksSH1UccznjiY81C8qd8GeoAWHheuMAA7gBlWJYVYYcviLCdbq9ZuupD/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oAAQigNqQgeAzIrgrgQAA"} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { config } from './config' const { newSupplyCap, receipt } = await Actions.token.setSupplyCapSync(config, { supplyCap: parseUnits('1000000', 6), token: '0x20c0000000000000000000000000000000000000', }) console.log('New supply cap:', newSupplyCap) // @log: New supply cap: 1000000000000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.setSupplyCap` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.token.setSupplyCap(config, { supplyCap: parseUnits('1000000', 6), token: '0x20c0000000000000000000000000000000000000', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args } = viem_Actions.token.setSupplyCap.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** New supply cap value */ newSupplyCap: bigint /** Transaction receipt */ receipt: TransactionReceipt /** Address that updated the supply cap */ updater: Address } ``` ## Parameters ### supplyCap - **Type:** `bigint` Maximum total supply allowed for the token. ### token - **Type:** `Address | bigint` Address or ID of the TIP-20 token. ## Viem - [`token.setSupplyCap`](https://viem.sh/tempo/actions/token.setSupplyCap) ================================================ FILE: site/tempo/actions/token.transfer.md ================================================ # `token.transfer` Transfers TIP-20 tokens from the caller to a recipient. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"dec220aff49bf6fbcd09bc1c824e3f8dc091edf7bd95fbbb92e4c24833c8f7ec","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+Ao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GYmaHlw4I5WZI62ao5VLiGPmyaAUgVoAYVwgBiRDZLRGEwC4KHGwFgdwiGPjZEdEi46gkUnAlDm5y5VA0WQj9FPHrENj8KcDPge5KaTG3qdFMWIBzJMX4kpklACWcXjEZl0nqgfZ/BEaAXAXsC05oBgX6aYiGZQ7QVsawVUyWbWbI52aiYKUuYyboVKVUxYU4Wk556wy/QYVJDowMlYwvwWA7gshEDWBQj/BeXWgqlirqn6jiKvg+g4QHJ4B7oGlEJGkqQQSmkwJMq3J6nGw/jXidy9SngqxgCXgXz/gvx3iqQfzELakDh/wgApV/iRU0oQLYQqosLMoGDsJygPI8LewZVnAAAS4Q+AJQ+MDc2h3BSgrg9JIASZBgnVJIoS10e0b0H0BK6pj4xKwV94EkMq/8p8mV41agJyvoUV5yKkwkKqzSLIuh4VIuc1qkYiWpPoRC6qBg6V70mV3eJIJQDc/w+oakj4vY6gbY0g1g4gLQvAsA0Qb1H1X1P1f1ANQNINuon131v1/1gN0M0NsN4NCNQNBpP80VECUCz8BYsATAvSSs/kUoMoosIyEsom7sCshNooTiQypN6spS1N2C5MyUwyCoioUICppsEyghoo5Vl8Mo2cucXAxNgUE0xcACBUCQFcpsVcrcrqHFdNeQiogIUIj4cyvYccXszy9ctAHy+oXyPyfyAKuoQKIKYKEKUKMK8KiKyKqK6KmKOKLQLcAcRcdcPK1gfKwqPtvtNort/coJlFou91Z8Dgz1cyAtaAJcbVSQm1KcLIm84gSAoAAQk0SQsqCArgrgQAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { config } from './config' const { receipt } = await Actions.token.transferSync(config, { amount: parseUnits('10.5', 6), to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) console.log('Transaction hash:', receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.transfer` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { parseUnits } from 'viem' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.token.transfer(config, { amount: parseUnits('10.5', 6), to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args } = viem_Actions.token.transfer.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Amount of tokens transferred */ amount: bigint /** Address tokens were transferred from */ from: Address /** Transaction receipt */ receipt: TransactionReceipt /** Address tokens were transferred to */ to: Address } ``` ## Parameters ### amount - **Type:** `bigint` Amount of tokens to transfer. ### to - **Type:** `Address` Address to transfer tokens to. ### token - **Type:** `Address | bigint` Address or ID of the TIP-20 token. ### memo (optional) - **Type:** `Hex` Optional memo to attach to the transfer event. ### from (optional) - **Type:** `Address` Address to transfer tokens from. When specified, transfers tokens from the given address (requires prior approval). Defaults to the caller's address. ## Viem - [`token.transfer`](https://viem.sh/tempo/actions/token.transfer) ================================================ FILE: site/tempo/actions/token.unpause.md ================================================ # `token.unpause` Unpauses a TIP-20 token, allowing transfers to resume. Requires the `UNPAUSE` role. [Learn more about token roles](https://docs.tempo.xyz/protocol/tip403/spec) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"acbdcb03cf8c56a50bc60fe3d4d353742e327ae6fa423ee3dd905872a93fd690","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJ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tdGGVIwAAPypFOBgOsQNsmolxFCEJmYGmm/2QCGhnE4CIAgGWlUwAGpeheJZhBIg9V8qAfU8B1dDE9J71p5GFVBhsTduhFJOAABZc6AQHSDVHQTYJsFDXgDRJ5LMehXYOsfA5hSVXIJIMcLgbRLhb5EOFgSQIBV/LDORTVP8KAKAciQAtFPg8IU+QfMQciELIQTuI8FeM+CbS+UJcJEXBIIIX4IRbvCZXvHNMAdQbJHQQpCwTYKpcwxNN/X1cw34MNMdBIDsX4SNOQfTIICtVoWguVIlDVSbZgl5K+MJELOQDsbNSyGREwhyN1GZOZawn1P1eAANOfdZUNKI7wtpKI2ItAQopGVoSIM5OtAyBtY6Q2IoFMS6TgL0PHFdWXFtddGIOo1ILdXtOsdozmPPJDV3VIXotEBor7e9R9cRXnYYxAJXYY/ogvWozmVIH0QxcY2HP7GHM1S1PSXIwo+I8ZRI3vZIr1VIxZIpDIwNNZENOpXIlpdpAo9gHNIox4yyEonQfWMSBBTNRIF4irJSBvNSDSYHJEUoIgawDsXoCExONfa2F0KuXoECHfT0dkYuPAARY/CuFWXkSYOuc0BuWEGo1YDYbRA4I4E4IMAWOE4WWwB2BoJ4ffNUa0d4bRDEjkMMSuECI0S/U0CQJQUoEbNEltbOfQcpGk0WBoGk2/AwHlesbMPYFyUIHYMuRUU/SuNWfmGIWAJgbKUyO6CrfKWKIqfdRKOpQaTKEyCKA2LIGKQqdyDyDsJfY2Kqao5YMyIkuUusJmF+ZyK6G6SUe6JpR6WWdcVMN6Y2D6MaKOTyOOawBODOeMhM1OEGfafTCY1dVojyGU+8T4GYusd07RfTUofFcQJAUAAIRQNeIQPACiEAVwVwIAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const { isPaused, receipt } = await Actions.token.unpauseSync(config, { token: '0x20c0000000000000000000000000000000000000', }) console.log('Is paused:', isPaused) // @log: Is paused: false ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.unpause` action and wait for inclusion manually: ```ts import { Actions as viem_Actions } from 'viem/tempo' import { Actions } from 'wagmi/tempo' import { waitForTransactionReceipt } from 'wagmi/actions' const hash = await Actions.token.unpause(config, { token: '0x20c0000000000000000000000000000000000000', }) const receipt = await waitForTransactionReceipt(config, { hash }) const { args } = viem_Actions.token.unpause.extractEvent(receipt.logs) ``` ## Return Type ```ts type ReturnType = { /** Whether the token is paused */ isPaused: boolean /** Transaction receipt */ receipt: TransactionReceipt /** Address that unpaused the token */ updater: Address } ``` ## Parameters ### token - **Type:** `Address | bigint` Address or ID of the TIP-20 token. ## Viem - [`token.unpause`](https://viem.sh/tempo/actions/token.unpause) ================================================ FILE: site/tempo/actions/token.watchAdminRole.md ================================================ # `token.watchAdminRole` Watches for role admin update events on TIP20 tokens. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"c420598bc27431292ec1a4b52f62cd46424331fc2b9c562b34ffb419fe3f27be","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinACuYADu4mj2qQDqW/YZYGhD/ACiJMcASnorpGAAKl6l5VKI6rK1yqoaLTp6eDWm22ankFisAGYBo5nKNGhNqM8DDM/NQAkxWOwuEZBMIXtp9AAOT4Kb4NGraNp4HEmLrgpBQkD2GEjPrwjyIqbI3xzNELAz5LGcNAQADWinxFRkNVJ9SQAFY/lSDCLxWA6T1EIzmadWYgAEyVBGYLk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T7gqE6LawGAEEdzPh+amLrBtr/wwDrDdAAqcAACyliAgj4N6OgKwUY/S0QYaTyEYGsKcYY2RcyoSuQSQRYXAkaWK4QSaosLAkg+SzhugZyOSt6+4UAsyuI5a3RYxyy10YgsyUOQgyioQKws4AScuwSrSGqGmCQQQEIEQEG+qvBjGYA6grKcG3QKwQqZxJGZW4hZxEIjq+WCQCYEIWGMqp2QQU6rQVRDYTatGt6DRUa+Kz4UOcgCYlGjGaAOy3B+qUGxqsG7KnK3K8AyGshaGDqEJnxcqEJ0JWwBJyGrUWWLGdBr4yeEuMQawXAYk8ohehhS+lUsE1JxwqQFmimYYrJaAb+duH+RQNJqQioHcfmAWEmy+LJyqbJ6+3JvJ4+DuApbJnAwp9W5K/m5Jz4lSn6fYBKOJRJcJeqYEiJMGW0ZqqJVqGJqG9qYqOJrqsq+JDGhJjpxJmUFGxW3EdGRJzGDB14t44evYpQRA1gCYvQIZ1g1gqh9sbw+ovQzsuCWoy8eAgiYImojMO8pCIM+8kwR8UifINC58ZAl8mU18MCg898hioCKCH8kCP8f8ACzCMASCYCqCn8tZpZcC5yWOFZyCQuNZ0Crg7Ce8+ogM9MDQ+CzMgQRCKZVgaZAcGZ+ovMlh/MVCeZiwHkQIVY6Ulc4RNcUAg5BojQWhPC5IiZBgG5IIPsvQ3C6ZeoyMP0MQsAGIZMjEfkwgLEbEtmnEYqKkEAtE8aRU6KY0kEz0xECYihxM/EKeeMnkaYPkTEAUaowUTC2c4Uo0UUmk0sqQvQYAYYqmcsaoIGJsC4Ex6sH4jkq88UoUScqU6cN+FUUQxUck6ukmV86+JJ7Uzkp2I2pcp4pA8WIo4EaYECuQ559gdkpQy04gSAoAAQigjiQgeA74IArgrgQAA=="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.token.watchAdminRole(config, { token: 1n, // Token ID or address onRoleAdminUpdated(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `() => void` Returns a function to unsubscribe from the event. ## Parameters ### onRoleAdminUpdated - **Type:** `function` ```ts declare function onRoleAdminUpdated(args: Args, log: Log): void type Args = { /** The role whose admin role is being changed */ role: Hex /** The new admin role */ newAdminRole: Hex /** The address that initiated the change */ sender: Address } ``` Callback to invoke when a role admin is updated. ### token - **Type:** `Address | bigint` Address or ID of the TIP20 token to watch. ### args (optional) - **Type:** `object` ```ts type Args = { /** Filter by role */ role?: Hex | Hex[] | null /** Filter by new admin role */ newAdminRole?: Hex | Hex[] | null /** Filter by sender */ sender?: Address | Address[] | null } ``` Optional filter arguments to narrow down the events to watch. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `function` ```ts declare function onError(error: Error): void ``` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Enable polling mode. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`token.watchAdminRole`](https://viem.sh/tempo/actions/token.watchAdminRole) ================================================ FILE: site/tempo/actions/token.watchApprove.md ================================================ # `token.watchApprove` Watches for token approval events on TIP20 tokens. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"a50530b6c3dfb0005748890f9451c15c1c16886305459d01bf4b5b8957109244","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinACuYADu4mj2qQDqW/YZYGhD/ACiJMcASnorpGAAKl6l5VKI6rK1yqoaLT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BKququYNtIRIxnupEPVDdK8KQo0CSEbOSFQgYLIkPHjKPPQkaEwtPOaKwm7NmtAFEPPsxvFolgAPypBnIhhxhmFeZrShATRHrGFgAYDIAKQlicCpzGTjYADUvQSsswCUlWEQ4iWcY+2SeSN4Vm8i6wha+ay+3QocnAAAssogIFeLXDoCsBGBUtENsmEl2GGGLA3CGOEe0vYrkEkHmFwC6iCuEC7q6CwJIBEvoboPMqErnGuMLG0riFuOUU0T0rtAIPWGtLwqECsBOJYrBDYvwpCtCkJgkEEBCBEC+hKrQdhmAOoPil+t0CsLSksfBoliSksRCA9gAgkHGBCGBnqnIEtkED6q0KkTWLmmup8jka6hMW9nIHGFhlsKMtQRKm+jKp+oSsSr+vAP+rwUBpqnBC8acfqi8e8WgDCR1GVBEGarRneL7izjEN/O5PKNHkIcxmBOiccKkCptxiGPibyrpggVrkUN/KkIqEXFZjZtlLiaSYgIPqSfAYEakMyZwLSdJllh3ngbbl7mAKel2FChCTCZ8eKv+D8R+vuPKgCWSkCQBmqqCfBBCeBmytCewNhrCdqVsPCbFMhtOOhl2JhnqWtE3BIIQSgGeE7p2KUEQNYHGL0M6dYNYKITrKAuoDKNIZQjAubDQr9FYIoUgnqK9I7NMCwnyFggvGQEvLFFpBfBAOvGQFvDvPvHTsfGfBfFfAsqmXfOmY/EfC/Nme/GuIotSWEv/McEAiQn0NIN3E9FArIXArFAoXQnqPqPKBGdyOodGYsM5ECGWNFMnM4WnFAHWWDlIWSL8P6YEEOSCEPL0O3EoXqCDDdDELABiOjDRJ5MIPRIxJpixPBPJBABRE+NRICu1EBCdLhHGIIVkFxH7vDC5CmO5LRN5GqH5AQiHEFCjCFCpBzKkNYGANZGFGAIVKEDFMeJHElCvGWUMriYHIPgiRVHZEtnVvHB+KQD5iKABCmM/LkAufYJZKUCNOIEgKAAEIoJYkIHgHuCAK4K4EAA=="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.token.watchApprove(config, { token: 0n, onApproval(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `() => void` Returns a function to unsubscribe from the event. ## Parameters ### onApproval - **Type:** `function` ```ts declare function onApproval(args: Args, log: Log): void type Args = { /** Amount approved */ amount: bigint /** Address of the token owner */ owner: Address /** Address of the spender */ spender: Address } ``` Callback to invoke when tokens are approved. ### token - **Type:** `Address | bigint` Address or ID of the TIP20 token to watch. ### args (optional) - **Type:** `object` ```ts type Args = { /** Filter by token owner address */ owner?: Address | Address[] | null /** Filter by spender address */ spender?: Address | Address[] | null } ``` Filter events by owner and/or spender addresses. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `function` ```ts declare function onError(error: Error): void ``` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Enable polling mode. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`token.watchApprove`](https://viem.sh/tempo/actions/token.watchApprove) ================================================ FILE: site/tempo/actions/token.watchBurn.md ================================================ # `token.watchBurn` Watches for token burn events on TIP20 tokens. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"964634b1472c31080644e57c6495fef8eddfe7936d04a402712785277c2e7797","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinACuYADu4mj2qQDqW/YZYGhD/ACiJMcASnorpGAAKl6l5VKI6rK1yqoaLTp6eDWm22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yD9J6tAFEK3iUnZg5gAPypBjLBixhyEaZzShADT9rSFgAYDICyRFicBhwGSVYADUvQksswUUUWVBvYFCeAb+3ifiF4EmDC6w/qvqMA6w3Q0ynAAAsiwgIGeK2joCsOGBEtEN0iuB2KGLzIXMGA4ekgosDDmFwIqqcuEOrpTCwJIBYuIboA0mYm2lFlAGkriPagkdkTkitAILWHNLgqECsKONItjnIn4kSoRgkEEBCBEIupSkgV+mAOoACuut0CsLCl0Xeg5jgV0RCItjvAkLGBCLyqenIM1kEMmq0P4VWN6q2jjmEUqlcheOtnILGJ+lsKUggZSsurSmukCiCmCvADukQfulyrsbMWersQcWgC8Q1HlKZr+sAReIbqjjEOvC5PKPbuQXHhlMBP8ccKkExlhsGBCXiqnlYakHCakIqMnBJlJohmCciaXnCS/mnkRsiZwKiZ5k8pJt8U4kOh2Ncg8S8UcRSt+KcautuAypcSyjcXupyjBA8Xyuis8ewF+q8fyVsO8eFE+hOG+h2B+kKXNMXBIGASgEeKru2KUEQNYLGL0OqdYNYNQSrEfNILYGAg0BAmjIENAmCJqJwXAtwb0G3JMMguaKgjbD3B/CvOFOpMvMPKPOPFPPDnPIvMvKvOvJvNvMcHvAfLqfoHOIjEwYbNdNfOFBwXfC9OrLwdyA6QIYsA5ECCWKFCHNoeHFAIAqbJUAwYacwZAgYNmSCAbPDEmaMG9EdDELABiJDJRG5MIDRHRGXjhDBDJBAKRHeBREcvVH+MPCBLGGQVkOxEboDI5MmC5FRB5GqN5D/L5HVAFIpPTKkL0GAMGHhhOPTCvELMiopPXGTnlD7DFAPJZGJCTvRq7KXh8QVNZM1tlgHC+KQFpiKD+MmCIrkFWfYGZKUD1OIEgKAAEIoLwkIHgFuCAK4K4EAA"} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.token.watchBurn(config, { token: 1n, // or token address onBurn(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `() => void` Returns a function to unsubscribe from the event. ## Parameters ### onBurn - **Type:** `function` ```ts declare function onBurn(args: Args, log: Log): void type Args = { /** Address whose tokens were burned */ from: Address /** Amount burned */ amount: bigint } ``` Callback to invoke when tokens are burned. ### token - **Type:** `Address | bigint` Address or ID of the TIP20 token. ### args (optional) - **Type:** `object` ```ts type Args = { /** Filter by burner address */ from?: Address | Address[] | null } ``` Optional filter arguments. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `function` ```ts declare function onError(error: Error): void ``` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Enable polling mode. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`token.watchBurn`](https://viem.sh/tempo/actions/token.watchBurn) ================================================ FILE: site/tempo/actions/token.watchCreate.md ================================================ # `token.watchCreate` Watches for new TIP20 token creation events on the TIP20 Factory. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"0fc1ecb422e1310805039e9f9c6a825260c57e6ebb91bb88edd178eeb92819a4","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinACuYADu4mj2qQDqW/YZYGhD/ACiJMcASnorpGAAKl6l5VKI6rK1yqoaLTp6eDWm22ankFisAGYBo5nKNGhNqM8DDM/NQAkxWOwuEZBMIXtp9AAOT4Kb4NGraNp4HEmLrgpBQkD2GEjPrwjyIqbI3xzNELAz5LGcNAQADWinxFRkNVJ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hUjON0DspwAALJCICDnhBY6ArDhgZLTKzKdihglKhzBi+H4Btq5BJC5hcDGqvLhDm6swsCSAeKqG6CDKuJjrHxQDlK4iYbZFlG1I7RiDlLnZCDUKhArDjhSJQQ6LlpfI/IsYJBBAQgRBHpcpEEwZgDqAIoXrdArB4rjH/qBY0HjEQiHYtwJCxgQhypvpyBDZBA2qtBRHVixoQZjoJEmq9HnZyCxggYwZoBtIEFconp8rnpIquEioYq3pMEPrSqXFbHvqXE3FbCAm3plRubwbIHXiO6k4xBrCu6cDygB7sGkYwnHCpAia0bBgoloDAFl6sZYmpCKhRY6515O5IlN74klRFCwk4nuGpD4nwla5ab25BJLqdjfK/HAn3GcrfhPFnrTSCpvHXpir3pSowS/HyoUoAnQZAnSkgnRTAZTjgadgWDAlwaoGHjHim4dilBEDWCxi9D6nWDWBcHYxSgvSNDeyoJajoIGCYJ/RWDiE4LAyezSEQyMwpzBDDQ5iZzRTZztx1zbxcK7yXxLyVxTy5weQNypBNyKLHDhlk5dza5LzxlDwjxjxJmTy1y8AzyKDzyLyZn+lrwbwwBbxnxBkXwE5hlHwnwWDnx7xXxKBVlgC3ymkeyEi2AEzPSvwfSBAfz2kKiUy/yxzyiulJxyEGCk5AiliRSKwWEqxhytn6D6i9D8FWkUg9mAiOQgify9AdkSF6igw3QxCwAYgYyUSuTCDoQnT0SMQwTSQQCkQPgUSYzJBXl0QgSxhsFZDsSknLBTkgjORUTuRqheQwI+R+SowBQKRByKAhxQACzz7ZRRCpSiTM6kZZyUmgkVRWRDZVayyuikDWYig/jJi9y5D/n2CmSlAjTiBICgABDri4h4C3ggCuCuBAA==="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.token.watchCreate(config, { onTokenCreated(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `() => void` Returns a function to unsubscribe from the event. ## Parameters ### onTokenCreated - **Type:** `function` ```ts declare function onTokenCreated(args: Args, log: Log): void type Args = { /** Address of the created token */ token: Address /** ID of the created token */ tokenId: bigint /** Name of the token */ name: string /** Symbol of the token */ symbol: string /** Currency of the token */ currency: string /** Quote token address */ quoteToken: Address /** Admin address */ admin: Address } ``` Callback to invoke when a new TIP20 token is created. ### args (optional) - **Type:** `object` ```ts type Args = { /** Filter by token address(es) */ token?: Address | Address[] | null /** Filter by token ID(s) */ tokenId?: bigint | bigint[] | null } ``` Optional filter arguments to watch for specific tokens. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `function` ```ts declare function onError(error: Error): void ``` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Enable polling mode. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`token.watchCreate`](https://viem.sh/tempo/actions/token.watchCreate) ================================================ FILE: site/tempo/actions/token.watchMint.md ================================================ # `token.watchMint` Watches for token mint events on TIP20 tokens. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"1e6861a9411f2b10135215821f2c629c4813bdfdb5bb1a235a11dc6a7b4e8738","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinACuYADu4mj2qQDqW/YZYGhD/ACiJMcASnorpGAAKl6l5VKI6rK1yqoaLTp6eDWm22ankFisAGYBo5nKNGhNqM8DDM/NQAkxWOwuEZBMIXtp9AAOT4Kb4NGraNp4HEmLrgpBQkD2GEjPr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tSDexCE8An8XF3FzwRNKF1hfVvUYB1hugRlOAnQaEBBTxm0dAVhwxAlogWkDEOxQxuZ85gxLCElJFAYcwuA5U9lwhldyYWBJAjEBDdBKl9EW0wsoB4lcRbUIjkjUkloBBaxpo0FQgVhRwRF0dxF3EcVcMEgggIQIh51iU4C30wB1BPlV1ugVgwUmir0bMMCmiIRWVXQEhYwIRD1OU5AGsghE1Wh3CqxPVm0Mc/D5VjlzwVs5BYxX0tg8kYDiVF1yUV1vlfl/l4At08Dd0WVVjRiuVViNi0AbjapspDNP1/9zxddEcYgl5HJ5RrcYMc9o93jjhUg6M0Ngx/iMVE9jDUhQTUhFRE4RMxNYNUogIoTC9QSH8k88MoTOAYTXNrlRNnibEB0OwTkLibitiiUvxdjl0twqVDi6UTid1mUoULij1EVrj2A31bj2Sth7iQo70Jwn0OwX0uTppC4JAgCUBDxFd2xSgiBrBYxeh5TrBrAyClY3h9Reh9R5B94AFtZAgUpGDz4noNS2DuRzQ4ErYO5H554QoVI55+5SEh5R5odJ4Z454F4l4V415jgN4t5VTKDVYtT/59Y6CDBT4wRNQmDwEWDVYTT3piZLY0Z/o7Jkwgog4VDQ4oAv5jZGhqDtT3gQyQAgQSw9ZYZDTRgXoDoYhYAMRwYyJnJhBKJqIi8sIoVJIIAiJbxSJtkapfxNoaJYwiCQYWI9ckyiyQRHJyJXI1QPJX4vJqpfI5JaZUggIh45xeAlSNzNytztydzdzrBehMo5Jq40Bgo9wvZIoe4zJhICdqNnZC8HjcoLIGt0s/ZnxSA1MRRvxkxeFcgxz7BjJShOpxAkBQAAhFBWEhA8BNwQBXBXAgA"} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.token.watchMint(config, { token: '0x20c0000000000000000000000000000000000001', onMint(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `() => void` Returns a function to unsubscribe from the event. ## Parameters ### onMint - **Type:** `function` ```ts declare function onMint(args: Args, log: Log): void type Args = { /** Address that received the tokens */ to: Address /** Amount minted */ amount: bigint } ``` Callback to invoke when tokens are minted. ### token - **Type:** `Address | bigint` Address or ID of the TIP20 token to watch. ### args (optional) - **Type:** `object` ```ts type Args = { /** Filter by recipient address */ to?: Address | Address[] | null } ``` Optional filter arguments. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `function` ```ts declare function onError(error: Error): void ``` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Enable polling mode. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`token.watchMint`](https://viem.sh/tempo/actions/token.watchMint) ================================================ FILE: site/tempo/actions/token.watchRole.md ================================================ # `token.watchRole` Watches for role membership update events on TIP20 tokens. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"4e73bd3d320afedbf0f32a0aefd66466de2992e0fa9666c2ae0e296a1f14a4da","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinACuYADu4mj2qQDqW/YZYGhD/ACiJMcASnorpGAAKl6l5VKI6rK1yqoaLTp6eDWm22ankFisAGYBo5nKNGhNqM8DDM/NQAkxWOwuEZBMIXtp9AAOT4Kb4NGraNp4HEmLrgpBQkD2GEjPrwjyIqbI3xzNELAz5LGcNAQADWinxFRkNVJ9SQAFY/lSDCLxWA6T1EIzmadWYgAEyVBGYLk+WalGj8kAJNb8XGc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DdAqkkiCcYsoBElcQ7VEisl0kjoBAawdosFQgVgRwxF8dJEPFcVrMEgggIQIg50SU0D30wB1BvkV1ugVgIVujr0nMCDuiIQVsBMEgYwIQOUj05BmsggE1Wh/DKxPVi1m0wiulS4zkts5AYw30tgCkUCSUF0KVl1fl/lAV4BN0yCd1WU9i5jj09jDi0BXi+oaozMv1wD7wTdMcYg1gLdOB5RndqD4MIIATjhUhmN0MgxIS0AP8rN59Uh4TUhFRS5JNpNUxwTUTq94TESv8USMUoTgT5dMSfjbF+12xdiBB9jXjjjiUgIzil1FpqUrj6Vbjt0WVEJHjOUkUXj2B303jBStgPikp71xxn12xX0RSdpu4JAoCLwygLA2xSgiBrAYxehNTrBrA6CjY3gmDCQB4T4tQR48BCpuCb4gZeg4FORBCIZPZghV534i0I4Owt5o4kp/5nYIR+hWCGgz5rZL4vSwRNQeDoE+DTYBCEEhC+ROD4Z3IkwEo049DM4oBvSDR1AWC3pyQzSDAgRiw7ZcYrTRgQYHoYhYAMR0Z6IfJhAmI8IWIa8iJEIlIIBqI3w6JdlepcJ8IIIYwqCsheJTcEyCyQQvIGI/I1RAoPTI8eowp1JeZUgIJrBaBFCYxq9cNxZJZJ1lY1YNZtddZZx5w1R1Ix4YAJ4Kpw4R9CoogcoZJclwSN5q9Pi6pHJmtEsk5DxSBtMRRdwkx+FchRz7AbJSgppxAkBQAAhFB2EhA8BnwQBXBXAgA="} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.token.watchRole(config, { token: '0x...', // Address or ID of the TIP20 token onRoleUpdated(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `() => void` Returns a function to unsubscribe from the event. ## Parameters ### onRoleUpdated - **Type:** `function` ```ts declare function onRoleUpdated(args: Args, log: Log): void type Args = { /** Role being updated */ role: Hex /** Account receiving or losing the role */ account: Address /** Address that updated the role */ sender: Address /** Whether the account has the role */ hasRole: boolean /** Type of role update */ type: 'granted' | 'revoked' } ``` Callback to invoke when a role membership is updated. ### token - **Type:** `Address | bigint` Address or ID of the TIP20 token. ### args (optional) - **Type:** `object` ```ts type Args = { /** Filter by role */ role?: Hex | Hex[] | null /** Filter by account */ account?: Address | Address[] | null /** Filter by sender */ sender?: Address | Address[] | null } ``` Filter parameters for the watch subscription. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `function` ```ts declare function onError(error: Error): void ``` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Enable polling mode. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`token.watchRole`](https://viem.sh/tempo/actions/token.watchRole) ================================================ FILE: site/tempo/actions/token.watchTransfer.md ================================================ # `token.watchTransfer` Watches for token transfer events on TIP20 tokens. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"5deeee8975448d70c44695a3fbb88e51e915d6eeb68dabfc6d4cce676856c16d","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIBBAYzUYQwCKnDQBDDkgCcVADYwwAczT4kAdioTSSmA0Qg+AoSJBzGYXIgAMVXvknj+ZGQF8K6bFYLEXWuvogABTi5uJwAJScvCZcMWAAZoxKiJwAwkJJSgA6YCxsHNGZyZQgYpL6ACyaZooqaogAbFqSuoHxWaXmlkgAjHYOpE405IjS7p44eIQk5P70ePFinACuYADu4mj2qQDqW/YZYGhD/ACiJMcASnorpGAAKl6l5VKI6rK1yqoaLTp6eDWm22ankFisAGYBo5nKNGhNqM8DDM/NQAkxWOwuEZBMIXtp9AAOT4Kb4NGraNp4HEmLrgpBQkD2GEjPrwjyIqbI3xzNELAz5LGcNAQADWinxFRkNVJ9SQAFY/lSDCLxWA6T1EIzmadWYgAEyVBGY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CujoCsBGGUtEJsg6mGFLMCiGDEa0rYgjPmFwDssCr0l2t2GzCwJIGEsYboLMsEquhVlAC0riPGpUa0V0ntAIA2OtJwqECsBOBYhztYpCtCgJgkEEBCBEA+hKgwZhmAOoPim+t0CsDSisbBnFlwSsRCHdp/AkHGBCDqiBnIPNkEJ6q0JkbWFmiupzvkU6ptFCi9nIHGBhlsMMnQRKk+jKq+oSsSqSvAN+gIX+pqu8ecaBu8V8WgHCZ1OVMFjhjRnAKnkUC/B5PKFHqIYxuBDEC/KkEppxiGASccEgWEVpGSa/JwIqKZhlrPr7rib3tSSVKSc/OSWPpSakKybSW3mZl7jeAkoet2G8QIB8XCT8eKv+P8S+vuPKsCcqmCb+hqghFCbqmyrCewJhvCdqVsIiXFIhtOKht2OhnqetK3BICQSgGeI7l2KUEQNYHGL0M6dYNYBIYbH/OoISN3MQlqIoQYOQmCJqKoVQnqL0JPJodMAwnyHPKgmQIvHFMvGfGvBfDvHvCcDfHfGfCKGmVfJmYfCfGfE/ISSEh/McN/Pgn0NIP0HIc9CAu9IEBAsGVYKGSyIDPqPKPAtGdobGUoXDK5CmDFGnO4ZnFAFWXTrIU9OSAGSAECOWJAr0LWWoXqMDDdDELABiGjNpJ5OtPREBGvMPgRAhApBAJRE+DRACskAxExBBHGCIVkNxEycsPOSCB5HRD5GqP5FguHMFMjKFKpDzKkL0GADZOFI8L+eVDHMlOlA/LnpXuBEvEPkiZVPZPNp1knB+KQB5iKABCmDfLkK+fYFZKUKNOIEgKAAEIoJokIHgHuCAK4K4EAA"} // @filename: config.ts // @errors: 2322 import type { Config } from 'wagmi' export const config = {} as Config // @filename: example.ts // ---cut--- import { Actions } from 'wagmi/tempo' import { config } from './config' const unwatch = Actions.token.watchTransfer(config, { token: 1n, onTransfer(args, log) { console.log('args:', args) }, }) // Later, stop watching unwatch() ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type `() => void` Returns a function to unsubscribe from the event. ## Parameters ### onTransfer - **Type:** `function` ```ts declare function onTransfer(args: Args, log: Log): void type Args = { /** Amount transferred */ amount: bigint /** Address sending the tokens */ from: Address /** Address receiving the tokens */ to: Address } ``` Callback to invoke when tokens are transferred. ### token - **Type:** `Address | bigint` Address or ID of the TIP20 token to watch. ### args (optional) - **Type:** `object` ```ts type Args = { /** Filter by sender address(es) */ from?: Address | Address[] | null /** Filter by recipient address(es) */ to?: Address | Address[] | null } ``` Optional filter to watch only transfers from or to specific addresses. ### fromBlock (optional) - **Type:** `bigint` Block to start listening from. ### onError (optional) - **Type:** `function` ```ts declare function onError(error: Error): void ``` The callback to call when an error occurred when trying to get for a new block. ### poll (optional) - **Type:** `true` Enable polling mode. ### pollingInterval (optional) - **Type:** `number` Polling frequency (in ms). Defaults to Client's pollingInterval config. ## Viem - [`token.watchTransfer`](https://viem.sh/tempo/actions/token.watchTransfer) ================================================ FILE: site/tempo/chains.md ================================================ # Chains The following Tempo chains are available: ```ts import { tempoDevnet, // [!code hl] tempoLocalnet, // [!code hl] tempoTestnet, // [!code hl] } from 'wagmi/chains' ``` ## Default Fee Token It is possible to set a default fee token for a Tempo chain by adding a `feeToken` property as an extension to the chain. Once set, all transactions will use this token as the default fee token, unless an override is provided at the transaction level. ```ts import { tempoTestnet } from 'wagmi/chains' const chain = tempoTestnet.extend({ feeToken: '0x20c0000000000000000000000000000000000001', }) ``` ================================================ FILE: site/tempo/connectors/dangerous_secp256k1.md ================================================ # `dangerous_secp256k1` Connector for a Secp256k1 EOA. :::warning NOT RECOMMENDED FOR PRODUCTION USAGE. This connector stores private keys in clear text, and are bound to the session length of the storage used. Instead, use this connector for testing workflows, like end-to-end tests. ::: ## Usage ```ts [wagmi.config.ts] import { createConfig, http } from 'wagmi' import { tempoTestnet } from 'wagmi/chains' import { dangerous_secp256k1 } from 'wagmi/tempo' // [!code focus] export const config = createConfig({ connectors: [dangerous_secp256k1()], // [!code focus] chains: [tempoTestnet], multiInjectedProviderDiscovery: false, transports: { [tempo.id]: http(), }, }) ``` ## Parameters ### account - **Type:** `LocalAccount` Optional account to use with connector. If not provided, one is created internally for you. ================================================ FILE: site/tempo/connectors/index.md ================================================ # Connectors Wagmi-specific connectors for Tempo. - [**`webAuthn`**](/tempo/connectors/webAuthn) Connector for a WebAuthn EOA - [**`dangerous_secp256k1`**](/tempo/connectors/dangerous_secp256k1) Connector for a secp256k1 (private key) EOA ================================================ FILE: site/tempo/connectors/webAuthn.md ================================================ # `webAuthn` Connector for a WebAuthn EOA. ## Usage ```ts [wagmi.config.ts] import { createConfig, http } from 'wagmi' import { tempoTestnet } from 'wagmi/chains' import { KeyManager, webAuthn } from 'wagmi/tempo' // [!code focus] export const config = createConfig({ connectors: [ webAuthn({ // [!code focus] keyManager: KeyManager.localStorage(), // [!code focus] }), // [!code focus] ], chains: [tempoTestnet], multiInjectedProviderDiscovery: false, transports: { [tempoTestnet.id]: http(), }, }) ``` :::warning The `KeyManager.localStorage()` implementation is not recommended for production use as it stores public keys on the client device, meaning it cannot be re-extracted when the user's storage is cleared or if the user is on another device. For production, you should opt for a remote key manager such as [`KeyManager.http`](/tempo/keyManagers/http). ::: ## Parameters ### keyManager - **Type:** `KeyManager` Public key manager that handles credential storage and retrieval. This is required for managing WebAuthn credentials. The `KeyManager` interface provides: - `getChallenge()`: Optional function to fetch a challenge for registration - `getPublicKey(parameters)`: Function to retrieve the public key for a credential - `setPublicKey(parameters)`: Function to store the public key for a credential See [`KeyManager`](/tempo/keyManagers/) for built-in implementations. ### createOptions (optional) Options for WebAuthn registration. #### createOptions.createFn - **Type:** `(options?: CredentialCreationOptions | undefined) => Promise` - **Default:** `window.navigator.credentials.create` Credential creation function. Useful for environments that do not support the WebAuthn API natively (i.e. React Native or testing environments). #### createOptions.label - **Type:** `string` Label associated with the WebAuthn registration. #### createOptions.timeout - **Type:** `number` A numerical hint, in milliseconds, which indicates the time the calling web app is willing to wait for the creation operation to complete. #### createOptions.userId - **Type:** `Bytes.Bytes` User ID associated with the WebAuthn registration. ### getOptions (optional) Options for WebAuthn authentication. #### getOptions.getFn - **Type:** `(options?: CredentialRequestOptions) => Promise` - **Default:** `window.navigator.credentials.get` Credential request function. Useful for environments that do not support the WebAuthn API natively (i.e. React Native or testing environments). ### rpId (optional) - **Type:** `string` The default RP ID to use for WebAuthn operations. Can be overridden by `createOptions.rpId` or `getOptions.rpId`. ================================================ FILE: site/tempo/getting-started.md ================================================ # Getting Started ## Overview [Tempo](https://tempo.xyz) is a purpose-built Layer 1 blockchain optimized for payments. It enshrines features like [token management](https://docs.tempo.xyz/protocol/tip20/overview), [Fee AMM](https://docs.tempo.xyz/protocol/fees), and a [stablecoin DEX](https://docs.tempo.xyz/protocol/exchange) directly into the protocol, as well as a [Tempo transaction type](https://docs.tempo.xyz/protocol/transactions) with support for batch calls, fee sponsorship, configurable fee tokens, concurrent transactions, access keys, and scheduled execution. ## Setup Wagmi React and Core both have first-class support for Tempo with [Hooks](/tempo/hooks/) and [Actions](/tempo/actions/). To get started, first follow the [Getting Started guide for React](/react/getting-started) or [Core](/core/getting-started) and make sure your [Viem](https://viem.sh) version is `{{viemVersion}}`. ::: code-group ```bash-vue [pnpm] pnpm add viem@{{viemVersion}} ``` ```bash-vue [npm] npm install viem@{{viemVersion}} ``` ```bash-vue [yarn] yarn add viem@{{viemVersion}} ```bash-vue [bun] bun add viem@{{viemVersion}} ``` ::: To dive a layer deeper, check out the [Viem Tempo docs](https://viem.sh/tempo). ## Use Wagmi Hooks Now that everything is set up, we can use regular Wagmi Hooks (e.g. `useSendTransactionSync`) that are decorated with [Tempo properties](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction) like `calls` (batch transactions), `feePayer` (fee sponsorship), `nonceKey` (concurrent transactions) and more! ::: code-group ```tsx [tokenMetadata.tsx] import { useSendTransactionSync } from 'wagmi' export function TokenMetadata() { const sendTransactionSync = useSendTransactionSync() return ( ) } ``` ```tsx [app.tsx] import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { WagmiProvider } from 'wagmi' import { config } from './config' import { TokenMetadata } from './tokenMetadata' const queryClient = new QueryClient() function App() { return ( ) } ``` ```tsx [config.ts] import { createConfig, http } from 'wagmi' import { tempoTestnet } from 'wagmi/chains' import { KeyManager, webAuthn } from 'wagmi/tempo' export const config = createConfig({ connectors: [ webAuthn({ keyManager: KeyManager.localStorage(), }), ], chains: [tempoTestnet], multiInjectedProviderDiscovery: false, transports: { [tempoTestnet.id]: http(), }, }) ``` ::: ## Use Tempo Hooks You can also use [Tempo-specific Hooks](/tempo/hooks/): ::: code-group ```tsx [tokenMetadata.tsx] import { Hooks } from 'wagmi/tempo' const alphaUsd = '0x20c0000000000000000000000000000000000001' export function TokenMetadata() { const { data: metadata, ...metadataQuery } = Hooks.token.useGetMetadata({ token: alphaUsd }) if (metadataQuery.isError) return
Error fetching metadata: {metadataQuery.error.message}
if (metadataQuery.isLoading) return
Loading metadata...
return
{metadata.name} ({metadata.symbol})
} ``` ```tsx [app.tsx] import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { WagmiProvider } from 'wagmi' import { config } from './config' import { TokenMetadata } from './tokenMetadata' const queryClient = new QueryClient() function App() { return ( ) } ``` ```tsx [config.ts] import { createConfig, http } from 'wagmi' import { tempo } from 'wagmi/chains' import { KeyManager, webAuthn } from 'wagmi/tempo' export const config = createConfig({ connectors: [ webAuthn({ keyManager: KeyManager.localStorage(), }), ], chains: [tempo], multiInjectedProviderDiscovery: false, transports: { [tempo.id]: http(), }, }) ``` ::: ## Next Steps After you have set up your Tempo with Wagmi, you can now: - [**Guides & Examples**](https://docs.tempo.xyz/guide/tempo-transaction) Follow guides on how to [use accounts](https://docs.tempo.xyz/guide/use-accounts), [make payments](https://docs.tempo.xyz/guide/payments), [issue stablecoins](https://docs.tempo.xyz/guide/issuance), [exchange stablecoins](https://docs.tempo.xyz/guide/stablecoin-exchange), and more! - [**Tempo React Hooks**](/tempo/hooks/) Browse the collection of React Hooks and learn how to use them. - [**Tempo Core Actions**](/tempo/actions/) Browse the collection of Core Actions and learn how to use them. ================================================ FILE: site/tempo/hooks/amm.useBurn.md ================================================ # `amm.useBurn` Burns liquidity tokens and receives the underlying token pair. [Learn more about the Fee AMM](https://docs.tempo.xyz/protocol/fees/spec-fee-amm) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"f352a044790f8cbde9e59508d0e42c0dd85e637c21507c3fb59ad6574684cfad","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUoiaicACUnABmAK5gjowQYJxY4nAwAKpgjGhwwURhcTCInCKkpgoUnLDWLGFwZWBxzABGZJFlbYwKpmgAOrms7FzppJk5eUZQENYIegCycTJojFgm8Jyi5WiVipykMFhHmWBiaymcEDHbnC3tZJxtGHd9JKl0bGbn17dtERgnAAjBZOMFQV8UvI0JEAHRDIYAWk4ABE5k1OPg0GgsE0APT4oiMGDMOFwfD42bzfFxNYmNbwfHjSa5fL+MQKBbIZAgOiiVhyfwsNgcTjANIZbJsuCcVyxUgQZicADkxNJKsRYBZ0umwRVABYAEwWFU1SSRIaEzjGix2+0OsAgAC6zuEml0BvUxnkShUiFBGnE2iCOqm7NkpnMwJsdlIDicUncnhweEIJHIGkCeGsKREzzipDAAGUMIkygZBHCBWS4pkAEKFktl6xwgBKOibABUvAAeADCKRivRqCX4kAA7mAAHz+ETiXQAdkXsl9yiQAA4g1odHg2k3S4l/CYzEgAMyx+yOPyIABsyeoXjTvkzAXoTBGYsrRnnEkQG63H1FHXRBvU0EM8G/Y8o3PS942vZxgUXB9MFTPR0z8LN3z0EVRm2ZhmDnD0pANVdgP9C9qGDXc9BraDT0QSjbCvRNECNM8UKfdCXw5bM9HiRJLlSOsYEbItD2sAchxHTgx0nGdgnGAUdDIOAAH4Kz4KsazhESxObRI4QABXsZgVImKSwGHapZLAccICnacuh4LS4GrAjdIbA8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FaMt+RrrPgbU2oHas5BAYSkXq1DbAgaRBeOUcMwVG+t7RRoq0SZjtaRiVk6cfkaoCsyNMTQ1AlcYaLuYBsAc8giUaBF6Y/xvAbAqgBwL0BcDomugVQKr1HGWBsmIAIQTy02YpIxB8gCQe9mkEyDM88mRgTeGoT8ZcwsAD8G/nFBMjZQ8ofbMqEjIvQ4YCMUkGwGRgbZ4Jf2RCZDBQnqhmAx2HPgWDATaVvwrMTyKyLARcwVo1ofsKBhZRaoYAAHVIPdDzBPtRBwY8EJiQUB8d+4VwLaH/n4A1AEGWQuGAymWgFwGRcIaTFrAFiuijMW2VkGdlBBwhVAl2YEF+TjgqwkcpsWgOjiNCY5scuOfHITmJyk5ycqgSnNTlpz05GczOVnOzk5zc5c4qubUeEmTjB4dcwEvyQ6Hcm/j083sAyX7H8nhTgQwcVwAXAeESMVQ34kQR8UTjiDEAl2WSWMzUjuRGGlo9xAXAW6LUEpe0IKQfRSlpS2RGUrKQkhPEpJ1cBcfwMvFEBIBQAgQACctFYEIBXArgIAA==="} import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' const burnSync = Hooks.amm.useBurnSync() // Call `mutate` in response to user action (e.g. button click, form submission) burnSync.mutate({ liquidity: parseUnits('10.5', 18), to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', userToken: '0x20c0000000000000000000000000000000000000', validatorToken: '0x20c0000000000000000000000000000000000001', }) console.log('Received user tokens:', burnSync.data?.amountUserToken) // @log: Received user tokens: 5250000000000000000n console.log('Received validator tokens:', burnSync.data?.amountValidatorToken) // @log: Received validator tokens: 5250000000000000000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `amm.burn` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { parseUnits } from 'viem' import { useWaitForTransactionReceipt } from 'wagmi' const burn = Hooks.amm.useBurn() const { data: receipt } = useWaitForTransactionReceipt({ hash: burn.data }) // Call `mutate` in response to user action (e.g. button click, form submission) burn.mutate({ liquidity: parseUnits('10.5', 18), to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', userToken: '0x20c0000000000000000000000000000000000000', validatorToken: '0x20c0000000000000000000000000000000000001', }) if (receipt) { const { args: { amountUserToken, amountValidatorToken } } = Actions.amm.burn.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `amm.burn` Return Type](/tempo/actions/amm.burn#return-type) ### mutate/mutateAsync See [Wagmi Action `amm.burn` Parameters](/tempo/actions/amm.burn#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`amm.burn`](/tempo/actions/amm.burn) ================================================ FILE: site/tempo/hooks/amm.useLiquidityBalance.md ================================================ # `amm.useLiquidityBalance` Gets the liquidity balance for an address in a specific pool. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"8ac7e459f30e286677d1cb839aa57883a14653c6b8b3bf03624ebf676bd6cacc","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUWKQQOBwYAJScUKJiiJwARowKplwAPpwArmCwAGamMFD+UBDWCHoAKvgwnDKiIpxwOdbW8HAFOTIyGJyk8BAyJFBxCaKcBeycyvUAjjlkGAB0ADpgGxu19Y3Nre2d3b39g3DDo+NiUzNznIvL65vPOw1NXAcdcF09fQNDIxKV0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awKC4yky0y4ynS5o76CRSxQGJqJ6Qysyxypy8CiMTmbmNgm/LUgC/GciqcxLYCmAWHfwJdUQJAUAQIeQNJPUPAQqEAVwVwIAA"} import { Hooks } from 'wagmi/tempo' const { data: balance } = Hooks.amm.useLiquidityBalance({ address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', userToken: '0x20c0000000000000000000000000000000000000', validatorToken: '0x20c0000000000000000000000000000000000001', }) console.log('Liquidity balance:', balance) // @log: Liquidity balance: 10500000000000000000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type See [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook return types. ### data See [Wagmi Action `amm.getLiquidityBalance` Return Type](/tempo/actions/amm.getLiquidityBalance#return-type) ## Parameters See [Wagmi Action `amm.getLiquidityBalance` Parameters](/tempo/actions/amm.getLiquidityBalance#parameters) ### query See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook parameters. ## Action - [`amm.getLiquidityBalance`](/tempo/actions/amm.getLiquidityBalance) ================================================ FILE: site/tempo/hooks/amm.useMint.md ================================================ # `amm.useMint` Mints liquidity tokens by providing a token pair. [Learn more about the Fee AMM](https://docs.tempo.xyz/protocol/fees/spec-fee-amm) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"4fca6eaaab4d04b51aad961895f40c6a81566cafdac628c7923a2a2603d064ae","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUoiaicACUnABmAK5gjowQYJxY4nAwAKpgjGhwwURhcTCInCKkpgoUnLDWLGFwZWBxzABGZJFlbYwKpmgAOrms7FzppJk5eUZQENYIegCycTJojFgm8Jyi5WiVipykMFhHmWBiaymcEDHbnC3tZJxt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K8N5LwYFJqNt3NWIeiLIa1Iodcaoa0CiDGh/w1MoYWkxUold3lrWlkyIBtmBDhFTgdrT1/C9Ee1doYnduMHuq9vGxYnXD9oK3xw9rJvGWsCQU0jclQX0m8kwS7GwUkisnwXsli09G8zO39AAlz13DilSeLxYlPHYmx3YSyd/Lm2KwW1+zXTKCMX5hMU4vZXcUpwiWKTxkG0SQsRCQ8X2AUBmczgRwBwWamc8XCUiXDnSViXiTyRBxSSiWRzQCyTdhu1jhOeqXDlKSHkwFubQFmYvg6QaSaRmjmkuXaQ7U6SGHlBWQSDWSjCgG7ySm/yA3zG7UNT7VBPgAqhIG2jXW8cjXFxSF1KGEhYiC4Bhd7RWH7VOEReHRRZVObR1TAExa/KBChdxdfWZThYvhUKRdqEGh2DJbRZ1K1CxdJVpfKHpaNQJfheZZJbZdRdJQpYCaEydskCh2fkQDIWab0DXTaaYme2vGNEyY+z6cDoGZ+2iAefKWeeWVWROlBdqZlfiehykCScNeHlVaUxYgNAye6e8E5H8D8rwFIItZAjRwSaLx1ZAH7kHnKQLCIqgBTmaydF/mjG9DVYx0sFcAE1zFgHfAAPFEZkEADyDyhmelhnhjYERi9wzYj393lED0hhDw1FJsmrigsq/GZnchEjig5kWmtD7DAw5SBRgHfVMCZfukMMNKeFaVSGCAJIUDhGeGFiuHWggP4BqCQf5baELGZQWirjybhBk01j5gM1zlMyNHM0s2s1s3s0c2c1c3c082818380C2C1C3C0izaHLiHYSTjjW39i23qz2x/Z2xfY2bfbu0/cDl/dA/23/eyX+0A/ObKFLYKBVFThjxvEiAzjAFcCrgmpkejODbKWHjDdEojZjw3bXRUhIIHlw70yGH8F3lECQFAECHkCNJSDwHZFcFcCAA=="} import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' const mintSync = Hooks.amm.useMintSync() // Call `mutate` in response to user action (e.g. button click, form submission) mintSync.mutate({ to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', userTokenAddress: '0x20c0000000000000000000000000000000000000', validatorTokenAddress: '0x20c0000000000000000000000000000000000001', validatorTokenAmount: parseUnits('100', 6), }) console.log('Liquidity minted:', mintSync.data?.liquidity) // @log: Liquidity minted: 100000000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `amm.mint` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { parseUnits } from 'viem' import { useWaitForTransactionReceipt } from 'wagmi' const mint = Hooks.amm.useMint() const { data: receipt } = useWaitForTransactionReceipt({ hash: mint.data }) // Call `mutate` in response to user action (e.g. button click, form submission) mint.mutate({ to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', userTokenAddress: '0x20c0000000000000000000000000000000000000', validatorTokenAddress: '0x20c0000000000000000000000000000000000001', validatorTokenAmount: parseUnits('100', 6), }) if (receipt) { const { args: { liquidity } } = Actions.amm.mint.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `amm.mint` Return Type](/tempo/actions/amm.mint#return-type) ### mutate/mutateAsync See [Wagmi Action `amm.mint` Parameters](/tempo/actions/amm.mint#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`amm.mint`](/tempo/actions/amm.mint) ================================================ FILE: site/tempo/hooks/amm.usePool.md ================================================ # `amm.usePool` Gets the reserves for a liquidity pool. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"a5e2597c7cc0e903cdeee24bcbbc6a915a731be45436f6ef363478a4ecfdc54e","data":"N4Igdg9gJgpgziAX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ApyqgBcUK6nYLmODk7TongJ4ySnzEUhRdUwMXB+BhGfiHCkAW4ZLnizwAwSTxT5WcdImcDMUpWdwqgLSz0BTi9hGDMcT+I+GSQSgEwbUCeL+EAj+JwrJ8sRKAmStb4yYWAF+CeQYw4IosUEHjC6ykwKYVMNgDTFUYOCuYioJIJfHFiSxWoUUH+PLFGiiJhOxsHotYAEkWTLJFgbWKMAi6+cTJ6sMyVZOclCstwNktYAPGjGxkOWPw2uJ1jPANxBOgFeyAPE75JZ9x2E7lv5JUiBS9x6XFWKFMVbl0uJKqNCfVGil/BM45EjyAPH8A/pRASAUAIEHkBgYUwZEhAK4FcBAA=="} import { Hooks } from 'wagmi/tempo' const { data: pool } = Hooks.amm.usePool({ userToken: '0x20c0000000000000000000000000000000000000', validatorToken: '0x20c0000000000000000000000000000000000001', }) console.log('User token reserve:', pool?.reserveUserToken) // @log: User token reserve: 1000000000000000000000n console.log('Validator token reserve:', pool?.reserveValidatorToken) // @log: Validator token reserve: 1000000000000000000000n console.log('Total supply:', pool?.totalSupply) // @log: Total supply: 1000000000000000000000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type See [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook return types. ### data See [Wagmi Action `amm.getPool` Return Type](/tempo/actions/amm.getPool#return-type) ## Parameters See [Wagmi Action `amm.getPool` Parameters](/tempo/actions/amm.getPool#parameters) ### query See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook parameters. ## Action - [`amm.getPool`](/tempo/actions/amm.getPool) ================================================ FILE: site/tempo/hooks/amm.useRebalanceSwap.md ================================================ # `amm.useRebalanceSwap` Performs a rebalance swap between user and validator tokens. [Learn more about the Fee AMM](https://docs.tempo.xyz/protocol/fees/spec-fee-amm) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"20c09f8cc1ff08a8faf46184bc97fb05274d872847ffff372666aabccf7c9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OuEcYeFghuUe8Hpu4HAegSKcGzdc4eCHmHDowIOcLcBNLDkZbMzrS+6cd2u7miq65kUUhrYArc/gp8ogSAoAgQ8gO9KQeA7IrgrgQAA="} import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' const rebalanceSwapSync = Hooks.amm.useRebalanceSwapSync() // Call `mutate` in response to user action (e.g. button click, form submission) rebalanceSwapSync.mutate({ amountOut: parseUnits('10.5', 6), to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', userToken: '0x20c0000000000000000000000000000000000000', validatorToken: '0x20c0000000000000000000000000000000000001', }) console.log('Amount in:', rebalanceSwapSync.data?.amountIn) // @log: 10605000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `amm.rebalanceSwap` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { parseUnits } from 'viem' import { useWaitForTransactionReceipt } from 'wagmi' const rebalanceSwap = Hooks.amm.useRebalanceSwap() const { data: receipt } = useWaitForTransactionReceipt({ hash: rebalanceSwap.data }) // Call `mutate` in response to user action (e.g. button click, form submission) rebalanceSwap.mutate({ amountOut: parseUnits('10.5', 6), to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', userToken: '0x20c0000000000000000000000000000000000000', validatorToken: '0x20c0000000000000000000000000000000000001', }) if (receipt) { const { args: { amountIn } } = Actions.amm.rebalanceSwap.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `amm.rebalanceSwap` Return Type](/tempo/actions/amm.rebalanceSwap#return-type) ### mutate/mutateAsync See [Wagmi Action `amm.rebalanceSwap` Parameters](/tempo/actions/amm.rebalanceSwap#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`amm.rebalanceSwap`](/tempo/actions/amm.rebalanceSwap) ================================================ FILE: site/tempo/hooks/amm.useWatchBurn.md ================================================ # `amm.useWatchBurn` Watches for liquidity burn events on the Fee AMM. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"1eb67ad9a75d59810fdaf0024451c348d0f712105fb6fc09eb9c9df760ca27f0","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXKLMzFGaugAssUmKykj9GVo6eO2deWZIRSC29o5+iABsVdRetb4NAfR4AGYArmCOjBBgnIdwMADqomi2AEKHpGAAPADC5/uMCgB8AAosPZmDoyHAAPyITjAAA6F04iIWpgAklAoZwwIdmAAjMicAA+lzAsB+ZigAG54YjEZlIdC4QiaTTriSyBiAAYWWgAEmAIlIpgUrg5hM4XN5/LQgsUIuQAF0xViZDIxcdSflKdTmTSrmQACoCeSc7l8gVCkViiVm6UWjkKpWHFVqtlkmBapk6oiiExQe7sQ38Y3Q61SmXC0VE0Pm2X2xVE5WqonqmBuj3M1wujXkqme/akCDMR4yCDWfgYnG/UxcZOuzW55nnACipALpAxAIBZDb0JbbYAlJwALx/ThECCMKCD2vZ91Z1P17WItgqjHSw4wedpreLz0rkyKFFgJzemQYrG4/Ezhfknc5pecc7PV4dgF06EAd3uTxeYAAdAAglocAUJwJYKJ+374M+/4ADIQAog4jmOE5Tne7oNrq1ykIGwacLhYBogA8qQAFQFApDwHA6HpjSp6Tv6OF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fuwyOJ/ceJKmxJk+5+/G2SA8FJVu1J+BHIV0h6m4DxzUTxsJ7xwqT6Yqr6YUUq/xX6QJ/B/6qq4JIGTKUJ6GMJqpcJU0jkzkyGm4pgsJWGhBUUSAMUhMpgJk/gRAFgf4VM1pFgFg4hhM/sXMVMwclMIw8hQQ4EShJM8cahSANMmhWwGcQsuhOcOM+cwEDID4xcwO4o5cjcPcD41ci80Ytoh8D4LcjEKZ8ZaZTcD4fcA8w8BozEW8O8+ZU8x4s8voWZJZS8aiK8D4a8bsm8dZZZnoe8cZDcuZiZYAx8EhxMH8N8l8IcPpSCQQD80w5gKhmCicswqgrgBMlCsAzQCSOUvU+UjkBYnipU0WFU1UPabAdUlGvUf4/UjM4CIuo0UcssdIqsCESEo4hc2S2JvSxU74KmJ0F0FAmk/hIAucogSAoAgQ8g8i5weAaUIArgrgQAA==="} import { Hooks } from 'wagmi/tempo' Hooks.amm.useWatchBurn({ onBurn: (args, log) => { console.log('args:', args) }, }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `amm.watchBurn` Parameters](/tempo/actions/amm.watchBurn#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`amm.burn`](/tempo/actions/amm.burn) - [`amm.watchBurn`](/tempo/actions/amm.watchBurn) ================================================ FILE: site/tempo/hooks/amm.useWatchMint.md ================================================ # `amm.useWatchMint` Watches for liquidity mint events on the Fee AMM. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"dcfbe669423c1e67e1fd5bfc996004b53912d26ef3dcef6280d135f90c3df485","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IC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9Byqzm1wt2QQ5QhxsS/hkswBFBzu1BUWoNI6UWp+0cUTBsQWpgkak+waYo5m4XA25WZUhmZuZ94uEj5zAu5s5z5nAehr5vBb5p4gh/hdVoABww89on44A5MYB0R9IMAQIYYjkOF+pvRyYcZ8NGD5RzIUIJxCsABqdmNVeoEsC6OAqgDyEBPAbfTRfJdkaDZZDldxBjIWSlR4R0PqXKdcTILEGNKiawFlRBBNXJECD8NxD2AObqRgKmLgXUMRBNKwxBAULdUgM6GgughTc6J0CGKKdglUBwgJLCL/EQKKLrc4L+b0NcHxFgAHKhSZaZQDfYf4WIPsJtWFeFLdMAeII5TtA8Q4B5bI+dOg7tbI2IfFF4fYX8WIUdL5BLf4flPQkERKc6A1DNIEDiEZRIrrGQX8Tde4MJF/WFVtf/GADtE5aQ7tC5DFLFAdXFF5Xouon5XogYtANYomO6ClEXAqB9E4NXYxY4LgC3VQVXajcPeqGSI4qEJDb9ECK448OvRPIDQ448KEdQYpJQ8XaJZ9B4tAa6e4wFR4rfBvP494pnL4u9dnW9EtctdkJYtYoYmFFteFdtJKZFKYntWY8AwdPFJY4lb5VY9gLddY4k+4TY1aXyfyNddcDdMkw7SODINKJADKOmUwByfwIgCwX8dmHkiwCweAumaOcWdmeONmEYdAoIMCLApAHAs+XOJATmQgrYEueWUgiuSmauICZeVyeuA2IwemXQUeLuduBORmJOMYIIPuDOWUoePA2YVQVwWmGSWAZoDRCqCaaqXyfMQRRqOTVqdqNgTqW9CaX8KaPmFeeaLUNOLWWkI2BCJCEcBaDac459d8NDO6J6CgJGSQkASuUQJAUAQIeQOAfqPAIqEAVwVwIAA=="} import { Hooks } from 'wagmi/tempo' Hooks.amm.useWatchMint({ onMint: (args, log) => { console.log('args:', args) }, }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `amm.watchMint` Parameters](/tempo/actions/amm.watchMint#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`amm.mint`](/tempo/actions/amm.mint) - [`amm.watchMint`](/tempo/actions/amm.watchMint) ================================================ FILE: site/tempo/hooks/amm.useWatchRebalanceSwap.md ================================================ # `amm.useWatchRebalanceSwap` Watches for rebalance swap events on the Fee AMM. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"a65363a61410810306bc28a64110f48e977141b2aff31cdee698fa19287f0ab5","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXKLMzFGaugAssUmKykj9GVo6eO2deWZIRSC29o5+iABsVdRetb4NAfR4AGYArmCOjBBgnIdwMADqomi2AEowAEaiMqInMADKAO6iWAAPABhc77RgKAB8AAosPZmDoyHAAPyITjAAA6F04OIWpgAklBUZwwIdmC8yJwAD6XMCwcFmKAAbixOJxmRRaMx2LZbKuZAAKgJ5MSAAYWWgAEmAIlIpgUrlF1M44qlMrQcsUiuQAF1laSZDJlcd6flmazeWyiO9GFB7uwhfwRWjVdLZfLFcrXerNQrRbr9YdDca6TAGTBzTzLXB/lgcKQxRK3RqPUqad73Vr/XqaQajTSTWGzSyo64Q6bGSXeftSBBmAAhGQQaz8YkvCGmLgF0PhyO884AUVItYTaOh0LII7RQ5HAEpOABeSGcIgQW3z7sViPlouVi04tiG4kaw4wHe98/F/ecQ8mRT4sBOa0yYmk8mUze77ef3tVtnnZ43g+L4/gBYlxw5NF/gefBAPeT5rB+WMADoAEEtDgChOCbBQoPuJ5XngkCUIAGQgBR5yXFc1ygDdaS3Ps+WuUhHWdThWLAQkAHlSFQqAoFIeA4EvPco2fW17RY4UwGJDjuN4/jB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ZJZK5PH15NoNFH+kvTPCBOmhBJxIhJlU/XlR/TymVQRMA2RNkLAz1UGgxONW5WxPYHw1xPNPuHxIwgwzimwzPFMBxMI3oKKiQBKg5lMEQn8CIAsGQiFn9IsAsFUI5kLg0OkC/iIRAT/lIWMBwWmHMF/nmGoTbiQCFg7gYUsJ7l1l2FsMHmZhHhtjHijAng4j3jnizAXnEmXgdGknLM3kPmvB3lhxVFngbNFGvkFPPgSUvjQE7NPnvkfh7NMT7JxlwV0CFkWwGCjKTL0IAQwiMO5hMNTMFlUFcHZg0lgGaFyRahWnahilrHCV6iSwGmGlHTYDGiYxWmQjWkljtkwVjD2gtFrg9nrjehOw5BdnIkomXH2kuhpMmW6kgi0y+mxB+jACcn8CHlECQFAECHkDsXODwDqhAFcFcCAA=="} import { Hooks } from 'wagmi/tempo' Hooks.amm.useWatchRebalanceSwap({ onRebalanceSwap: (args, log) => { console.log('args:', args) }, }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `amm.watchRebalanceSwap` Parameters](/tempo/actions/amm.watchRebalanceSwap#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`amm.rebalanceSwap`](/tempo/actions/amm.rebalanceSwap) - [`amm.watchRebalanceSwap`](/tempo/actions/amm.watchRebalanceSwap) ================================================ FILE: site/tempo/hooks/dex.useBalance.md ================================================ # `dex.useBalance` Gets a user's token balance on the Stablecoin DEX. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"86f30c8b6ecfcd05a596ac74359c0fbce656e58c96f45bc8cceeb1ce8f608b07","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS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WcGXZSZx6vZ3WA5PxA2eGo5o2n6E57AG2U5qFCQM5Wgc52kK29Qa2GFe+nSYg7kSAnksspgqkIARAFgZ0Z0FgFgIJwg3SE4qsfSnYh4PYrysOiJXy44SosyT45sC4FYQQK5osoEZoCEmSiSPihyGkroJInw5IqIPoGIwI2kQY+INyLFEoRe7FvIMJXFQQElVFg4AyI4MoKJkoAlKo3gJF/gCBeAPFzFjYz+u4UJvIasSyeAjkTkVkRESQqsDFIVIVYAHyu4yJ3ylgrgMsuosAVYScUUw0gg/UCUoi6O6UmUOUMAeUbRjUyVNIZo1kaVQ02EuEWs1kwcM0IyloB0tAcYbIEoUALYqgEE1gTYrYbIEEFgqg94kgEoqgogLYyQCobIbIAE1gkgMAcYqgkgqgBQFgyQDkyQyQl0M0lymyyUh0x0oVe1+1B1h1+1F0W0YA10+VEKfhxkflAVYsiAaOplMACe/gfqogSAoAgQ8gd8eoeAIUIArgrgQAA=="} import { Hooks } from 'wagmi/tempo' const { data: balance } = Hooks.dex.useBalance({ account: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000001', }) console.log('DEX balance:', balance) // @log: DEX balance: 1000000000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type See [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook return types. ### data See [Wagmi Action `dex.getBalance` Return Type](/tempo/actions/dex.getBalance#return-type) ## Parameters See [Wagmi Action `dex.getBalance` Parameters](/tempo/actions/dex.getBalance#parameters) ### query See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook parameters. ## Action - [`dex.getBalance`](/tempo/actions/dex.getBalance) ================================================ FILE: site/tempo/hooks/dex.useBuy.md ================================================ # `dex.useBuy` Buys a specific amount of tokens from the Stablecoin DEX orderbook. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"19b864958a3edb268ed55df991f577eacfa8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vZNwthzlxkz0gyveNjvffayyNHdnziLbNO2pVG7EDc3jsApEQEzlnarB9VUmgpyhWbhDdd5bmmDbLsmx0FECQFAECEqjmjwHZFcFcCAA==="} import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' const buySync = Hooks.dex.useBuySync() // Call `mutate` in response to user action (e.g. button click, form submission) buySync.mutate({ amountOut: parseUnits('100', 6), maxAmountIn: parseUnits('105', 6), tokenIn: '0x20c0000000000000000000000000000000000001', tokenOut: '0x20c0000000000000000000000000000000000002', }) console.log('Transaction hash:', buySync.data?.receipt.transactionHash) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `dex.buy` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' import { useWaitForTransactionReceipt } from 'wagmi' const buy = Hooks.dex.useBuy() const { data: receipt } = useWaitForTransactionReceipt({ hash: buy.data }) // Call `mutate` in response to user action (e.g. button click, form submission) buy.mutate({ amountOut: parseUnits('100', 6), maxAmountIn: parseUnits('105', 6), tokenIn: '0x20c0000000000000000000000000000000000001', tokenOut: '0x20c0000000000000000000000000000000000002', }) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `dex.buy` Return Type](/tempo/actions/dex.buy#return-type) ### mutate/mutateAsync See [Wagmi Action `dex.buy` Parameters](/tempo/actions/dex.buy#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`dex.buy`](/tempo/actions/dex.buy) ================================================ FILE: site/tempo/hooks/dex.useBuyQuote.md ================================================ # `dex.useBuyQuote` Gets the quote for buying a specific amount of tokens. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"cb4e5f5fb447a1a65ef7af20e203bda1f35f12b1e876616083f30b47831f53fb","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUoiaicACUnABmAK5gjowQYJxY4nAwAKpgjGhwwURhcTCInCKkpgoUnLDWLGFwZWBxzABGZJFlbYwKpmgAOrms7FzppJk5eUZQENYIegCycTJojFgm8Jyi5WiVipykMFhHmWBiaymcEDHbnC3tZJxtGHd9JKl0bGbn17dtERgnAAjBZOMFQV8UvI0JEAHRDIYAWk4ABE5k1OPg0GgsE0APT4oiMGDMOFwfD42bzfFxNYmNbwfHjSa5fL+MQKBbIZAgOiiVhyfwsNgcTjANIZbJsuCcVyxUgQZicADkxNJKsRYBZ0umwRVABYAEwWFU1SSRIaEzjGix2+0OsAgAC6zuEml0BvUxnkShUiFBGnE2iCOqm7NkpnMwJsdlIDicUncnhweEIJHIGkCeGCJwgOA4GGiUFEYm6vX6nAAPpwErAYlGoP5qQsQAAVfBAmQRLhwOLWazwODxGQyV6nCAyEhQWqlnYxdicZRAgCOJVIGARYC1Ha7PfK/cHcGHKzHh3gk+ns7EsUXy84a7Im61Q13nG7IgPA6HI7PE6nMAziWN4LqQS6dg+67PtuMFvh+vaHj+p7jheAFAXOt5gfej4bluO4QfBX5Hieo4oXAl6Ade853hBOGbv4IjiLoADs0g+ooyhIAaQZaDoeDAaI/gmGYSAAMyxvYjh+IgAAcybUF4aa+JmAT0Hg1gpJ+a4QDQ5Z9L8NZ1jADZmE2VAtngcH7n237Hr+ZEUehIE0auUFwgxHpIDJ3pyBx/repoIZ4NpNBCVGYkSfGUnOMCBryZgqZ6OmfhZmpegiqMPB8IIHlMVIPm+pxiABc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owoiJ1RYbSpsQLQopIArR+prQdQpRBo5ibbQDRBvEnHD6j4AD8ZQtGNQy8+Ye0YQmCOO+ZYAGAyAzoaMRAEA864IAA1MCNcBmJBsnN6TSsYnoDiUehykbIHhphQlQqwg7MJNhpwMsKsOsBWsGK0DCLKERiRoWhEJkH7sOb+suEMA2BMFwA1tsB9hBCcA0BuH+seKPoFtsHYcnCnCWfxvuaBn2G0CIHkLQSkDGpTEBiwLYeILYiFu7jEMEKJJENTtFiaQrmAMxMZgzsJHEPZhBaLqPklhBaJFzv0DEHCKJG5mgB5pvMEPeHOZ9LidsDtojpKMeNJqwUbLQTIHCPLqWDBkadFrTnFn9Ali2EzpZmljZmzplpzjRdhR5p5jRfRWgKJUiMGFELMjBEbnAPMZ+BpOYhnKoIMYtu8fqIpecGUNHnbjUJpbCFiTEbiWUPpWUOoLYoOcHqbuHiqKZfHvpRKUZR7vWorGZbkZZQ0VqPjkCIpgJaJYxVFisiabadBaZhxSllZjxezlljsrYYJV5iJewArmJUlaWBJVoLEiLDLkCHLqlXtNapyFqdwqYIOP4EQBYHCMCJVXaD6XyiEjJC4sGTVC6noGblGbKo1HJAmeEpiimXoOYZBJdAYgZLWNysZI2GmnoFZJ+DZMRPZKQo5FRDzILE+Nan6WJBYEGSKiVLCsFELO1V6otPIvGUoq6prP4JYXgG1XVTVNCo6v6FYH1XSmYr8GYOwlAGUPXMtI6NKkIodbGZYK4FwhpLAEwMUuKJnLKPKI8vbL8c7K7O7GwJ7NchDR8lDXbM8uqMwG8s0VHFRGUCFECOnJDdnLnOIgXEXAQS9WgPonEqyHqCqPXPHs3K3MXJKoSv3IPBYNYACrzXzfzQLSNGvFPJ3LTZzUPILZLVLfaEaGvBvPSWpScSqKYvQqwu9YgPHoTZvP4KgoJIgKAIEGrO0q6ggK4K4EAA=="} import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' const { data: quote } = Hooks.dex.useBuyQuote({ amountOut: parseUnits('100', 6), tokenIn: '0x20c0000000000000000000000000000000000001', tokenOut: '0x20c0000000000000000000000000000000000002', }) console.log('Amount needed:', quote) // @log: Amount needed: 100300000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type See [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook return types. ### data See [Wagmi Action `dex.getBuyQuote` Return Type](/tempo/actions/dex.getBuyQuote#return-type) ## Parameters See [Wagmi Action `dex.getBuyQuote` Parameters](/tempo/actions/dex.getBuyQuote#parameters) ### query See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook parameters. ## Action - [`dex.getBuyQuote`](/tempo/actions/dex.getBuyQuote) ================================================ FILE: site/tempo/hooks/dex.useCancel.md ================================================ # `dex.useCancel` Cancels an order from the Stablecoin DEX orderbook. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"d99005d358f82f6b8da0b324b8d268d476741fc0146d122b7f8fb1d35c61bdc0","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6INYQYCKc1qJg1jAyAMoY0Yg8fIIAdLC0aQCucDAAwlEx8YnWaQBKOtmkYAAqXgA8+aEAZowKFJzZYPyQAO5gAHz+IuK6ACwAzLLySiqIAIxW1OLaQZHRsQnR/iZmSABMNnakDk5IAGzunjh4hCTkGoFMrOxcBoIjmrqqFzOKyjUGlWOjwHyMe3MR2CJzOfkWbg81C8d18jwC9BebA4nEyXzGl2hcgB82mKy0oL0eNkpihx3sjnhB1U12Rtz09z8T0xeha3UcjFCXTyhU2JWiTVa7U63V6EAGgwAFFh7MwdGQ4AB+ZLgjJ0HIiopbUppAAKqvVpDgkrAbQ6XR6/SGAEodak4HqsrkCkbxWVKmhqnVGs1bdKHXKFQAdMBgURquAqmLCn1i7bWfxQCD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3QIctIccTpCcGqUWvS4QqCmyF8mCHSAEkqJA94cSYg0lMSQiacoQCOuaI11sXA416CU1LW8As1SiC1CS241ipCYA61rezYo121jSri3c5SB1Mgc1JVi1p1JCwia1tEG111W1TiE19101T1L1x1S1Z1n1F1kVJ0qgCw0MG0UM/JzKx1KVopXKyKSA4wVw2V/Ksp+VeAuKRV5Mcs3kVVSsNVXAPVvGH4/VUNzIfJsVDKlleAlVKNaV6N5evK2N3gYE/ggheA1lRlS0BwK0cN8w8VhMIAX0+ixNNYXkHBfkAUYAKVqKbNEprg80IQsAWIbwnE3luE+EDYxEiJZElEbWbANEJk7lSV6YVBuovlhoL00QqkJkDOhQUCt840nmY4j4AEbAYQEeKYIS4C2kG6CghmRUxkEQVk/AnQB5TibYZEF8R4w+1tJoMK7kuklVCtgUFAFUw+WFE6EFUtPiuUst8t+F/l0QGQ8SmoOG8s4cMY/gnsogSAoAgQ8glqoQeAm4IArgrgQAA==="} import { Hooks } from 'wagmi/tempo' const cancelSync = Hooks.dex.useCancelSync() // Call `mutate` in response to user action (e.g. button click, form submission) cancelSync.mutate({ orderId: 123n, }) console.log('Cancelled order ID:', cancelSync.data?.orderId) // @log: Cancelled order ID: 123n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `dex.cancel` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const cancel = Hooks.dex.useCancel() const { data: receipt } = useWaitForTransactionReceipt({ hash: cancel.data }) // Call `mutate` in response to user action (e.g. button click, form submission) cancel.mutate({ orderId: 123n, }) if (receipt) { const { args: { orderId } } = Actions.dex.cancel.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `dex.cancel` Return Type](/tempo/actions/dex.cancel#return-type) ### mutate/mutateAsync See [Wagmi Action `dex.cancel` Parameters](/tempo/actions/dex.cancel#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`dex.cancel`](/tempo/actions/dex.cancel) ================================================ FILE: site/tempo/hooks/dex.useCreatePair.md ================================================ # `dex.useCreatePair` Creates a new trading pair on the Stablecoin DEX. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"30ad47475bf43802763bb99c5cf8fdf2fdf294d49b87a8e6428158f4753de2e3","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6INYQYCKc1qQwojQACqKMpADKGGDWiDx8ggB0sLTZAK5wMADCUTEw8YkpadkASjoFpGAAKl4APCWhAGaMChScBWD8kADuYAB8/iLiugAsAMyy8koqiACMcxri2kGR0XEJyanW/iZmSABMNnakDk5IAGzunjh4hCTkGoFMrOxcBkE000ukeVmMK2Uam2Wh0eEBRnO5muwVu9z8iEuCxe1C8718XwC9F+bA4nDywNmT0ey0UUMQS2oOzhegpslMyJu9kcGMubg8uLeeg+fm+xL03SGjkYoUGxTKB0qRxq1k6PT6AyGIwg4wmAAosPZmDoyHAAPwZBG5OiFeXlQ7VE7ZeJ3Y1OOBqsC9fqDYZjSYASktWTg1vyRVK9qVjtqDTQTVaHS6Xo1vu1uoAOmAwKJjXBDdYYHLI4qqsc0v4oBBrAg9IDON12BF7aYFJxRJwzKNOGg7lBW5xDYlOLLlEWACIAUQAGtks1mAHIQGgZFr4RhwTgb9ucOAnfCkUIQIqcQ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roQY0fHbuqlairqqqfVa8ePa3VCfBRieBYYZhY5rFVjbRblrGo1rDrNrjrbr9rA5g4rrtqNezrY5Vedfk47YHru1M4XxXqjZ3ru0vqfrnNraB4tPE0MbeasaIbakGbhbCaEa2bkaPFOafIqbOAab+acaobGaRaffxayb/fKbubg/XfaaBaPehaCa4ao/Sbb5QeuaQbE/Q/BboambvfibfeJbyaAqWUMfVAOr6P6RFasfWQxkRf2O0QxrFhJrdbpe5U5fxZ5Jo4Dezb1fLk7e/rHeufdAFhVBOV5b2YBe9B++aBm/8fPa3ALoQhYASR/gFIaejJug2JOJuJeIBI7s2BhJ7XyeSqBrdCrQ6e7QGfbIP898SgQcyJ+Uv7wI0Ip7igCEIxuk+FnI4MCgLLF1G8gPpx6/AAYMLhC68ROE74D/Jfyp7ZB+UsUVyCqiSgap0ohqLAdgKwE5QKAA0R/h6y3qa5S43/L8A7F1YHche2MUWmaGyAqp4BwnTXAAEVzqPGCgbJTrjUCNYtA7IAvxgB5kQAboUQEgFACBB5AhaUIHgFvAgBXArgIAA=="} import { Hooks } from 'wagmi/tempo' const createPairSync = Hooks.dex.useCreatePairSync() // Call `mutate` in response to user action (e.g. button click, form submission) createPairSync.mutate({ base: '0x20c0000000000000000000000000000000000001', }) console.log('Base token:', createPairSync.data?.base) console.log('Quote token:', createPairSync.data?.quote) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `dex.createPair` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const createPair = Hooks.dex.useCreatePair() const { data: receipt } = useWaitForTransactionReceipt({ hash: createPair.data }) // Call `mutate` in response to user action (e.g. button click, form submission) createPair.mutate({ base: '0x20c0000000000000000000000000000000000001', }) if (receipt) { const { args: { base, quote } } = Actions.dex.createPair.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `dex.createPair` Return Type](/tempo/actions/dex.createPair#return-type) ### mutate/mutateAsync See [Wagmi Action `dex.createPair` Parameters](/tempo/actions/dex.createPair#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`dex.createPair`](/tempo/actions/dex.createPair) ================================================ FILE: site/tempo/hooks/dex.useOrder.md ================================================ # `dex.useOrder` Gets an order's details from the Stablecoin DEX orderbook. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"1815c3299836587ecb4ba2019dc58a529df6920eadae785fd12d0d622fd85358","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUWKQQOBwYAJScUKJiiJzAADpgnBmc7LCkAJJQSQBGjAqmaADcaZmczKL8ZEkABha0ACTAIqSmCq6NlemZhXz8ANIwGE0t7Z3dvf3VjHAAQowFnEMQcqJg85lojNb8SWAArsyFZLsZoswQJ2BoRSVlV5ykMLWm3U+lD69hMCIPxeVUyZnowL+oIyiwAYiYsEU+FsdtDOAAzBEAFQOR04p3OlzSrk4AB9OPdYOjTDAoP4oBBrAg9Fj8DBODJRCJOHATtZrPA4OiTjIZBg3vBNiQoHEEqIMexOMp2QBHE5kDAAOjSOrArPZnO5vP5guFovF7zgUtpsrECtISrZnDVGu1YF1+o5XK4xoFcCFIrFEqtMmltvl6MVyud6tIWt1aU9hp9fL9AfNwetMvidsjDujLrjbo9TuTPNTpsDFsloZtOY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kCqX8kUZC/8gCICCgYCkCHwbAMCTBElOC9YSQuSJIlChMxMDSnsjCoIYybCHCXCnEEebBrq25jVOg+S+Mnh54Ee/g1qogSAoAgQ8gRKB4eAL8IArgrgQAA==="} import { Hooks } from 'wagmi/tempo' const { data: order } = Hooks.dex.useOrder({ orderId: 123n, }) console.log('Order details:', order) // @log: Order details: { amount: 100000000n, maker: '0x...', isBid: true, ... } ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type See [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook return types. ### data See [Wagmi Action `dex.getOrder` Return Type](/tempo/actions/dex.getOrder#return-type) ## Parameters See [Wagmi Action `dex.getOrder` Parameters](/tempo/actions/dex.getOrder#parameters) ### query See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook parameters. ## Action - [`dex.getOrder`](/tempo/actions/dex.getOrder) ================================================ FILE: site/tempo/hooks/dex.usePlace.md ================================================ # `dex.usePlace` Places a limit order on the Stablecoin DEX orderbook. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"dc89ef7c90b6e3e69c1c36d86e7178af7ac3a72d19bcb225b4b1bdc2a7afa924","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUoiaicACUnABmAK5gjowQYJxY4nAwAKpgjGhwwURhcTCInCKkpgoUnLDWLGFwZWBxzABGZJFlbYwKpmgAOrms7FzppJk5eUZQENYIegCycTJojFgm8Jyi5WiVipykMFhHmWBiaymcEDHbnC3tZJxtGHd9JKl0bGbn17dtERgnAAjBZOMFQV8UvI0JEAHRDIYAWk4ABE5k1OPg0GgsE0APT4oiMGDMOFwfD42bzfFxNYmNbwfHjSa5fL+MQKBbIZAgOiiVhyf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2pX6466Xk8pY0Dim8/gV8ogSAoAgQ8gqrKQeA7IrgrgQAA=="} import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' import { Tick } from 'viem/tempo' const placeSync = Hooks.dex.usePlaceSync() // Call `mutate` in response to user action (e.g. button click, form submission) placeSync.mutate({ amount: parseUnits('100', 6), tick: Tick.fromPrice('0.99'), token: '0x20c0000000000000000000000000000000000001', type: 'buy', }) console.log('Order ID:', placeSync.data?.orderId) // @log: Order ID: 123n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `dex.place` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { parseUnits } from 'viem' import { Tick } from 'viem/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const place = Hooks.dex.usePlace() const { data: receipt } = useWaitForTransactionReceipt({ hash: place.data }) // Call `mutate` in response to user action (e.g. button click, form submission) place.mutate({ amount: parseUnits('100', 6), tick: Tick.fromPrice('0.99'), token: '0x20c0000000000000000000000000000000000001', type: 'buy', }) if (receipt) { const { args: { orderId } } = Actions.dex.place.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `dex.place` Return Type](/tempo/actions/dex.place#return-type) ### mutate/mutateAsync See [Wagmi Action `dex.place` Parameters](/tempo/actions/dex.place#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`dex.place`](/tempo/actions/dex.place) ================================================ FILE: site/tempo/hooks/dex.usePlaceFlip.md ================================================ # `dex.usePlaceFlip` Places a flip order that automatically flips to the opposite side when filled. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"0b032ce2f26b3ba60b7d704cf92957c90fd7feb051b6dc255273d25ecb860c75","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUoiaicACUnABmAK5gjowQYJxY4nAwAKpgjGhwwURhcTCInCKkpgoUnLDWLGFwZWBxzABGZJFlbYwKpmgAOrms7FzppJk5eUZQENYIegCycTJojFgm8Jyi5WiVipykMFhHmWBiaymcEDHbnC3tZJxtGHd9JKl0bGbn17dtERgnAAjBZOMFQV8UvI0JEAHRDIYAWk4ABE5k1OPg0GgsE0APT4oiMGDMOFwfD42bzfFxNYmNbwfHjSa5fL+MQKBbIZAgOiiVhyfwsNgcTjANIZbJsuCcVyxUgQZicADkxNJKsRYBZ0umwRVABYAEwWFU1SSRIaEzjGix2+0OsAgAC6zuEml0BvUxnkShUiFBGnE2iCOqm7NkpnMwJsdlIDicUncnhweEIJHIGkCTBGYoAKoxrPx/CJxLoAOzSH2KZRIA1BrQ6PAFov+ExmJBG2P2Rx+FzJ6heNO+TMBeh4awpERpGQOGAAMRMWAAyhhEmUDII4bBaHC4pkAAqz6wLperxJwgBKOjipDAea8AB4AMIpGK9GoJfiQADuYAAfCWHpIMCoGyL6tYBgAzA2IZ4Bsc6Lus57WG2UZ1t28a9s4ABsA6YKmejpn4WbjnoIqjDwfCCEBZYgUa5bgTW/repocF6JuRjtuY9YgLYPaJogRpGvhQ5ESOHLZuRuZcDutESNBMHVn6SBKWxTZ6HJkYdogvH8VhglGgAHKJhE+BmklkSA8SJJcqT7jAR6IWea7WC+b4fpwX6/gBwTjAKOhkHAAD8G7UXA250Huh7HqeyGuXCB72MwgUTO5YDvtUXlgN+EB/v+XRUYYkW7g5TknkhK4Jd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5LHDrRAu0PHEuOeXZJcfZXE/ogkjuLuHuNOJ7h/0YxU0Q2eH2Qs3b1edeGmSAHAD7QXcG/stC8Arwj4J8c+M3xbr+0VQ4fP+EtAKRR88c+/Srhj2CgRVDeECfwJglEBIBQAgQeQMeRSCe8EArgVwEAA==="} import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' import { Tick } from 'viem/tempo' const placeFlipSync = Hooks.dex.usePlaceFlipSync() // Call `mutate` in response to user action (e.g. button click, form submission) placeFlipSync.mutate({ amount: parseUnits('100', 6), flipTick: Tick.fromPrice('1.01'), tick: Tick.fromPrice('0.99'), token: '0x20c0000000000000000000000000000000000001', type: 'buy', }) console.log('Flip order ID:', placeFlipSync.data?.orderId) // @log: Flip order ID: 456n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `dex.placeFlip` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { parseUnits } from 'viem' import { Tick } from 'viem/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const placeFlip = Hooks.dex.usePlaceFlip() const { data: receipt } = useWaitForTransactionReceipt({ hash: placeFlip.data }) // Call `mutate` in response to user action (e.g. button click, form submission) placeFlip.mutate({ amount: parseUnits('100', 6), flipTick: Tick.fromPrice('1.01'), tick: Tick.fromPrice('0.99'), token: '0x20c0000000000000000000000000000000000001', type: 'buy', }) if (receipt) { const { args: { orderId } } = Actions.dex.placeFlip.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `dex.placeFlip` Return Type](/tempo/actions/dex.placeFlip#return-type) ### mutate/mutateAsync See [Wagmi Action `dex.placeFlip` Parameters](/tempo/actions/dex.placeFlip#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`dex.placeFlip`](/tempo/actions/dex.placeFlip) ================================================ FILE: site/tempo/hooks/dex.useSell.md ================================================ # `dex.useSell` Sells a specific amount of tokens on the Stablecoin DEX orderbook. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"ae5fe3560e82c82e12f7f413d98649d47715c71ac035ce263b44bcd061feddc4","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUoiaicACUnABmAK5gjowQYJxY4nAwAKpgjGhwwURhcTCInCKkpgoUnLDWLGFwZWBxzABGZJFlbYwKpmgAOrms7FzppJk5eUZQENYIegCycTJojFgm8Jyi5WiVipykMFhHmWBiaymcEDHbnC3tZJxtGHd9JKl0bGbn17dtERgnAAjBZOMFQV8UvI0JEAHRDIYAWk4ABE5k1OPg0GgsE0APT4oiMGDMOFwfD42bzfFxNYmNbwfHjSa5fL+MQKBbIZAgOiiVhyfwsNgcTjANIZbJsuCcVyxUgQZicADkxNJKsRYBZ0umwRVABYAEwWFU1SSRIaEzjGix2+0OsAgAC6zuEml0BvUxnkShUiFBGnE2iCOqm7NkpnMwJsdlIDicUncnhweEIJHIGkCeGsKRE5RgMhkAGUMIkygZBHDYLQ4XFMsXCyWy9Y4QAlHRxUhgAAqXgAPABhFIxXo1BL8SAAdzAAD5/CJxLoAOzL2S+5RIAAcQa0OjwmSLpcS/hMZiQAGZY/ZHH5EAA2ZPULxp3yZgL0JgjMWVoyLiSIFuO4+oom6IN6mghngv6nlGl7XvGt7OMCy5PpgqZ6OmfhZp+egiqMtR0AuHpSAa66gf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xHZHgbhVMK18twBEPgGUN9FHH5fpa4Pmps86jAIElXIK3oIaxSEZkTcUvq8JE7pS6oBNhS8CBBHK3oNNDoga0a3S6rsHaoI+FermLAF+I9gzqDCzhDJmU9DDHDKSGwIjOFgzuTmDLFsm+ztTTNZ00Nb+CzB5PFAZJzEjNaIOHWgctUsMXoTi3dJYSaU8CK+CNQQoHCM8CLFcOtLAfwDULqZi20DDNsgtEPJ03CK+hrPzFhtBu7ArqlubH7AHPzHNv1i7G7Izp7PqD7Ou9bPzD7jBpHInlbqnlezbonIHPjEXru+ezHNey+zlkaPnEXEW9aU9fqD2O67vHYBSIgH7DO382pPBXlKs3CEG7ywtE6/gJXSAMvKIEgKAIENVAtN7ggK4K4EAA="} import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' const sellSync = Hooks.dex.useSellSync() // Call `mutate` in response to user action (e.g. button click, form submission) sellSync.mutate({ amountIn: parseUnits('100', 6), minAmountOut: parseUnits('95', 6), tokenIn: '0x20c0000000000000000000000000000000000001', tokenOut: '0x20c0000000000000000000000000000000000002', }) console.log('Transaction hash:', sellSync.data?.receipt.transactionHash) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `dex.sell` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' import { useWaitForTransactionReceipt } from 'wagmi' const sell = Hooks.dex.useSell() const { data: receipt } = useWaitForTransactionReceipt({ hash: sell.data }) // Call `mutate` in response to user action (e.g. button click, form submission) sell.mutate({ amountIn: parseUnits('100', 6), minAmountOut: parseUnits('95', 6), tokenIn: '0x20c0000000000000000000000000000000000001', tokenOut: '0x20c0000000000000000000000000000000000002', }) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `dex.sell` Return Type](/tempo/actions/dex.sell#return-type) ### mutate/mutateAsync See [Wagmi Action `dex.sell` Parameters](/tempo/actions/dex.sell#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`dex.sell`](/tempo/actions/dex.sell) ================================================ FILE: site/tempo/hooks/dex.useSellQuote.md ================================================ # `dex.useSellQuote` Gets the quote for selling a specific amount of tokens. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"e032bbb5ac251a0290eacf6fd15a7b454e27c2398bf4e185fb4d8d10e5253e5b","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUoiaicACUnABmAK5gjowQYJxY4nAwAKpgjGhwwURhcTCInCKkpgoUnLDWLGFwZWBxzABGZJFlbYwKpmgAOrms7FzppJk5eUZQENYIegCycTJojFgm8Jyi5WiVipykMFhHmWBiaymcEDHbnC3tZJxtGHd9JKl0bGbn17dtERgnAAjBZOMFQV8UvI0JEAHRDIYAWk4ABE5k1OPg0GgsE0APT4oiMGDMOFwfD42bzfFxNYmNbwfHjSa5fL+MQKBbIZAgOiiVhyfwsNgcTjANIZbJsuCcVyxUgQZicADkxNJKsRYBZ0umwRVABYAEwWFU1SSRIaEzjGix2+0OsAgAC6zuEml0BvUxnkShUiFBGnE2iCOqm7NkpnMwJsdlIDicUncnhweEIJHIGkCeGCJwgOA4GGiUFEYm6vX6nAAPpwErAYlGoP5qQsQAAVfBAmQRLhwOLWazwODxGQyV6nCAyEhQWqlnYxdicZRAgCOJVIGARYC1Ha7PfK/cHcGHKzHh3gk+ns7EsUXy84a7Im61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N9sHy6ozA3ydRjyVEZQ/Vdsmcv0OcecUihcMAxcHc/iaARiyNDcdocerc7cpcUqNcqoS8Fg1goKnNXN3NPNI068U83c2qrNg87NvNYt4t9oRo68m8tJzxSlj1ViRwHC04VlNQ/VW8/g6CgkiAoAgQ6s3SkqCArgrgQAA==="} import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' const { data: quote } = Hooks.dex.useSellQuote({ amountIn: parseUnits('100', 6), tokenIn: '0x20c0000000000000000000000000000000000001', tokenOut: '0x20c0000000000000000000000000000000000002', }) console.log('Amount received:', quote) // @log: Amount received: 99700000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type See [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook return types. ### data See [Wagmi Action `dex.getSellQuote` Return Type](/tempo/actions/dex.getSellQuote#return-type) ## Parameters See [Wagmi Action `dex.getSellQuote` Parameters](/tempo/actions/dex.getSellQuote#parameters) ### query See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook parameters. ## Action - [`dex.getSellQuote`](/tempo/actions/dex.getSellQuote) ================================================ FILE: site/tempo/hooks/dex.useTickLevel.md ================================================ # `dex.useTickLevel` Gets the tick level information at a specific tick on the Stablecoin DEX orderbook. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"57b65b077fbeb672f0d0226a0c174adf10d17a4561575135f580ae6d087d726d","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHJwAKozW/P4i4roALOrG8koqiAka4tpBkdH+JmZIAIw2dqQOTlLunjh4hCTkGoF4ABRYpBA4HBgAlJxQomKInDl5/AAyMCQyAHQASjoArqRgAGqiMkswnAA+nEtgsABmpjBQ/lAQ1gh64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ZSWhi+4mHHCzChgB4tZiH5qSjgWyTd4VTY5K6cBwXGbsV9Q2FzDdxoBSZ5mZaCUVl65zYEJu7LarZe7rZ1abRmVqWtZmUWUWV5zZBwC9BGrMjl5wBwkAaHBcBwyqCAnw5MmLQZiRUjBz4t58SJWUZBmd5vkjDpVoAjDqDhJfnj4vFV4rkJVy6UaIBL65WZUUk965X5WHFFWPHMiG4m6mWZTmUp5DBWVjY2WO65b2Uu6OWlbOUNluVbSeU7a9I+XdVoB+UBVx6wiJ47DJ6kCp5lS/xiApkoAdRlpBb+BECUq8xErJydl2r/grxOqSLrigJBBT6jkKLbhxh9pkTTmbxUTDlMpLgyB5gCQJSaSeTBTiTViHAnBnCNj4J3x3DGichmhdgWhqh9iaiQjpTDj6i1r/iqDrh9lqCur3WJSyAhgupdqcJ1quhTnbX+BjGLgSaY3pHXVPhWBBqth5Q/Xuy94uZRrFBgDD6iBNH5W82kJiAyATCMBIiSxNwYAjBEogpy3lSuCQKUxPXRgkT9wZiwBMAvacATTvjQzaLL5rQbS7J3TLKwQTQuwbKsznSXTXQVIQD3ThWAyQgjA/XQxwxKQqTTwA3Fjoy0wfwExEwkzWBy2h1h3h0R1h1UzyzoKGJYocqAq4r8z4ox3iySzSyywwDCyKzVEEllUuzs1L4/ViH+DcaiBICgCBDyBlqZgsIICuCuBAA==="} import { Hooks } from 'wagmi/tempo' import { Tick } from 'viem/tempo' const { data: level } = Hooks.dex.useTickLevel({ base: '0x20c0000000000000000000000000000000000001', tick: Tick.fromPrice('1.001'), isBid: true, }) console.log('Tick level:', level) // @log: Tick level: { head: 1n, tail: 5n, totalLiquidity: 1000000000n } ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type See [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook return types. ### data See [Wagmi Action `dex.getTickLevel` Return Type](/tempo/actions/dex.getTickLevel#return-type) ## Parameters See [Wagmi Action `dex.getTickLevel` Parameters](/tempo/actions/dex.getTickLevel#parameters) ### query See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook parameters. ## Action - [`dex.getTickLevel`](/tempo/actions/dex.getTickLevel) ================================================ FILE: site/tempo/hooks/dex.useWatchFlipOrderPlaced.md ================================================ # `dex.useWatchFlipOrderPlaced` Watches for flip order placed events on the Stablecoin DEX. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"ec2db8af3c2ec972afbe7d0d286151f1c33da31056ce694679eda2d35e5d89ec","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXLC0UZq6ACyxSYrKSH0ZWjp47f4mZkhFILb2jn6IAGxV1F61vg0B9HgAZgCuYI6MEGCcB3AwAOqiaLYAYiZYAPKksKQACjIOMFAAPABhM57RgKAB8AAosPZmDoyHAAPyITjAAA6504WPmpgAklBkZwwAdmAAjMicAA+FzAsFBZigAG4MVisZkkSj0ZjWaz2B98YTSWDTFxqUKFCLkABdKlEg4yGSyo50/JMlk81nMUT8MiEgAGFloABJgCJSKYFK49bKDcbTWhzYordLZcSFUraTB6X9mdyNWgBPJ9YaTWaLVabSH7Y7LXqXdS3YrqcqvarfTzXB6VQz06y9qQIMwAEIyCDWfiC4VgUU07M+9VYs4AUVIBdIhMhkLIbZRLbbAEpOABecGcIgQRhQQfJz3eqBZ1M5hucNgKwkOg4wBdz7dp5erqYKXHVshEUQyQnEskUmd1+e3xf1v1anXtlG20MO8PWh9z3ONsAnkYV53jIb5fgJFFO3ZFEAHc7keZ43g+cDrD+AA6ABBLQ4AoThSwUOCEPwICQJQn40KgdCABkIAUQcRzHCcp13Jc/QDHUwGDO0wydH9a0f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oCXl3qJiJIfCiCZrJnhDydWNPvbtQUKUfJwOoCip5o3sstyayUfBZuKSKYfipk0ryZKf7jKWAHjD9C+luJimSTSWidqqBnqhBvNEanibBoSRoUhramSY6lKpSTRtSa6bSThKRj5BRluKYDSaNPnBkNlEgLlGzKYGhP4EQBYOhErDGRYBYAYWzIXMrALLQnzILJAkwnRDYZzPLG3IrErCgtUOgnwjrO4UPFTKPDbOPH6JPNPCpCfPPIvA1h+NGN+OvIGGAFvJ+DGFaHvHohqbPNWGfHABfFAFfNorfMuCNA/HKNeC/MuG/MBJ/LOU/GQP/JQroErLEMsGmWAhYVAjAo3OYHYa3Igh3KoK4KzCJLAM0OUrVHNA1F5AWIkm1Plp1D1DAH1D9HNAtHQEtNZKtHXFLJRNtOqLXB7A7H8FBOyC7D7MOKODtGdFyasi1DBBZu9JiJ9GAHpP4MPKIEgKAIEPIJYmcHgOVCAK4K4EAA==="} import { Hooks } from 'wagmi/tempo' Hooks.dex.useWatchFlipOrderPlaced({ onFlipOrderPlaced: (args, log) => { console.log('args:', args) }, }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `dex.watchFlipOrderPlaced` Parameters](/tempo/actions/dex.watchFlipOrderPlaced#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`dex.placeFlip`](/tempo/actions/dex.placeFlip) - [`dex.watchFlipOrderPlaced`](/tempo/actions/dex.watchFlipOrderPlaced) ================================================ FILE: site/tempo/hooks/dex.useWatchOrderCancelled.md ================================================ # `dex.useWatchOrderCancelled` Watches for order cancelled events on the Stablecoin DEX. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"ee48b5f79e7f2895e840942af571c220f1e3dff682b0163666b36294801e6325","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAW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GqFVlQJ4qsgm85JgiRWVHe4v0B1hBdAVr9b2l1UjnTumXfRlckD+3DrXZw3RG7eGbgnIIYJKXQADDr7KNCOAIjGAPED4DAJcQaOpYBDiKsHaBaZ9cAiUeCM8CMVzAAal+gYnqBNG42PyoFIknjwDr2lQ5mUn3XyRonpX50HCmEyk4AAFkZQXJFIsxMhCQtVRYoISQYEMctQlxAV8BhVHJGA1ouBLFpFhUfUWBxBkEgCQCSNBZZRuNmo2twt/kEE9V9558RBBF4szh+4qxMxxEn4X4mJUl0lcM9gwRYg/Rg0Nktk60wB4g6ko0pgDgeknDC0QCY0nDYhItBQ9hpxYh01RkzMwQIV2DoQeJBYq0zVeC+EEkOY0l4sZBpwy0600AlFJ8Nkw0V8YBI0GlCCY0WljlTlE0LlrJUjQjxlUiMi7h6iTlSonksch04AOcQEZkrRltVBqcHcZcPwjg0BEQz150lxBirQlcPsVdEQJjhjOB1B7EKCOd1EBiujhir05ipiQ968r4hjERFi91v0tce9VJqoXUswUiXI0jGjsj1lQ0tkI1/I9lijY0yid8k1Llqjbkxk6ja0Gj/imikoqImJK0sxTBGiOJxJlYpIkAZIjpTBJx/AiALBpxfo0SLALAT8joz8/oo45Yrphhb8ggVwH9TpdYX8FZDZAZjYP945wZv8rZVpbYFw2QUpGInZEEXY3Y84FZYh/YfZ5ZyTS4ghg53pzAn8a59YZhVBXBDoPxYBmhSFdI/IDJdR9RoEzIiNLIbIYA7Jqo/IAo6AgpsIMYs4dxIpop1ZzT4oUYWQ8YyYgwQx7YCVVjFETIBwr1SpKoKBYJ8CQBrZRAkBQBAh5AD4zg8B1IQBXBXAgA==="} import { Hooks } from 'wagmi/tempo' Hooks.dex.useWatchOrderCancelled({ onOrderCancelled: (args, log) => { console.log('args:', args) }, }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `dex.watchOrderCancelled` Parameters](/tempo/actions/dex.watchOrderCancelled#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`dex.cancel`](/tempo/actions/dex.cancel) - [`dex.watchOrderCancelled`](/tempo/actions/dex.watchOrderCancelled) ================================================ FILE: site/tempo/hooks/dex.useWatchOrderFilled.md ================================================ # `dex.useWatchOrderFilled` Watches for order filled events on the Stablecoin DEX. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"d6ebca7ccec7392508f050d98ee570f2e62a86cf7af165696dace79303079a4f","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXLC0UZq6ACyxSYrKSH0ZWjp47f4mZkhFILb2jn6IAGxV1F61vg0B9HgAZgCuYI6MEGCcB3AwAOqiaLYA8qSwpABijDJyUAA8AMJne0YCgAfAAKLD2Zg6MhwAD8iE4wAAOudOGj5qYAJJQeGcMAHZgAIzInAAPhcwLBAWYoABuFFotGZOEI5GoxmM9gvbG4wlA0xccl8hQC5AAXTJeIOn0lRyp+TpDI5jOYon4ZFxAAMLLQACTAESkUwKVyayXavUGtBGxSm8WS/Ey8lymDUmCK9mcVyStnKznPMg8hHCgWSkNgND28mOmSyymuhX0z0c1Xq0hanX6w3G03mzNWm0mzVRqVOinymlJv1osRpjOW7O2s3ki1Z6054sS6PS2PO+Nuj0c719ivuquMvakCDMABCMgg1n4vP5Ebjo8HnLAAFFSFP0wjQaCyHuETu9wBKTgAXmBnCIEEYUEvI4TNLXr7HSrRbE+uOtBxgd8ByAxMv04H8pgUTEIzIIhRBkXF8SJEkX2A1DQM9VMNQRVsCw7EDKzAs4nhed5PndXFD2ZBEAHc7keAM3g+L4ADo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emTLym8Sih8Ywd8WtL8W+qSgCZBkCXKSCZxEBplKBoBKYMCQdM1IfOvCgGgaYBFP4EQBYCxErCaRYBYJwZLNwcrErOkMAorGAqMBAn/HrOYBIZfNIcrAULIZsJPHbIobPDzAvD7EvH7CvO6IHOvFwfXF6ZvM3IrBIUIUEKfK6eIYPMbMPAUKoK4BLDgrAM0MEhNDkJVN6JONOOJn5itOtDAJtEjMWVdHQDdFcHjN/OGZ9OdN3HFF8AeMyMHBJFJLeC9KnpQk3tRGJrDKiPDGAL5P4HPKIEgKAIEPIAImcHgENCAK4K4EAA="} import { Hooks } from 'wagmi/tempo' Hooks.dex.useWatchOrderFilled({ onOrderFilled: (args, log) => { console.log('args:', args) }, }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `dex.watchOrderFilled` Parameters](/tempo/actions/dex.watchOrderFilled#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`dex.buy`](/tempo/actions/dex.buy) - [`dex.watchOrderFilled`](/tempo/actions/dex.watchOrderFilled) ================================================ FILE: site/tempo/hooks/dex.useWatchOrderPlaced.md ================================================ # `dex.useWatchOrderPlaced` Watches for order placed events on the Stablecoin DEX. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"3e7dca1cf113bef29341a671f24d7e6ec1d9eec74f78c78ceefe4f494ee9551f","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXLC0UZq6ACyxSYrKSH0ZWjp47f4mZkhFILb2jn6IAGxV1F61vg0B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ygBwhI8E3EzAXK0Kl6NqdUEkmqdUt696JghIdU/SGy3YxMwgXQMcFgB8NMqQVM8c58cwPG8CSAJ8cwt82cshaC3gGCb8QQoIEa0AvYk+e0ukcA3mMAuI8kGAaEIMsKpinUx4+MKMcmxh4oaklEo4M2AA1HTO5PUIWClnwVQNZHQngJAZWuElqKpuaMavgHiLPlMKspwAALLSgdRpS+xaAEidpBTWD6oLi9pXDKZhEtowCtSMBYxcCGo1J5F2IsDiDOJ6EGG+a+zOgpavTQa7YTLTi9oiJUEiBFKw534PargVJqIaLzIMr0Z7CgixDdgHrsqcpqhgDxCwrnpTAHBYozF/oGGXozGxD7YCh7DwSxAvokrI6ghWqZApGBRJFrijoQj5L3LhKvKnYyDwQ/RQbNIkHsrHr0EwBnrwq+GXrIpCoip3piqPr3H7Fkr3FPF3AQnCqrTKr254ZwBx5mIjy+Ru6qCB5t5NIVTcSjwIgCaUZoTYnlgV4y5V5xI4mcDqAqYKrj734UJF77SEljwiaMnEm75QGMkIiUkcbUlN6wy3SLprh3EdQPFQkvFspHqcqnrDS8o/FXr/HsFAn1QgkyqkrgmQaQnqnQkoRAZOSgZrimBQmdQxSnzxRICJSkymBwT+BEAWDwR0x2kWAWD8GkyCH0x0zpAQK0xxxnywKkQyEUy8xZz8x0y5xCz5wqGvwSzqFlyYyVxqzVxei1z1zSQTzNytzRYsIdwDxdzzg9xgB9yvgRhmhDxcLkmNzlhTwzxzzSQLxLy5krz8BrwEgbxbwgIxwFC7xRy0xyESFBCXypzmByGZx3w5yqCuAkzcSwDNDBKFRDQlQOQ5i2JVTea1QNQwBNS3RDQjR0BjRGSTTJwzRzRJyGwETATMi6wmz9iDhzQbQYnF4VSgQiYXSohXRgCqT+DlyiBICgCBDyCiJnB4DZQgCuCuBAA==="} import { Hooks } from 'wagmi/tempo' Hooks.dex.useWatchOrderPlaced({ onOrderPlaced: (args, log) => { console.log('args:', args) }, }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `dex.watchOrderPlaced` Parameters](/tempo/actions/dex.watchOrderPlaced#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`dex.place`](/tempo/actions/dex.place) - [`dex.watchOrderPlaced`](/tempo/actions/dex.watchOrderPlaced) ================================================ FILE: site/tempo/hooks/dex.useWithdraw.md ================================================ # `dex.useWithdraw` Withdraws tokens from the Stablecoin DEX to your wallet. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"1ba49397fce40202581f9380b2e1c849c02f8b39dbc63f623cec1edd321703c9","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUoiaicACUnABmAK5gjowQYJxY4nAwAKpgjGhwwURhcTCInCKkpgoUnLDWLGFwZWBxzABGZJFlbYwKpmgAOrms7FzppJk5eUZQENYIegCycTJojFgm8Jyi5WiVipykMFhHmWBiaymcEDHbnC3tZJxtGHd9JKl0bGbn17dtERgnAAjBZOMFQV8UvI0JEAHRDIYAWk4ABE5k1OPg0GgsE0APT4oiMGDMOFwfD42bzfFxNYmNbwfHjSa5fL+MQKBbIZAgOiiVhyfwsNgcTjANIZbJsuCcVyxUgQZicADkxNJKsRYBZ0umwRVABYAEwWFU1SSRIaEzjGix2+0OsAgAC6zuEml0BvUxnkShUiFBGnE2iCOqm7NkpnMwJsdlIDicUncnhweEIJHIGkCeGsKREnAA7nl8FB4wWAMoYRJlAyCOGwWhwuKZADqxdLogrVescIASjo4qQwAAVLwAHgAwikYr0agl+JAC2AAHz+ETiXQAdk3sl9yiQwKNQa0OjwReUHa7iX8JjMSAAzLH7I4/IgAGzJ6heNO+TMBehMCMYq1kY64SC4R4+oo+6IN6m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BqiunGwQFcFcCAA==="} import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' const withdrawSync = Hooks.dex.useWithdrawSync() // Call `mutate` in response to user action (e.g. button click, form submission) withdrawSync.mutate({ amount: parseUnits('100', 6), token: '0x20c0000000000000000000000000000000000001', }) console.log('Transaction hash:', withdrawSync.data?.receipt.transactionHash) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `dex.withdraw` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' import { useWaitForTransactionReceipt } from 'wagmi' const withdraw = Hooks.dex.useWithdraw() const { data: receipt } = useWaitForTransactionReceipt({ hash: withdraw.data }) // Call `mutate` in response to user action (e.g. button click, form submission) withdraw.mutate({ amount: parseUnits('100', 6), token: '0x20c0000000000000000000000000000000000001', }) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `dex.withdraw` Return Type](/tempo/actions/dex.withdraw#return-type) ### mutate/mutateAsync See [Wagmi Action `dex.withdraw` Parameters](/tempo/actions/dex.withdraw#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`dex.withdraw`](/tempo/actions/dex.withdraw) ================================================ FILE: site/tempo/hooks/faucet.useFund.md ================================================ # `faucet.useFund` Hook for funding an account with testnet tokens on Tempo's testnet. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"1a95b41c202f29f8ef89605e6082e91c25c3ea600cf822463485a078a7ff5484","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgD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FIaHficdLEkTds67B0STaTRMe7BpR7JTF7e8Tc6c5jTc0HUgGHR8mHaKWYbsfTfCXHOAUIxpIlNCVQTw3XaowcK2eIYXSnFoK2f4x09osCzgdQYlV00IqVTI/nMC8XCVQsGCworC82BCtQ5Co+dcfCTbEOMDW8l83cls/c87UTI8ns08vDAjC8mkq8lTW8j7JjB8nctAKiojd8kHNMCHEOUwfivKHuQkPuFAJE0wDIfwIgCwJIUEZSiwCwVk8qTEN/DkrkpAaqD5XkwnAUlwIU7qJAPaMUmEYaSUvAc4yaO0QwR0LCFqN0JaZWGAVaP0MUS0Hoe4HaN/QYA6GqI6KYHk86WMYwdqEy26QFEEYYYFfqUFIaNkeEKU8Nb6WFU1XxeIAWd0T0UWM5EObGF2PGaxBVfFZVVtLgIxcBSBCpAqEVEgGyHxMQVMfODNbRMAOHYMSqmWaqgpTeOqlreARq9xFqvxR8mpIBUIbq9NEOKqlsAakxKuDBTHJqrK1qyahhYuGa/CHqwRBamqwa0xYatasa3xNqqazqySx5NYVQaqalEKk6AyoIca4y6QGK4UqYUUxKwaacfwHgvAIytku6j6x6vEZ4VvQOLYMIbYcOOwOAYOdo5ACSWgdUzC1G9G/yYy0EUEUy+6UUsqEIWAREa4f8aaZCCIM8C8K8G8O8R8AcNgQcIgrwyaMglUWaZ0Fy2IPCNNWnWoGbPeHKCzT9VatgMIMPDUDGOG3kCUZdBQAzVyOiYCVifgLyAWb5QSciJlfC1G6SWSeSCIfWuSBSY2w2s2021bA2hScXYMVwLyFCodECioGG7Sd+BGpGxATCgWcaryfwJLUQJAUAQIeQI1UIPATcEAVwVwIAA="} import { Hooks } from 'wagmi/tempo' const fund = Hooks.faucet.useFund() // Call `mutate` in response to user action (e.g. button click) fund.mutate({ account: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef', }) console.log('Transaction hashes:', fund.data) // @log: Transaction hashes: ['0x...', '0x...'] ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Synchronous Usage Use `useFundSync` to wait for the transactions to be included on a block before returning: ```ts twoslash // @twoslash-cache: {"v":1,"hash":"70c6e7579f56d5a55b4b8b81f596b6b59a686064ee970a2e241dca8d21b48c36","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6INYQYCKcAGYArmBQAMoYYNaIPHyCAHQRolHWOulRcDAAYjHxidbpAEo6UaRgACpeADwAwqERjAoUnDH8kADuYAB8/iLiugAsAMyy8koqiAAcGuLaQdGxCUn+JmZIAEw2dqQOTkgAbO6eOHiEJOQagUys7FwGgqOauqoTs4rKahWWh0eHeRl25kOwWOpz8iAAjAB2K7ULy3XwPAL0Z5sDiRbK5BjCL4XKzGOYAxDnIFrPBZHIg2SmSFHeyOOH7KYozA3PR3PyPbF6DaORihHqFEqbcqtdqdbq9AbDAAUWHszB0ZDgAH4UmDMgS8gViqUthUAArqzWkOCysAdLo9MB9CCDIYASj1aTgBoZaHyktN5SqNTqjRwdodCudSqGAB0wGBRBq4GrchKTdLtlQoBBrAg9O9IuxIqVTApOKIwJXrCEYlx+oxlJXq6Ym4xRDJK8wIPXOBAIpxClw0AJ5Mq4O6E+L6jAXgByOCcGgiMz+zjVNC1MLL/AwZcnMKnMXV0gwXKMLBoH3+MQKAvIZAgOjJrByfwAAy/19oCZYuK4YBUkMThXEiUgIGYTh536UQFGYRgAHoaAXBMExFNAT04ABBLAsGVd1OGABNOE4EIwkAzhmCiMQaG6Rg4HNeQoHLUDOAAXmAjJ6UJANMzKJICLQ6tODPLc6k4ZUSNIzgmgAIxo0cwGkmT+zAFoTGsfh2OAAiOKGKiaNEGhlSAhw6zANAUnnCxaFgUQoDkmAYAidI3PnUD3VcFSZJYuBRDkuQoB0himNictvJE0j4yimSpSgHDa17SyfKaRCFLQJSYtIqcwEir8PxAABdCgnzVE5mH8crk2tJcAFp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QGkvjrOtyn8HG1ECQFAECHkEzVCDwGvBAFcFcCAA="} import { Hooks } from 'wagmi/tempo' const fundSync = Hooks.faucet.useFundSync() // Call `mutate` in response to user action fundSync.mutate({ account: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef', }) console.log('Receipts:', fundSync.data) // @log: Receipts: [{ blockNumber: 123n, ... }, { blockNumber: 123n, ... }] ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `faucet.fund` Return Type](/tempo/actions/faucet.fund#return-type) ### mutate/mutateAsync See [Wagmi Action `faucet.fund` Parameters](/tempo/actions/faucet.fund#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`faucet.fund`](/tempo/actions/faucet.fund) ================================================ FILE: site/tempo/hooks/fee.useSetUserToken.md ================================================ # `fee.useSetUserToken` Sets the user's default fee token preference. [Learn more about fees](https://docs.tempo.xyz/protocol/fees) ## Usage ::: code-group ```ts [example.ts] import { Hooks } from 'wagmi/tempo' const setUserToken = Hooks.fee.useSetUserToken() // Call `mutate` in response to user action setUserToken.mutate({ token: '0x20c0000000000000000000000000000000000001', }) ``` ```ts [wagmi.config.ts] filename="wagmi.config.ts" // @noErrors import { createConfig, http } from 'wagmi' import { tempo } from 'wagmi/chains' import { KeyManager, webAuthn } from 'wagmi/tempo' export const config = createConfig({ connectors: [ webAuthn({ keyManager: KeyManager.localStorage(), }), ], chains: [tempo], multiInjectedProviderDiscovery: false, transports: { [tempo.id]: http(), }, }) ``` ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `fee.setUserToken` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const setUserToken = Hooks.fee.useSetUserToken() const { data: receipt } = useWaitForTransactionReceipt({ hash: setUserToken.data }) // Call `mutate` in response to user action (e.g. button click, form submission) setUserToken.mutate({ token: '0x20c0000000000000000000000000000000000001', }) if (receipt) { const { args } = Actions.fee.setUserToken.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `fee.setUserToken` Return Type](/tempo/actions/fee.setUserToken#return-type) ### mutate/mutateAsync See [Wagmi Action `fee.setUserToken` Parameters](/tempo/actions/fee.setUserToken#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`fee.setUserToken`](/tempo/actions/fee.setUserToken) ================================================ FILE: site/tempo/hooks/fee.useUserToken.md ================================================ # `fee.useUserToken` Gets the user's default fee token preference. [Learn more about fees](https://docs.tempo.xyz/protocol/fees) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"b8231de1b5901110cbc0e94b2094ed4e055d2895dce944b0b9737724513705ec","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUWKQQOBwYAJScUKJiiJzaaACqcGQAKgLyAHQASjoArqRgAGqiMkUwnAA+nEVgsABmpjBQ/lAQ1gh6mfg1MqIinHBF1tbwcM1FMjIYnKTwEDIkUHEJopzN7JzKNQCO1aQYuQA6YBcX/YPDXGMTUzNzC0twK2sbYtu7+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fOB3F6y2iwADiFxFQbSCArQVS4I3b1RNQtRsBtQqMkGTSbBJAEUyT1frRsQcQaQwAkV7Q1zKxeJnQXRXSPhigahQDviqDYTWATgThgTYRPQG6SAaiqCiDviSIGhihigABC1gkgMAxskgqgzQFgkidWkikir0VMJu177ZWXis8gSlpMiA12vX3ohM3LVZr3Gh73nLn3uXv3glhMDyJu/gcCogSAoAgQ8g/8doeAOUIArgrgQAA=="} import { Hooks } from 'wagmi/tempo' const { data: userToken } = Hooks.fee.useUserToken({ account: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', }) console.log('Fee token address:', userToken?.address) // @log: Fee token address: 0x20c0000000000000000000000000000000000000 console.log('Fee token ID:', userToken?.id) // @log: Fee token ID: 0n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type See [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook return types. ### data See [Wagmi Action `fee.getUserToken` Return Type](/tempo/actions/fee.getUserToken#return-type) ## Parameters See [Wagmi Action `fee.getUserToken` Parameters](/tempo/actions/fee.getUserToken#parameters) ### query See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook parameters. ## Action - [`fee.getUserToken`](/tempo/actions/fee.getUserToken) ================================================ FILE: site/tempo/hooks/fee.useWatchSetUserToken.md ================================================ # `fee.useWatchSetUserToken` Watches for user token set events on the Fee Manager. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"f9462d4450dd5426fccf47a3f9f6bfcb416366af2a61b5019d81726cd9f71789","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXABmMLjC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AsABqWGD1eoSMcTG/KgPiE+PARPNhbxHkMDSUJFfASXU8CGEFAAWWdDQCa2/kyAJGtXOmsDhUfntU8RfAYJx38kYDOi4C5FbHtRxzHFFC7VIFISgNo0IlkJdHE36k4LOEhRkJ0Rqg3xEGUT60L2K37AgXcmgXlk4SOQPTaFBFiFLETUuWuS7TAHiH6QzQnAOFmXcPrWgKzXcNiCSwTDaFvFiF+TLRkAc1BExR4KhBUnfnbXdQhAUUKVsJ5AyxkFvE7TuCMSX0uRTV3xgHTUGXIKzVGReTeXzU+U8myKiPLWyLyLQBaIukamBRJznTgCF0wV2WnC21UFZ0gyXVgiODQAREfS3RfDGOnB13+271mImM4HUFFjAyF3MVGP6ImNfSWPmKd0PQEXGIRFWMvTY0902nahDU4HKQaJaIKIuWTWuTTVUnuQqOzWqNPwLS+QaL+XWWaPYC7VaMBLuHaNymElEjbQHFMBaJ7VVgyE0iQG0melMBYn8CIAsFvFhixIsAsFv2egTjhlhg+if1SFGFfyzmHgti/3HltiQFhntjLlnmdjRj2BAI9lOm9ifFZFHH9ijllEW1DnDiqjkn5NtBDglDjjv10FhlC0GH7jegNnGCCBzmpPTlpJhinlcCelglgGaFYWshijsmDFDDfRo3ci8hgB8nahilyM6HiiuGGk4lbkynkFSn1BNiZgPARByk0lplZkrGrF9gZT3gtychPFfUalagoDWlIJAE9lECQFAECHkE/jODwFMhAFcFcCAA"} import { Hooks } from 'wagmi/tempo' Hooks.fee.useWatchSetUserToken({ onUserTokenSet: (args, log) => { console.log('args:', args) }, }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `fee.watchSetUserToken` Parameters](/tempo/actions/fee.watchSetUserToken#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`fee.setUserToken`](/tempo/actions/fee.setUserToken) - [`fee.watchSetUserToken`](/tempo/actions/fee.watchSetUserToken) ================================================ FILE: site/tempo/hooks/index.md ================================================ # Overview | Hook | Description | |--------|-------------| | **AMM Hooks** | | | [`amm.useBurn`](/tempo/hooks/amm.useBurn) | Hook for burning liquidity tokens and receiving the underlying token pair | | [`amm.useLiquidityBalance`](/tempo/hooks/amm.useLiquidityBalance) | Hook for getting the liquidity balance for an address in a specific pool | | [`amm.useMint`](/tempo/hooks/amm.useMint) | Hook for minting liquidity tokens by providing a token pair | | [`amm.usePool`](/tempo/hooks/amm.usePool) | Hook for getting the reserves for a liquidity pool | | [`amm.useRebalanceSwap`](/tempo/hooks/amm.useRebalanceSwap) | Hook for performing a rebalance swap between user and validator tokens | | [`amm.useWatchBurn`](/tempo/hooks/amm.useWatchBurn) | Hook for watching liquidity burn events | | [`amm.useWatchMint`](/tempo/hooks/amm.useWatchMint) | Hook for watching liquidity mint events | | [`amm.useWatchRebalanceSwap`](/tempo/hooks/amm.useWatchRebalanceSwap) | Hook for watching rebalance swap events | | **Faucet Hooks** | | | [`faucet.useFund`](/tempo/hooks/faucet.useFund) | Hook for funding an account with testnet tokens | | **Fee Hooks** | | | [`fee.useSetUserToken`](/tempo/hooks/fee.useSetUserToken) | Hook for setting the user's default fee token preference | | [`fee.useUserToken`](/tempo/hooks/fee.useUserToken) | Hook for getting the user's default fee token preference | | [`fee.useWatchSetUserToken`](/tempo/hooks/fee.useWatchSetUserToken) | Hook for watching user token set events | | **Nonce Hooks** | | | [`nonce.useNonce`](/tempo/hooks/nonce.useNonce) | Hook for getting the nonce for an account and nonce key | | [`nonce.useWatchNonceIncremented`](/tempo/hooks/nonce.useWatchNonceIncremented) | Hook for watching nonce incremented events | | **Policy Hooks** | | | [`policy.useCreate`](#TODO) | Hook for creating a new transfer policy for token access control | | [`policy.useData`](#TODO) | Hook for getting the data for a transfer policy, including its type and admin address | | [`policy.useIsAuthorized`](#TODO) | Hook for checking if an address is authorized by a transfer policy | | [`policy.useModifyBlacklist`](#TODO) | Hook for modifying the blacklist for a blacklist-type transfer policy | | [`policy.useModifyWhitelist`](#TODO) | Hook for modifying the whitelist for a whitelist-type transfer policy | | [`policy.useSetAdmin`](#TODO) | Hook for setting the admin for a transfer policy | | [`policy.useWatchAdminUpdated`](#TODO) | Hook for watching policy admin update events | | [`policy.useWatchBlacklistUpdated`](#TODO) | Hook for watching blacklist update events | | [`policy.useWatchCreate`](#TODO) | Hook for watching policy creation events | | [`policy.useWatchWhitelistUpdated`](#TODO) | Hook for watching whitelist update events | | **Reward Hooks** | | | [`reward.useClaim`](/tempo/hooks/reward.useClaim) | Hook for claiming accumulated rewards | | [`reward.useSetRecipient`](/tempo/hooks/reward.useSetRecipient) | Hook for setting or changing the reward recipient for a token holder | | [`reward.useDistribute`](/tempo/hooks/reward.useDistribute) | Hook for distributing tokens to opted-in holders | | [`reward.useUserRewardInfo`](/tempo/hooks/reward.useUserRewardInfo) | Hook for getting reward information for a specific account | | [`reward.useWatchRewardRecipientSet`](/tempo/hooks/reward.useWatchRewardRecipientSet) | Hook for watching reward recipient set events | | [`reward.useWatchRewardDistributed`](/tempo/hooks/reward.useWatchRewardDistributed) | Hook for watching reward distributed events | | **Stablecoin DEX Hooks** | | | [`dex.useBalance`](/tempo/hooks/dex.useBalance) | Hook for getting a user's token balance on the Stablecoin DEX | | [`dex.useBuy`](/tempo/hooks/dex.useBuy) | Hook for buying a specific amount of tokens from the Stablecoin DEX orderbook | | [`dex.useBuyQuote`](/tempo/hooks/dex.useBuyQuote) | Hook for getting the quote for buying a specific amount of tokens | | [`dex.useCancel`](/tempo/hooks/dex.useCancel) | Hook for canceling an order from the orderbook | | [`dex.useCreatePair`](/tempo/hooks/dex.useCreatePair) | Hook for creating a new trading pair on the DEX | | [`dex.useOrder`](/tempo/hooks/dex.useOrder) | Hook for getting an order's details from the orderbook | | [`dex.usePlace`](/tempo/hooks/dex.usePlace) | Hook for placing a limit order on the orderbook | | [`dex.usePlaceFlip`](/tempo/hooks/dex.usePlaceFlip) | Hook for placing a flip order that automatically flips when filled | | [`dex.useTickLevel`](/tempo/hooks/dex.useTickLevel) | Hook for getting the price level information at a specific tick | | [`dex.useSell`](/tempo/hooks/dex.useSell) | Hook for selling a specific amount of tokens from the Stablecoin DEX orderbook | | [`dex.useSellQuote`](/tempo/hooks/dex.useSellQuote) | Hook for getting the quote for selling a specific amount of tokens | | [`dex.useWatchFlipOrderPlaced`](/tempo/hooks/dex.useWatchFlipOrderPlaced) | Hook for watching flip order placed events | | [`dex.useWatchOrderCancelled`](/tempo/hooks/dex.useWatchOrderCancelled) | Hook for watching order cancelled events | | [`dex.useWatchOrderFilled`](/tempo/hooks/dex.useWatchOrderFilled) | Hook for watching order filled events | | [`dex.useWatchOrderPlaced`](/tempo/hooks/dex.useWatchOrderPlaced) | Hook for watching order placed events | | [`dex.useWithdraw`](/tempo/hooks/dex.useWithdraw) | Hook for withdrawing tokens from the DEX to the caller's wallet | | **Token Hooks** | | | [`token.useAllowance`](/tempo/hooks/token.useGetAllowance) | Hook for getting the amount of tokens that a spender is approved to transfer on behalf of an owner | | [`token.useApprove`](/tempo/hooks/token.useApprove) | Hook for approving a spender to transfer TIP-20 tokens on behalf of the caller | | [`token.useBalance`](/tempo/hooks/token.useGetBalance) | Hook for getting the token balance of an address | | [`token.useBurn`](/tempo/hooks/token.useBurn) | Hook for burning TIP-20 tokens from the caller's balance | | [`token.useBurnBlocked`](/tempo/hooks/token.useBurnBlocked) | Hook for burning TIP-20 tokens from a blocked address | | [`token.useChangeTransferPolicy`](/tempo/hooks/token.useChangeTransferPolicy) | Hook for changing the transfer policy for a TIP-20 token | | [`token.useCreate`](/tempo/hooks/token.useCreate) | Hook for creating a new TIP-20 token and assigning the admin role to the calling account | | [`token.useGrantRoles`](/tempo/hooks/token.useGrantRoles) | Hook for granting one or more roles to an address | | [`token.useHasRole`](/tempo/hooks/token.useHasRole) | Hook for checking if an address has a specific role | | [`token.useMetadata`](/tempo/hooks/token.useGetMetadata) | Hook for getting the metadata for a TIP-20 token, including name, symbol, decimals, currency, and total supply | | [`token.useMint`](/tempo/hooks/token.useMint) | Hook for minting new TIP-20 tokens to a recipient | | [`token.usePause`](/tempo/hooks/token.usePause) | Hook for pausing a TIP-20 token, preventing all transfers | | [`token.useRenounceRoles`](/tempo/hooks/token.useRenounceRoles) | Hook for renouncing one or more roles from the caller's address | | [`token.useRevokeRoles`](/tempo/hooks/token.useRevokeRoles) | Hook for revoking one or more roles from an address | | [`token.useSetRoleAdmin`](/tempo/hooks/token.useSetRoleAdmin) | Hook for setting the admin role for another role | | [`token.useSetSupplyCap`](/tempo/hooks/token.useSetSupplyCap) | Hook for setting the supply cap for a TIP-20 token | | [`token.useTransfer`](/tempo/hooks/token.useTransfer) | Hook for transferring TIP-20 tokens from the caller to a recipient | | [`token.useUnpause`](/tempo/hooks/token.useUnpause) | Hook for unpausing a TIP-20 token, allowing transfers to resume | | [`token.useWatchAdminRole`](/tempo/hooks/token.useWatchAdminRole) | Hook for watching role admin update events | | [`token.useWatchApprove`](/tempo/hooks/token.useWatchApprove) | Hook for watching token approval events | | [`token.useWatchBurn`](/tempo/hooks/token.useWatchBurn) | Hook for watching token burn events | | [`token.useWatchCreate`](/tempo/hooks/token.useWatchCreate) | Hook for watching new token creation events | | [`token.useWatchMint`](/tempo/hooks/token.useWatchMint) | Hook for watching token mint events | | [`token.useWatchRole`](/tempo/hooks/token.useWatchRole) | Hook for watching role membership update events | | [`token.useWatchTransfer`](/tempo/hooks/token.useWatchTransfer) | Hook for watching token transfer events | ================================================ FILE: site/tempo/hooks/nonce.useNonce.md ================================================ # `nonce.useNonce` Hook for getting the nonce for an account and nonce key. This is useful for managing multiple nonce lanes for parallel transaction submission. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"0f0dff491f1f51aaa648ec0523093330756da7886231a68a5880eae563132b80","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELw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kg71khkgFologEMANotoUYqsXc0kPiSzaMlwqt/AYlRAkBQBAh5AmE9Q8BvIQBXBXAgA==="} import { Hooks } from 'wagmi/tempo' const { data: nonce } = Hooks.nonce.useNonce({ account: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', nonceKey: 1n, }) console.log('Nonce:', nonce) // @log: Nonce: 42n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type See [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook return types. ### data See [Wagmi Action `nonce.getNonce` Return Type](/tempo/actions/nonce.getNonce#return-type) ## Parameters See [Wagmi Action `nonce.getNonce` Parameters](/tempo/actions/nonce.getNonce#parameters) ### query See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook parameters. ## Action - [`nonce.getNonce`](/tempo/actions/nonce.getNonce) ================================================ FILE: site/tempo/hooks/nonce.useWatchNonceIncremented.md ================================================ # `nonce.useWatchNonceIncremented` Hook for watching nonce incremented events. This event is emitted whenever a transaction is executed using a specific nonce key. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"3c41f7db5af5a58ed8f5640547d78b93c2c5a437602369ef24ea876941670c37","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXJBg1rjCmroALLFJispqGpk6eO2d/iZmSEUgtvaOfogAbFXUXrW+DQH0eABmAK4daIwQYJxHcDAA6qJotgByF50Akh2kMMzyNFAAPABhC4HRgKAB8AAosPYfk44AB+RCcYAAHUunExi1MbygSM4YCOzAARmROAAfK5gWCgsxQADc6MxmMyiORaIxzOZDmsEBOaHxAAMLLQACTA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DNRmI4ImwNsABqXWedeoOMfLMQqgSSaVPAFA1JbZQUITGFK1JpCzGYFdTgaKD0M4eqYcTIIkXGVZS4TKGEepP0b8RpfAatOaRgHmLgS1OpF3KyFgcQIJMwiwiLfKT0fLBGNHC7PiX5aojpYkEQa1B7C4VhRcIcdpExWpDGIFEFDjA4SEWIQZGg4VUVZDMAeIbFR9GYI4clFYiDCwmVFY2IK7B0A4F8WIf9dVGQCbSEJ1TI0CZNEqOdfIm4LZDOYFB7GQF8JDB4KZRYm9UVe9AySVUI59OVN9fgxVH9d484jVd4r4tAOEkKYGPVSGCmH3BnHRfkZnVQGPFfAfQaJeFMZEKTJjb8AkjlZAqfMk5EdQfZGIzPThPEqkuTMkifC/TjDEwkzgGkwTfTBfCmSGbdYcN4s4D4uEn4oVP4u9cVQEx9YE2VIlMEhVb9CaKEgDRlWE9gZDeEzUh4REz8GDBSeDYcRDHUjowyUYEyJAMyAWDSPhIgCwF8XWR0iwCwcQgWCuPWAoeQzBCWHuTQXBYwKCFQ4WLWH+HWfWbQyhEBc2fQqebmWeT8dkZCHkPkTk1eZUVUGUQUI+Hea0c+B0HMk+M+UJA+K+FBXQXWXoKwMWR+VQnBRQ9+TucwNQ4hHWAoVQVwfmXkWAZoFJLqLaXqCMKMeTMLMaSab4NgGaT/LaF8HaBWd2eBUuP4M6E0VuI6Jcv0ZEW6Eye6MOGsOseeQvBk8TS8OTYGcGCgUmYIkAOEUQJAUAQIeQcqC4PAFqEAVwVwIAA=="} import { Hooks } from 'wagmi/tempo' Hooks.nonce.useWatchNonceIncremented({ onNonceIncremented: (args, log) => { console.log('args:', args) }, }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `nonce.watchNonceIncremented` Parameters](/tempo/actions/nonce.watchNonceIncremented#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`nonce.getNonce`](/tempo/actions/nonce.getNonce) - [`nonce.watchNonceIncremented`](/tempo/actions/nonce.watchNonceIncremented) ================================================ FILE: site/tempo/hooks/policy.useCreate.md ================================================ # `policy.useCreate` Creates a new transfer policy for token access control. [Learn more about transfer policies](https://docs.tempo.xyz/protocol/tip403/overview) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"e13be9674f34cecb6d1efe8ccab1940abeb9e94a06d019450df7b8523742032d","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6INYQYCKc1qQwojQAyhhg1og8fIIAdGwm1hhpAK5wMADCUTEw8YlpAEo6uaRgACpeADyFoQBmjAoUnLlg/JAA7mAAfP4i4roALADMsvJKKogAjFbU4tpBkdFxCdb+JmZIAEw2dqQOTkgAbO6eOHiEJOQagUys7FwGgmOauqpXc0UyjUGnWOjwXyMB3MJ2CZwufmWbg81C8D18zwC9DebA4nEyjGyPwm11hciBiwBay04L0BKJslMMNO9kciKOqluqPuekefhe2L0bV6jkYoR6BWK2zKuxa7U63V6/QgQ2GAAosPZmDoyHAAPzJSEZCBZHL5IolHYVAAKWp1pDgcrAHS6PT6gxGAEpDak4MbTXlJZaZRVqmhag1mq1nQq3crVQAdMBgUTauCa6wwCUW6XlPZUKAQawIPRfThtdgRS2mBScUScMwDfEmwk5JNJgByEBoyXq+EYcE4A7rnDgu3wpFCEHynEIAk4yhinAGokYaEHFdIC/wWbQ5zCFzFYCTaAgnAARlnTNYZLlYFBOOL6+eZEX+BeYJus1Fw3UayOonTUICjSfwxAUEtkGQEA6FTLA5H8AADZD11oJMWFxLhgBSQxOFcctJ2YTgAHIVwUZhGAAehod5iPbZ0RTQI9OAAQSwLA1U9ThgCTTgImArDOGYXIxBoboB2teQoH/fCAF4cPSekzSDXNdk4+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hUIHPJMPW2OA295Y24XeAM2wRS2uampZeW2sAe2gQrMfW5JPBVJV2sZd2mQc2mmhpa2hhAxO2+iB22pYOw2sO9JN229aOr2uO2pBO/23tfQpaQcxAYdEcoIS2h69afG3GaYaGd60m26EmEASmymLiJm9WVmrgIuXoEuTWwuuurGK6xYFGzGvAJmquycmuxEGYBu8CfwSYvAe6hGhaaYQlIe1aRYDG5uzKU0e3IY5IJYMASerGachlJAOc2aEIWAHED4biAGvCAifAnkrciiaiUXNgOiUyH6tOUGloo0IGnaVGNSOQ1gwobXWBEaT7CLCOoCMIBA7MUpUhHSPTBQR7fKEyZ4wkfgboMy5Jc8CiAhI8OQ3+n6KlNyPSQtYtIVZAFKYiMVCVKVGVOVBVJVFVNVDVLVHVPVA1I1E1M1C1K1c8FfOhx1Z1V1aGd1T1b1X1f1QNd1ENMNCNKNGNENeNSQRNERxKaqPSK6LydtXyOnLR1wUBr40zdk4iXe1sfe0q1OYBioS2vUd6bIVWOQ/wV/UQJAUAQIeQL9UIPAdcEAVwVwIAA="} import { Hooks } from 'wagmi/tempo' const createSync = Hooks.policy.useCreateSync() // Call `mutate` in response to user action (e.g. button click, form submission) createSync.mutate({ addresses: [ '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', '0x70997970C51812dc3A010C7d01b50e0d17dc79C8', ], type: 'whitelist', }) console.log('Policy ID:', createSync.data?.policyId) // @log: Policy ID: 1n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `policy.create` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const create = Hooks.policy.useCreate() const { data: receipt } = useWaitForTransactionReceipt({ hash: create.data }) // Call `mutate` in response to user action (e.g. button click, form submission) create.mutate({ addresses: [ '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', '0x70997970C51812dc3A010C7d01b50e0d17dc79C8', ], type: 'whitelist', }) if (receipt) { const { args: { policyId } } = Actions.policy.create.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `policy.create` Return Type](/tempo/actions/policy.create#return-type) ### mutate/mutateAsync See [Wagmi Action `policy.create` Parameters](/tempo/actions/policy.create#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`policy.create`](/tempo/actions/policy.create) ================================================ FILE: site/tempo/hooks/policy.useData.md ================================================ # `policy.useData` Gets the data for a transfer policy, including its type and admin address. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"a27f67c0f419f67e0995e3865a87b2d08d15ce406ed36312f2acb9580f1cc1e3","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUWKQQOBwYAJScUKJiiJzAADpgnBmcolDMpkkAglBQpPBwANxpmZyYOEkAChAm1hgAKl4VYK6cAD6cAK5gsABmpjBQ/lAQ1gh6LfgwnDKiIpxwfdbWpUN9MjIYnCVwjSRQcQminEPs1fOcAI59ZBgAdGlvYHMLSytrG1s7ewO8GOYzOYku12UCweT1eYHen0Wyy4v02cDg212+0OINO8XBV1IN2hj1IL3eaUR3xR6zRGIB2OBMhOYIuhOJ91J5PhPKpyNWtP+WKBR2ZoPxbMhtxhZOe/hE4l0ABZ1MZ5EoVIglRpxNoghL/CYzEgAEw2OykBxOJAADncnhweEIJHIGkCeGs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YwEhLBY50hjAsh8FEiShoC9aZIGNZG2gYFVVMZFsaBxK8hOzxhphhMehlh0U8A7ZH8U8GSNFERzhrhvVHh5i3hRyfhAR5iQR2gIR5iYRyhTCkR0RjycRCRWgszghKRpz6R1i1FDRDxXz3DJRrxPhg1Jyw1ya4jY1fxk1AJdxLRbRHRXR7wPdE9/RkxQxmd2xxuux0xsxxxaA4D66rLnA6xhNwNE9zLZ6rL+xAxnLZDnePLfLDGV9Ys7wLVtxH8eRcJjxq+2LzFuLclBLNR1yxLdxjRZLH8FLcJ4J3Uy1RI0JL8G1pAwJW1jD0+qJsSGJWJOJPY+JEsD+RJrYB4qoSjrcppJjNJlpGEmjtpHciATJOTTpIBkcX+D0XJzQPJlk8UXpAp9kqUoptjrQ2UnQUp2Y2cuYvTq8Xw/IqIQoFYTILIEo2p0oXI5cj+3YNovrnYmoJplJn+5plUxgVpobz4M4Jokbn4uTbJ1j0cEQZAccaUtQYpWUOAebMphbNBfTbUU7aiZjZtijLbSA2o7bQQREwb5gvbDJgc2TQ7eAiJRjSsgbhjhJ8jJoFgFJfrlg+TegWbq7SQm0emNAJgIgP+zsWj4bABdsnosAG4pCc0N4P0K0vGFuO0+0h0bAx0Cd9OT0EoSQnb4IXQ/06kmk3s5w4McYCcSQrYCMOUtmINRuZ6b7/J5uGHogvMCUtmb1xub7YktHbUukvMCYtm/gQiogSAoAgQ8gZ8Xo57CArgrgQAA="} import { Hooks } from 'wagmi/tempo' const { data: policyData } = Hooks.policy.useData({ policyId: 1n, }) console.log('Policy admin:', policyData?.admin) // @log: Policy admin: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb console.log('Policy type:', policyData?.type) // @log: Policy type: whitelist ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type See [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook return types. ### data See [Wagmi Action `policy.getData` Return Type](/tempo/actions/policy.getData#return-type) ## Parameters See [Wagmi Action `policy.getData` Parameters](/tempo/actions/policy.getData#parameters) ### query See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook parameters. ## Action - [`policy.getData`](/tempo/actions/policy.getData) ================================================ FILE: site/tempo/hooks/policy.useIsAuthorized.md ================================================ # `policy.useIsAuthorized` Checks if an address is authorized by a transfer policy. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"8b9aa7de863db2bb7feb28203f7e1e641e9774ded5f3aee5221a9605f2ab7693","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUWKQQOBwYAJScUKJiiJwARnxyomCcAD6cAK5gsABmpjBQ/lAQ1gh6ACr4MJwyoiKccLnW1vBwhbkyMhicpPAQMiRQcQminIXsnMoNAI65ZBgAdAA6YJubdQ1NLW0dXT19A0NwI2MTYtOz85xLKxtbL7uNzVyHnXDdvf2Dw1GpWuUxmpDm9Qey1Ia22r0h+0+7W+v1OAIuQPG8RuYIhi2hsJeOwRH1ayOOfzOgKu2NBd0hjxhq38InEugALOpjPIlCpEOyNOJtEFaf4TGYkAAmGx2UgOJxIAAc7k8ODwhBI5A0gTw1ggYBajDgAEFcsp2IwAF6lJKpEYwDLZPIFGDFMxlKgVKp4N6IslHH4nf7nS7A2m3cH3RlrFmaXSqACMsh5yiQCel1CFOiYJrNhFIVtKYpKUpl9kcfkQCfZKuoXnVvi1AXoTFY7C4BkEsbZSAAbIrk4pU4guZphXhO0ZxeYM7ZywrEABmBO1zBqvQavzalt6FhsDicNgmawYbsSRAAdgF3KHfN7gq02b0R8YJ+LEsQs9l8sri4vq/rDdG38GgdxAHowEcRh9TyOAYAASVzc0C2tKAAB4AGF9WKBQKBSNIHTAAA+UJ7GYHQyDgAB+JJJ1WF8T1WXI4MQ01kMLKBVgAB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pISCOK0BOI8k3QaG3QZL4LAEPjECSiQBSnNlME6H8CIAsFWATHFIsAsEwLrh7EyybhTD5HwPbiCFQ3IKIJADnC9gXGVH9jXDfmAnoN1B1yNAJkOmulEhMkzhdDdCLFUNcl9FJC+ApDRBDExBBA8ijAJEPmwKlAsHwPPmHHTGII7lNMig4nVMoN/GoL1MAkzAUH8CxzwDVNlPPElFwMHAvisGbCCEDVEHDKJj02WHIOkE1O/GfksFcDNj1FgFbC0VKi2kEDWkKFqnwxajak6hgG6nHwNC4BmkmCSDDN1mBGqk2joniiYn2jNJdmOgeiegaleivElCgEXFUAwmsF7F7EXHZAwgsFUHS0kElFUFEEXGSEVF9gACFrBJAYALxVBJBVBCgLBkhD1khkhPoHo74LSEw7pWZsswSUkni8yCybQ8MhzCZShst/B3FRAkBQBAh5A8F9Q8B8oQBXBXAgA="} import { Hooks } from 'wagmi/tempo' const { data: isAuthorized } = Hooks.policy.useIsAuthorized({ user: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', policyId: 1n, }) console.log('Is authorized:', isAuthorized) // @log: Is authorized: true ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type See [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook return types. ### data See [Wagmi Action `policy.isAuthorized` Return Type](/tempo/actions/policy.isAuthorized#return-type) ## Parameters See [Wagmi Action `policy.isAuthorized` Parameters](/tempo/actions/policy.isAuthorized#parameters) ### query See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook parameters. ## Action - [`policy.isAuthorized`](/tempo/actions/policy.isAuthorized) ================================================ FILE: site/tempo/hooks/policy.useModifyBlacklist.md ================================================ # `policy.useModifyBlacklist` Modifies the blacklist for a blacklist-type transfer policy. Requires policy admin role. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"8612238fb35eb7ea94d9d2808311c32ba32c9e01a54e93a2838af6a38747928f","data":"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11LWVQdWi9RUT1TW+C7W5TKdR9AeaO0O8OmxSeJ+8WjkADX9HYIC/evQR+gYo+yCokMtDW2DdwhCu+3WtqHuMeABbgBefAOud2huJ/B27FeO1VGAa+YaAjd+BBuAGBCAEFGg+RF+gBD+rdb+8CxEP+6gchkCAhlQMDam4B5wb4DkGCiifwf4vASmgm8GNYctKWnYADCBtOhh3UOwQh7IaqXYZ4OUVQDh79CwQaawK+eRxR5RyQVRtcdR7BzRlYJRyGHRtRjRhRox7R3R/R6IJWtdWmyDaCkGEIWAekSEHSJyb8ASaIISaAlcySGSb3NgeSKs/k1mhWksC470FyZmZGXmneO4HyKKB/foBPZRB1bFUwJ9NgMIUQgMG5GxQKVPBQMnDaSKAyBKMYIqnutcSSORECII8JxWXeaJTKI2hcYNcxSqCNKNGNONBNJNFYFNM+9NTNbNXNfNQtYtUtctStatWteqYKE2zgXYIqYKYDDuN9dqDePaIIqU1DJ0oAsO2BiO6KaRpBqAppvmpWPIfW90KIqOgYvIYQoCGxJhoI/wag0QJAUAQIeQVG0IPAL8EAVwVwIAA"} import { Hooks } from 'wagmi/tempo' const modifyBlacklistSync = Hooks.policy.useModifyBlacklistSync() // Call `mutate` in response to user action (e.g. button click, form submission) modifyBlacklistSync.mutate({ address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', policyId: 1n, restricted: true, }) console.log('Transaction hash:', modifyBlacklistSync.data?.receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `policy.modifyBlacklist` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const modifyBlacklist = Hooks.policy.useModifyBlacklist() const { data: receipt } = useWaitForTransactionReceipt({ hash: modifyBlacklist.data }) // Call `mutate` in response to user action (e.g. button click, form submission) modifyBlacklist.mutate({ address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', policyId: 1n, restricted: true, }) if (receipt) { const { args } = Actions.policy.modifyBlacklist.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `policy.modifyBlacklist` Return Type](/tempo/actions/policy.modifyBlacklist#return-type) ### mutate/mutateAsync See [Wagmi Action `policy.modifyBlacklist` Parameters](/tempo/actions/policy.modifyBlacklist#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`policy.modifyBlacklist`](/tempo/actions/policy.modifyBlacklist) ================================================ FILE: site/tempo/hooks/policy.useModifyWhitelist.md ================================================ # `policy.useModifyWhitelist` Modifies the whitelist for a whitelist-type transfer policy. Requires policy admin role. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"7679b70c1a9955fc42af8bd9929c68a4bdb7d8b9fde73dc5c771f97554c0150a","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6INYQYCKczNCMAGYYAOr4jDQmIgDKGGDWiDx8ggB0bCbWGHkArnAwALJRsQlJMClo6Zl5AEo6paRgACpeADwAwqHRjAoUnKVg/JAA7mAAfP4i4roALADMsvJKKogAjNLU4tpBkVAx8YnJjGkZ1v4mZkgATDZ2pA5OSABs7p44eEIJHIGkCTFY7C4BkES00um+6mM22Uag0xx0eGhRke5lewXenz8iGeAA4/tQ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IyZKcYDK7S6SWRECXw0J6W8MPISJHKXWhcINMxGqcNSNaNWNeNRNVYZNE+tNDNLNHNPNAtItEtMtCtKtGtJqMKLdWdbIedGACgMKfWzgPYUqA6Xwxa8LZU7oCRtSKR+BsA+ppWfePILWj0UIsO7ovIGh6B4BBh3w/wKg0QJAUAQIeQGjUIahhAVwVwIAA"} import { Hooks } from 'wagmi/tempo' const modifyWhitelistSync = Hooks.policy.useModifyWhitelistSync() // Call `mutate` in response to user action (e.g. button click, form submission) modifyWhitelistSync.mutate({ address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', allowed: true, policyId: 1n, }) console.log('Transaction hash:', modifyWhitelistSync.data?.receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `policy.modifyWhitelist` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const modifyWhitelist = Hooks.policy.useModifyWhitelist() const { data: receipt } = useWaitForTransactionReceipt({ hash: modifyWhitelist.data }) // Call `mutate` in response to user action (e.g. button click, form submission) modifyWhitelist.mutate({ address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', allowed: true, policyId: 1n, }) if (receipt) { const { args } = Actions.policy.modifyWhitelist.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `policy.modifyWhitelist` Return Type](/tempo/actions/policy.modifyWhitelist#return-type) ### mutate/mutateAsync See [Wagmi Action `policy.modifyWhitelist` Parameters](/tempo/actions/policy.modifyWhitelist#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`policy.modifyWhitelist`](/tempo/actions/policy.modifyWhitelist) ================================================ FILE: site/tempo/hooks/policy.useSetAdmin.md ================================================ # `policy.useSetAdmin` Sets the admin for a transfer policy. Requires current policy admin role. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"fbe0fb128f663b81203c3f14323f7bbd58a2ebdc7f33ada3627157b6f722bbb1","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6INYQYCKccDoAglDMpgDKGGDWiDx8ggB0bCbWGBkArpHx0bEJSdYZAEo6+aRgACpeADwAwqEAZowKFJz5YPyQAO5gAHz+IuK6ACwAzLLySiqIAIwATBri2kGRaDFxYInJ/iZmSOvBdqQOTkgAbO6eOHiEJOQagUys7FwGguOaulUAA55oplGoNlodHhfkYTuZzrZ7I4/IhVssHtQvM9fG8AvRPmwOJxsoxcv9JncpqDFndIVs8KTybJTAibJdrqjVgB2TGYJ56F5+d4EvTtPqORihXpFEr7Q7WVodLo9PoDCDDEYACiw9mYOjIcAA/KlYVkIDk8oUYMVdqUDuUMgAFPUG0hwJVgTrdXr9IajACUpvScHNloKsrt8sd1TQtQazTaXpVvvVmoAOmAwKJ9XBddYYDKbXKykcqFAINYEHpfpx2uwIjo0KYFJxlIXRPa6w3RCSLWS8pnMwA5CA0VL1fCMOCcaecXtwcr4UihCCFTiEARtuxcQaiRhoGf10jbwtoK5ha5SsCZtAQTgAI0LpmsMnysCgnGlvYfMkr/EfGBj0LUgajqFt504UC81CSIMn8MQFGrZBkBAOgcywOR/AAA1ww9aEzFgiS4YA0kMThXDrFdmE4AByPcFDiA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uP6TSzNXAvC5CWSbNiO8AnNkiPNpV/N1uHEmYTNKcYtrNOS0tamXNANrSfNiS0igtyt8BhYotGSEtlCUtUEMtMgOt8t+tTSSSYAtVCZSAMwyw5Kg1p05KmgGaIAPN41j1ea01iAUw9w71X0813Kf0zMd6Ya/1eNWh4c48kca0McZNp1aqSaXtSwGZvt+MidSsgdT1LKqIqghaEdpZX1i1egv17Mgk54KdxNYA3AKc+AGNfsMeCgyNnAVNSKQEtN7aDN+gbdX4Zik+iCRN7ymdqwKZlKOM50+dQQjdl47yrdcAKg91uZwdr0Fhc1iE/gGRo12emdUw50OdhZ31jNU99CdgG9qQ8Uaw70qgtw3IQIkgFg2U1gtcT9Z9r979n9D439QEv9L9b9H9X9P9qwz9/9EDQDtcgdiIU1r0NMu0IQsAhI3wQkGkM4lE7Q1E0JlpzErEbA7EfJaxK1RM1ggRZoWkW1t15QBk9kUeLQlOqCq042Gm1tMEYQx+1oVS7yZkdOCg/WDUdkYkrkPQ3FGSD4cQlC14uBlDEsdKgUFkaNsU4qkq0qsq8qiqUwyqqq6qmq2quqUw+qhqxqpq5qlq1qD4JeFkYNnAywkUbUuBrlNGYJ9QN9A8d97dUJSjjoPNRopBpNWhGQK9qd1469+AuB/gE+ogSAoAgQ8ga6oQeAh4IArgrgQAA=="} import { Hooks } from 'wagmi/tempo' const setAdminSync = Hooks.policy.useSetAdminSync() // Call `mutate` in response to user action (e.g. button click, form submission) setAdminSync.mutate({ admin: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', policyId: 1n, }) console.log('Transaction hash:', setAdminSync.data?.receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `policy.setAdmin` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const setAdmin = Hooks.policy.useSetAdmin() const { data: receipt } = useWaitForTransactionReceipt({ hash: setAdmin.data }) // Call `mutate` in response to user action (e.g. button click, form submission) setAdmin.mutate({ admin: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', policyId: 1n, }) if (receipt) { const { args } = Actions.policy.setAdmin.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `policy.setAdmin` Return Type](/tempo/actions/policy.setAdmin#return-type) ### mutate/mutateAsync See [Wagmi Action `policy.setAdmin` Parameters](/tempo/actions/policy.setAdmin#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`policy.setAdmin`](/tempo/actions/policy.setAdmin) ================================================ FILE: site/tempo/hooks/policy.useWatchAdminUpdated.md ================================================ # `policy.useWatchAdminUpdated` Watches for policy admin update events on the TIP403 Registry. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"c97041b0026ec81821f4e52786e61b498aaf99fd2e23ce80fa9483d396001836","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXGwm1hhRmroALLFJispIAGwamTp47Yyd/iZmSEUgtvaOfogjVdRetb4NAfR4AGYArmCOjBBgnCdwMADqomi2AIJQzKYAqlhQTzBQAB4AMJXI6MBQAP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FDH9FRnwTKIJPhFODVgANSUzar1BliBiYFUCqTgJ4Cd66JFL6hoYrI8reLcbzADScAACyCo2UXk24mQpIyaoM7K1wnKsI7i/wsEni3izCGUjAIMXAskC46aca4iLA4gpknB3B2mZkHogYB02UVwz6/hwS5aoBIgXi12U+82W4NCLAUODCUyMyMGRwUIsQA4va8KiKZ6YA8QxyI68wJwjylRW63BY6lRsQBKooRw4EsQC6PyOWUIIqth8IdkZkR6+aLh3K+RI2Mg4E50Z6aAUS/+8KA6UBMAw6pyGhY6ly8Ak6OKM6+KUxPRfyUxsxTwJxWKS01KsuX6cArGIg5iZwXADuqgeupef6pEDxqIuGYGsE7xNYIe1Op+vxaAqI6gZS+htx4SbxwKNY80Px0JaA/xWesG9xMJnAoJqGTG6GYA70G0ta240yBxZxCxcK/aiKQ69kqKGx462x2K06eKryBxJKvyxxp6pxrJ5xnUWkOkh624pgZxF6L+zkSArkCMpg0k/gRAFg4ElM0pFgFgWBCMOBVMmMh86MEc2MAcxg2EFBVB18FM+B9Buws8zMzBqcwMGc0EXIB440Aoc0rE1YaA1cxcTgdc9of21o1cU0YArp5csYHpzc2Brs6WEcHc6M3cGpfc0EOpZMI8FMBQd88MpEsAzQOioUpUEUWkhYYicUmmSUKUbAaUU+pU4E5UlUdwJ0yEss9UjUGoQcik9UnYHIksCsI4Y4Wc5irxkSMUf4hGS0a0FAL0ahIAacogSAoAgQ8gOCVweA/kIArgrgQAA="} import { Hooks } from 'wagmi/tempo' Hooks.policy.useWatchAdminUpdated({ onAdminUpdated: (args, log) => { console.log('args:', args) }, }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `policy.watchAdminUpdated` Parameters](/tempo/actions/policy.watchAdminUpdated#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`policy.setAdmin`](/tempo/actions/policy.setAdmin) - [`policy.watchAdminUpdated`](/tempo/actions/policy.watchAdminUpdated) ================================================ FILE: site/tempo/hooks/policy.useWatchBlacklistUpdated.md ================================================ # `policy.useWatchBlacklistUpdated` Watches for blacklist update events on the TIP403 Registry. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"2b35d7c59b68fad10378a67e4629e5fec424fa0a78d71f66ebd0b164e0ee522b","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXGwm1hhRmroALLFJispIAGwamTp47Yyd/iZmSEUgtvaOfogjVdRetb4NAfR4AGYArmCOjBBgnCdwMADqomi2AEIyDvwmIgCqWFBPMCgAB4AMJXI6MBQAPgAFFh7MwdGQ4AB+RCcYAAHWunFxK1MAEkoGjOGATswAEZkTgAHxuYFgELMUAA3NjcbjMqj0VicRyOdNOkSSRTIaYuHTRQpxcgALq00knGQyBVnRn5Vns/kck5/AGkEkAAwstAAJMARKRTApXIaFcazRa0FbFLa5QqycrVQyYEzAWy+dqHNYIGc0EaTebLdbbfbI06XTbDe66Z6VXS1b6NQH+a5vermTmOUdSBBmG8INZ+CKxWAJfSC/6tbirgBRUilg3omEwsid9HtzsASk4AF4oZwiBBGFARxmfX6oPms4Xm5x2jISc6TjBl4u99m1xvrQS62QiKJN+iyZTqfPG0v7yum4Grm8Pl80L9/jRid2YVy6IAO5PK87xVp+34AlAAB0ACCWhwBQnAyBACjAaB+DvhBjA/Hqv4wQAMmhI7jpO06zgeq6BiGYAQgoJJgnRkJUS+/LyKIFJyH+nAUnwciiNcT77sJh5gK4Q7olOM7YmAoiInA8LWLutwPJh2GfLhX74YC/hQJWCB6DknBHOwnAgc8+DWrx4GaSINw6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Z5GD0ZmDmYChw4P48Zv4Jggh/48gE5BCU4d4WD05wFM5j5uYDgpD85IYi5EIeQjwJoZgMBy5eJaw0BW5a4nAu5HR0dbRW5gxIS0A4zG5ExEz+5XirQh4K5R5x4voX4WDegmZBhP4BCI4SYQA15HTzBnSGY05VBXA0YQxYBmgPEYpap4oTJSwDFUonMMpspC02A8pajaoYJ6pGo7hLosJ1ZY5fxOotRo47J5zARuwuRlZtYyIS5gk4SK9kpAIuN1ptoKAvpbCQAC5RAkBQBAh5B2Erg8AwoQBXBXAgA"} import { Hooks } from 'wagmi/tempo' Hooks.policy.useWatchBlacklistUpdated({ onBlacklistUpdated: (args, log) => { console.log('args:', args) }, }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `policy.watchBlacklistUpdated` Parameters](/tempo/actions/policy.watchBlacklistUpdated#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`policy.modifyBlacklist`](/tempo/actions/policy.modifyBlacklist) - [`policy.watchBlacklistUpdated`](/tempo/actions/policy.watchBlacklistUpdated) ================================================ FILE: site/tempo/hooks/policy.useWatchCreate.md ================================================ # `policy.useWatchCreate` Watches for policy creation events on the TIP403 Registry. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"410c78052455bb6978da5eacfc5719ebc1462a6449aaa6683f5090198fea83d5","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXGwm1hhRmroALLFJispIAGwamTp47Yyd/iZmSEUgtvaOfogjVdRetb4NAfR4A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TplkaFjJpwAYXpUNKDRReJMJqw0sABqOGWNeocMPPEAqgBSV+PAefR1FWTUADEZClfAHEZPeYTqTgAAWUlCMmch7EyDxADUNhJSARDXiVGiglVUtSSkYC+i4Ekn7BDUtV0iNEXVIAOhILILEzGidDz1WnWzxUsIcVTQfxEHMXqyuGvmnG7CwRYDezwS6R6TfSOGBFiELArV+X+UXTAHiGWXrXmBOEORSNHTIMbRSNiEqz5COAQliB7URRkDC2BHpU0IhHMjGlnRjTBA/FaSiPqxkAQh2kXTQHcSv1+WrVfxgDrVWWEMbU2XgBbV/2hU7XaPKKRXaK6KeEWJbXGgxU52PTgHV1oUeVjGe1UClyt26lCnwjODQDhAgwfVGhONjEd3R2d2QVOLhHUFSSkPVx8SOOuLOJg0+NuJLwX0+KeLJ1eLAFulmizR7G6VmOWN6J+SrX+VrQsmBVGKbQmNbShQ7RilmN7WuQWIXSWLxJWMaknXUhnR7FMGWOOn3xsiQDsjBlMHEn8CIAsAQjhhZIsAsFALBnNnhltkGBgMXgmCCAgiQJQK9lbiQDhl9l3n9mwNJgODwMHk+kjkahPE9HPDjmvFjCTgfFTnSnTnOS/Gzn+lzhAiuinl0ElJLj5NhmriXjrkahFI3jQMWFUFcFBnwlgGaBkT8nykCkDGDFgxEyilildTYAShb3ygQkKjRnHn5gqkVCdlqkGigCzEZG5lQnQnLGjj13eLcVCmPBg3GmmgoCukEJACHlECQFAECHkEgSuDwA8hAFcFcCAA="} import { Hooks } from 'wagmi/tempo' Hooks.policy.useWatchCreate({ onPolicyCreated: (args, log) => { console.log('args:', args) }, }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `policy.watchCreate` Parameters](/tempo/actions/policy.watchCreate#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`policy.create`](/tempo/actions/policy.create) - [`policy.watchCreate`](/tempo/actions/policy.watchCreate) ================================================ FILE: site/tempo/hooks/policy.useWatchWhitelistUpdated.md ================================================ # `policy.useWatchWhitelistUpdated` Watches for whitelist update events on the TIP403 Registry. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"2c18a2554a7d5904a09f15c11717794915bec94d2536640e09fff9a27cdf3002","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXGwm1hhRmroALLFJispIAGwamTp47Yyd/iZmSEUgtvaOfogjVdRetb4NAfR4AGYArmCOjBBgnCdwMADqomi29/iMNCYiAKpYUE8wUAAPABhK5HRgKAB8AAosPZmDoyHAAPyITjAAA6104OJWpgAklBUZwwCdmAAjMicAA+NzAsHBZigAG4sTicZkUWjMdj2ezpp1CcTyRDTFxaSKFGLkABdGkkk4yGTys4M/Istl89knX7/UjEgAGFloABJgCJSKYFK4DfKjabzWhLYobbL5aSlSr6TBGQDWbytQ5rBAzmhDcazRarTa7RHHc7rQa3bSPcraaqfer/XzXF61Uzs+yjqQIMwAEIyCDWfjC0VgcV0/N+zU4q4AUVIJf1aOh0LIXbRHa7AEpOABeSGcIgQRhQUfp72+qB5zMFlucdoyYlOk4wFdL/dZ9ebq34+tkIiiLdo0kUqkLpvLh+r5sBq6vd4wT5oH5/GhEntoU5NEAHcnheN4PkYb5dX/AA6ABBLQ4AoThKwUUDwPwD8oJgv8ATggAZCAFFHCcpxnOdDzXANgzAcEFGJUF6IhajXz5eRRHJOQAM4ck+DkURrmfA8RKPMBXGHNFp1nLEwFEBE4Dhaw91uB4sJwr9oJ/WCAX8KAqwQPQck4I52E4MDnjeRQLMgrSRBuXTOBgEh6zgOD/DEBQjOQZAQDo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mDLzbypzOAMzpwQKZwnycwHCiH5wQxFzITcjHiTQzAYDlx8R1hoCty1xOBdwOjo42itxBjEmRmNwJgxn9zYZDzLR8SjzjyfSvy6AMy9AMyDBfyIDLy/zEwgDrzWk8HJx0xpyqCuCozBiwDNBeKxR1QJSmQlhGJpROaZQ5QwB5Q7R1RwQNRNR3AXTYRqxywAjdSajRz2SPzDzDachKxazjiTglxR71IYbATcbrTYibQSSWEgAFyiBICgCBDyCcJXB4DhQgCuCuBAA=="} import { Hooks } from 'wagmi/tempo' Hooks.policy.useWatchWhitelistUpdated({ onWhitelistUpdated: (args, log) => { console.log('args:', args) }, }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `policy.watchWhitelistUpdated` Parameters](/tempo/actions/policy.watchWhitelistUpdated#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`policy.modifyWhitelist`](/tempo/actions/policy.modifyWhitelist) - [`policy.watchWhitelistUpdated`](/tempo/actions/policy.watchWhitelistUpdated) ================================================ FILE: site/tempo/hooks/reward.useClaim.md ================================================ # `reward.useClaim` Claims accumulated rewards for the caller. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"9473592640bf3f33afde9fa50fd54b096479002e7102d5dd65de5dc109750e9f","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6INYQYCKc1jKiLADKGGDWiDx8ggB0pDAA7uJQqQCucDAAwlGx8dapAEo6eaRgACpeADxFoQBmjAoUnHlg/JCZYAB8/iLiugAsAMyy8koqLhri2kGR0cxxCf4mZkgATDZ2pA5OSABs7p44eIQk5BqBTKzsXAaCo5q6qurGc8pq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DgotSQqYgYkrr3SnJMqqL/TDRhhjQ4w9KczcwwC8yCK4qSx6CEpRDhDrycLbz+JJSIokCtgqJiCDhKJ2yMLrZsG+UkxcABWbxBW+bwChXyIRVqJzYMIXxTgEQmp2x+VJXuLlypVtiyphW2WRU5VnyxUFXe5ZjFXsIFJcLBxpWVWZWqJRW5VgKYVAlZR7AIhqV0WIATCQl4BZWsX6XwmbJjUmXcXNQXT8gWV4BHLWWPRtiZiT5PlDzHBhAnAJTVDbXQxeX4qEptrqyS7jyJRFwsKnUDXKWSCQgfLgkTV6AZAnUMCrIaWzUnQTBuCLWol8WrV6DrUnKbWXUHU3XcAkz4BJDrgSTgGX7ViuCeJcy9A8xMhiwgBXoghw0RzALs4Vz7XXXfhKX0WyRgkLBwg/BFQ/JQ1k0JSw1wAqA/UzUbInSqCTKmUbQKD+CQF4CXYU355TLU1IBWCg0Eqk2HXih2Cs1JASQFRTATCqBnCTIIiSAWDfTWA8zK2q3q2a3a1US63uX61q0a1a061617Aq0W1G3W3uXTVwg0V/WwjbLpQhCwDYgvAgR9TIRtAXhXi3hS4PjPj+ZsBqRKFhKSXP5GgDTYRlQyj4RsHvZFApY1zLzMYjoVVsBhCK5Bg2yy2kRxIKDUbmT0QawmAsTdArbsJUQPjlwJTR7aUVDLJ8TkTnJgBiQ3LSSPL90D0WCI62TR7nl5qrn1Ay03XG4K3XmSWpBZV6jGhfWpCM3F0s34DR7+Bs6iBICgCBDyD0qhB4DbggCuCuBAA=="} import { Hooks } from 'wagmi/tempo' const claimSync = Hooks.reward.useClaimSync() // Call `mutate` in response to user action (e.g. button click, form submission) claimSync.mutate({ token: '0x20c0000000000000000000000000000000000000', }) console.log('Transaction hash:', claimSync.data?.receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `reward.claim` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const claim = Hooks.reward.useClaim() const { data: receipt } = useWaitForTransactionReceipt({ hash: claim.data }) // Call `mutate` in response to user action (e.g. button click, form submission) claim.mutate({ token: '0x20c0000000000000000000000000000000000000', }) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `reward.claim` Return Type](/tempo/actions/reward.claim#return-type) ### mutate/mutateAsync See [Wagmi Action `reward.claim` Parameters](/tempo/actions/reward.claim#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`reward.claim`](/tempo/actions/reward.claim) ================================================ FILE: site/tempo/hooks/reward.useDistribute.md ================================================ # `reward.useDistribute` Distributes tokens to opted-in holders. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"59eb218042188d5a1a816d7393c55eedf583a5a887465c49947319b9a1e69626","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUoiaicACUnABmAK5gjowQYJxY4nAwAKLKZME6+GSInCKkpgoUnAmMaAD8xQA6IADuMIxNnAA+nE0Kre0gkcUARowKpmgNYCxsHGkZ2bnkVFAQ1gh6AMIpJBxwnKIlaGWKnKQwWOeZYGJoyakQMZwFZJxoEJxgccxkjNZhnH6ADoplMALScAAiazgxXwaDQWFhAHpkURGDBmEC4Phkat1si4ncTHd4Mj0qRMjlCstqKIFBtkMgQHRRKw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lRrmzw8ppuU+2oIEHhg2fwGyUQJAUAQIeQSalIPAEaEAVwVwIAA"} import { Hooks } from 'wagmi/tempo' import { parseEther } from 'viem' const distributeSync = Hooks.reward.useDistributeSync() // Call `mutate` in response to user action (e.g. button click, form submission) distributeSync.mutate({ amount: parseEther('1000'), token: '0x20c0000000000000000000000000000000000000', }) console.log('Amount:', distributeSync.data?.amount) // @log: Amount: 1000000000000000000000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `reward.distribute` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { parseEther } from 'viem' import { useWaitForTransactionReceipt } from 'wagmi' const distribute = Hooks.reward.useDistribute() const { data: receipt } = useWaitForTransactionReceipt({ hash: distribute.data }) // Call `mutate` in response to user action (e.g. button click, form submission) distribute.mutate({ amount: parseEther('1000'), token: '0x20c0000000000000000000000000000000000000', }) if (receipt) { const { args: { funder, amount } } = Actions.reward.distribute.extractEvent(receipt.logs) } ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `reward.distribute` Return Type](/tempo/actions/reward.distribute#return-type) ### mutate/mutateAsync See [Wagmi Action `reward.distribute` Parameters](/tempo/actions/reward.distribute#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`reward.distribute`](/tempo/actions/reward.distribute) ================================================ FILE: site/tempo/hooks/reward.useSetRecipient.md ================================================ # `reward.useSetRecipient` Sets or changes the reward recipient for a token holder. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1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6WIHtKAF7V4gAAvMgC3GfIgDTAs8OZD5lXjS5ksI5SWmdBZQHUSYBqA/kand5Bc4+atNwOnQU5bwlOY0FTnhm34rBkyOvHMtfxABZ9MgTKFlGyg5RcoeUfKAVEKhFSqAxUEqKVDKjlQKolUKqNVEJAzIJlTeTMVwMdBCCwAKQwIDCE7yoj9Afwf4QCFvBAjgR4cbAKCKB1t5TVPq6QAIk6Bd4IxI+DvdiEMWjx+Q0En8RhCNlMAC0j6kQbjCmE7gvBxEZoNZAoB6yNRmo/RRgNJBGBsVZuIEF+NtDwL6DXoOQDFGpH4jGoWIKUWgMylZTspOU3KXlPykFTCpRU4qSVNKllTypVAiqZVKqnVRFROIUaV1ABFSjpRfUdQ+oRYHKGuA8C6PPSv+F4Cx1EApeSIQ7xyDI07QSufTqQDwKk8/c9A7oWdV6H9DnQ1MPAv4H9iiAkAoAQIPIG7ShA8A94EAK4FcBAA=="} import { Hooks } from 'wagmi/tempo' const setRecipientSync = Hooks.reward.useSetRecipientSync() // Call `mutate` in response to user action (e.g. button click, form submission) setRecipientSync.mutate({ recipient: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) console.log('Holder:', setRecipientSync.data?.holder) // @log: Holder: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 console.log('Recipient:', setRecipientSync.data?.recipient) // @log: Recipient: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `reward.setRecipient` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const setRecipient = Hooks.reward.useSetRecipient() const { data: receipt } = useWaitForTransactionReceipt({ hash: setRecipient.data }) // Call `mutate` in response to user action (e.g. button click, form submission) setRecipient.mutate({ recipient: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) if (receipt) { const { args: { holder, recipient } } = Actions.reward.setRecipient.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `reward.setRecipient` Return Type](/tempo/actions/reward.setRecipient#return-type) ### mutate/mutateAsync See [Wagmi Action `reward.setRecipient` Parameters](/tempo/actions/reward.setRecipient#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`reward.setRecipient`](/tempo/actions/reward.setRecipient) ================================================ FILE: site/tempo/hooks/reward.useUserRewardInfo.md ================================================ # `reward.useUserRewardInfo` Gets reward information for a specific account. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"b99d265574b0d65166a26926a44acc97a9953933b2ed8abd0b6af7abb3256072","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6INYQYCKcUKJiiJzAADpgnEmcpDAA7uJQAEow1oxYjPJoMQAGFrQAJMAipKYKriUA3AnJKemZAApkACoC8jEARowKpmjNicmpGaRQAEKiMqJg1jCDw6PjrpwAPpwArmCwAGamMFD+UBDWCHrd+DCci+Fwe9YrcHBHezIyGG1wEBkJCgESiok4R3YnGUDwAjnsyBgAHT+ETiXQAFnUxnkShUiAxGnE2iCkTE/hMZiQACYbHZSA4nEgABzuTw4PCEEjkDSBJisdhcAyCVGaXSqQk4xTKNRErQ6PDCoyU8y04L0xl+RA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Info({ account: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) console.log('Reward recipient:', data?.rewardRecipient) // @log: Reward recipient: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb console.log('Reward balance:', data?.rewardBalance) // @log: Reward balance: 1000000000000000000n console.log('Reward per token:', data?.rewardPerToken) // @log: Reward per token: 385802469135802469135n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type See [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook return types. ### data See [Wagmi Action `reward.getUserRewardInfo` Return Type](/tempo/actions/reward.getUserRewardInfo#return-type) ## Parameters See [Wagmi Action `reward.getUserRewardInfo` Parameters](/tempo/actions/reward.getUserRewardInfo#parameters) ### query See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook parameters. ## Action - [`reward.getUserRewardInfo`](/tempo/actions/reward.getUserRewardInfo) ================================================ FILE: site/tempo/hooks/reward.useWatchRewardDistributed.md ================================================ # `reward.useWatchRewardDistributed` Watches for reward distributed events. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"802abf398fe8f0c7b5d0b17bdfce85c29d28ef5e8d8bbd8b8bebd7ceec8598b4","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXKQwAO7iUFGaugAssUmKykgAbBqZOnjtXaQ9eWZIRSC29o5+iGNV1F61vg0B9HgAZgCuYI6MEGCcZ3AwAOqiaLYASp3dACKMIqSMACMzjQoAAeADCNxOjAUAD4ABRYezMHRkOAAfkQnGAAB1bpwCWtTABJKCYzhgM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FDNAJUdxTxdjYmGlAAWQQXOyMjrEyCpEuiBmsDZTrCRFcTtHPBUPwHoUCkYEBi4DYjGlEGDUgWQRYHEAkVoLUyIicJ3zswUnOxuEZUcKCUwQ/xEA8QGxuE/j7FrD8UoWoSOlmXmSgxOHhFiBTA7XhURWPTAHiFOX7Q7DOCeVyLXToMHVyNiC639BOAPFiBnR+Uy3hB9X0JRDUhmnNRzTMM5WSIGxkAPEPWPTQEiSf3hW7R/xgD7XOVASHSxRxTHTxUnT6IaL+T6MGJeHWOxVmmpSF3fTgEN24TLm7GB1UGVwjwiRclfnLixBwxA3PCuO7FX1r0TweIrk4HUHKUUMNziRd1eKmnuKOJBRr1kMoz+PeKZy+NP1MmWirTrDmWWM2JGLhS7URV7XUlRRmOuTmJAMWO8mWJJV+TWPYCGM2OBlmkOi8XYDrAPWJJPRuA0kmG0iQF0jhlMBYn8CIAsAPBqm5NKhgLhjgJS3dmQN7jQP3kvCwPMFwNPijmcAQJHhIITkZnIJTgBnTlPD5HQmzgWxVFAnVE1AVDFGLgYkBMrgIWrkejXngMGC3lRlwL3k7lPElNbj7llOWFUAVP2HHmVLwBZn4zIEwDTBymAjzj1K+0VFQkJikI1jwDpTAWJDBiKloVyluH8LDSMHhnXlUAmGRk9jUHbnQOoCAjAGdK2FdIHmWFcFhlflgGaC0VsligckdGdCETclU08h8hgD8mWlijCy4kSgeD2k4iXmDkygtEDjSmDixA6m0nFjfA/CzEzktyAQwxclXGmlmkWganxGDLAHykKmKmqiPOPOPPqkekkJAFTlECQFAECHkCwRuDwHMhAFcFcCAA"} import { Hooks } from 'wagmi/tempo' Hooks.reward.useWatchRewardDistributed({ onRewardDistributed: (args, log) => { console.log('args:', args) }, token: '0x20c0000000000000000000000000000000000000', }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `reward.watchRewardDistributed` Parameters](/tempo/actions/reward.watchRewardDistributed#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`reward.distribute`](/tempo/actions/reward.distribute) - [`reward.watchRewardDistributed`](/tempo/actions/reward.watchRewardDistributed) ================================================ FILE: site/tempo/hooks/reward.useWatchRewardRecipientSet.md ================================================ # `reward.useWatchRewardRecipientSet` Watches for reward recipient set events when token holders change their reward recipient. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"28f0780d1d18e58ea2ba233fff27ee55459d9d43aeb92be79062c38ef7f6b813","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXKQwAO7iUFGaugAssUmKykgAbBqZOnjtXaQ9eWZIRSC29o5+iGNV1F61vg0B9HgAZgCuYI6MEGCcZ3AwAOqiaLYASp3dH9aMWIzyaAAyjoADwAYRuJ0YCgAfAAKLD2Zg6MhwAD8iE4wAAOrdOPi1qYAJJQDGcMBnZgAIzInAAPncwLAoWYoABuXH4/GZdGYnF4rlcwgyWCkMkAAwstAAJMARKRTApXOL6ZxJTK5WgFYplcgALqqikyGSqi7M/LszmCrntH5/AESqWy+WK5Wq9XOrWu8X6w1nY2mpkwFkwS0CziuQPm1kc8MnUgQZgAIRkEGs/DJVOhpi4DLNwYtscFNwAoqQE2LMXC4WQK5iyxWAJScAC8MM4RAgjCgzbzQZDUCjBZjVvxbGNZK1ZxgQ4Hs8Lo8445MiiJYCcRFEMjJFOptL70dD85H4ZuHzmUG+v3+6+BaDJ1Z5mK6r3w56+MDtN6BOgAdABBLQ4AoThUwUZ8XneT55ive1bz/AAZCAFGbNsOy7Htj1DIsuTQAR5EdDUXR1FUD2HbDF2sS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YmreaMT0o6c+4o9xLx+xNKa69Km6rkzK5xe6VxJBx6KK9x56zx7A36rxfJLw7xQEz6Jk76M4pgLxv6YBnkSA3kDMpgCk/gRAFgv400apI0NBDMWcVWKwcgIwQCkwPMQQYE7B5gXB9cZ8q8TcHguw18iCd8whXcRMvcxs/c4Yg8V2aoc8SOyok8ScZ0yJI8vpE8yMv8ug00/Q6Q+pBcnBRpu8IA+8ECcZdcEsjcl8tpcsCCbcQheAas6mZAmAzYeEUcYAhEnoY8boXsoY5ClCkqVCRIFMg0iipZN0UAUARaRgjMEZqg2cjBaQ8ZoCJZ8gZp4wUCPBywrg9MVEsAzQPi0UNUcU8YiYyUqU6UWUMAOUT0NU7WakDUDwf0785cgZHUXUZcrUn8d4VYPI1syEqE7YXUW0IJ5SSUT410t0eI90eIw5vUyUA0Q0U0gFQFQFc0yMZhIA3cogSAoAgQ8gvCNweAoUIArgrgQAA=="} import { Hooks } from 'wagmi/tempo' Hooks.reward.useWatchRewardRecipientSet({ onRewardRecipientSet: (args, log) => { console.log('args:', args) }, token: '0x20c0000000000000000000000000000000000000', }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `reward.watchRewardRecipientSet` Parameters](/tempo/actions/reward.watchRewardRecipientSet#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`reward.setRecipient`](/tempo/actions/reward.setRecipient) - [`reward.watchRewardRecipientSet`](/tempo/actions/reward.watchRewardRecipientSet) ================================================ FILE: site/tempo/hooks/token.useApprove.md ================================================ # `token.useApprove` Approves a spender to transfer TIP-20 tokens on behalf of the caller. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"2bf003f5493f7e541fe74b232dddbd8b378080a8e7358ad94560ea26b9b9c7a7","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnE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NBrrEgUXTvqIcH6iCp+lyBoE11Tpt3TukwLulwzHibAnuszlEEQzxBMzXgbsAEklzp6cGEQecG4mELtGZC2jkd03pVF2eQC+FAoOQVYDU6KE1QdG3Qklj2xxAnQaQIQXbEDBz9YiW/RMEIckO5g7+pYKOJpQbBQDEBhYDNl+8NsGOV+KxHBGeyGaA8bOYgD8HOzfq/DIIMEOyFhDAIfMOsFELwZhQz4A4C+NviobJDaGUECwGBFBEZC3BOGKxVnMpFcR/8NI8xZ1jKE9ZKh4oaocHLaFiJ6hcjZocaP6wYj4lHQ+Rpoxmb8ZehyiDZJY0GE7QRheSsYUMHlATDcRSzdkbMKuH7Dbhywn4asL+FPCzhmwi4ZkyqbXDamhwhpccICbNKNhLw7YW8JqWfC6l3Sxpo8O9QAjWlrwy4R0tqVeNvhEyppVMrSbLNVA0Iq2Q+ngZ6BIR72aMPbMj5wjeIpi05mBnCUojyhyS4RHUPSU4jFm0wjxRsvxwp9g+1WRRoEodlPhjQ0fQGLH00jx8FA6yo0J9j9lp9iwfWYRKHKNDjZJs02WbPNkWzLZVs62LbDtj2wHYjsJ2M7BdjaDvVMMXy5wCAivS5hYAf4YTOKHCGygYscWDGIDGxi4xSQbAAmOFkpUpZosaMeLOqGYBJYWZuDY+OeRsUHx7Fx8EWPtGtAjgciUMd9Dq28a/R5WUkF1MknBCFEFAGbJOArDTwUt+ANQROtkzaDYwdke0dOCEJChwh30xsKWFn3UTsrGMKoUEHCFUB2xnwkQCgFLFaGqhoVsKiOQiujnIr45qKpORitTnYqM5bQM0FLCMgWwocFgGHIjnjUJr7QEajOOnBYHt0M+O87oXbFNUOJ/GOkOENavTiCTHiQc9EbPS3RWK4Qeau5MHKLWUKIVFUFhNmsrXVrFG6cfwBXFEBIBQAgQeQJrhSAuyEArgVwEAA="} import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' const approveSync = Hooks.token.useApproveSync() // Call `mutate` in response to user action (e.g. button click, form submission) approveSync.mutate({ amount: parseUnits('10.5', 6), spender: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) console.log('Approved amount:', approveSync.data?.amount) // @log: Approved amount: 10500000n console.log('Owner:', approveSync.data?.owner) // @log: Owner: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb console.log('Spender:', approveSync.data?.spender) // @log: Spender: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.approve` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { parseUnits } from 'viem' import { useWaitForTransactionReceipt } from 'wagmi' const approve = Hooks.token.useApprove() const { data: receipt } = useWaitForTransactionReceipt({ hash: approve.data }) // Call `mutate` in response to user action (e.g. button click, form submission) approve.mutate({ amount: parseUnits('10.5', 6), spender: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) if (receipt) { const { args: { amount, owner, spender } } = Actions.token.approve.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `token.approve` Return Type](/tempo/actions/token.approve#return-type) ### mutate/mutateAsync See [Wagmi Action `token.approve` Parameters](/tempo/actions/token.approve#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`token.approve`](/tempo/actions/token.approve) ================================================ FILE: site/tempo/hooks/token.useBurn.md ================================================ # `token.useBurn` Burns TIP-20 tokens from the caller's balance. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"5b6d09a09c9cff3e14ddc9584d71dec809880c31569d5f43fb47e4d50b5f31db","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUoiaicACUnABmAK5gjowQYJxY4nAwAKpgjGhwwURhcTCInCKkpgoUnLDWLGFwZWBxzABGZJFlbYwKpmgAOrms7FzppJk5eUZQENYIegCycTJojFgm8Jyi5WiVipykMFhHmWBiaymcEDHbnC3tZJxtGHd9JKl0bGbn17dtERgnAAjBZOMFQV8UvI0JEAHRDIYAWk4ABE5k1OPg0GgsE0APT4oiMGDMOFwfD42bzfFxNYmNbwfHjSa5fL+MQKBbIZAgOiiVhyfwsNgcTjANIZbJsuCcVyxUgQZicADkxNJKsRYBZ0umwRVABYAEwWFU1SSRIaEzjGix2+0OsAgAC6zuEml0BvUxnkShUiFBGnE2iCOqm7NkpnMwJsdlIDicUncnhweEIJHIGkCeGsKREzzipDAAGUMIkygZBHC0AJ5HC4pkAEKFktl6xwgBKOhbABUvAAeADCKRivRqCX4kAA7mAAHz+ETiXQAdmXsl9yiQAA4g1odHg2i3S4l/CYzEgAMyx+yOPyIABsyeoXjTvkzAXoTBGYsrRkXEkQLcdx9RRN0Qb1NBDPBf1PKNL2veNb2cYFlyfTBUz0dM/CzT89BFUZOBrfh5AXD0pANddQP9CDg33PQiJIyNz0QK8QFsG9E0QI0LzQl9MLfDlsz0eJEkuVIGxgZsi2PawhxHMdOAnac52CcYBR0Mg4AAfgrPgqwYsB6ybI82zhAAFexmA0iY5LAUdqkUsBJwgGdZy6Hg9Lgata0MiSpNbRJO27Is+xwWz7PHJzlNnIYwHUuB0msIE/JMk8qGpBZ9D02J2ALIsqk4HsAEkzJNQifNlGJFWVZQgWsMI5FIFVZQBGRRESGAETAIYADkIBoMoe3wRh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HY5fC6j0zZ0ts2M/RlkLUZpJ0l+KdFfloCQzCM62pgBtqw1B6NJV0pdFpBXSro2wCeMVFiPeHAyk8x4iWQDMYFiLi86efdXKiY2Gxy9l405HeuWH5gT0hYU9PeEFEPiol56p8RelFAvjzgOenJKwG1n9CPwKeL8PeOQMl690v0MvUxmfQKyWNogujW+t7Afr0Jn6rGVwBwi4Sf0da39N9JA29gAMREwDHaJIjADgMREUDexgalgZONremUZBlIy2boNFUfDeRoIyYaWoiGbDCRmwWcGUMxksjLBjIAEa6MvBHiURsQwOjsN/BqDGRm4LkahD6GijXKMo0bYxC/BnDQITw0wa0NkhCjRhko28FRDC6uAi8FuG54b0tGYg3RpIMypS8qOsgmgfIIsaQJ7C1UdQbQGYSaDY0NgxxtYlUYXhJAm6HnogBqGdZhI1UeoT3U4hr1j6nIFnupDZ5kCBBBoCwB4zGFCDaBMyToZwGdjLhjQUANxoOGsD3h7wF4A0IOBF6ElJARoVQKIAvBtAtwBoA0I2GsCSAYAy4LnqoBiAWA2gSiNoG0E7qxYGhvdf+CulzCwAvw+OcUEwNlDygH66MAGFjBxikg2A+MOzHCK8wE5ER1UVUOqGYAeYcuDAinHzF/CCw6wg8N+OLAOjWhBwnBKZOkmvymBgUP0B5hJHWjmDwQnUBQJywThXAzo5OfgDUGZpcM2gWMMZPtBTiki4QB6U2LLCF7IZWQ3mUEHCFUB+Z7wkQCgLLAdiqgKsFgKrPVmNEmj7QZoIYK4BTjTsbaAvK6ELz8yyjdGWkOENYxTjRF+2uwpUPfxqCOjrUzoh+inH8Clw9GiAUAIEHkB+EUgXWBAK4FcBAA"} import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' const burnSync = Hooks.token.useBurnSync() // Call `mutate` in response to user action (e.g. button click, form submission) burnSync.mutate({ amount: parseUnits('10.5', 6), token: '0x20c0000000000000000000000000000000000000', }) console.log('Burned amount:', burnSync.data?.amount) // @log: Burned amount: 10500000n console.log('From:', burnSync.data?.from) // @log: From: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.burn` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { parseUnits } from 'viem' import { useWaitForTransactionReceipt } from 'wagmi' const burn = Hooks.token.useBurn() const { data: receipt } = useWaitForTransactionReceipt({ hash: burn.data }) // Call `mutate` in response to user action (e.g. button click, form submission) burn.mutate({ amount: parseUnits('10.5', 6), token: '0x20c0000000000000000000000000000000000000', }) if (receipt) { const { args: { amount, from } } = Actions.token.burn.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `token.burn` Return Type](/tempo/actions/token.burn#return-type) ### mutate/mutateAsync See [Wagmi Action `token.burn` Parameters](/tempo/actions/token.burn#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`token.burn`](/tempo/actions/token.burn) ================================================ FILE: site/tempo/hooks/token.useBurnBlocked.md ================================================ # `token.useBurnBlocked` Burns blocked TIP-20 tokens from a specific address. Requires appropriate permissions. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"0df2568dc9b4097277b953d5c3f9968dc9462d150265a4dbab251c23f27cd1be","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUoiaicACUnABmAK5gj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PjILRg4PUYA4vgviEMMb9Z6CDZIakIRpiBlASJGzpYyLyKKJ1KKCuCqLqKoZD0Sa6LxwGJWo8KzSmJXR6qWLmNoA2KhLhIwCRKVjJLzCC5AjZ5cC2pIoopOqnDM4kDvRQCRpHSmr4p2RahDDrJePlCVrHJ+ORHwCBNDQhNiBhPcrmqRNUzRPhqxM+P2qJNjy85BPKM7BrHhM8rZNagxMRDePxMOpFJJMlOpOhMVOZN6YpCgNvWcM5n1aEbY4YN6BpOiDYPA1fgGhuBYKSREN4KyQhDg5DZKNmNGKWMXTWOKS2NGJuPVRjhWPmKpArM8LdM1YGhHz9PfV456BHMMCiMnjiP/aiSqCqAyOwaQ3yOLOKNQ77N6rcARD4CaO0AKIaZ6OOMJARJRhJI03uN6B/MUg2bKBLTnRmJ6qPaegHYXP+jQLEZrz44/OKRwsqB3MBgPMk7OCLaEOcj+AAWYNPFovvbfifVHj+ivYkN6B7PrMHOmkUhlDuyA1LaqDfi7hLySAWC0LWARL8tehCsitittASvONSuCvCuiviuSu4bSsqtysKsxAA3Y4SMg2uCvq5iwBgQybihSyCB4zpaExQwkxkykhsCUyJYWstb5DWu9SqjqjMDZaMXSVCOIIDi3mQQyytgbweIfzKxVzCnTj5EXItJCGmDFNgxn6iFPBcvBAV4KBwgFj6ypDPQx78A1BZ1xNtAkzHI3RVwBv0ODhAaOxaxkZD1usFAqighwiqDezfiRAUBawaOqgTZTYzZzYLZLYrZrYbZbY7Z7YHZHYnZnYXZXY3Z3ZmhazQ5uy0Dw6o5bvbsOgrvVzRt+ub6OX6gcsouZJ2A8vezVuRtwgjPmRwg3NNj4s3SEtVz+DdyjOICgCBDyBOEpD44ICuCuBAA="} import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' const burnBlockedSync = Hooks.token.useBurnBlockedSync() // Call `mutate` in response to user action (e.g. button click, form submission) burnBlockedSync.mutate({ amount: parseUnits('10.5', 6), from: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) console.log('Transaction hash:', burnBlockedSync.data?.receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.burnBlocked` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { parseUnits } from 'viem' import { useWaitForTransactionReceipt } from 'wagmi' const burnBlocked = Hooks.token.useBurnBlocked() const { data: receipt } = useWaitForTransactionReceipt({ hash: burnBlocked.data }) // Call `mutate` in response to user action (e.g. button click, form submission) burnBlocked.mutate({ amount: parseUnits('10.5', 6), from: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) if (receipt) { const { args } = Actions.token.burnBlocked.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `token.burnBlocked` Return Type](/tempo/actions/token.burnBlocked#return-type) ### mutate/mutateAsync See [Wagmi Action `token.burnBlocked` Parameters](/tempo/actions/token.burnBlocked#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`token.burnBlocked`](/tempo/actions/token.burnBlocked) ================================================ FILE: site/tempo/hooks/token.useChangeTransferPolicy.md ================================================ # `token.useChangeTransferPolicy` Changes the transfer policy for a TIP-20 token. Requires appropriate permissions. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"c50850524110b7ca9c0fc4ed621eb980504ba6bbaaa0473aa617fef54500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6kQhQ66Bzu1G6xRd7Qhx64AVAkbzr066YkRR0gRvBeJ/AhiTry8Y7JBMZIbRzsapbz6Mo7Ar6ChOphojhtgGYa60ZJALA5prBr4wGIHVAoGYG4GEHwHIGkRoHYGcJ4G6JEHMHsG0G6JU6iRhy6Y7YkYQhYAmQYRHIwpvxVJEh1I58ly9JDIuc2ATITSninr4afrOh6iAwIoQwhxrh+HpZEoJD6DagFcVFIZbsfwMp2I2AwgoDixLlbFMoVMFBTsTpCpeMHh+BphdL9acI9J5EMIJC+Go4BGZZbUWpspg0MBQ1RoKBso2otJK0LBq1m0/H/GG1eorppHHiQry9R8YpR78DgHcq4bbHJHihCafQFDK6IjSgAHL78AJD/AH9RAkBQBAh5Af1Qg8AEIQBXBXAgA==="} import { Hooks } from 'wagmi/tempo' const changeTransferPolicySync = Hooks.token.useChangeTransferPolicySync() // Call `mutate` in response to user action (e.g. button click, form submission) changeTransferPolicySync.mutate({ policyId: 1n, token: '0x20c0000000000000000000000000000000000000', }) console.log('Transaction hash:', changeTransferPolicySync.data?.receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.changeTransferPolicy` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const changeTransferPolicy = Hooks.token.useChangeTransferPolicy() const { data: receipt } = useWaitForTransactionReceipt({ hash: changeTransferPolicy.data }) // Call `mutate` in response to user action (e.g. button click, form submission) changeTransferPolicy.mutate({ policyId: 1n, token: '0x20c0000000000000000000000000000000000000', }) if (receipt) { const { args } = Actions.token.changeTransferPolicy.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `token.changeTransferPolicy` Return Type](/tempo/actions/token.changeTransferPolicy#return-type) ### mutate/mutateAsync See [Wagmi Action `token.changeTransferPolicy` Parameters](/tempo/actions/token.changeTransferPolicy#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`token.changeTransferPolicy`](/tempo/actions/token.changeTransferPolicy) ================================================ FILE: site/tempo/hooks/token.useCreate.md ================================================ # `token.useCreate` Creates a new TIP-20 token, and assigns the admin role to the calling account. [Learn more](https://docs.tempo.xyz/protocol/tip20/overview) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"3d490a002c7e2f3cbae101c3273591aa8fdaec268e90c4041b25fc475f2316e1","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6INYQYCKc1qQwojQAyhhg1og8fIIAdGgC8mkArnAwAMJRMTDxiWkASjo5pGAAKl4APAWhAGaMChScOWD8kADuYAB8/iLiugAsAMyy8koqiACMVtTi2kGR0XEJ1v4mZkgATDZ2pA5OSABs7p44eIQk5BqBTKzsXAaCo5q6qpezimUag0ax0eE+Rn25mOwVO5z8SzcHmoXnuvieAXorzYHE4mX48m+4yuMLkgIW6lWWjBenxhNkpmhJ3sjgRh1UNxRdz0Dz8zyxelaPUcjFC3XyRS2pR2zTaHS6PT6EEGQwAFFh7MwdGQ4AB+ZIQjJZMC5CXFbblAAKmu1pDgsrA7U63V6A2GAEoDak4EaCSa8oVzdLylU0DV6k0Wo75S6lSqADpgMCiLVwDXWGDiwNSsq7KhQCDWBB6T6cVr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gVZfQrUL+B/8ogJAKAECDyBf0oQKqQgFcCuAgAA"} import { Hooks } from 'wagmi/tempo' const createSync = Hooks.token.useCreateSync() // Call `mutate` in response to user action (e.g. button click, form submission) createSync.mutate({ currency: 'USD', name: 'My Company USD', symbol: 'CUSD', }) console.log('Token address:', createSync.data?.token) // @log: Token address: 0x20c0000000000000000000000000000000000004 console.log('Token ID:', createSync.data?.tokenId) // @log: Token ID: 4n console.log('Admin:', createSync.data?.admin) // @log: Admin: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.create` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const create = Hooks.token.useCreate() const { data: receipt } = useWaitForTransactionReceipt({ hash: create.data }) // Call `mutate` in response to user action (e.g. button click, form submission) create.mutate({ currency: 'USD', name: 'My Company USD', symbol: 'CUSD', }) if (receipt) { const { args: { token, tokenId, admin } } = Actions.token.create.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `token.create` Return Type](/tempo/actions/token.create#return-type) ### mutate/mutateAsync See [Wagmi Action `token.create` Parameters](/tempo/actions/token.create#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`token.create`](/tempo/actions/token.create) ================================================ FILE: site/tempo/hooks/token.useGetAllowance.md ================================================ # `token.useGetAllowance` Gets the amount of tokens that a spender is approved to transfer on behalf of an owner. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"b0c37f5d3bb0182fd912e817d276901fd1c5110436708118f3f541db520ed0f9","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUWKQQOBwYAJScUKJiiJwARowKplwAPpwArmCwAGamMFD+UBDWCHoAKvgwnDKiIpxwOdbW8HAFOTIyGJyk8BAyJFBxCaKcBeycyvUAjjlkGAB0ADpgGxu19Y3Nre2d3b39g3DDo+NiUzNznIvL65vPOw1NXAcdcF09fQNDIxKV0m01Iszq9yWpFWWxeEL2HzaXx+J3+50BY3i11B4IWUJhz228PeLSRR1+pwBlyxINuEIe0JW/hE4l0ABZ1MZ5EoVIg2RpxNogjT/CYzEgAEw2OykBxOJAADncnhweEIJHIGkCeGsEDAzVEvQgAHdRGAOklUukwFlcvkYEUzKUqOVKnhXgjSYdvsc/mcLkCaTcwXcGatmZpdKoAIyybnKKQCrQ6PCGmQms0dUXFSXS+yOPyIaNs5XULxq3yagL0JisdhcAyCCOspAANk5ckUCcQnM0QrwjaMYvMUpAtnz8sQEqVHjLqr06r8WprehYbA4swE8mbEkQAHZY1yu7ze4KU3o0FuwNnxVO87KC84AMwl2eYec+DX+GgrkDdc1oIweq5HAMAAOI6AAgkaprmjAAA8ADCepFAoFApGkGQAHyhPYzA6GQcAAPxJIOKyXvw8grDkoEQWg0HprBHQrAACnhBGkHASEoWk6FWth0SkXwgjkVe1G0VBMGZjAKwAEo6DkpBgAAaoaSzwfxNpYRsYCiPhcBYA49Q0eBkmMdJZQVFU+jCcGnBCoBiicNUACSLEShYm6UWAnBphmcFMgKChVMgyAgHQelYHI/gAAZxWgcC0Bsa71pwwA8MJcCcK4UzhMwnAAOSmgozCMAA9DQdYFbC/6OEBPmQVgWDBLEwAbJwnC6vqXDpTS6GMHAAA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IxgmgckwgWBxB+hlTvcFY9NK4ZZ6ob10yW1SRkgRAZYz89QuU1J4BTVSoLUt0WNiiChggnxogDtIMTsyoIcwA9xEMLsxQch8MBzfsGErsBynwD8MgCgVgnwFMKM+9gg7hQzwyEpEt6g8lYyV1WyYoz8ZAVhwcEge0cSeM+yzs2MhNElrtxNJN7sZNyojzlyqMjzTy0BPyOZBQ4BohylMc4psdzRLiUkuAZpVAvDVcGiwKkh+cKd0IwLViuikhYLOB1BFcgMBiQLoL8cDdYLhckKATii140KMK2csLqiqZYRls1tDzAJjzPzzzuMjteNrzhzkM7z0MHz6SHtZNXzXtKMPz2AIcvyRKEgfytA/y7IQd6gwdxK4CKkxBgokBQpVZTAswqAiALAVhoxdKLALB2TKkWwpw9xWxeTeROlqBLk8Au0hSulHxFQ+lJT6UPkdRLi/ITZLRMJUlYkHESgRUahiR9gyQfQKQ0QAxMQJg7JQx8QcUTKJRJBTlOxCVpBrL9ZUxFY0ThxFQHKnlWxnLvBlL/BeDbL8cdxdAl8Ox4xeQrA3L1ksqkhowLBVADK2rrwzZbxmq8qxTXAVZdRYBaws40pZpBBJoCg8oRce5SoKoYAqoLjuoRqaR9SsrJoZoyIsVFojYsq1pzoWldpbpaA9w2QJQoAnxVBEJrBWxWwXxEIWqu9JAJRVBRAnxkgFQ2Q2QAAhawSQGAPcVQSQVQAoCwZIaHZIZIR6Daa5MgQ6vcZfSQPcBGiwRCGMBUaMU66wJ8SCCwZqxCPcKAHG5IVqmACwKAaMfG6wRGxCBUSGjqLFQ6jyawNq5mlm1mtm9m5myG56BajlHnA3Y2aSRAYXTy6SPvfwOtUQJAUAQIeQOePUPABKEAVwVwIAA"} import { Hooks } from 'wagmi/tempo' const { data: allowance } = Hooks.token.useGetAllowance({ account: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', spender: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8', token: '0x20c0000000000000000000000000000000000000', }) console.log('Allowance:', allowance) // @log: Allowance: 10500000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type See [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook return types. ### data See [Wagmi Action `token.getAllowance` Return Type](/tempo/actions/token.getAllowance#return-type) ## Parameters See [Wagmi Action `token.getAllowance` Parameters](/tempo/actions/token.getAllowance#parameters) ### query See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook parameters. ## Action - [`token.getAllowance`](/tempo/actions/token.getAllowance) ================================================ FILE: site/tempo/hooks/token.useGetBalance.md ================================================ # `token.useGetBalance` Gets the token balance of an address. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"c7528612435a35df89295a7a12ef72ca886311a30623cf9079ae2b6b2e88aefc","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUWKQQOBwYAJScUKJiiJwARowKplwAPpwArmCwAGamMFD+UBDWCHoAKvgwnDKiIpxwOdbW8HAFOTIyGJyk8BAyJFBxCaKcBeycyvUAjjlkGAB0ADpgGxu19Y3Nre2d3b39g3DDo+NiUzNznIvL65vPOw1NXAcdcF09fQNDIxKV0m01Iszq9yWpFWWxeEL2HzaXx+J3+50BY3i11B4IWUJhz228PeLSRR1+pwBlyxINuEIe0JW/hE4l0ABZ1MZ5EoVIg2RpxNogjT/CYzEgAEw2OykBxOJAADncnhweEIJHIGkCeGsEDAzWSokaYA6SVS6TAWVy+RgRTMpSo5UqeFeCNJh2+xz+ZwuQJpNzBdwZq2Zml0qgAjLJucokAB2AVaHR4Q3Gjqi4qS6X2Rx+RARtnK6heNW+TUBehMVjsLgGQSh1lIABsAGZo4pY4hOZohXg60YxeYpSBbDn5YgJU2i5hVXp1X4tZW9Cw2BxZgJ5A2JIgm9IuR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' const { data: balance } = Hooks.token.useGetBalance({ account: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) console.log('Balance:', balance) // @log: Balance: 10500000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type See [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook return types. ### data See [Wagmi Action `token.getBalance` Return Type](/tempo/actions/token.getBalance#return-type) ## Parameters See [Wagmi Action `token.getBalance` Parameters](/tempo/actions/token.getBalance#parameters) ### query See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook parameters. ## Action - [`token.getBalance`](/tempo/actions/token.getBalance) ================================================ FILE: site/tempo/hooks/token.useGetMetadata.md ================================================ # `token.useGetMetadata` Gets the metadata for a TIP-20 token, including name, symbol, decimals, currency, and total supply. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"ba0d6e59f59bb9a5429e5c8f90558913930bfe2f294f96336382a6252f972e31","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUWKQQOBwYAJScUKJiiJzAADpgnBmc1gCupKTy1hhJIqSmCgDcaZlxMNYsojJwSWDZzABGZJXpmQCO2RA0ACoC8gD8SQAGFrQAJMAlZa4TnAA+nNlgsABmpjBQXdVgoswwxWiligeZWKLZcHvjnG18cqLpaxvbu1Cr65swOzM+yqmTg2SwWBkGAAwqIsI82owFKYuB9/oC9r9PgDvlcMnAMO0IDIzhcKiCMmgBg0AMrgyFFJ5IlF4zjnN5wLZkAAKxMYhQAklAEcywKi/l8gVj0bi0q5pZK9v4oBBrAg9IN8DBODJRCJOGDrNZ4JzsjIoZx8nBiSQfvExJwtuw2VrOH0yBgAHRpH1gTXa3X6w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ZdfFPXVzrkpMReltuu6Ms5ej19foy2o512TCpKFC9dGkq4THzuFUpBckJQVhU6D9UnDC+re4tSPuX3DKtfh95wy/1nNJQz1DfZbR9DWUYDRytA1ubGVAEcaZNJg2QQt4NG9HnNJDjdVw4qGs+FOhjiXwsN9PJOLbx2nVBpqVPA6cRs40nTeYTPd6RxtJNUaQEmJzIA3Blj0a2NaARjc9I7hqxheH8G6vpt42PUpeAmjyFOG8igy/I4MxcIOAk3LiWVq42TWIZADIz9eeh5zQqkRSqbCOxhkjppqiB4pwE3PHk6KccjDAlIvEBkKZvd6BIlTqgFU77zCgRRteQQTk4dQwC6HoTOpgHnqfhMHQuVVAaDnoCUOCGRonUuGSKqCDWnUM3ppIP8ZSopnUzaZtM8dEkOnQwofUGE84DdIfJfwsAMqO2lkRdRFEjoFRK7m0R6IDEbAIxF3tqIOJgIGdcFBWd8QjxAkoKW2ONPCQghR40SaYEwmsDpnRzY58c6OYSRyh78I65JkTXRMtUXcuvLpMjxiCzm+KzvKiEufGldJk49+ChWojFUgJtzkGrpLjP3PbGjNGPJoCefBRdJ7NF5hdfGciyJnbz/SL04XHvz+BEoSAUAIEHkCeo/weAcRCAFcCuAgAA=="} import { Hooks } from 'wagmi/tempo' const { data: metadata } = Hooks.token.useGetMetadata({ token: '0x20c0000000000000000000000000000000000000', }) console.log('Currency:', metadata?.currency) // @log: Currency: USD console.log('Name:', metadata?.name) // @log: Name: United States Dollar console.log('Symbol:', metadata?.symbol) // @log: Symbol: USD console.log('Decimals:', metadata?.decimals) // @log: Decimals: 18 console.log('Total Supply:', metadata?.totalSupply) // @log: Total Supply: 1000000000000000000000n ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type See [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook return types. ### data See [Wagmi Action `token.getMetadata` Return Type](/tempo/actions/token.getMetadata#return-type) ## Parameters See [Wagmi Action `token.getMetadata` Parameters](/tempo/actions/token.getMetadata#parameters) ### query See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook parameters. ## Action - [`token.getMetadata`](/tempo/actions/token.getMetadata) ================================================ FILE: site/tempo/hooks/token.useGrantRoles.md ================================================ # `token.useGrantRoles` Grants roles to an address for a TIP-20 token. Requires appropriate permissions. [Learn more about token roles](https://docs.tempo.xyz/protocol/tip403/spec) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"f4391afb0618a6365e397f75dd69c90dea54e09d9cd37c91d8c93575a93d1dde","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6INYQYCKcCqSiYGgAShBycADKGGDWiDx8ggB0aALy2QCucDAA4lEx8YkpadmxOoWkYAAqXgA8AMKhAGaMChSchWD8kADuYAB8/iLiugAsAMyy8koqiACMcxri2kGR0XEJ8DXW/iZmSABMNnZRjn6IAGzunjh4hCTkGoFMrOxcBkE000ukeVmMK2Uam2Wh0eEBRnO5muwVuDicVwWL2oXnevi+AXovzYHE4eX48mBsyQj0ey0UUMQ6moOzhenJlNkpmRN3s92clzcHhxbz0Hz83yJem6Q0cjFCgxK5QOVWOqWsnR6fQGQxGEHGEwAFFh7MwdGQ4AB+DII3L5MBFJUVQ7VdXZAAKpvNpDgmrAvX6g2GY0mAEobVk4HaKQ7imVnarkm76mhGi12l1/dqg3qDQAdMBgURmuAm6wwRXxlVHJNpfxQCDWBB6QGcbrsCLO0wKTikGttjuiTjNACS7suFjJ9uyBYLADkIDQMs18Iw4Jw15wh3B1fg+5BipxCAIyXYuKNRIw0Ov26RTxW0BU4Oj5WAC3lOAAjCumawyQqwFAnAKkOn4yI2/BfjAt4VqQDRNN2W69vAbBhDA2T+GICjNsgyAgHQxZYHI/gAAZkdetAFiwJJcMAmSGJwrhtn2zCcA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hCQFivz01cCM2ALM0s7wBs0ZKc2DU83UKhAeUC100hzC0vKi3JLi0ebs3VK1Iy0RJy183eSK0VhC3xKq1JLdwa2S0c063c1631zy2A0LBvRbWg1rDMx7V4Cc2w3w1oinWIBzDnWTlurZrXV6BeoFqyRwTlh+HLhPgvihD1DR3WyO1Kr0iWp9ndp4BR0xLJ1kpHWjl+2qBzAo3urjph2Y0R1gFhDx1gDcAhz4AZAkTJQ9E5EdRzJk09bQSU0bpVx11wADwQBaJ35AJx3gqO2SBRqsyUHWrsij02x90qB51w0F2wyPAupB3eBYT+B9F4AHXrXzCqFp2MjgjsFbpz1iR2D90ZDJTrCXBiqqCPDO2SAWDazWC5y3332P24ov2fhv3QQf1zAP1P0/1/3dAANAPf2v25yw3toI1+2ixPQhCwDEj/ByRPWMTMRoHsScTcR8Rs5sCCTeS3VxwPVlG2gvXEz3W8w2TeQN4dAy5gJXQXZebISljIIQFxhFLgpOToQKAHZjReRKSBT8ADC6Wm2fjcSAKvhCEkO8zZAkpxQuScpJS0B8oCpCoirA3iqSrSoT1yoKpKoqpqoapao6p6oGqfjpQuSJrwCFTFSAJBqVQUBKP2hZRloWAVoNpePeO1pWNgCuBCHJVyb0nNDn0KiX0N15SyOGyc2WiSG/w50PSPjRDPjgoL1CH+C36iBICgCBDyBvqhA2oICuCuBAA"} import { Hooks } from 'wagmi/tempo' const grantRolesSync = Hooks.token.useGrantRolesSync() // Call `mutate` in response to user action (e.g. button click, form submission) grantRolesSync.mutate({ to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', roles: ['issuer'], token: '0x20c0000000000000000000000000000000000000', }) console.log('Transaction hash:', grantRolesSync.data?.receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.grantRoles` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const grantRoles = Hooks.token.useGrantRoles() const { data: receipt } = useWaitForTransactionReceipt({ hash: grantRoles.data }) // Call `mutate` in response to user action (e.g. button click, form submission) grantRoles.mutate({ to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', roles: ['issuer'], token: '0x20c0000000000000000000000000000000000000', }) if (receipt) { const events = Actions.token.grantRoles.extractEvents(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `token.grantRoles` Return Type](/tempo/actions/token.grantRoles#return-type) ### mutate/mutateAsync See [Wagmi Action `token.grantRoles` Parameters](/tempo/actions/token.grantRoles#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`token.grantRoles`](/tempo/actions/token.grantRoles) ================================================ FILE: site/tempo/hooks/token.useHasRole.md ================================================ # `token.useHasRole` Checks if an address has a specific role for a TIP-20 token. [Learn more about token roles](https://docs.tempo.xyz/protocol/tip403/spec) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"306dac353c73a78bf54e64cd30cbda4af1447f271833545285c0d219109fa181","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUWKQQOBwYAJScUKJiiJwARnxyomCcAD6cAK5gsABmpjBQ/lAQ1gh6ACr4MJwyoiKccLnW1vBwhbkyMhicpPAQMiRQcQminIXsnMoN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izY0qXiu3Ti53Gknis2Vi/i/XQS64zmOEL7X7RKHCgiuCozSHEzJCy8zjVC3jdC9U9HFzHCnHeTfCoihIAi8WUiinWYanBoWnaywM3pMQCKJAKKO2UwTofwIgCwVYKMIKiwCwfUvpZsSQwZWVaZeVPAfdK0m0gsEOfFFZJcKsIIGio0ImC0BCa0QpIFNMu1EkA4ckb0SkdEf0LESYAyEMAkCVSKyUVQAUBFU0uKhcTSRK7Fe8ScJ8e0vADy/weQ+KsYncXQacGZE0vkd2YlAcS2N5VwtFJICDZYJVN2JK5wO022PUWAGseubKJaQQOaQoYqe3KqGqeqGARqZEg0LgYaSYdXTSOaRaHCcVb2TSLaK6CZVi46WgBMdkSUKANsVQCCawFsdsdkCCCwVQJ8SQJq0QNsZIRUdkdkQ5awSQGAR2SQVQQoCwZIJnZIZIb6fqJasqBa0gYm4KN6MqE6QKawUKhmxmpm5mlm1mnJb6X6G681UY8YgmcmnZRAO3bKs0M/fwFdUQJAUAQIeQKBfUAahAVwVwIAA"} import { Hooks } from 'wagmi/tempo' const { data: hasRole } = Hooks.token.useHasRole({ account: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', role: 'issuer', token: '0x20c0000000000000000000000000000000000011', }) console.log('Has issuer role:', hasRole) // @log: Has issuer role: true ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Return Type See [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook return types. ### data See [Wagmi Action `token.hasRole` Return Type](/tempo/actions/token.hasRole#return-type) ## Parameters See [Wagmi Action `token.hasRole` Parameters](/tempo/actions/token.hasRole#parameters) ### query See the [TanStack Query query docs](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) for more info hook parameters. ## Action - [`token.hasRole`](/tempo/actions/token.hasRole) ================================================ FILE: site/tempo/hooks/token.useMint.md ================================================ # `token.useMint` Mints new TIP-20 tokens to a recipient. Requires the `ISSUER` role. [Learn more about roles](https://docs.tempo.xyz/protocol/tip20/spec#role-based-access-control) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"81309f31f44049ff315a55266231b03aaae8e5d9663c808078d1f3aa60a60d20","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUoiaicACUnABmAK5gjowQYJxY4nAwAKpgjGhwwURhcTCInCKkpgoUnLDWLGFwZWBxzABGZJFlbYwKpmgAOrms7FzppJk5eUZQENYIegCycTJojFgm8Jyi5WiVipykMFhHmWBiaymcEDHbnC3tZJxtGHd9JKl0bGbn17dtERgnAAjBZOMFQV8UvI0JEAHRDIYAWk4ABE5k1OPg0GgsE0APT4oiMGDMOFwfD42bzfFxNYmNbwfHjSa5fL+MQKBbIZAgOiiVhyfwsNgcTjANIZbJsuCcVyxUgQZicADkxNJKsRYBZ0umwRVABYAEwWFU1SSRIaEzjGix2+0OsAgAC6zuEml0BvUxnkShUiFBGnE2iCOqm7NkpnMwJsdlIDicUncnhweEIJHIGkCeGsKREnGY/QAyhhEmUDII4WgBPI4XFMoti6XrHCAEo6OKkMAAFS8AB4AMIpGK9GoJfiQADuYAAfP4ROJdAB2JeyX3KJAADiDWh0eEL5xLiX8JjMSAAzLH7I4/IgAGzJ6heNO+TMBehMEZiitGBcSRCbtuPqKBuiDepoIZ4D+J5RheV7xjezjAkuj6YKmejpn4WYfnoIqjJw1b8PI84elIBpriB/rgcGe56IRxGRmeiCXiAtjXomiBGueqHPhhr4ctmejxIklypPWMCNoezaDsOo6cOOU6zsE4wCjoZBwAA/OWfCVvRYB1g2TaJHCAAK9jMGpEwyWAI7VPJYAThA04zl0PA6XAVY1vp4mSWgR4tu2aCdj2/ZDjZckKU5s5DGAqlwOk1hAj5RnWP41ILPoOmxOwBb9FUnDdgAkiZJoEV5srVtsqSiFAUCnB5WoAH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1m1b3W221aD21E39vZou0j7S2b1J2z29Wqtq9D2LrY9uHV1bX5N69RHeqQGGL71D6adVGP+ya5cBS685fOgB1JYl1dUZQcul3V1RY8pK/dRupVCHroCEOKoDurgItj4DMQhA6Ds3Uaqj0Eiipf6D/13p/9/aC9R1kAP3wgD16VRCAT6zjr0gk6sArQKhi8Yn0n2u9C+qLw+g31+8bSB+k/WtiG98mJvdbEM2/q9w3ealMPqdRyzANTsf8OZo0wgYMUUo68WBhzHgY7xAowUDRBgjsiRRnIfTEpueCKbm8CGZTYhnoMAbjwHwRg+pmAyATNMGG0QDxiw3DjsMGETCIrooB4YiNtS/DERB02EbhwxGcjCRlIwkRgBZGwiWRF02UY9NrEFfTRnY3zC6MlUzjOuOE3cbWpsmxuHxtYyNyJMKhwTaoYYwyZ1ComOUHJiMT8YtDyhDjFJh0PSaZN6h0TRobE2aG2NAmlQpxiqjCZuMTGEw3oVMNyauDPeBoP9J4M96W8ggFTcZraXD6bVZmV1WPqENuwVZaEMQ7hjGiUZmtihgKTYV6BOpDMTqZTasL4Lt63gTeIDTkC71Ug6CFALw1QDsJ95WB5mIAKROsBJACMasdWBrE1haxtYOsXWHrH1gGxDYRsY2CbFNhmxzYFsbQI6t6D8HnU10uYWAJ+BozigYGsoVzO5lhhvQEYSMNgCjAcy0i0s9I6GB5nVDMBvMSArRKvESDzkfw7MWsP3GFHWBeYqMa0AOGzQzJNYpBUwDUKegctxIhqXxOCELQKBA2scSWD7jtz8Aag3tIJm0ELATJVoScYhnCCPTaxhYQfJzBhgKAqhQQcIVQCbDvCRAKAwsGhPrFoC1YjQ9WRrM1laztZOs3WSQL1n6yDZhso2cbJNmmyzZ5si2M0L6K8gOxaAz2T7DmNzEOg0xycJOKQKeIB8DoQfE2DaI8YaQ4QozJOI8X+4wir8MITujUErHWpqx1YJOP4GLiiAkAoAQIPIDgCrRQcCAVwK4CAA="} import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' const mintSync = Hooks.token.useMintSync() // Call `mutate` in response to user action (e.g. button click, form submission) mintSync.mutate({ amount: parseUnits('10.5', 6), to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) console.log('Minted amount:', mintSync.data?.amount) // @log: Minted amount: 10500000n console.log('Recipient:', mintSync.data?.to) // @log: Recipient: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.mint` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { parseUnits } from 'viem' import { useWaitForTransactionReceipt } from 'wagmi' const mint = Hooks.token.useMint() const { data: receipt } = useWaitForTransactionReceipt({ hash: mint.data }) // Call `mutate` in response to user action (e.g. button click, form submission) mint.mutate({ amount: parseUnits('10.5', 6), to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) if (receipt) { const { args: { amount, to } } = Actions.token.mint.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `token.mint` Return Type](/tempo/actions/token.mint#return-type) ### mutate/mutateAsync See [Wagmi Action `token.mint` Parameters](/tempo/actions/token.mint#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`token.mint`](/tempo/actions/token.mint) ================================================ FILE: site/tempo/hooks/token.usePause.md ================================================ # `token.usePause` Pauses a TIP-20 token, preventing transfers. Requires appropriate permissions. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache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iOePcGvQy9Ie5VybSEFTyWgSFJFFe1ehFBnfKGvIC2tbI420OPmuiOwc2/I6e3q7UdIBGy/TIE2nmWWmvfwGqUQJAUAQIeQOVUIakBAVwVwIAA="} import { Hooks } from 'wagmi/tempo' const pauseSync = Hooks.token.usePauseSync() // Call `mutate` in response to user action (e.g. button click, form submission) pauseSync.mutate({ token: '0x20c0000000000000000000000000000000000000', }) console.log('Transaction hash:', pauseSync.data?.receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.pause` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const pause = Hooks.token.usePause() const { data: receipt } = useWaitForTransactionReceipt({ hash: pause.data }) // Call `mutate` in response to user action (e.g. button click, form submission) pause.mutate({ token: '0x20c0000000000000000000000000000000000000', }) if (receipt) { const { args } = Actions.token.pause.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `token.pause` Return Type](/tempo/actions/token.pause#return-type) ### mutate/mutateAsync See [Wagmi Action `token.pause` Parameters](/tempo/actions/token.pause#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`token.pause`](/tempo/actions/token.pause) ================================================ FILE: site/tempo/hooks/token.useRenounceRoles.md ================================================ # `token.useRenounceRoles` Renounces roles from the caller for a TIP-20 token. [Learn more about token roles](https://docs.tempo.xyz/protocol/tip403/spec) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"b76e1df0be1a3b2792bb8c4a1ab224f7963d06a0ffa907fcd104f996453f6d0e","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6INYQYCKcpPIQAK5g1jAAShBycADKGHGIPHyCAHRoAvK50XCJUbHxSSnpcbkJOtGkYAAqXgA8AMKhAGaMChScsfyQAO5gAHz+IuK6ACwAzLLySiqIAIwA7Bri2kGRkBWJyfA11v4mZkgATDZ2pA5OSABs7p44eIQk5BqBTKzsXAMgimml0T0WxmWyjU2y0OjwQKMF3MN2CdwefkQVxeHmoXg+vm+AXofzYHE4BX48hBM2e0khimhiHU1B28L0lOpslMKNu9kcmPmV1eePeek+fh+JL03QqaEYoUGpXqBziR2qGWsnR6fQGQ1GEwAFFh7MwdGQ4AB+LKI/KFMDFZXlNVVE6a3IABVN5tIcG1YF6/UGYGGEDG4wAlDacnA7VSHSUyqrKsc0u76mhGi12l0A7rg6HwwAdMBgURmuAm+JKpMxF2p07+KAQawIPRAzjddgRZ3WUwKCKpzvd0ScZoASQ9VwsFPtuRLJYAchAaFlmvhGHBOJvOKO4Jr8KRQjEt4QBBS7FwRqJGGgt13SBeYBT7mEHgqwCWCpwAEbP0zWDI0SwFAnCKqOP4yC2/C/jAD7PpEmZNP2u49pWoSlLk/hiAobbIMgIB0OWWByP4AAGFF3rQJYsGSXDANkhicK4nZHswnAAOTXgozCMAA9DQ/wcQuAZyh+nAAIJYFghoRpwwAlpwnAhGE9GcMw0RiDQAybh68hQChLEALyMXknIJk6ybqm6cSySJSmIVmnCGopSmcG0P6aQUn5gG5bmhB0JjWPwRnALJnBGeM6maaINCGgx5lZBxFi0LkaUcQMR4pFkyAcZucDRGQHEALrMRGriuX5BlwKIkEwFAo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CwWqawbOJu5W1u9uzu7u3u5ugejurun8HuuCPulutu8e4euCTm1EAMnm4M+6EIWAUkAEeSbGZiViefUPKU3iASG7NgYSfElo3atq8o20XGFqnWQmWyL/DfDoIHUBc6RjbcXyK6NgMIIfRMXJWuw0cHBQTLYabyZSIKfgAYFCkmn8XiABD8L/K+x+9qvFeKVyJlW3XKdlIqOaVyRKTiHVCwPVM1Mh8h41DKSaZ+5igrcHM46utuJO8SOweukPFBuq3ISGy0XIcW8JC2fIGu5Oh2r/fwBOUQJAUAQIeQBtCOjkBAVwVwIAA="} import { Hooks } from 'wagmi/tempo' const renounceRolesSync = Hooks.token.useRenounceRolesSync() // Call `mutate` in response to user action (e.g. button click, form submission) renounceRolesSync.mutate({ roles: ['issuer'], token: '0x20c0000000000000000000000000000000000000', }) console.log('Transaction hash:', renounceRolesSync.data?.receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.renounceRoles` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const renounceRoles = Hooks.token.useRenounceRoles() const { data: receipt } = useWaitForTransactionReceipt({ hash: renounceRoles.data }) // Call `mutate` in response to user action (e.g. button click, form submission) renounceRoles.mutate({ roles: ['issuer'], token: '0x20c0000000000000000000000000000000000000', }) if (receipt) { const events = Actions.token.renounceRoles.extractEvents(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `token.renounceRoles` Return Type](/tempo/actions/token.renounceRoles#return-type) ### mutate/mutateAsync See [Wagmi Action `token.renounceRoles` Parameters](/tempo/actions/token.renounceRoles#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`token.renounceRoles`](/tempo/actions/token.renounceRoles) ================================================ FILE: site/tempo/hooks/token.useRevokeRoles.md ================================================ # `token.useRevokeRoles` Revokes roles from an address for a TIP-20 token. Requires appropriate permissions. [Learn more about token roles](https://docs.tempo.xyz/protocol/tip403/spec) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"feffa8dd71c04910b36e8e796cdfdc9026dde663ac6793cf3241ca53a1f00b9f","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6INYQYCKcpDBEAjAAShBycADKGGDWiDx8ggB0aDFg2QCucHFRMfGJKWnZsTqFpGAAKl4APADCoQBmjAoUnIVg/JAA7mAAfP4i4roALADMsvJKKogAjOrU4tpBkdH8cQnwVdb+JmZIAEw2dqQOTkgAbO6eOHiEJOQagUys7FwGgkmml0D1Wi0UyjUGi2OjwAKMZ3MV2CNzufkQFxmz2oXjevk+AXoPzYHE4eX2YCB00eAHZwcsoZstLC9OT5KdTEjrvZHOi5hZsZhXnp3n4vkS9J0Bo5GKF+iVansDpVUtZ2l0en0BkMIKMxgAKLD2Zg6MhwAD8GXhuXyRQVZX2FSOquyAAVjabSHB1WBur1+oMRuMAJRWrJwG0Uu2lJVO5Iu2poepNVodX2agM6vUAHTAYFEJrgRusMHlMfKh3jaX8UAg1gQegBnE67AiDtMCgilebrdEnEaAElXRcLGTbbncwA5CA0DKNfCMOCcRecPtwVX4UihCDFTiEARkuxcYaiRhoJct0iH0toW5hO6ysC5vKcABGpdM1hkhVgUE4cr7V8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5r1Ys71gheA/q5aEkFSYgGQ31usRMnsYAPsMKmcAw2cnIJc35ZcB6ZSay4Q0SdCDCiyV0CQJAf4FNfYl4wSPCBQvEuYh63NXAvN/8/NPO8AQtKSot81EtWioQ6eRGXNwc8tkyfNcSyt6Owt5SlSGt3CWtUtbkMtetPNhtitxt8EqtItFt4tVtNc2tcNBhNqfaH0ftN1egotWNONS5zgMwbgq53qRaH1egpNcsEkkQJYkRc4d4tUeCYAtQKdFsPtkgVg/tk5tqaNOdDAJK854MOaagqgBN65dKyMUsV6AaFat4rcGdls3Awc+AGQ+EcUkxFRrU0yTNw24ErNe65cndcAvcEA6in+AC6dD4oQediNl16KKNv0eArd94mdk9Kg5dD1ldE6YqtdqE/gjRt1U+cNMwLMhdSABdxNegjQC9mdZBU9GQcUqwFw4qqgDwPa+ddU1g2cn939v9n0/9r4gD4EwDMwP9f9FgADQDX9MDoD4DkDnQWNr0T1y5rg90IQsAxIfwkk2MNEdE7KTELEbEnEfObAPELpUJ1NmMfx1ouM/06NNN1gFkbknebQKuIC50T2QW8EbAYQyBxkeSL9+oumCgV2w0rkskPk/AyUKeUSdZbE/8j40hDDccRKkU9kDqaUtAvK/Kgqwqoq4qkq0qsqFw8qiqyqqq6qmq2quq+qhqr4SU9kaawaxp+U/84apUFA9k0UTENaFgdaba4TETza7jYArg0hhVcm3JT9bdi97kdgb9WUWjbs2Qot5o2Qyd4SFsuQz9HdXd0h/gH+ogSAoAgQ8gP6S9rICArgrgQAA==="} import { Hooks } from 'wagmi/tempo' const revokeRolesSync = Hooks.token.useRevokeRolesSync() // Call `mutate` in response to user action (e.g. button click, form submission) revokeRolesSync.mutate({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', roles: ['issuer'], token: '0x20c0000000000000000000000000000000000000', }) console.log('Transaction hash:', revokeRolesSync.data?.receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.revokeRoles` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const revokeRoles = Hooks.token.useRevokeRoles() const { data: receipt } = useWaitForTransactionReceipt({ hash: revokeRoles.data }) // Call `mutate` in response to user action (e.g. button click, form submission) revokeRoles.mutate({ from: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', roles: ['issuer'], token: '0x20c0000000000000000000000000000000000000', }) if (receipt) { const events = Actions.token.revokeRoles.extractEvents(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `token.revokeRoles` Return Type](/tempo/actions/token.revokeRoles#return-type) ### mutate/mutateAsync See [Wagmi Action `token.revokeRoles` Parameters](/tempo/actions/token.revokeRoles#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`token.revokeRoles`](/tempo/actions/token.revokeRoles) ================================================ FILE: site/tempo/hooks/token.useSetRoleAdmin.md ================================================ # `token.useSetRoleAdmin` Sets the admin role for a specific role on a TIP-20 token. Requires appropriate permissions. [Learn more about token roles](https://docs.tempo.xyz/protocol/tip403/spec) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"c4dfbc1c2509d94e1eda6bf007b494a3199ae8c05d6345fb80ca7a05858d98eb","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMx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t5EYQz+CYtS29xojyCg82600UhkSU/AgwklWSMESQSCEEdBn1mDaYDK+UoUGqpgLUkkkq0qS0FUoUvqNUSC9qCjsUhUkkSaFgKaOaujejmaajrgdBAVXGOJm92dbdQUdgu9jUwjUcZN1orBcCkdQM/dOdEEQ9dB/gG+ogSAoAgQ8ga67dXICArgrgQAA==="} import { Hooks } from 'wagmi/tempo' const setRoleAdminSync = Hooks.token.useSetRoleAdminSync() // Call `mutate` in response to user action (e.g. button click, form submission) setRoleAdminSync.mutate({ adminRole: 'defaultAdmin', role: 'issuer', token: '0x20c0000000000000000000000000000000000000', }) console.log('Transaction hash:', setRoleAdminSync.data?.receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.setRoleAdmin` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const setRoleAdmin = Hooks.token.useSetRoleAdmin() const { data: receipt } = useWaitForTransactionReceipt({ hash: setRoleAdmin.data }) // Call `mutate` in response to user action (e.g. button click, form submission) setRoleAdmin.mutate({ adminRole: 'defaultAdmin', role: 'issuer', token: '0x20c0000000000000000000000000000000000000', }) if (receipt) { const { args } = Actions.token.setRoleAdmin.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `token.setRoleAdmin` Return Type](/tempo/actions/token.setRoleAdmin#return-type) ### mutate/mutateAsync See [Wagmi Action `token.setRoleAdmin` Parameters](/tempo/actions/token.setRoleAdmin#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`token.setRoleAdmin`](/tempo/actions/token.setRoleAdmin) ================================================ FILE: site/tempo/hooks/token.useSetSupplyCap.md ================================================ # `token.useSetSupplyCap` Sets the supply cap for a TIP-20 token. Requires appropriate permissions. [Learn more about roles](https://docs.tempo.xyz/protocol/tip20/spec#role-based-access-control) ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"d3b1cd4a14575e906a78bb7cbc3171540f904daf431667513fb951963d8d9fc1","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUoiaicACUnABmAK5gjowQYJxY4nAwAKpgjGhwwURhcTCInCKkpgoUnLDWLGFwZWBxzABGZJFlbYwKpmgAOrms7FzppJk5eUZQENYIegCycTJojFgm8Jyi5WiVipykMFhHmWBiaymcEDHbnC3tZJxtGHd9JKl0bGbn17dtERgnAAjBZOMFQV8UvI0JEAHRDIYAWk4ABE5k1OPg0GgsE0APT4oiMGDMOFwfD42bzfFxNYmNbwfHjSa5fL+MQKBbIZAgOiiVhyfwsNgcTjANIZbJsuCcVyxUgQZicADkxNJKsRYBZ0umwRVABYAEwWFU1SSRIaEzjGix2+0OsAgAC6zuEml0BvUxnkShUiFBGnE2iCOqm7NkpnMwJsdlIDicUncnhweEIJHIGkCeGsKRE5R0AGU4lgNhgAMKiLCFjCJMoGQRwtACeRwuKZQtFktlyvV2vWOEAJR0cVIYAAKl4ADzllIxXo1BL8SAAdzAAD5/CJxLoAOy72S+5RIYEANiDWh0eEyaGLpZkFarNcS/hMZiQAGZY/ZHH5EKfk2oLw018TMAnoJgRjFBsjG3CQXHPH1FGPRBvU0EM8Bg18o0/b941/ZwjVUQDMF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oYcDogcp4kQFA+sVWPstA9WLWureryr6rtcNcwdOuuFKz10az48GzWTgc4rukcIBj1kcIwT8qfCTYqz3TvTNc/gvchjiAoAgQ8gERKQnTCArgrgQAA==="} import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' const setSupplyCapSync = Hooks.token.useSetSupplyCapSync() // Call `mutate` in response to user action (e.g. button click, form submission) setSupplyCapSync.mutate({ supplyCap: parseUnits('1000000', 6), token: '0x20c0000000000000000000000000000000000000', }) console.log('Transaction hash:', setSupplyCapSync.data?.receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.setSupplyCap` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { parseUnits } from 'viem' import { useWaitForTransactionReceipt } from 'wagmi' const setSupplyCap = Hooks.token.useSetSupplyCap() const { data: receipt } = useWaitForTransactionReceipt({ hash: setSupplyCap.data }) // Call `mutate` in response to user action (e.g. button click, form submission) setSupplyCap.mutate({ supplyCap: parseUnits('1000000', 6), token: '0x20c0000000000000000000000000000000000000', }) if (receipt) { const { args } = Actions.token.setSupplyCap.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `token.setSupplyCap` Return Type](/tempo/actions/token.setSupplyCap#return-type) ### mutate/mutateAsync See [Wagmi Action `token.setSupplyCap` Parameters](/tempo/actions/token.setSupplyCap#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`token.setSupplyCap`](/tempo/actions/token.setSupplyCap) ================================================ FILE: site/tempo/hooks/token.useTransfer.md ================================================ # `token.useTransfer` Transfers TIP-20 tokens from the caller to a recipient. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"7775daec2b381b6bcd7a8eff1994271be08a51ae7321b1edd956fd4293c96767","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6IAAUoiaicACUnABmAK5gjowQYJxY4nAwAKpgjGhwwURhcTCInCKkpgoUnLDWLGFwZWBxzABGZJFlbYwKpmgAOrms7FzppJk5eUZQENYIegCycTJojFgm8Jyi5WiVipykMFhHmWBiaymcEDHbnC3tZJxtGHd9JKl0bGbn17dtERgnAAjBZOMFQV8UvI0JEAHRDIYAWk4ABE5k1OPg0GgsE0APT4oiMGDMOFwfD42bzfFxNYmNbwfHjSa5fL+MQKBbIZAgOiiVhyfwsNgcTjANIZbJsuCcVyxUgQZicADkxNJKsRYBZ0umwRVABYAEwWFU1SSRIaEzjGix2+0OsAgAC6zuEml0BvUxnkShUiFBGnE2iCOqm7NkpnMwJsdlIDicUncnhweEIJHIGkCeGsKREnD2ojAcBiZAAyhhEmUDII4WgBPI4XFMgAVePF0ukCuJOEAJR0cVIYBbXgAPABhFIxXo1BL8SAAdzAAD5/CJxLoAOyb2S+5RIYFGoNaHR4Qsd8uV6z+ExmJAAZlj9kcfkQADZk9QvGnfJmAvQmBGMUayMdcJBcI8fUUfdEG9TQQzwECbyjB8n3jF9nCNYFP0wVM9HTPwswAvQRVGAsGydd0NykAAOXdoP9ODg1PPR634eRkLvRBHxAWxn0TRAjU3HDv3w38OWzPR4kSS5UmbGA2yLEtL0SCcpxnTg50XFdgnGAUdDIOAAH5qz4Ws2MbeTFIvLsrzhAA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PSwFj1R6E9agUZTlx1djpcdT/m5K+ZQCDeCdAurAPalPsEBp7c7o+JVDQCAB5wZ6XPO/HndIpaAmua7Trmtsxx7bdUYQJ/zECWW1/d2p3OqJUCuQq45phUS3ENDfp5PFgTXjYFb0d6FgFGcLxohXYVh3ENYUECEFg0Dw+M2Xq+AkEW8pZATbeLIKcHyCj4wUd+p/TgWsI/6GgpKJ5BSh+QFhkgN+K4yMEeNTBnQgMKArEEHg3Akgy3tLJgR2CNs1jRwdPFwSoKhwrgkoO4NmEUN4mJs+pjQ18FlCch8QvIVUKSE1CUhpiNIQY1KFCMc0FQoRVY2SGKpxFxQjIVEOMYCLmG4jYRQUNqFKL6hkivhdIoCEaKLG8i0RYotuR6LGhqgCwHwL/ltDsZnjFVGLPMGvZuIRoPYTrzWxDDyIow8YcAEmHTCyGnCqxZdgxmCQAFZ4KbMQuBCkKLBzgfiYtlJlUAVe59SmfvVya2LfMtM/YS2AgBlAmZRoLLDljywFYisJWMrBViqw1Y6sDWJrC1jawdYusPWNoPNQnQEyzergAdLmFgCAQVc4oBBZjA2EmZcY+MQmKSDYAkwdM/S4LLKEMzGZVQ6oZgOZmOlyCuyIEcWJZHCiMKZYcsUmNaHHChp2kQSZAqYBYaAxYW8kSsYsnBDRoFAGrTOFrCtw65+ANQU2iozaD4wmkJ0POHILhAzpbYKsdJvHRmX6hQQcIVQG7DfCRAKAKsZLI7FoAZZClLMkpezPKVcyqlvM2pQLIaXCzmlZoWFRRAdi7YLA+2E7GSvJX2h8V+cPOOeIW5f0eoB6c4IgDdi/LrGRkOEECrziLz6ZSoZlesRQVsqTaxmLlfLJVC5K+VVUbZefEFX1g84/geuKICQCgBAg8gIQikDPAIBXArgIAA="} import { Hooks } from 'wagmi/tempo' import { parseUnits } from 'viem' const transferSync = Hooks.token.useTransferSync() // Call `mutate` in response to user action (e.g. button click, form submission) transferSync.mutate({ amount: parseUnits('10.5', 6), to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) console.log('Transfer amount:', transferSync.data?.amount) // @log: Transfer amount: 10500000n console.log('From:', transferSync.data?.from) // @log: From: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb console.log('To:', transferSync.data?.to) // @log: To: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.transfer` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { parseUnits } from 'viem' import { useWaitForTransactionReceipt } from 'wagmi' const transfer = Hooks.token.useTransfer() const { data: receipt } = useWaitForTransactionReceipt({ hash: transfer.data }) // Call `mutate` in response to user action (e.g. button click, form submission) transfer.mutate({ amount: parseUnits('10.5', 6), to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEbb', token: '0x20c0000000000000000000000000000000000000', }) if (receipt) { const { args: { amount, from, to } } = Actions.token.transfer.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `token.transfer` Return Type](/tempo/actions/token.transfer#return-type) ### mutate/mutateAsync See [Wagmi Action `token.transfer` Parameters](/tempo/actions/token.transfer#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`token.transfer`](/tempo/actions/token.transfer) ================================================ FILE: site/tempo/hooks/token.useUnpause.md ================================================ # `token.useUnpause` Unpauses a TIP-20 token, allowing transfers to resume. Requires appropriate permissions. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"d93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obxe2rUMbBQdTIqKyISRyfgHoPc8xK8aiXeM8LvGuu0P5PyEyFFIKWgTFIlA+w+glQXCqLvNC0dKo221OZWtiOwR2uo9eioKao0QfTeHGuaJW8WsAVWrvfwZ0UQJAUAQIeQA1CWxkBAVwVwIAA="} import { Hooks } from 'wagmi/tempo' const unpauseSync = Hooks.token.useUnpauseSync() // Call `mutate` in response to user action (e.g. button click, form submission) unpauseSync.mutate({ token: '0x20c0000000000000000000000000000000000000', }) console.log('Transaction hash:', unpauseSync.data?.receipt.transactionHash) // @log: Transaction hash: 0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ### Asynchronous Usage The example above uses a `*Sync` variant of the action, that will wait for the transaction to be included before returning. If you are optimizing for performance, you should use the non-sync `token.unpause` action and wait for inclusion manually: ```ts import { Hooks } from 'wagmi/tempo' import { Actions } from 'viem/tempo' import { useWaitForTransactionReceipt } from 'wagmi' const unpause = Hooks.token.useUnpause() const { data: receipt } = useWaitForTransactionReceipt({ hash: unpause.data }) // Call `mutate` in response to user action (e.g. button click, form submission) unpause.mutate({ token: '0x20c0000000000000000000000000000000000000', }) if (receipt) { const { args } = Actions.token.unpause.extractEvent(receipt.logs) ``` ## Return Type See [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook return types. ### data See [Wagmi Action `token.unpause` Return Type](/tempo/actions/token.unpause#return-type) ### mutate/mutateAsync See [Wagmi Action `token.unpause` Parameters](/tempo/actions/token.unpause#parameters) ## Parameters ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ### mutation See the [TanStack Query mutation docs](https://tanstack.com/query/v5/docs/framework/react/reference/useMutation) for more info hook parameters. ## Action - [`token.unpause`](/tempo/actions/token.unpause) ================================================ FILE: site/tempo/hooks/token.useWatchAdminRole.md ================================================ # `token.useWatchAdminRole` Watches for role admin update events on TIP20 tokens. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"149a552ec742b4dd66646f0d767625b9e60928a7afe48d207c20bce63c3d7530","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXGgC8lGaugAssUmKymoamTp47fydeWZIRSC29o5+iABsVdRetb4NAfR4AGYArmCOjBBgnIdwMADqomi2AIJQzKYAShByADwAwuf7jAUAD4ABRYezMHRkOAAfkQnGAAB0LpxUQtTABJKBwzhgQ7MABGZE4AB9LmBYACzFAANzI1GozKw+FIlEMhmkT4wHEAAwstAAJMARKRTApXDzSZw+YLhWhRYoJcgALpSvEyGRS46U/K0+nshlmADuz1eYA+cl5/KFIrFEqlMpt8rtPJVasOGq1FJgVJgerZBuu3tIVtltsVkrJjrlCvFrtVZPVmrJ2p9urpAdcXp11Iz7P2nOYACEZBBrPwcQTAaYuCnvb7/ezzgBRUickPwkEgsjt+Gt9sASk4AF4gZwiBBGFAh3Wc37s2nc/rUWwNTj5YcYAuG9v08vOKuTIoMWAnERRDIcXjCcTZ4v53eG3mGecLTBTaYAKpYKD3P04rsmXhI17ieF53i5AA6R4tDgChOFLBRgNA/AP3NKCABkIAUIdR3HSdp13JcAwmeQcQAFQ6MAsQAeVIZ4oFIeA4CIv1nzRf5ARxP4wABBRWMbBl5FEAk5GxeECT4ORRAuR9dQEjNXAHeEJynZEwFESE4HBawtyuW4ULQt9/CgMsED0HJOH2dhOBAh58DFThyIxAAFAoLE4UiLk5OROFEcCLkOH8/zgSD/DEBRzOQZAQDoTSsDkfweWStA4FoZEQlaBFwkMTgswLCBmE4AByECFFeAB6GgWmK5FkSO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NuCUDuY0YaXuf08eWMIM/cYeW7cMp0SMnkKeRgkmamWIPOeec0u0zg7+NeP+fg+0wuPeVQZ0rYCuN0vAcWLTMgTAIcLyCiKiWieiKARiOdC2P0K2fBPABiXNFiGyDEOnJ1fYFI5yNyDyPqZ+XQamHoFYGOKmdIbMoILyG0pAGcgs3eWYVwQmeBWAZoJxbKHqPKKyQsLjBzSqaqNgWqODMAHqSCPqZmNWfWEaMaVOd8dOBWKATsJkbWbCXCMcMaZabBMvDaICTjY6FEU6FELyeEYqfkdyawfUhCxCpC5ClC1C/Uw6cGKwkAWuUQJAUAQIeQJhc4cYBAVwVwIAA=="} import { Hooks } from 'wagmi/tempo' Hooks.token.useWatchAdminRole({ onRoleAdminUpdated: (args, log) => { console.log('args:', args) }, token: '0x20c0000000000000000000000000000000000000', }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `token.watchAdminRole` Parameters](/tempo/actions/token.watchAdminRole#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`token.setRoleAdmin`](/tempo/actions/token.setRoleAdmin) - [`token.watchAdminRole`](/tempo/actions/token.watchAdminRole) ================================================ FILE: site/tempo/hooks/token.useWatchApprove.md ================================================ # `token.useWatchApprove` Watches for token approval events on TIP20 tokens. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"1549f2859212b937c8657167655eeec354f9caa629bbd015ce5aa6a9316baad6","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXGgC8lGaugAssUmKymoam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umOkg2iWVBYl/FrEiwAGpfp1x6hwwlNn9b4uY9BU8hEwluRX1OkcV9FMNIZYUABZZ0eKOyBWLQHEV1FCdFC4TFEEbRD0G8XRfRElGKRgS6LgfiOhT1B1NNFgcQRhRAzjGiFQl0JTUaCbTLLFZcVQuAA/EQPRQrc4Y+acHseBRBZBWaepRpa9fYQEWIYsXNR5Z5UdMAeICZEtUcQ4NZPwrtJAstPw2IbLOMfYM8WIBtPZObQEPVTIIQoyOaCVQNCQ7FFwwrGQM8Ede4WxLfR5AtE/GAYtKZO+MtOZH5P5atQFMKfIxIg5fIootADoq6cqGFSnTdOACXIhJOCcU7VQbnVDXdDCZOGEH9U9G8KYicQ3SHfvBYlOTgdQVBFgiXJxSY4YlOADVYpY93G9aRPYmEDYl9RDP3HaXqONXsBpFojokoh5fNZ5ItYyd5Go8teom/GtIFUKFo8FfZdo9gUdTo0E+4boq8PtGSQdXsYdCEowlWDIcyJASyF6UwXefwIgCwM8X6PEiwCwF/F6NWP6XWMeH6S2QGQ2YwQeaYcwYuK2GGZYX6O2aoCAluNGaA92C6L2EmH2L0P2MgGOGUHbEOMOCOY0CTQOMU8UBOD+aY+hNONADOIeXQVky2AuH6Rk6ksuK8QA96YAm2ZwAoVQcArYZ2LkvATGQjMgTAUsLScCSCGCOCBCC1FCdmHUTme+PAeCRCDNGSVEV7dcfYNQ5SNSDSTKNUpAX6WIFYCk1IAGUYIILSA0+MpkkA22VwZ6DCWAZoQRTydKHyIMOTQDDjEKcKGASKXqdKM8TKEGMmemAqPUY2U8acHMekamT8b8SsQqKqCYmxfyfcADDqRELqRELSGEfyPkdSawQk+chcxcpc5clcwktqJiGgkAD2UQJAUAQIeQBBc4cYBAVwVwIAA"} import { Hooks } from 'wagmi/tempo' Hooks.token.useWatchApprove({ onApproval: (args, log) => { console.log('args:', args) }, token: '0x20c0000000000000000000000000000000000000', }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `token.watchApprove` Parameters](/tempo/actions/token.watchApprove#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`token.approve`](/tempo/actions/token.approve) - [`token.watchApprove`](/tempo/actions/token.watchApprove) ================================================ FILE: site/tempo/hooks/token.useWatchBurn.md ================================================ # `token.useWatchBurn` Watches for token burn events on TIP20 tokens. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"6bdef3454b786456322850b22fda9f6b5e83f7c766139b4da151ac51f819efe7","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXGgC8lGaugAssUmKymoamTp47fydeWZIRSC29o5+iABsVdRetb4NAfR4AGYArmCOjBBgnIdwMADqomi2AEKHpGAAPADC5/uMCgB8AAosPZmDoyHAAPyITjAAA6F04iIWpgAklAoZwwIdmAAjMicAA+lzAsB+ZigAG54YjEZlIdC4QiaTT9qQIMwMQADCy0AAkwBEpFMClcnMJnG5fIFaCFilFyAAuuKsTIZOLjqT8pTqTTXOqSTAyTBtUzOKz2Y8ZBBrPwMTjfqYuESNYatVTTecAKKkNmkDEAgFkX3Q72+gCUnAAvH9OEQIIwoBHnQajVB9Zrye7mWxVRiZYcYOnXeSi6mszScyZFCiwE4iKIZBisbj8cmM8bS26dYjzs9Xv6AXToQB3e5PF5gAB0AEEtHAKJwrQoR2P8H2pwAZCAKCPR2PxxOdzPdzgTeQYgAqHTAaIA8qRp1AoKR4HAj8by0jvr8MV8wD8FHfE1mXkUQcTkdFoRxPg5FEC422LDsELLeFXDDaE4wTeEwFEUE4GBaxCyuW5V3XfwoGt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EMcugXsjM601su+oJQQjs0w5ge+bsgszgBQqgcJfsCJuwSJb0ZAmAEYvkl414d4D4T4PKb4iM5IyMPceAj4z41qdEKIc2SK+wzBrEHEXEvkNMvxS+O0a0QJm06QKcQQvkEJVJLJOc0WrgC0VcsAzQ8CWk3kukZobIBkxkMGZklkMA1k+U3kk42ph0EMciIUnMv0dIoM24u4MYisoqHc4uQ4q6mUuUFAOovk0IhkPInE1gXxuZeZ+ZBZhZRZXx6UqEEBIAssogSAoAgQ8gi85w4wCArgrgQAA==="} import { Hooks } from 'wagmi/tempo' Hooks.token.useWatchBurn({ onBurn: (args, log) => { console.log('args:', args) }, token: '0x20c0000000000000000000000000000000000000', }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `token.watchBurn` Parameters](/tempo/actions/token.watchBurn#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`token.burn`](/tempo/actions/token.burn) - [`token.watchBurn`](/tempo/actions/token.watchBurn) ================================================ FILE: site/tempo/hooks/token.useWatchCreate.md ================================================ # `token.useWatchCreate` Watches for new TIP20 token creation events on the TIP20 Factory. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"ac42775d21c15bba9530036c843c3f7209edb0afc3fa66af279c7dfb7b6482f6","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXGgC8lGaugAssUmKymoamTp47fydeWZIRSC29o5+iABsVdRetb4NAfR4AGYArmCOjBBgnIdwMADqomi2AMKkMPcwADyP5/uMCgB8AAosP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eUXCD8UscrAAageg1XqEDHLiQOAVpj0B3z9X0XZDoxFA8S8TYx+kpQAFlrRPJ1I2xMhsQ40xYWVEEk0ClLx1D8BI03JGAdouBKJOwk1I160BR91SBJFGDmDVNnCbRy52ozt2s2VRkXC4A/8RBPF+tzhP5RxWwqEWBQc6EpkZkwN9gARYgIkP8YU4UXtkJ4gjle1+xDgHl90wBl1mD+0yjYhOtjR9gjxYgp1CUZAbsAQBUjDQRLFeZt0s1gQ3FRkUj+sZAjw+p900AElsiO1ciEUe0TkQF+0Ll4Ah1oDsVx0himiiUhjRj7htih1UoKVxdn04AGMRBiFjg5dOBVAtdGNPd/xzjoRMMANLw7jwx/cydA8zjwxoR1BWY6MTj35o9LIXi0BypniAVXjt8PjgTvjWc/jr8tJ6py02xpl1jdiJjoUpj4Vu0QpkV5iB0ljh0sUx0HJ1jp0vkti90djKS9jzx102It02xTBdjD1b8FIkAlJzpTByJ/AiALAjwHp+SLALBkDzoZZHoHo9Y24lYB5VY3pjAXwCCro/ph4AYHpjZqgp475IZqCbZtp7Z0ZHZnRnYxRC5JQ05PYnZdRfZ4Iww0BA5MdU445fwI4o4ZBHSw5fwE5Ex5BrAU4i005M5s5c5dRq4i5zT65nRy5K5QyzSPYIzXBN5dA1SVhd4O5ZSe5zxFSiDz4AYCgr4zp/xYBmhtEjJgpTJvRfQ8NlM7JHIYBnJ6pgpQpdRwprhuo15CZYotQNYwAUZNw6RcYXw3xCw4oMobiP1LJtxcMqoEQapsJZCQBbZRAkBQBAh5BMFzhxgEBXBXAgA="} import { Hooks } from 'wagmi/tempo' Hooks.token.useWatchCreate({ onTokenCreated: (args, log) => { console.log('args:', args) }, }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `token.watchCreate` Parameters](/tempo/actions/token.watchCreate#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`token.create`](/tempo/actions/token.create) - [`token.watchCreate`](/tempo/actions/token.watchCreate) ================================================ FILE: site/tempo/hooks/token.useWatchMint.md ================================================ # `token.useWatchMint` Watches for token mint events on TIP20 tokens. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"bca02bde7cbd2b13b68198315831f106355326a3a7bb259d3bedb8adc457d8c2","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXGgC8lGaugAssUmKymoamTp47fydeWZIRSC29o5+iABsVdRetb4NAfR4AGYArmCOjBBgnIdwMADqomi2ALKmaAA8AMLn+4wKAHwAFFh7MwdGQ4AB+RCcYAAHQunARC1MAEkoJDOGBDswAEZkTgAH0uYFg3zMUAA3HCEQjMhCobD4dTqe10QADCy0AAkwBEpFMClcrIJnHZXJ5aD5ikFyAAusLMTIZMLjiT8hSqdTXMriTBSTB1YzOPtSBBmAAhGQQaz8dHYn4vbWqsmUw3nACipBNpHR/3+ZC9UI9XoAlJwALy/ThECCMKChwkq3Vqx1J50ahFsRXoiWHGApvVQfNql1MzMmRTIsBOIiiGTozE4vEJnUFotp11gZ5Vn3/WlQgDu9yeLwAdABBLRwCicS0KAdD/BdtAjgAyEAUoYjUZjcbb+pLzI6YHRABUj6iAPKkMdQKCkeBwPcGpnWL4/dGfMDfBRPg8I+SiNicholC2J8HIogXM2Tr6r+cKuMGULRrGcJgKIIJwEC1h5lctwLku/hQFaCB6DkRrsJwg4PPg/KcCeyIAAoFBYnATPInDMA6MAkFWcAjv4YgKCRyDICAdDoVgcj+KyMloHAtBwiErTQuEhicFqxqmpwADkg4KJxAD0NAtNpcJwkcJxoGcFxjlgWD/K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BauBTSviwDNDgIqQuTqRGgmgPy6TAaGTGRsCmSCEuQjhqnbSAxVi+QahMwazqa0h/TribiRhSyIJ5FMLaR9gzrJTwipTwhuRQjaQcjMTWBvHZk5m5l5n5kFlvGJTwRAEgBiyiBICgCBDyATznDjAICuCuBAA==="} import { Hooks } from 'wagmi/tempo' Hooks.token.useWatchMint({ onMint: (args, log) => { console.log('args:', args) }, token: '0x20c0000000000000000000000000000000000000', }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `token.watchMint` Parameters](/tempo/actions/token.watchMint#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`token.mint`](/tempo/actions/token.mint) - [`token.watchMint`](/tempo/actions/token.watchMint) ================================================ FILE: site/tempo/hooks/token.useWatchRole.md ================================================ # `token.useWatchRole` Watches for role membership update events on TIP20 tokens. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"2a04f664116ac7d0cf34ca591cad47cbc06e1aab303131a088a76159faf54e6c","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXGgC8lGaugAssUmKymoamTp47fydeWZIRSC29o5+iABsVdRetb4NAfR4AGYArmCOjBBgnIdwMADqomi2AEoQcgA8AMLn+4wKAHwAFFh7MwdGQ4AB+RCcYAAHQunARC1MAEkoJDOGBDswAEZkTgAH0uYFg3zMUAA3HCEQjMhCobD4dTqaQXjB0QADCy0AAkwBEpFMClc7IJnE5PL5aAFimFyAAuqLMTIZKLjiT8hSqUzqQ5rBBjmgOVzef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QWxdbC9MAOzRcPBFgD7IhPpAZH9fYf4WIbxa/f5QFIqVdMAeINZVtLcQ4Y5RIydUg9tRI2IarEsfYP8WIZFG5Xbf4O1FQkEXRG2RdJNIEKxTpE2fpBrGQP8W6VdNAEJWIhteI4FFtDZb+dtHZeAaFbteFYqFokou5Fo9o+4WYvZCaXFDnK9OANXBhfUXcV7VQSXX3RCBaPUA0KEWDN9UCA43cUPEvX9TRDYtAKEdQYhcQtXOaPYnKM424xDN4i44QrDN4u48nR4vfGKPafNJcZomqVo+Yrov5HooFZtPyMFQYjtEYrtWFHtBFSYwdW5GYldOYnEhY4CWdIyBdJcUweY9dA/IKJAEKNGUwFSfwIgCwP8fGJkiwCwUAtGX2AmfGKwHGeuBOJueAreeeaYcwFApObuZwQmTArYbOdmXA/OKGIucWEuSWMuYCBeDGQmUOOuIOTGAUzeVuEU5AmmZOOmAoVQaUweWU3YeU7mMgTALsByPCAiYiUiciT1aiDWN0LWH+PAMiCiStIyZEEHWVfYCwyyGyOyDqDU3QEOAOXk3U9IDeIIByJA1YE0iU2YVwVGPUWAZoORFKNqdKAyTMJDCTQqEqR2NgcqPwtqP8DqMmVUmAPqLUKOGAIWUaRsWkWWZWHsPsfqaaAJO9D8RDTaeEbaeEByKEHKLkWyawVkhcxcpc5clc1c1k9ab6fgkAAuUQJAUAQIeQBBc4cYBAVwVwIAA=="} import { Hooks } from 'wagmi/tempo' Hooks.token.useWatchRole({ onRoleUpdated: (args, log) => { console.log('args:', args) }, token: '0x20c0000000000000000000000000000000000000', }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `token.watchRole` Parameters](/tempo/actions/token.watchRole#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`token.grantRoles`](/tempo/actions/token.grantRoles) - [`token.watchRole`](/tempo/actions/token.watchRole) ================================================ FILE: site/tempo/hooks/token.useWatchTransfer.md ================================================ # `token.useWatchTransfer` Watches for token transfer events on TIP20 tokens. ## Usage ::: code-group ```ts twoslash [example.ts] // @twoslash-cache: {"v":1,"hash":"f4621a5648e0a663badc09437893499eb743897952bf9f61a7fc56fc1e4f1550","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BLAWywlLQAIAJCCAawRU4aAIYckATioAbGGADmafEgCsVMaQUwGiELwFCQMxmFyIADFQDG+caOs1yiSQF8K6bOYLEylanS6ICxsHDx8gv4i4roAzADssvJKKojq1OLaQQaRsqbmAEw2dqQOTkgW7p44eIQk5BqBTKzsXGgC8lGaugAssUmKymoamTp47fydeWZIRSC29o5+iABsVdRetb4NAfR4AGYArmCOjBBgnIdwMADqomi2ACqlYHD7ZAA8AMLn+4wKAD4ABRYezMHRkOAAfkQnGAAB0LpxkQtTABJKAwzhgQ7MABGZE4AB9LmBYH8zFAANyI5HIzLQ2EIpF0un7UgQZhYgAGFloABJgCJSKYFK5ucTOLyBUK0CLFOLkABdSU4mQySXHcn5am01l09o8vmC4Wi8WS6UmuVm7nK1WHdWaskwCkwXUsziuJ3ayk0j3szkAIRkEGs/CxeP+pi4JK1Lp1ftZ5wAoqQOaQsUCgWR07DU+mAJScAC8AM4RAgjCgRdjztdUG98d9euRbHVWLlhxgjfrPYTLc4bZMijRYCcRFEMixOPxhNrPrdfebHvOz1Er3eGdhWYZsIA7vcni83mQAHQAQS0cAonBDCn3h/wa43Z4AMhAFEXS+XK9Wl27EwNDowCxR5gIxAB5UhzygKBSHgOB/3dVlrF+f4sR+MA/gUJDAOReRRDxORMVhPE+DkdckNwxFXALWEKyrREwFEcE4FBaxuyuW5H2fE8digUMED0HJOH2dhOAPB58FFThHjRAAFAoLE4CZ5BU49N04GASDHOBT38MQFCE5BkBAOgWKwOR/G5Gy0DgWhERCVo4XCQxPVEjlmE4AByA8FGYRgAHoaBabzEURI4TjQM4LnPLAsCBItmWRHI9NUsBTy4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E9jyvsCoXJIpMpOlIrMSc/o5p/hqakOkNqUEOlPSUgL9EyZPBbK4A9KhLAM0Fwi5KlO5J7L+sxgFMFDAKFD1KlKeBGUDMTHLPlHqPrHxNuAyOTLTCWGWAVJVKMRrt5LuD+u1EiJ1EiOlLCN5HyEpNYASTObOXOfOQuYuQSa1DRFQSAM7KIEgKAIEPIF/OcOMAgK4K4EAA=="} import { Hooks } from 'wagmi/tempo' Hooks.token.useWatchTransfer({ onTransfer: (args, log) => { console.log('args:', args) }, token: '0x20c0000000000000000000000000000000000000', }) ``` <<< @/snippets/react/config-tempo.ts{ts} [config.ts] ::: ## Parameters See [Wagmi Action `token.watchTransfer` Parameters](/tempo/actions/token.watchTransfer#parameters) ### config `Config | undefined` [`Config`](https://wagmi.sh/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider). ## Action - [`token.transfer`](/tempo/actions/token.transfer) - [`token.watchTransfer`](/tempo/actions/token.watchTransfer) ================================================ FILE: site/tempo/keyManagers/http.md ================================================ # `KeyManager.http` Manages public key registrations remotely on a server. ## Usage ```ts [wagmi.config.ts] import { createConfig, http } from 'wagmi' import { tempoTestnet } from 'wagmi/chains' import { KeyManager, webAuthn } from 'wagmi/tempo' // [!code focus] export const config = createConfig({ connectors: [webAuthn({ keyManager: KeyManager.http('/keys'), // [!code focus] })], chains: [tempoTestnet], multiInjectedProviderDiscovery: false, transports: { [tempoTestnet.id]: http(), }, }) ``` ::: tip In order for the above code snippet to work, you need to have a server running at the provided URL. Below is an example using a [Cloudflare Worker](https://developers.cloudflare.com/workers) (but can work with any server runtime). [See more](https://docs.tempo.xyz/sdk/typescript/server/handler.keyManager) ```ts import { env } from 'cloudflare:workers' import { Handler, Kv } from 'tempo.ts/server' export default { fetch(request) { return Handler.keyManager({ kv: Kv.cloudflare(env.KEY_STORE), path: '/keys', }).fetch(request) }, } satisfies ExportedHandler ``` ::: ## Parameters ### url - **Type:** `string` URL to the key manager server. ### options #### options.fetch - **Type:** `typeof globalThis.fetch` - **Default:** `globalThis.fetch` Fetch function to use for the key manager server. ================================================ FILE: site/tempo/keyManagers/index.md ================================================ # Overview WebAuthn-based accounts in Tempo require the public key to be attached to transactions and other protocol features. However, **it is not possible to extract a public key from a WebAuthn credential after its registration**. To solve this, we maintain a `credentialId → publicKey` mapping that stores the public key when the credential is first created. Key Managers are responsible for managing this mapping, allowing users to access their accounts from any device without losing their public key. - [**`http`**](/tempo/keyManagers/http) Manage public key registrations remotely on a server - [**`localStorage`**](/tempo/keyManagers/localStorage) Manage public key registrations locally on the client device ================================================ FILE: site/tempo/keyManagers/localStorage.md ================================================ # `KeyManager.localStorage` Manages public key registrations in local storage on the client device. :::warning The `KeyManager.localStorage()` implementation is not recommended for production use as it stores public keys on the client device, meaning it cannot be re-extracted when the user's storage is cleared or if the user is on another device. For production, you should opt for a remote key manager such as [`KeyManager.http`](/tempo/keyManagers/http). ::: ## Usage ```ts [wagmi.config.ts] import { createConfig, http } from 'wagmi' import { tempoTestnet } from 'wagmi/chains' import { KeyManager, webAuthn } from 'wagmi/tempo' // [!code focus] export const config = createConfig({ connectors: [webAuthn({ keyManager: KeyManager.localStorage(), // [!code focus] })], chains: [tempoTestnet], multiInjectedProviderDiscovery: false, transports: { [tempoTestnet.id]: http(), }, }) ``` ================================================ FILE: site/tsconfig.json ================================================ { "compilerOptions": { "baseUrl": ".", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "jsx": "preserve", "lib": ["DOM", "ESNext"], "module": "ESNext", "moduleResolution": "Bundler", "noUnusedLocals": true, "paths": { "~/*": ["src/*"] }, "resolveJsonModule": true, "skipLibCheck": true, "strict": true, "strictNullChecks": true, "target": "esnext", "types": ["vite/client", "vitepress"] }, "include": ["./*.ts", "./.vitepress/**/*.ts", "./.vitepress/**/*.vue"], "exclude": ["dist", "node_modules", "snippets"] } ================================================ FILE: site/uno.config.ts ================================================ import { defineConfig, presetAttributify, presetIcons, presetWind3, } from 'unocss' export default defineConfig({ shortcuts: [ [ 'btn', 'px-4 py-1 rounded inline-flex justify-center gap-2 text-white leading-30px children:mya !no-underline cursor-pointer disabled:cursor-default disabled:bg-gray-600 disabled:opacity-50', ], ], presets: [ presetWind3({ dark: 'media', }), presetAttributify(), presetIcons({ scale: 1.2 }), ], }) ================================================ FILE: site/vercel.json ================================================ { "cleanUrls": true, "redirects": [ { "source": "/core/api/actions/sendTransactionSync", "destination": "/core/api/actions/sendTransaction", "permanent": true }, { "source": "/core/api/actions/sendCallsSync", "destination": "/core/api/actions/sendCalls", "permanent": true }, { "source": "/react/api/hooks/useSendTransactionSync", "destination": "/react/api/hooks/useSendTransaction", "permanent": true }, { "source": "/react/api/hooks/useSendCallsSync", "destination": "/react/api/hooks/useSendCalls", "permanent": true }, { "source": "/tempo/actions/reward.start", "destination": "/tempo/actions/reward.distribute", "permanent": true }, { "source": "/tempo/actions/reward.watchRewardScheduled", "destination": "/tempo/actions/reward.watchRewardDistributed", "permanent": true }, { "source": "/tempo/actions/nonce.getNonceKeyCount", "destination": "/tempo/actions/nonce", "permanent": true }, { "source": "/tempo/actions/nonce.watchActiveKeyCountChanged", "destination": "/tempo/actions/nonce", "permanent": true }, { "source": "/tempo/actions/amm.watchFeeSwap", "destination": "/tempo/actions/amm", "permanent": true }, { "source": "/tempo/hooks/reward.useStart", "destination": "/tempo/hooks/reward.useDistribute", "permanent": true }, { "source": "/tempo/hooks/reward.useWatchRewardScheduled", "destination": "/tempo/hooks/reward.useWatchRewardDistributed", "permanent": true }, { "source": "/tempo/hooks/nonce.useNonceKeyCount", "destination": "/tempo/hooks/nonce", "permanent": true }, { "source": "/tempo/hooks/nonce.useWatchActiveKeyCountChanged", "destination": "/tempo/hooks/nonce", "permanent": true }, { "source": "/tempo/hooks/amm.useWatchFeeSwap", "destination": "/tempo/hooks/amm", "permanent": true }, { "source": "/cli", "destination": "/cli/getting-started", "permanent": true }, { "source": "/core", "destination": "/core/getting-started", "permanent": true }, { "source": "/core/migration-guide", "destination": "/core/guides/migrate-from-v1-to-v2", "permanent": true }, { "source": "/core/:name(faq)", "destination": "/core/guides/:name", "permanent": true }, { "source": "/core/ethers-adapters", "destination": "/core/guides/ethers-web3", "permanent": true }, { "source": "/core/:section(chains)", "destination": "/core/api/:section", "permanent": true }, { "source": "/core/:section(actions|connectors)/:name", "destination": "/core/api/:section/:name", "permanent": true }, { "source": "/core/config", "destination": "/core/api/createConfig", "permanent": true }, { "source": "/core/api/actions/getAccount", "destination": "/core/api/actions/getConnection", "permanent": true }, { "source": "/core/api/actions/switchAccount", "destination": "/core/api/actions/switchConnection", "permanent": true }, { "source": "/core/api/actions/watchAccount", "destination": "/core/api/actions/watchConnection", "permanent": true }, { "source": "/react", "destination": "/react/getting-started", "permanent": true }, { "source": "/react/comparison", "destination": "/react/comparisons", "permanent": true }, { "source": "/react/migration-guide", "destination": "/react/guides/migrate-from-v1-to-v2", "permanent": true }, { "source": "/react/:name(faq)", "destination": "/react/guides/:name", "permanent": true }, { "source": "/react/ethers-adapters", "destination": "/react/guides/ethers", "permanent": true }, { "source": "/react/:section(actions|chains)", "destination": "/react/api/:section", "permanent": true }, { "source": "/react/:section(connectors|hooks)/:name", "destination": "/react/api/:section/:name", "permanent": true }, { "source": "/react/config", "destination": "/react/api/createConfig", "permanent": true }, { "source": "/react/WagmiConfig", "destination": "/react/api/WagmiProvider", "permanent": true }, { "source": "/react/prepare-hooks/usePrepareContractWrite", "destination": "/react/api/hooks/useSimulateContract", "permanent": true }, { "source": "/react/prepare-hooks/usePrepareSendTransaction", "destination": "/react/api/hooks/useEstimateFeesPerGas", "permanent": true }, { "source": "/react/api/actions/useAccount", "destination": "/react/api/actions/useConnection", "permanent": true }, { "source": "/react/api/actions/useAccountEffect", "destination": "/react/api/actions/useConnectionEffect", "permanent": true }, { "source": "/react/api/actions/useSwitchAccount", "destination": "/react/api/actions/useSwitchConnection", "permanent": true }, { "source": "/core", "destination": "/core/getting-started", "permanent": true }, { "source": "/tempo", "destination": "/tempo/getting-started", "permanent": true }, { "source": "/vue/api/actions/useAccount", "destination": "/vue/api/actions/useConnection", "permanent": true }, { "source": "/vue/api/actions/useAccountEffect", "destination": "/vue/api/actions/useConnectionEffect", "permanent": true }, { "source": "/vue/api/actions/useSwitchAccount", "destination": "/vue/api/actions/useSwitchConnection", "permanent": true }, { "source": "/examples/connect-wallet", "destination": "/react/guides/connect-wallet", "permanent": true }, { "source": "/examples/send-transaction", "destination": "/react/guides/send-transaction", "permanent": true }, { "source": "/react/guides/sending-transactions", "destination": "/react/guides/send-transaction", "permanent": true }, { "source": "/react/guides/reading-contracts", "destination": "/react/guides/read-from-contract", "permanent": true }, { "source": "/examples/contract-write(-dynamic)?", "destination": "/react/guides/write-to-contract", "permanent": true }, { "source": "/react/guides/writing-to-contracts", "destination": "/react/guides/write-to-contract", "permanent": true }, { "source": "/examples/custom-connector", "destination": "/dev/creating-connectors", "permanent": true }, { "source": "/examples/sign-message", "destination": "https://1.x.wagmi.sh/examples/sign-message", "permanent": false }, { "source": "/examples/sign-in-with-ethereum", "destination": "https://1.x.wagmi.sh/examples/sign-in-with-ethereum", "permanent": false } ] } ================================================ FILE: site/vue/api/Nuxt.md ================================================ # Nuxt [Nuxt Module](https://nuxt.com/docs/guide/concepts/modules) for Wagmi. Adds all [Composables](/vue/api/composables) as [auto-imports](https://nuxt.com/docs/guide/concepts/auto-imports). ## Usage ::: code-group ```ts twoslash [nuxt.config.ts] // @twoslash-cache: {"v":1,"hash":"a2f343760fd46f812e97826b5b6d3f1fdddb4ec07dbbf76cb4790a6383711285","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIBjCGDhpesAGbswMAHIBXegGEhkgOaJeAERiTp8pSvaqAOmHYBbLBFKiJU2QrTKwayiBHMbSAJxVWMMFU0fCQARgA2KjRPVRgGRBA7PUdnVz97JAAGKn58T2Z+GnJEbwBfCnRsXATCEnIouniQFg4uPiSHAxcjRiksOTQNAEkwfqd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M1KpJEOwQN6hxq6U15EZCyLaBi6oEAQKo/gALTimwGAY9LCzAFVzAaPzAAaoTwj8AAs6LhAA7PzvClHjtu8CMUnPLoM6rnTS5gCuQi8IwfDAKUpixqYZPeSAsZ4+40RfAAHCn/yBMESAZ6CpCxE0P0whkiB/CAuT5IU+KIPCuc5NA1QgA8C28NHkIpBMOfcilvD897v0nUY/NXtItCPLYOjMLSd+VlCajBnT1Oe4L/ZweY7C/UQcgYC/W9vzPOYBSjcDcLzaISBQBdmEKuPAs4QClFKEAA"} import { defineNuxtConfig } from 'nuxt/config' export default defineNuxtConfig({ modules: ['@wagmi/vue/nuxt'], }) ``` ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ================================================ FILE: site/vue/api/WagmiPlugin.md ================================================ # WagmiPlugin [Vue Plugin](https://vuejs.org/guide/reusability/plugins.html#plugins) for Wagmi. ## Import ```ts import { WagmiPlugin } from '@wagmi/vue' ``` ## Usage ::: code-group ```ts [main.ts] import { createApp } from 'vue' import { WagmiPlugin } from '@wagmi/vue' import App from './App.vue' import { config } from './config' createApp(App) .use(WagmiPlugin, { config }) .mount('#app') ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type WagmiPluginProps } from '@wagmi/vue' ``` ### config [`Config`](/vue/api/createConfig#config) object to inject with context. ::: code-group ```ts [main.ts] import { createApp } from 'vue' import { WagmiPlugin } from '@wagmi/vue' import App from './App.vue' import { config } from './config' createApp(App) .use(WagmiPlugin, { config // [!code focus] }) .mount('#app') ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### initialState `State | undefined` - Initial state to hydrate into the [Wagmi Config](/vue/api/createConfig). Useful for SSR. ::: code-group ```ts [main.ts] import { createApp } from 'vue' import { WagmiPlugin } from '@wagmi/vue' import App from './App.vue' import { config } from './config' createApp(App) .use(WagmiPlugin, { config, initialState: /* ... */ // [!code focus] }) .mount('#app') ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### reconnectOnMount `boolean | undefined` - Whether or not to reconnect previously connected [connectors](/vue/api/createConfig#connectors) on mount. - Defaults to `true`. ::: code-group ```ts [main.ts] import { createApp } from 'vue' import { WagmiPlugin } from '@wagmi/vue' import App from './App.vue' import { config } from './config' createApp(App) .use(WagmiPlugin, { config, reconnectOnMount: false // [!code focus] }) .mount('#app') ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## configKey Key to use to provide/inject `Config` via `WagmiPlugin`. ```ts import { configKey, type Config } from '@wagmi/vue' import { inject } from 'vue' inject(configKey) ``` ================================================ FILE: site/vue/api/actions.md ================================================ # Actions Sometimes the declarative nature of Vue Composables doesn't work for parts of your app. For those cases, you can use Wagmi Core Actions directly! All the Wagmi Core Actions are importable using the `@wagmi/vue/actions` entrypoint. For example, you can use the `watchBlockNumber` action to watch for block number changes. ::: code-group ```vue [index.vue] ``` <<< @/snippets/react/config.ts[config.ts] ::: See the [Wagmi Core docs](/core/api/actions) for more info on what actions are available. ================================================ FILE: site/vue/api/chains.md ================================================ # Chains Viem `Chain` objects. More info at the [Viem docs](https://viem.sh/docs/chains/introduction). ## Import Import via the `'@wagmi/vue/chains'` entrypoint (proxies all chains from `'viem/chains'`). ```ts import { mainnet } from '@wagmi/vue/chains' ``` ## Available Chains Chain definitions as of `viem@{{viemVersion}}`. For `viem@latest`, visit the [Viem repo](https://github.com/wevm/viem/blob/main/src/chains/index.ts). ================================================ FILE: site/vue/api/composables/useBalance.md ================================================ --- title: useBalance description: Composable for fetching native currency balance. --- # useBalance Composable for fetching native currency balance. ## Import ```ts import { useBalance } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseBalanceParameters } from '@wagmi/vue' ``` ### address `Address | undefined` Address to get balance for. [`enabled`](#enabled) set to `false` if `address` is `undefined`. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: --- ### blockNumber `bigint | undefined` Block number to get balance at. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get balance at. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseBalanceReturnType } from '@wagmi/vue' ``` ## Action - [`getBalance`](/core/api/actions/getBalance) ================================================ FILE: site/vue/api/composables/useBlockNumber.md ================================================ --- title: useBlockNumber description: Composable for fetching the number of the most recent block seen. --- # useBlockNumber Composable for fetching the number of the most recent block seen. ## Import ```ts import { useBlockNumber } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseBlockNumberParameters } from '@wagmi/vue' ``` ### cacheTime `MaybeRef | undefined` Time in milliseconds that cached block number will remain in memory. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### chainId `MaybeRef | undefined` ID of chain to use when fetching data. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### scopeKey `MaybeRef | undefined` Scopes the cache to a given context. Composables that have identical context will share the same cache. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### watch `MaybeRef | undefined` - Enables/disables listening for block number changes. - Can pass a subset of [`UseWatchBlockNumberParameters`](/vue/api/composables/useWatchBlockNumber#parameters) directly to [`useWatchBlockNumber`](/vue/api/composables/useWatchBlockNumber). ::: code-group ```vue [index.vue] ``` ```vue [index-2.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseBlockNumberReturnType } from '@wagmi/vue' ``` ## Action - [`getBlockNumber`](/core/api/actions/getBlockNumber) - [`watchBlockNumber`](/core/api/actions/watchBlockNumber) ================================================ FILE: site/vue/api/composables/useBytecode.md ================================================ --- title: useBytecode description: Composable for retrieving the bytecode at an address. --- # useBytecode Composable for retrieving the bytecode at an address. ## Import ```ts import { useBytecode } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Parameters ```ts import { type UseBytecodeParameters } from '@wagmi/vue' ``` ### address `Address | undefined` The contract address. ::: code-group ```vue [index.vue] ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockNumber `bigint | undefined` The block number to check the bytecode at. ::: code-group ```vue [index.vue] ``` <<< @/snippets/react/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` The block tag to check the bytecode at. ::: code-group ```vue [index.vue] ``` <<< @/snippets/react/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` The chain ID to check the bytecode at. ::: code-group ```vue [index.vue] ``` <<< @/snippets/react/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```vue [index.vue] ``` <<< @/snippets/react/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Hooks that have identical context will share the same cache. ::: code-group ```vue [index.vue] ``` <<< @/snippets/react/config.ts[config.ts] ::: ## Return Type ```ts import { type UseBytecodeReturnType } from '@wagmi/vue' ``` ## Action - [`getBytecode`](/core/api/actions/getBytecode) ================================================ FILE: site/vue/api/composables/useChainId.md ================================================ --- title: useChainId description: Composable for getting current chain ID. --- # useChainId Composable for getting current chain ID. ## Import ```ts import { useChainId } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseChainIdParameters } from '@wagmi/vue' ``` ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseChainIdReturnType } from '@wagmi/vue' ``` `number` Current chain ID from [`config.state.chainId`](/vue/api/createConfig#chainid). ::: info Only returns chain IDs for chains configured via `createConfig`'s [`chains`](/vue/api/createConfig#chains) parameter. If the active [connection](/vue/api/createConfig#connection) [`chainId`](/vue/api/createConfig#chainid-1) is not from a chain included in your Wagmi `Config`, `useChainId` will return the last configured chain ID. ::: ## Action - [`getChainId`](/core/api/actions/getChainId) - [`watchChainId`](/core/api/actions/watchChainId) ================================================ FILE: site/vue/api/composables/useChains.md ================================================ --- title: useChains description: Composable for getting configured chains --- # useChains Composable for getting configured chains ## Import ```ts import { useChains } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseChainsParameters } from '@wagmi/vue' ``` ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseChainsReturnType } from '@wagmi/vue' ``` `readonly [Chain, ...Chain[]]` Chains from [`config.chains`](/vue/api/createConfig#chains). ## Action - [`getChains`](/core/api/actions/getChains) ================================================ FILE: site/vue/api/composables/useClient.md ================================================ --- title: useClient description: Composable for getting Viem `Client` instance. --- # useClient Composable for getting Viem [`Client`](https://viem.sh/docs/clients/custom) instance. ## Import ```ts import { useClient } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseClientParameters } from '@wagmi/vue' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when getting Viem Client. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseClientReturnType } from '@wagmi/vue' ``` `Client | undefined` Viem [`Client`](https://viem.sh/docs/clients/custom) instance. ## Action - [`getClient`](/core/api/actions/getClient) - [`watchClient`](/core/api/actions/watchClient) ================================================ FILE: site/vue/api/composables/useConfig.md ================================================ --- title: useConfig description: Composable for getting `Config` from the `WagmiPlugin`. --- # useConfig Composable for getting [`Config`](/vue/api/createConfig#config) from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ## Import ```ts import { useConfig } from 'wagmi' ``` ## Usage ::: code-group ```vue [index.vue] ``` ::: ## Return Type ```ts import { type UseConfigReturnType } from 'wagmi' ``` ================================================ FILE: site/vue/api/composables/useConnect.md ================================================ --- title: useConnect description: Composable for connecting accounts with connectors. --- # useConnect Composable for connecting accounts with [connectors](/vue/api/connectors). ## Import ```ts import { useConnect } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseConnectParameters } from '@wagmi/vue' ``` ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseConnectReturnType } from '@wagmi/vue' ``` ::: tip Not all connectors support connecting directly to a `chainId` (e.g. they don't support programmatic chain switching). In those cases, the connector will connect to whatever chain the connector's provider (e.g. wallet) is connected to. ::: ## Action - [`connect`](/core/api/actions/connect) ================================================ FILE: site/vue/api/composables/useConnection.md ================================================ --- title: useConnection description: Composable for getting current connection. --- # useConnection Composable for getting current connection. ## Import ```ts import { useConnection } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue twoslash [index.vue] // @twoslash-cache: {"v":1,"hash":"13c71d856a5988592573d4377882b1c1fa1e1a07a6da8a54925e9753a897fb69","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgBhSWBhiJYADwjJ/dgHNedGmChxeCsNr0BeU1t1rSMZlEmsMvVAB0pvHwCNWECIA1gCitFgBDqRwiLzAXj6JiQ5OLm6w/MyCrGix8d5JhbwpzmCuvGDMALYwsR4gIWj4ZHAizGD1ANwJRYUladKkrHUEaGhYMQD0kzBNLW1gAHQSXT29yY6l5cxY7ACqQyP4YxOI0zvsi7PN0QvLEJMXqwWFAL7dL+9rvP6BQQAq7BqsQAjAAmAAMUI+SU0YDQpGYYhicW+SX6ZTcMDAcD2YHYJGibAASvAIKxCXk0b0MdsoFAHHAUfUIbQYOyOeyQQAWKAAdhBAA4RGDfNy+VAAJySsEAZlgzF8INlsoArDAedzOc91ujNgNfsE5CkaFBYnKIYLVdbBTDel8XnrUpjeFVsuI2qxWLKqY6afqXU4GfBmSBWW0QSDfLAIarJXy+b5ZQA2WWR5N8iFgwWC5OimBg5ggvmy+PJiMgnW6ny0tyGoLGxym0HctUpiEgu1FB1JHuJRYD3g810QBy8AeLLu8QnsfgYAASXHwAH5YoxGCIONjcqYt/C1BOAHwUXhYZiImo0aKxABqZFnC6XAAVz9VZi0+JZD7wn6QIFV2FkNRfAgclHDAQ8+AAH2kIwYG0JQoA+V4T3yJI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gDcYAnEAGhDRgA808AKAQwBsBLZuASgAJMcvAKpwYAYQhgwMAMZp2kgArNSzALYwapOAB4ZkgGbsA5rzo0wUOLwlgjpgLw3DJgHy8nwADphef3vp2JgD8iAEupgA+zkFRvACuljBG0lAA3D4Avj7salgQpGjCorbScgpgyqoaWghUcGgqDIgAjAAsVKwwYMZo+EgATADMVI2kxpp4IuKSZfJKKuqaZHUgHNJIAAxUMviLcmRI7ZkAujvQuIggufmFvMD82DDFM1Ky85WLNSu8mbwGpAgal4AHIAAIAd2YxjU7AA9ER4jAQZQQDVmEhQOZunAKng0AhMpkgA=="} import { type UseConnectionParameters } from '@wagmi/vue' ``` ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts twoslash // @twoslash-cache: {"v":1,"hash":"b6f1971287fb7adb77e1a5d5dc952329e6dd516b560ac655f5064dcb9d4b925c","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAJMcvAKpwYAYQhgwMAMZp2kgEow0AV1JgAKthgAeGZIBm7AOa86NMFDi8JYY2YC8to6YB8vZ5ojLDcXcAAOmC8obzMUFCk8HCIvKpWMMbSUADcwWHhkdFworHxickwaRlhMvjM7GBxCbBFJSFlFVUAklA1hVXF6Y2hBlKyaBCkHXVdDZnscHbScsVxhmyiPZNwyv2z8mAmC0swK2FTM4NVO7yLrMuloVMAIlMbg/P8pKr717xwaMxq+YEgUAekk2xX+PQAvh4AD68by+fxBXpZKIxOIAQWyMQOoQiKNy8Di0QiklYGF4yAxeLgFF4ADp6ZScnBkABdFnY3jlSrVXiMOwOcz0GBWGz9AUAflszRCcTFpmQ/y5VTg/xZyDAqgAtgAjMgsvgw2pJcYcpVgNpxDU6sim4GDYZxY5yYYco52ubtF5vV3Td1bM4XK5Iu5AgYe3aXd7BtayP2nCNBzJfH6qP4gR4esHBSG8GFwpL+em06GwnwF3RFtzBdiarDDNDCURO+RKFTqLQ6SggZOkBiIACMABYqKxhSY0PgkAAmADMVG+pBMKjwInEcdbag02hwXY40iQAAYqFzSMw5uQB4PwSzj9BcIgQDW673eMB+DpG2uwy2wMpNx3BHBc5SAgTVeAAcgAAQAd2YExNXYAB6Ig3nArtNRUZgkFACxhTgBQwDwNAEHBcEgA=="} import { type UseConnectionReturnType } from '@wagmi/vue' ``` ## Action - [`getConnection`](/core/api/actions/getConnection) ================================================ FILE: site/vue/api/composables/useConnectionEffect.md ================================================ --- title: useConnectionEffect description: Composable for listening to connection lifecycle events. --- # useConnectionEffect Composable for listening to connection lifecycle events. ## Import ```ts import { useConnectionEffect } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type useConnectionEffectParameters } from '@wagmi/vue' ``` ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### onConnect `` MaybeRef<((data: { address: `0x${string}`; addresses: readonly [`0x${string}`, ...`0x${string}`[]]; chain: Chain | undefined chainId: number; connector: Connector; isReconnected: boolean }) => void)> | undefined `` Callback that is called when connection is made. ::: code-group ```tsx [index.tsx] import { useConnectionEffect } from '@wagmi/vue' function App() { useConnectionEffect({ onConnect(data) { // [!code focus] console.log('Connected!', data) // [!code focus] }, // [!code focus] }) } ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### onDisconnect `MaybeRef<(() => void)> | undefined` Callback that is called when there no more connections. ::: code-group ```tsx [index.tsx] import { useConnectionEffect } from '@wagmi/vue' function App() { useConnectionEffect({ onDisconnect() { // [!code focus] console.log('Disconnected!') // [!code focus] }, // [!code focus] }) } ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Action - [`getConnection`](/core/api/actions/getConnection) - [`watchConnection`](/core/api/actions/watchConnection) ================================================ FILE: site/vue/api/composables/useConnections.md ================================================ --- title: useConnections description: Composable for getting active connections. --- # useConnections Composable for getting active connections. ## Import ```ts import { useConnections } from 'wagmi' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseConnectionsParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseConnectionsReturnType } from 'wagmi' ``` ## Action - [`getConnections`](/core/api/actions/getConnections) - [`watchConnections`](/core/api/actions/watchConnections) ================================================ FILE: site/vue/api/composables/useConnectorClient.md ================================================ --- title: useConnectorClient description: Composable for getting a Viem `Client` object for the current or provided connector. --- # useConnectorClient Composable for getting a Viem [`Client`](https://viem.sh/docs/clients/custom) object for the current or provided connector. ## Import ```ts import { useConnectorClient } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseConnectorClientParameters } from '@wagmi/vue' ``` ### account `Address | Account | undefined` Account to use with client. Throws if account is not found on [`connector`](#connector). ```vue ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use with client. ```vue ``` ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### connector `Connector | undefined` - Connector to get client for. - Defaults to current connector. ```vue ``` ## Return Type ```ts import { type UseConnectorClientReturnType } from '@wagmi/vue' ``` ## Action - [`getConnectorClient`](/core/api/actions/getConnectorClient) ================================================ FILE: site/vue/api/composables/useConnectors.md ================================================ --- title: useConnectors description: Composable for getting configured connectors. --- # useConnectors Composable for getting configured connectors. ## Import ```ts import { useConnectors } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseConnectorsReturnType } from '@wagmi/vue' ``` `readonly Connector[]` Connectors from [`config.connectors`](/vue/api/createConfig#connectors-1). ## Action - [`getConnectors`](/core/api/actions/getConnectors) ================================================ FILE: site/vue/api/composables/useDisconnect.md ================================================ --- title: useDisconnect description: Composable for disconnecting connections. --- # useDisconnect Composable for disconnecting connections. ## Import ```ts import { useDisconnect } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseDisconnectParameters } from '@wagmi/vue' ``` ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseDisconnectReturnType } from '@wagmi/vue' ``` ## Action - [`disconnect`](/core/api/actions/connect) ================================================ FILE: site/vue/api/composables/useEnsAddress.md ================================================ --- title: useEnsAddress description: Composable for fetching ENS address for name. --- # useEnsAddress Composable for fetching ENS address for name. ## Import ```ts import { useEnsAddress } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ::: warning Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `useEnsAddress`. You can use Viem's built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this. ::: ## Parameters ```ts import { type UseEnsAddressParameters } from '@wagmi/vue' ``` --- ### blockNumber `bigint | undefined` Block number to get ENS address at. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get ENS address at. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### coinType `number | undefined` The [ENSIP-9](https://docs.ens.domains/ens-improvement-proposals/ensip-9-multichain-address-resolution) coin type to fetch the address for. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### name `string | undefined` Name to get the address for. [`enabled`](#enabled) set to `false` if `name` is `undefined`. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Composables that have identical context will share the same cache. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### universalResolverAddress `Address | undefined` - Address of ENS Universal Resolver Contract. - Defaults to current chain's Universal Resolver Contract address. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseEnsAddressReturnType } from '@wagmi/vue' ``` ## Action - [`getEnsAddress`](/core/api/actions/getEnsAddress) ================================================ FILE: site/vue/api/composables/useEnsAvatar.md ================================================ --- title: useEnsAvatar description: Composable for fetching ENS avatar for name. --- # useEnsAvatar Composable for fetching ENS avatar for name. ## Import ```ts import { useEnsAvatar } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ::: warning Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `useEnsAvatar`. You can use Viem's built-in [`normalize`](https://viem.sh/docs/ens/utilities/normalize) function for this. ::: ## Parameters ```ts import { type UseEnsAvatarParameters } from '@wagmi/vue' ``` --- ### assetGatewayUrls `{ ipfs?: string | undefined; arweave?: string | undefined } | undefined` Gateway urls to resolve IPFS and/or Arweave assets. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### blockNumber `bigint | undefined` Block number to get ENS avatar at. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get ENS avatar at. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### gatewayUrls `string[] | undefined` A set of Universal Resolver gateways, used for resolving CCIP-Read requests made through the ENS Universal Resolver Contract. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### name `string | undefined` Name to get the avatar for. [`enabled`](#enabled) set to `false` if `name` is `undefined`. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Composables that have identical context will share the same cache. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### universalResolverAddress `Address | undefined` - Address of ENS Universal Resolver Contract. - Defaults to current chain's Universal Resolver Contract address. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseEnsAvatarReturnType } from '@wagmi/vue' ``` ## Action - [`getEnsAvatar`](/core/api/actions/getEnsAvatar) ================================================ FILE: site/vue/api/composables/useEnsName.md ================================================ --- title: useEnsName description: Composable for fetching primary ENS name for address. --- # useEnsName Composable for fetching primary ENS name for address. ## Import ```ts import { useEnsName } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseEnsNameParameters } from '@wagmi/vue' ``` ### address `Address | undefined` Name to get the resolver for. [`enabled`](#enabled) set to `false` if `address` is `undefined`. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: --- ### blockNumber `bigint | undefined` Block number to get ENS name at. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get ENS name at. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Composables that have identical context will share the same cache. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### universalResolverAddress `Address | undefined` - Address of ENS Universal Resolver Contract. - Defaults to current chain's Universal Resolver Contract address. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseEnsNameReturnType } from '@wagmi/vue' ``` ## Action - [`getEnsName`](/core/api/actions/getEnsName) ================================================ FILE: site/vue/api/composables/useEstimateGas.md ================================================ --- title: useEstimateGas description: Composable for estimating the gas necessary to complete a transaction without submitting it to the network. --- # useEstimateGas Composable for estimating the gas necessary to complete a transaction without submitting it to the network. ## Import ```ts import { useEstimateGas } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseEstimateGasParameters } from '@wagmi/vue' ``` ### accessList `AccessList | undefined` The access list. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### account `Address | Account | undefined` Account to use when estimating gas. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` Chain ID to target when estimating gas. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### connector `Connector | undefined` Connector to estimate with. If no [`account`](#account) is provided, will use default account from connector. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### data `` `0x${string}` | undefined `` A contract hashed method call with encoded function data. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### gas `bigint | undefined` Gas provided for transaction execution. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: --- ### gasPrice `bigint | undefined` The price in wei to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### maxFeePerGas `bigint | undefined` Total fee per gas in wei, inclusive of [`maxPriorityFeePerGas`](#maxPriorityFeePerGas). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### maxPriorityFeePerGas `bigint | undefined` Max priority fee per gas in wei. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: --- ### nonce `number` Unique number identifying this transaction. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Composables that have identical context will share the same cache. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### to `Address | undefined` The transaction recipient or contract address. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### type `'legacy' | 'eip1559' | 'eip2930' | undefined` Optional transaction request type to narrow parameters. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### value `bigint | undefined` Value in wei sent with this transaction. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseEstimateGasReturnType } from '@wagmi/vue' ``` ## Action - [`estimateGas`](/core/api/actions/estimateGas) ================================================ FILE: site/vue/api/composables/useReadContract.md ================================================ --- title: useReadContract description: Composable for calling a read-only function on a contract, and returning the response. --- # useReadContract Composable for calling a **read-only** function on a contract, and returning the response. A **read-only** function (constant function) on a Solidity contract is denoted by a pure or view keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas. ## Import ```ts import { useReadContract } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseReadContractParameters } from '@wagmi/vue' ``` ### abi `Abi | undefined` The contract's ABI. Check out the [TypeScript docs](/vue/typescript#const-assert-abis-typed-data) for how to set up ABIs for maximum type inference and safety. ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### account `Account | undefined` Account to use when calling the contract (`msg.sender`). ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### address `Address | undefined` The contract's address. ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### args `readonly unknown[] | undefined` - Arguments to pass when calling the contract. - Inferred from [`abi`](#abi) and [`functionName`](#functionname). ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: --- ### blockNumber `bigint | undefined` Block number to call contract at. ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to call contract at. ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### functionName `string | undefined` - Function to call on the contract. - Inferred from [`abi`](#abi). ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Composables that have identical context will share the same cache. ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-read.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseReadContractReturnType } from '@wagmi/vue' ``` The return type's [`data`](#data) property is inferrable via the combination of [`abi`](#abi), [`functionName`](#functionname), and [`args`](#args). Check out the [TypeScript docs](/vue/typescript#const-assert-abis-typed-data) for more info. ## Type Inference With [`abi`](#abi) setup correctly, TypeScript will infer the correct types for [`functionName`](#functionname), [`args`](#args), and the return type. See the Wagmi [TypeScript docs](/vue/typescript) for more information. ::: code-group ```ts twoslash [Inline] // @twoslash-cache: {"v":1,"hash":"c9cd30cf155368eb52dff62473381dfcdf7018daabaed2ca4c58019bdbc995a3","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BjCMONAAlPgFcAbNROwCqcGACUYAQygBhFmlKTGaCWm6kwAFWwwAPAApgAHTDsz7TDkFGQAM25hlASxY2A3CfPswkgLYxBNlInMABzD1NzNkkaAFluNEkAIydeJ0xrECInGAB3d09zEKwEuEFjSK8zH39AhRDwwqqLHUzpKC44OALK9gBfZABdCK8IBJK0MvYK5rNLAPYbbhC0ACYAVgA2Hq8B4ZM+9gAfaaaWq0W7B2dXEBHzGoWghvuzaLiE5NT0jEzsvJ2RTAEymYBgJFIQ1e7DGaBB5TOXkedWCYWhXnmmWWYDWW0BZj2ET6AEohhRLklJLxJI4YAB5Ww2cnPMJk7zgsgAPkoIGipAYiE2VF4MDCaHwSCF1EkpFCMAFIE6fAYwpCuEQAAYqIx8DKlDRyIK+hR0Do8IQITyaPQ8PoqU5JHBiexuKIJNI5DjFMoDDNzJjLvZHGgXGB8d4/E96mizu8YPFEik0hlLv98nczsVSgjekjIyiXoj/a1Lu1Ot0M71CWdYfDTrnixclisNttK7soQdjvWMSWbEGbmH2w98+wWY1enGE19k79Uzl09Cs5NBGCIZ3erXsz3Zsix9GJ7NzgtmzjW+Hq2ASWybJTqbSGUz96jQmzPbYnKFyWuufosHr/ANOAAH0AH5BBEcQpFkeRvTQAAFAD5TIOBfTOAN+2uENbmhPdx2hKdPiTH4/gXcNlymP1mjwg90UbE8QDLeAK2hS9RnGbcqKqDCQGxXE21YjdDhOLieIHbCh1w0d8NjRIPkTb4UxsNNyOBbcf0hfZNw4lcd2o6TaKLOY+14ls8WHAkhNJQZyVvKkaUYelGUoZ8GjfFgPy/dkIU5YkILdaDPQUfVVHULQdF0AA6aLORMJxfCwCB+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hSs+oKcE3qRBeuwZAZxUMBgAOQJuNxQIse5jfcYfLYc3RY5mkfYMbtM9uGy7NQAnBYxulDMAcGgc3RMfcSq6Mb/oNkizKMEJ7k3TKw99Aj1WC3vQjcllN42t39HvdoAgIkXgABlbgWAsBucz1UR3oGXcLjL14D3ifmhR/18AL3ghjcJeL6X8ksecbx/r+YY0hQ++utb9K2V8qnaKuVaq9VmrtW6v1YahrUgNVmotVau3yezAltHNb+ytu3fRbMFu/XxvR9ytTgqpVKqNRqo1VqnVeqDVKqXya1flrrXG8T9jkk0WZORX8yYDyIBJIEgKANdKKHAKGHgJMCAH0H0EAA="} import { createConfig, http, useReadContract } from '@wagmi/vue' import { mainnet, sepolia } from 'wagmi/chains' const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) // ---cut--- const result = useReadContract({ abi: [ { type: 'function', name: 'balanceOf', stateMutability: 'view', inputs: [{ name: 'account', type: 'address' }], outputs: [{ type: 'uint256' }], }, { type: 'function', name: 'totalSupply', stateMutability: 'view', inputs: [], outputs: [{ name: 'supply', type: 'uint256' }], }, ], address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'balanceOf', // ^? args: ['0x6b175474e89094c44da98b954eedeac495271d0f'], // ^? }) result.data // ^? ``` ```ts twoslash [Const-Asserted] // @twoslash-cache: {"v":1,"hash":"b21638ef6d0df571da0457691c07531820bda58a8bf70cddee1ce9852f692ff4","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BjCMONAAgEMAjAS0XakYnKCwA2GdqgA6YdvMHDRYCe0w4B0kADMArmEZpeLLQG5ZCxSPGSwnALYxNIbpzGcDMAPLazFhULWKpJsnDQAsrpoPLxivJjORLwwAO5+cgFKNuy8YFhRcAKByqoyGZbyxdl2js6cjMz6aOkVmUGq6k7sWiJQQnBwLQoAvgC65uVWJZIQUflohVPZZa2VWcFq2F1aurloAEwArABsQ/JjE8MU7MD+a+2Snc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PgBwLwIILCCIJINIDIMQMoIwGoNDBEPgMQIYJ3F0DQJYLuTYLgA4Kmy4OiGINIPlAELByENoNkDEKQK+UYKkOYLgFYMkGwNwMUMIJUL4LUIoI0OENoJ0IkKYPQNkJMPYLMPwIsN4P4JsMV1PROVa1Yw0kTHR0IJ+3v1lytGvHlw0JfzEzf24M/xgG/1/ySMzEAJALAKSIgOPzQFPxACgxgxAAcL0MkOkKMJcOkQUI8O4MsO8MELsNEPoJKKcJkMwNcPkPcKUJ4NUPIPqK0LoPEOaIMOcLaMqM6M8J6PUN8P6OKJQOGNaLkKqK6NqOsL6JEO0KaLmLKOMLGM4ImKsN6NsP8ITECKmhCO4LCLxznCiNGRzGgGin9w4BiHYCHkpwyFIQcgAHJ8lPiKACR0JPj19tBfiCQgtERPjd4QTJhfFUAVV2BPiTVfi9oETdtPjmE/jJhqVYSvjBk0Td1/Arh/APjx5viYcoTLAASB0ylySFAwTRUITTwaT5AYTRkCQsTgA4TPi10kScS0k8TWSMhCSwBRguA4Be4+FmgRDHjA9ZEXjgN/UwMX1DBXQDYYgMT5BasBBPjtdac9cGdDdmcTc2dzdptudDh5trdgT1TiCYcvsuhATU8fAoTaCNT1cpBtTqcdc6d9dGcjcWdTd2dJtTTZtzTedltPiBThhfRaCb80BT1CDZAhR3VOAkBQAXRpQ4AQx64EBhhhggA"} import { createConfig, http, useReadContract } from '@wagmi/vue' import { mainnet, sepolia } from 'wagmi/chains' const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) // ---cut--- const abi = [ { type: 'function', name: 'balanceOf', stateMutability: 'view', inputs: [{ name: 'account', type: 'address' }], outputs: [{ type: 'uint256' }], }, { type: 'function', name: 'totalSupply', stateMutability: 'view', inputs: [], outputs: [{ name: 'supply', type: 'uint256' }], }, ] as const const result = useReadContract({ abi, address: '0x6b175474e89094c44da98b954eedeac495271d0f', functionName: 'balanceOf', // ^? args: ['0x6b175474e89094c44da98b954eedeac495271d0f'], // ^? }) result.data // ^? ``` ::: ## Action - [`readContract`](/core/api/actions/readContract) ================================================ FILE: site/vue/api/composables/useReconnect.md ================================================ --- title: useReconnect description: Composable for reconnecting connectors. --- # useReconnect Composable for reconnecting [connectors](/core/api/connectors). ## Import ```ts import { useReconnect } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` ::: ::: tip When [`WagmiPlugin['reconnectOnMount']`](/vue/api/WagmiPlugin#reconnectonmount) is `true`, `reconnect` is called automatically on mount. ::: ## Parameters ```ts import { type UseReconnectParameters } from '@wagmi/vue' ``` ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseReconnectReturnType } from '@wagmi/vue' ``` ## Action - [`reconnect`](/core/api/actions/reconnect) ================================================ FILE: site/vue/api/composables/useSendTransaction.md ================================================ --- title: useSendTransaction description: Composable for creating, signing, and sending transactions to networks. --- # useSendTransaction Composable for creating, signing, and sending transactions to networks. ## Import ```ts import { useSendTransaction } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseSendTransactionParameters } from '@wagmi/vue' ``` ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseSendTransactionReturnType } from '@wagmi/vue' ``` ## Action - [`sendTransaction`](/core/api/actions/sendTransaction) ================================================ FILE: site/vue/api/composables/useSignMessage.md ================================================ --- title: useSignMessage description: Composable for signing messages. --- # useSignMessage Composable for signing messages. ## Import ```ts import { useSignMessage } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseSignMessageParameters } from '@wagmi/vue' ``` ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseSignMessageReturnType } from '@wagmi/vue' ``` ## Action - [`signMessage`](/core/api/actions/signMessage) ================================================ FILE: site/vue/api/composables/useSignTransaction.md ================================================ --- title: useSignTransaction description: Composable for creating, and signing transactions to networks. --- # useSignTransaction Composable for signing transactions. ## Import ```ts import { useSignTransaction } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseSignTransactionParameters } from '@wagmi/vue' ``` ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseSignTransactionReturnType } from '@wagmi/vue' ``` ## Action - [`signTransaction`](/core/api/actions/signTransaction) ================================================ FILE: site/vue/api/composables/useSignTypedData.md ================================================ --- title: useSignTypedData description: Composable for signing typed data and calculating an Ethereum-specific EIP-712 signature. --- # useSignTypedData Composable for signing typed data and calculating an Ethereum-specific [EIP-712](https://eips.ethereum.org/EIPS/eip-712) signature. ## Import ```ts import { useSignTypedData } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseSignTypedDataParameters } from '@wagmi/vue' ``` ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseSignTypedDataReturnType } from '@wagmi/vue' ``` ## Type Inference With [`types`](/core/api/actions/signTypedData#types) setup correctly, TypeScript will infer the correct types for [`domain`](/core/api/actions/signTypedData#domain), [`message`](/core/api/actions/signTypedData#message), and [`primaryType`](/core/api/actions/signTypedData#primarytype). See the Wagmi [TypeScript docs](/vue/typescript) for more information. ::: code-group ```ts twoslash [Inline] // @twoslash-cache: {"v":1,"hash":"d347b35c1f3533593f8f8fd4f638678cdbe6746b6703290029ec262c44dffe62","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BjCMONAAjgEsBzMAFWwwoAEQCGaMYnYBVODADKvAUNESxAJRhoArqRU4APDrABrSAHcwAPkog2Y0g0QA2KgBsYYHmnxIAjADMVJKkPNp43HyCOGqSdu5cYLiIAAxUjPiOYow05K4AvhToQniEJOQhdM4gABRiiWJwAJTsOvJK0ariksZmlja1WNkAttpkcAD80sAAOmDsi+zMYABmvNPsAMIs6zzsAD5tYLDryVAA3PNL7CM6kmhcLJtyMACy9xJPYAAKo+OkOCGAAGqVoABJgGxSEkeAVgRR2J0DMIemIAKKkUgQUgxGCIuYLG5LTA4OAza7EqnIWjSaGwgC60lIMDEUBY7gw7DxcTEf1IYjGeWQDKuRKpNxp0mB9O8yEhsrhDOBTOOpySwjFEuJUvYwNWJly33lULQMO8BWVqpM6vOWu1S11wLZUBZcDgJsVlpV0htMDOmspDvYToARhAIO5PWbYd7rSd/RrLkGHWGMDQPQqYxarb6EwHk+LU7S9aH0/B/NHzUqfWrE3aU9q0xmAExV2O5usF+3B5vwQLtnO1v3dxsSvtwAAsg5r8dtgaLTZLwLLGYArDO43n54Xg4sJy5N52R0me8Xpav4AB2I/D/OnsfU5eXuAADlvc/rC73Ief5bgACcH7bl+u57hO/ipMBXYPou45/hm/iVlm1ZbjBDZwU+F7/v4bYoR2d47meS7YYhA74UOn6jphOoIRW04UbOIHUT+EEboxaEnhhrF0XA/iHhxx73tx4G8f4N6CYRoHEfBpEVu+klUbBPFyXxQGKcxymiapLZQRp6Hftppb/i2y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q7EsnuZXgHE06w6om669oIA8mw4BHYkMgZDQB/YrDxKNImKSDsAPptAdCJKojqC1DNDzDzA6npJiA0IgY0C1AHK4Y5FLBEbSDIBjjADbHnIADkhK3piI1K3pio3plaFAHpXp0g3p4O/pxOkZlWcAIZRQKYapKYQu7pcEnpta3pcmMZgZRGiZYZGZEZ7A3pnKuZsa3p+ZoZ4ZWZop5ZOWQZe0BZyZhZTGlI/BDBFZaa/pFpQ+RILR4Q5qvZw5fZI5I5Nw/RY4WZOwFgPZcEIx3pYIWwIgLYYggQUAAEAAYgBDDuiEEMufsVeOiIwKkGuAAIKhhbBXibnohXiBCTgiCrCvgiAiCvixRzmIqtkkgQAxGLBZkABCEAoYH5xIC5YIoY/5EF/50FoYUFkFsF8F8FCFkFSFEFaFUFEFIFbZpRW+dhJZAAEjAMChAIiIBaGAAIQgVJl2bNB2BChiBICgDVBeDcAsAM4IAFAFBAA"} import { useSignTypedData } from '@wagmi/vue' // ---cut--- const signTypedData = useSignTypedData() signTypedData.mutate({ types: { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], }, primaryType: 'Mail', // ^? message: { // ^? from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) ``` ```ts twoslash [Const-Asserted] // @twoslash-cache: {"v":1,"hash":"eaf9c3d409bf800893a6c4a9064554dc68fdcaaccc9fdd1dd7d8f8bf1a066ba2","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808BjCMONAAkxzkXeAB0w7Ye1IwAhlBYAbDOwAKZOC15jJMuakEidoiVLCz2YcQFsYvfuDMwrAbm27hag0a4X2VtqQCWYAOb2jsIAvhR8wbouGsY2liA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sgJEMAB2QAOS3DIXhBTDIWjjIUZ6IUoVwnoUlTIXF44VhCOAVAUCOCV4IVdBIV8TIXhSEWYVlSkWUW0UoXbBMUKjIUsW4XsX0WflcUixYUxKsXkVsUhDsDny/ysDpALBgC5w65y7oiwUy7u6MIY7sh8iCCCBKVC7iBQ66E0DsjcQ4hsXCCvEDHcUuToU6XyXCB0m8k752UuXyWuWuXgmGztnCD0UgIJC2WXD5nIVkJAJlzhjiAFhQDvIABiK59ozCC8oV7yRYr4zCjAhIyIAAgqEkAq+NFcwq+MWGXAMPaGXGXPaIGgFeUOZSIDKafvRQAEIQChJVW6BBVkKhINWdUNU9WhLdVdV9UDUDWDVdXDWdXjXdWdWtVLCRCfm8DIUAASMAKQEA4QTVoSAAhK1WRWpHyKCG/FvIgKAKyM6PnCwNiAgCECEEAA=="} import { useSignTypedData } from '@wagmi/vue' // ---cut--- const types = { Person: [ { name: 'name', type: 'string' }, { name: 'wallet', type: 'address' }, ], Mail: [ { name: 'from', type: 'Person' }, { name: 'to', type: 'Person' }, { name: 'contents', type: 'string' }, ], } as const const signTypedData = useSignTypedData() signTypedData.mutate({ types, primaryType: 'Mail', // ^? message: { // ^? from: { name: 'Cow', wallet: '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826', }, to: { name: 'Bob', wallet: '0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB', }, contents: 'Hello, Bob!', }, }) ``` ::: ## Action - [`signTypedData`](/core/api/actions/signTypedData) ================================================ FILE: site/vue/api/composables/useSimulateContract.md ================================================ --- title: useSimulateContract description: Composable for simulating/validating a contract interaction. --- # useSimulateContract Composable for simulating/validating a contract interaction. ## Import ```ts import { useSimulateContract } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseSimulateContractParameters } from '@wagmi/vue' ``` ### abi `Abi | undefined` The contract's ABI. Check out the [TypeScript docs](/vue/typescript#const-assert-abis-typed-data) for how to set up ABIs for maximum type inference and safety. ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### accessList `AccessList | undefined` The access list. ::: code-group ```vue [index.ts] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### account `Account | undefined` Account to use when calling the contract (`msg.sender`). Throws if account is not found on [`connector`](#connector). ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### address `Address | undefined` The contract's address. ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### args `readonly unknown[] | undefined` - Arguments to pass when calling the contract. - Inferred from [`abi`](#abi) and [`functionName`](#functionname). ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: --- ### blockNumber `bigint | undefined` Block number to call contract at. ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to call contract at. ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: --- ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### connector `Connector | undefined` [Connector](/vue/api/connectors) to simulate transaction with. ::: code-group ```vue [index.ts] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### dataSuffix `` `0x${string}` | undefined `` Data to append to the end of the calldata. Useful for adding a ["domain" tag](https://opensea.notion.site/opensea/Seaport-Order-Attributions-ec2d69bf455041a5baa490941aad307f). ::: code-group ```vue [index.ts] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### functionName `string | undefined` - Function to call on the contract. - Inferred from [`abi`](#abi). ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### gas `bigint | undefined` Gas provided for transaction execution. ::: code-group ```vue [index.ts] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: --- ### gasPrice `bigint | undefined` The price in wei to pay per gas. Only applies to [Legacy Transactions](https://viem.sh/docs/glossary/terms#legacy-transaction). ::: code-group ```vue [index.ts] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### maxFeePerGas `bigint | undefined` Total fee per gas in wei, inclusive of [`maxPriorityFeePerGas`](#maxPriorityFeePerGas). Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```vue [index.ts] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### maxPriorityFeePerGas `bigint | undefined` Max priority fee per gas in wei. Only applies to [EIP-1559 Transactions](https://viem.sh/docs/glossary/terms#eip-1559-transaction). ::: code-group ```vue [index.ts] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: --- ### nonce `number` Unique number identifying this transaction. ::: code-group ```vue [index.ts] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### type `'legacy' | 'eip1559' | 'eip2930' | undefined` Optional transaction request type to narrow parameters. ::: code-group ```vue [index.ts] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### value `bigint | undefined` Value in wei sent with this transaction. ::: code-group ```vue [index.ts] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Composables that have identical context will share the same cache. ::: code-group ```vue [index.ts] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseSimulateContractReturnType } from '@wagmi/vue' ``` The return type's [`data`](#data) property is inferrable via the combination of [`abi`](#abi), [`functionName`](#functionname), and [`args`](#args). Check out the [TypeScript docs](/vue/typescript#const-assert-abis-typed-data) for more info. ## Type Inference With [`abi`](#abi) setup correctly, TypeScript will infer the correct types for [`functionName`](#functionname), [`args`](#args), and [`value`](#value). See the Wagmi [TypeScript docs](/vue/typescript) for more information. ## Action - [`simulateContract`](/core/api/actions/simulateContract) ================================================ FILE: site/vue/api/composables/useSwitchChain.md ================================================ --- title: useSwitchChain description: Composable for switching the target chain for a connector or the Wagmi `Config`. --- # useSwitchChain Composable for switching the target chain for a connector or the Wagmi [`Config`](/vue/api/createConfig#config). ## Import ```ts import { useSwitchChain } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ::: tip When connected, `switchChain` will switch the target chain for the connector. When not connected, `switchChain` will switch the target chain for the Wagmi [`Config`](/vue/api/createConfig#config). ::: ## Parameters ```ts import { type UseSwitchChainParameters } from '@wagmi/vue' ``` ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseSwitchChainReturnType } from '@wagmi/vue' ``` ## Action - [`switchChain`](/core/api/actions/switchChain) ================================================ FILE: site/vue/api/composables/useSwitchConnection.md ================================================ --- title: useSwitchConnection description: Composable for switching the current connection. --- # useSwitchConnection Composable for switching the current connection. ## Import ```ts import { useSwitchConnection } from 'wagmi' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseSwitchConnectionParameters } from 'wagmi' ``` ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseSwitchConnectionReturnType } from 'wagmi' ``` ## Action - [`switchConnection`](/core/api/actions/switchConnection) ================================================ FILE: site/vue/api/composables/useTransaction.md ================================================ --- title: useTransaction description: Composable for fetching transactions given hashes or block identifiers. --- # useTransaction Composable for fetching transactions given hashes or block identifiers. ## Import ```ts import { useTransaction } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseTransactionParameters } from '@wagmi/vue' ``` --- ### blockHash `bigint | undefined` Block hash to get transaction at (with [`index`](#index)). ```vue ``` ### blockNumber `bigint | undefined` Block number to get transaction at (with [`index`](#index)). ```vue ``` ### blockTag `'latest' | 'earliest' | 'pending' | 'safe' | 'finalized' | undefined` Block tag to get transaction at (with [`index`](#index)). ```vue ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ```vue ``` ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### hash `` `0x${string}` | undefined `` Hash to get transaction. [`enabled`](#enabled) set to `false` if `hash` and [`index`](#index) are `undefined`. ```vue ``` ### index `number | undefined` An index to be used with a block identifier ([hash](#blockhash), [number](#blocknumber), or [tag](#blocktag)). [`enabled`](#enabled) set to `false` if `index` and [`hash`](#hash) are `undefined`. ```vue ``` ## Return Type ```ts import { type UseTransactionReturnType } from '@wagmi/vue' ``` ## Action - [`getTransaction`](/core/api/actions/getTransaction) ================================================ FILE: site/vue/api/composables/useTransactionReceipt.md ================================================ --- title: useTransactionReceipt description: Composable for return the Transaction Receipt given a Transaction hash. --- # useTransactionReceipt Composable for return the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash. ## Import ```ts import { useTransactionReceipt } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseTransactionReceiptParameters } from '@wagmi/vue' ``` ### hash `` `0x${string}` | undefined `` A transaction hash. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### chainId `config['chains'][number]['id'] | undefined` The ID of chain to return the transaction receipt from. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### scopeKey `string | undefined` Scopes the cache to a given context. Composables that have identical context will share the same cache. ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseTransactionReceiptReturnType } from '@wagmi/vue' ``` ## Action - [`getTransactionReceipt`](/core/api/actions/getTransactionReceipt) ================================================ FILE: site/vue/api/composables/useWaitForTransactionReceipt.md ================================================ --- title: useWaitForTransactionReceipt description: Composable that waits for the transaction to be included on a block, and then returns the transaction receipt. If the transaction reverts, then the action will throw an error. Replacement detection (e.g. sped up transactions) is also supported. --- # useWaitForTransactionReceipt Composable that waits for the transaction to be included on a block, and then returns the transaction receipt. If the transaction reverts, then the action will throw an error. Replacement detection (e.g. sped up transactions) is also supported. ## Import ```ts import { useWaitForTransactionReceipt } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type WaitForTransactionReceiptParameters } from '@wagmi/core' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ```vue [index.vue] ``` ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ### confirmations `number | undefined` The number of confirmations (blocks that have passed) to wait before resolving. ```vue [index.vue] ``` ### onReplaced ` (({ reason: 'replaced' | 'repriced' | 'cancelled'; replacedTransaction: Transaction; transaction: Transaction; transactionReceipt: TransactionReceipt }) => void) | undefined ` Optional callback to emit if the transaction has been replaced. ```vue [index.vue] ``` ### pollingInterval `number | undefined` - Polling frequency (in milliseconds). - Defaults to the [Config's `pollingInterval` config](/vue/api/createConfig#pollinginterval). ```vue [index.vue] ``` ### hash `` `0x${string}` | undefined `` The transaction hash to wait for. [`enabled`](#enabled) set to `false` if `hash` is `undefined`. ```vue [index.vue] ``` ## Return Type ```ts import { type UseWaitForTransactionReceiptReturnType } from '@wagmi/vue' ``` ## Action - [`waitForTransactionReceipt`](/core/api/actions/waitForTransactionReceipt) ================================================ FILE: site/vue/api/composables/useWatchBlockNumber.md ================================================ # useWatchBlockNumber Composable that watches for block number changes. ## Import ```ts import { useWatchBlockNumber } from '@wagmi/vue' ``` ## Usage ::: code-group ```ts [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseWatchBlockNumberParameters } from '@wagmi/vue' ``` ### chainId `config['chains'][number]['id'] | undefined` ID of chain to watch blocks at. ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ### emitMissed `boolean` Whether or not to emit missed blocks to the callback. Defaults to `false`. Missed blocks may occur in instances where internet connection is lost, or the block time is lesser than the polling interval of the client. ### emitOnBegin `boolean` Whether or not to emit the block to the callback when the subscription opens. Defaults to `false`. ### enabled `boolean` Whether or not to watch for blocks. Defaults to `true`. ### onBlockNumber `(block: Block, prevblock: Block | undefined) => void` Callback for when block changes. ### onError `((error: Error) => void) | undefined` Error thrown from getting the block. ### poll `boolean | undefined` - Whether or not to use a polling mechanism to check for new blocks instead of a WebSocket subscription. - Defaults to `false` for WebSocket Clients, and `true` for non-WebSocket Clients. ### pollingInterval `number | undefined` - Polling frequency (in milliseconds). - Defaults to the [Config's `pollingInterval` config](/core/api/createConfig#pollinginterval). ### syncConnectedChain `boolean | undefined` - Set up subscriber for connected chain changes. - Defaults to [`Config['syncConnectedChain']`](/core/api/createConfig#syncconnectedchain). ## Return Type ```ts import { type UseWatchBlockNumberReturnType } from '@wagmi/vue' ``` Function for cleaning up watcher. ## Action - [`watchBlockNumber`](/core/api/actions/watchBlockNumber) ================================================ FILE: site/vue/api/composables/useWatchContractEvent.md ================================================ # useWatchContractEvent Composable that watches and returns emitted contract event logs. ## Import ```ts import { useWatchContractEvent } from '@wagmi/vue' ``` ## Usage ::: code-group ```ts [index.vue] ``` <<< @/snippets/abi-event.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseWatchContractEventParameters } from '@wagmi/vue' ``` ### abi `Abi` The contract's ABI. Check out the [TypeScript docs](/vue/typescript#const-assert-abis-typed-data) for how to set up ABIs for maximum type inference and safety. ### address `Address | undefined` The contract's address. ### args `object | readonly unknown[] | undefined` - Arguments to pass when calling the contract. - Inferred from [`abi`](#abi) and [`eventName`](#eventname). ### batch `boolean | undefined` - Whether or not the events should be batched on each invocation. - Defaults to `true`. ### chainId `config['chains'][number]['id'] | undefined` ID of chain to use when fetching data. ### config `Config | undefined` [`Config`](/react/api/createConfig#config) to use instead of retrieving from the nearest [`WagmiProvider`](/react/api/WagmiProvider). ### eventName `string` - Event to listen for the contract. - Inferred from [`abi`](#abi). ### onError `((error: Error) => void) | undefined` Error thrown from getting the block number. ### onLogs `(logs: Log[], prevLogs: Log[] | undefined) => void` Callback for when logs changes. ### poll `boolean | undefined` - Whether or not to use a polling mechanism to check for new blocks instead of a WebSocket subscription. - Defaults to `false` for WebSocket Clients, and `true` for non-WebSocket Clients. ### pollingInterval `number | undefined` - Polling frequency (in milliseconds). - Defaults to the [Config's `pollingInterval` config](/core/api/createConfig#pollinginterval). ### strict `boolean | undefined` - Defaults to `false`. ### syncConnectedChain `boolean | undefined` - Set up subscriber for connected chain changes. - Defaults to [`Config['syncConnectedChain']`](/core/api/createConfig#syncconnectedchain). ## Return Type ```ts import { type UseWatchContractEventReturnType } from '@wagmi/vue' ``` Hook returns `void` ## Action - [`watchContractEvent`](/core/api/actions/watchContractEvent) ================================================ FILE: site/vue/api/composables/useWriteContract.md ================================================ --- title: useWriteContract description: Composable for executing a write function on a contract. --- # useWriteContract Composable for executing a write function on a contract. A "write" function on a Solidity contract modifies the state of the blockchain. These types of functions require gas to be executed, hence a transaction is broadcasted in order to change the state. ## Import ```ts import { useWriteContract } from '@wagmi/vue' ``` ## Usage ::: code-group ```vue [index.vue] ``` <<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ## Parameters ```ts import { type UseWriteContractParameters } from '@wagmi/vue' ``` ### config `Config | undefined` [`Config`](/vue/api/createConfig#config) to use instead of retrieving from the [`WagmiPlugin`](/vue/api/WagmiPlugin). ::: code-group ```vue [index.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Return Type ```ts import { type UseWriteContractReturnType } from '@wagmi/vue' ``` The return type's [`data`](#data) property is inferrable via the combination of [`abi`](#abi), [`functionName`](#functionname), and [`args`](#args). Check out the [TypeScript docs](/vue/typescript#const-assert-abis-typed-data) for more info. ## Type Inference With [`abi`](/core/api/actions/writeContract#abi) setup correctly, TypeScript will infer the correct types for [`functionName`](/core/api/actions/writeContract#functionname), [`args`](/core/api/actions/writeContract#args), and the [`value`](/core/api/actions/writeContract##value). See the Wagmi [TypeScript docs](/vue/typescript) for more information. ## Action - [`writeContract`](/core/api/actions/writeContract) ================================================ FILE: site/vue/api/composables.md ================================================ # Composables Vue Composables for accounts, wallets, contracts, transactions, signing, ENS, and more. ## Import ```ts import { useConnection } from '@wagmi/vue' ``` ## Available Composables ================================================ FILE: site/vue/api/connectors/baseAccount.md ================================================ --- title: baseAccount --- ================================================ FILE: site/vue/api/connectors/coinbaseWallet.md ================================================ ================================================ FILE: site/vue/api/connectors/injected.md ================================================ --- title: injected --- ================================================ FILE: site/vue/api/connectors/metaMask.md ================================================ --- title: metaMask --- ================================================ FILE: site/vue/api/connectors/mock.md ================================================ --- title: mock --- ================================================ FILE: site/vue/api/connectors/porto.md ================================================ --- title: porto --- ================================================ FILE: site/vue/api/connectors/safe.md ================================================ --- title: safe --- ================================================ FILE: site/vue/api/connectors/walletConnect.md ================================================ --- title: walletConnect --- ================================================ FILE: site/vue/api/connectors.md ================================================ # Connectors Connectors for popular wallet providers and protocols. ## Import Import via the `'@wagmi/vue/connectors'` entrypoint. ```ts import { injected } from '@wagmi/vue/connectors' ``` ## Available Connectors ::: tip Some connectors require third-party packages. See the "Install" section on each connector's page for more info on license, version, and more. ::: ================================================ FILE: site/vue/api/createConfig.md ================================================ --- title: createConfig --- ================================================ FILE: site/vue/api/createStorage.md ================================================ --- title: createStorage --- ================================================ FILE: site/vue/api/errors.md ================================================ # Errors Error classes used by Wagmi. ================================================ FILE: site/vue/api/transports/custom.md ================================================ --- title: custom --- ================================================ FILE: site/vue/api/transports/fallback.md ================================================ --- title: fallback --- ================================================ FILE: site/vue/api/transports/http.md ================================================ --- title: http --- ================================================ FILE: site/vue/api/transports/unstable_connector.md ================================================ --- title: unstable_connector --- ================================================ FILE: site/vue/api/transports/webSocket.md ================================================ --- title: webSocket --- ================================================ FILE: site/vue/api/transports.md ================================================ # Transports [`createConfig`](/vue/api/createConfig) can be instantiated with a set of Transports for each chain. A Transport is the intermediary layer that is responsible for executing outgoing JSON-RPC requests to the RPC Provider (e.g. Alchemy, Infura, etc). ## Import ```ts import { http } from '@wagmi/vue' ``` ## Built-In Transports Available via the `'@wagmi/vue'` entrypoint. ================================================ FILE: site/vue/api/utilities/deserialize.md ================================================ --- title: deserialize --- ================================================ FILE: site/vue/api/utilities/serialize.md ================================================ --- title: serialize --- ================================================ FILE: site/vue/getting-started.md ================================================ # Getting Started ## Overview Wagmi is a collection of Vue composition utilities for Ethereum. You can learn more about the rationale behind the project in the [Why Wagmi](/vue/why) section. ## Automatic Installation For new projects, it is recommended to set up your Wagmi app using the [`create-wagmi`](/cli/create-wagmi) command line interface (CLI). This will create a new Wagmi project using TypeScript and install the required dependencies. ::: code-group ```bash [pnpm] pnpm create wagmi ``` ```bash [npm] npm create wagmi@latest ``` ```bash [yarn] yarn create wagmi ``` ```bash [bun] bun create wagmi ``` ::: Once the command runs, you'll see some prompts to complete. ```ansi Project name: wagmi-project Select a framework: Vue / Vanilla ... ``` After the prompts, `create-wagmi` will create a directory with your project name and install the required dependencies. Check out the `README.md` for further instructions (if required). ## Manual Installation To manually add Wagmi to your project, install the required packages. ::: code-group ```bash-vue [pnpm] pnpm add @wagmi/vue viem@{{viemVersion}} @tanstack/vue-query ``` ```bash-vue [npm] npm install @wagmi/vue viem@{{viemVersion}} @tanstack/vue-query ``` ```bash-vue [yarn] yarn add @wagmi/vue viem@{{viemVersion}} @tanstack/vue-query ``` ```bash-vue [bun] bun add @wagmi/vue viem@{{viemVersion}} @tanstack/vue-query ``` ::: - [Viem](https://viem.sh) is a TypeScript interface for Ethereum that performs blockchain operations. - [TanStack Query](https://tanstack.com/query/v5) is an async state manager that handles requests, caching, and more. - [TypeScript](/vue/typescript) is optional, but highly recommended. Learn more about [TypeScript support](/vue/typescript). ### Create Config Create and export a new Wagmi config using `createConfig`. ::: code-group <<< @/snippets/vue/config.ts[config.ts] ::: In this example, Wagmi is configured to use the Mainnet and Sepolia chains, and `injected` connector. Check out the [`createConfig` docs](/vue/api/createConfig) for more configuration options. ::: details TypeScript Tip If you are using TypeScript, you can "register" the Wagmi config or use the hook `config` property to get strong type-safety in places that wouldn't normally have type info. ::: code-group ```ts twoslash [register config] // @twoslash-cache: {"v":1,"hash":"a23946e4e600232f2356272aa1638ad6dfa3cb14a3230c917234b4d331429652","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgAhVhBEBrAHKCAtgCMyAHhGT+7AOa86NMFDi8AwoZO8AvLfvHdpGMyiTWGXqgAdKV4QrUUVAFFaLEUPUjhEXmAgkNTUjy8fP1h+ZkFWNETk4LTS3gzvMF9eMGYNGESAkAi0fDI4EWYwJoBuFLLSiqzpUlZGgjQ0LASAehmYVvbOsAA6CV7+gfTPSurmLHYAVVHx/EnpxDn99hWFtvjltYgZ642S0oBfPvevzd4wpTKAAq7HqiQAjAAmAAMsO+aQMYDQpGYYgSST+aSGVT8MDAcEOYHYJHibAASvAIKwSUVMQNsXsoFAPHB0U1obQYFzuVzwQAWKAAdnBAA4RJCtHzBVAAJwyyEAZlgzC04IVCoArDB+XyeW8tlidsMASobBkaFBEoroSKNXaRfCBr93obMjjeBp8uJOqxWAraS76Ub3V5mfA2SAOZ1weCtLBoRqZYLBVoFQA2BUxtOC6GQkUitMSmCQ5jgwUKpNp6Pg/UGkIMvwm5RmzwWiF8zXp6Hgx1lZ1pfupFbD3j8j0QDy8YcrXu8EnsfgYAASXHwAH5EoxGCIOHjCrZd0jdNOAHwUXhYZgo+o0eKJABqZAXy9XAAUr3UFu0+I4T7xX6QEAaOwsi6FoEBUp4YAnnwAA+0iWDARhgDAUDfB857FGk07oQAumevAiPgzDsGAACSUBmPQeJWIRrjIE0REkfiTS4cgYCaDopBsU07BQKxTh0WARjGAxIBMaRcCsexnFkDxIB8ax56yKwMBiAAIswaDMIJWgmKRaAnowl7Xl+8Q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bzMCQKAcwSsJBgDwDYj4HwgA=="} // @errors: 2322 import { type Config } from '@wagmi/vue' import { mainnet, sepolia } from '@wagmi/vue/chains' declare const config: Config // ---cut--- import { useBlockNumber } from '@wagmi/vue' useBlockNumber({ chainId: 123 }) declare module '@wagmi/vue' { interface Register { config: typeof config } } ``` ```ts twoslash [hook config property] // @twoslash-cache: {"v":1,"hash":"b0daf106bbcd51604a04f61b444559e5b4612f840caeff27571cf1d2939b54a2","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgAhVhBEBrAHKCAtgCMyAHhGT+7AOa86NMFDi8AwoZO8AvLfvGKvEfmbswASShm9DCW1gZgRsbIADognt5gcDEAushgmjqkKTHsUMlOHq7RsV4+iSApadpkWSA5ye6yrDBiACLMaMz5WiY+aAB8jFjMpMwaMDSkcAD6APyIvACqsgpKaulkAArDo+NkcPqu7nE+/g0wTa3tzH3c80vyiirqVaQASuOCpGAAKtgwuo1mmg2h0+lEwOwNFgIKQ0NJlo81i9KCAoEoEIgCGg0Fg4IgAPT4gDuzGMGnYADo4Ph8URBDB8cwsOx8QYoRA4MwtE04PiZA9Vs8Mii4B1YUgAJxUJpgYxofBIACMABYqGLjOM8PyVk91uRpT5cIgAAxUOIjMRkSUAXwo6D+eEIJH11HMTDYnB48IFupeujs4RMulIMGYaLArAwvFQ4N4cd43NWAFFaFhFCHJvNgLH47mQ2HJJHeLB+MxBKw0Fmc7ma7x8+Gi2AdvMYkn5XsRMwwDEANzV2vx+uFqOfVgtrE4vGE8b4DtdikSXv9gd10MNqNM9gLUhj3gxfDY3EExnMikzudgBcQE/sJdSAfWvv3uOP/uJlTfSEweaKgBMxoAp9czCNALTQPFeGzZ8ayHCMo2COAFghZ1OVYd44AgVhnSraCV1goswygEM4AgmJjVoGBKKoyiVSgAB2RUAA4RF/LRlToqAJQlX8AGZYC5RUeJ4gBWGAVWVai7xXPM12HBNERsfMa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KsV4qJToslHpeT3GhMKUpEpdVCrCWKqVapvArFbLKq1FZDUmotRqu1daXVerUgGkNEa7AxrzBsJNaas15rbCWnseYa1SAbXOfgVGry9pOEOsdU6Bd/iXWul2O6j0B4vSHp9dwbj4y/XBNaf6z9B5vWHh/CWLt/KO3lkgXFgDSCqzwGECI4CPYL2NsvIKKK3awADhTOEwAqaaz1FsgQJ0NBZwAAKs3JJzGAmdwTgg1sjF4jAWWgJUvYniRxSHWm4CiJazAkCgHMAhCQYA8Ch2tNaIAA=="} // @errors: 2322 import { type Config } from '@wagmi/vue' import { mainnet, sepolia } from '@wagmi/vue/chains' declare const config: Config // ---cut--- import { useBlockNumber } from '@wagmi/vue' useBlockNumber({ chainId: 123, config }) ``` By registering or using the hook `config` property, `useBlockNumber`'s `chainId` is strongly typed to only allow Mainnet and Sepolia IDs. Learn more by reading the [TypeScript docs](/vue/typescript#config-types). ::: ### Add Plugin to App Add the `WagmiPlugin` to your app instance and pass the `config` you created earlier to the plugin options. ::: code-group ```tsx [main.ts] import { WagmiPlugin } from '@wagmi/vue' // [!code focus] import { createApp } from 'vue' import { config } from './config' // [!code focus] import App from './App.vue' createApp(App) .use(WagmiPlugin, { config }) // [!code focus] .mount('#app') ``` ```vue [App.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: Check out the [`WagmiPlugin` docs](/vue/api/WagmiPlugin) to learn more about the plugin API. ### Setup TanStack Query After the `WagmiPlugin`, attach the `VueQueryPlugin` to your app, and pass a new `QueryClient` instance to the `queryClient` property. ::: code-group ```tsx [main.ts] import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query' // [!code focus] import { WagmiPlugin } from '@wagmi/vue' import { createApp } from 'vue' import { config } from './config' import App from './App.vue' const queryClient = new QueryClient() // [!code focus] createApp(App) .use(WagmiPlugin, { config }) .use(VueQueryPlugin, { queryClient }) // [!code focus] .mount('#app') ``` ```vue [App.vue] ``` <<< @/snippets/vue/config.ts[config.ts] ::: Check out the [TanStack Query docs](https://tanstack.com/query/latest/docs/framework/vue/overview) to learn about the library, APIs, and more. ### Use Wagmi Now that everything is set up, every component inside your app can use Wagmi Vue Composables. ::: code-group ```vue [App.vue] ``` ```tsx [main.ts] import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query' import { WagmiPlugin } from '@wagmi/vue' import { createApp } from 'vue' import { config } from './config' import App from './App.vue' const queryClient = new QueryClient() createApp(App) .use(WagmiPlugin, { config }) .use(VueQueryPlugin, { queryClient }) .mount('#app') ``` <<< @/snippets/vue/config.ts[config.ts] ::: ## Next Steps For more information on what to do next, check out the following topics. - [**TypeScript**](/vue/typescript) Learn how to get the most out of Wagmi's type-safety and inference for an enlightened developer experience. - [**Connect Wallet**](/vue/guides/connect-wallet) Learn how to enable wallets to connect to and disconnect from your apps and display information about connected accounts. - [**Vue Composables**](/vue/api/composables) Browse the collection of Vue Composables and learn how to use them. - [**Viem**](/vue/guides/viem) Learn about Viem and how it works with Wagmi. ================================================ FILE: site/vue/guides/chain-properties.md ================================================ # Chain Properties Some chains support additional properties related to blocks and transactions. This is powered by Viem's [formatters](https://viem.sh/docs/chains/formatters) and [serializers](https://viem.sh/docs/chains/serializers). For example, Celo, ZkSync, OP Stack chains support all support additional properties. In order to use these properties in a type-safe way, there are a few things you should be aware of.
::: tip Make sure you follow the TypeScript guide's [Config Types](/vue/typescript#config-types) section before moving on. The easiest way to do this is to use [Declaration Merging](/vue/typescript#declaration-merging) to "register" your `config` globally with TypeScript. <<< @/snippets/vue/config-chain-properties.ts[config.ts] ::: ## Narrowing Parameters Once your Config is registered with TypeScript, you are ready to access chain-specific properties! For example, Celo's `feeCurrency` is available. ::: code-group ```ts [index.tsx] import { parseEther } from 'viem' import { useSimulateContract } from '@wagmi/vue' const result = useSimulateContract({ to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), feeCurrency: '0x…', // [!code focus] }) ``` <<< @/snippets/vue/config-chain-properties.ts[config.ts] ::: This is great, but if you have multiple chains that support additional properties, your autocomplete could be overwhelmed with all of them. By setting the `chainId` property to a specific value (e.g. `celo.id`), you can narrow parameters to a single chain. ::: code-group ```ts [index.tsx] import { parseEther } from 'viem' import { useSimulateContract } from '@wagmi/vue' import { celo } from '@wagmi/vue/chains' const result = useSimulateContract({ to: '0xd2135CfB216b74109775236E36d4b433F1DF507B', value: parseEther('0.01'), chainId: celo.id, // [!code focus] feeCurrency: '0x…', // [!code focus] // ^? (property) feeCurrency?: `0x${string}` | undefined // [!code focus] }) ``` <<< @/snippets/vue/config-chain-properties.ts[config.ts] ::: ## Narrowing Return Types Return types can also have chain-specific properties attached to them. There are a couple approaches for extracting these properties. ### `chainId` Parameter Not only can you use the `chainId` parameter to [narrow parameters](#narrowing-parameters), you can also use it to narrow the return type. ::: code-group ```ts [index.tsx] import { useWaitForTransactionReceipt } from '@wagmi/vue' import { zkSync } from '@wagmi/vue/chains' const { data } = useWaitForTransactionReceipt({ chainId: zkSync.id, hash: '0x16854fcdd0219cacf5aec5e4eb2154dac9e406578a1510a6fc48bd0b67e69ea9', }) data?.logs // ^? (property) logs: ZkSyncLog[] | undefined ``` <<< @/snippets/vue/config-chain-properties.ts[config.ts] ::: ### `chainId` Data Property Wagmi internally will set a `chainId` property on return types that you can use to narrow results. The `chainId` is determined from the `chainId` parameter or global state (e.g. connector). You can use this property to help TypeScript narrow the type. ::: code-group ```ts [index.tsx] import { useWaitForTransactionReceipt } from '@wagmi/vue' import { zkSync } from '@wagmi/vue/chains' const { data } = useWaitForTransactionReceipt({ hash: '0x16854fcdd0219cacf5aec5e4eb2154dac9e406578a1510a6fc48bd0b67e69ea9', }) if (data?.chainId === zkSync.id) { data?.logs // ^? (property) logs: ZkSyncLog[] | undefined } ``` <<< @/snippets/vue/config-chain-properties.ts[config.ts] ::: ## Troubleshooting If chain properties aren't working, make sure [TypeScript](/vue/guides/faq#type-inference-doesn-t-work) is configured correctly. Not all chains have additional properties, to check which ones do, see the [Viem repo](https://github.com/wevm/viem/tree/main/src/chains) (chains that have a top-level directory under [`src/chains`](https://github.com/wevm/viem/tree/main/src/chains) support additional properties). ================================================ FILE: site/vue/guides/connect-wallet.md ================================================ # Connect Wallet The ability for a user to connect their wallet is a core function for any Dapp. It allows users to perform tasks such as: writing to contracts, signing messages, or sending transactions. Wagmi contains everything you need to get started with building a Connect Wallet module. To get started, follow the [build your own](#build-your-own) walkthrough. ## Build Your Own Wagmi provides you with the Composables to get started building your own Connect Wallet module. It takes less than five minutes to get up and running with Browser Wallets, WalletConnect, and Coinbase Wallet. ### 1. Configure Wagmi Before we get started with building the functionality of the Connect Wallet module, we will need to set up the Wagmi configuration. Let's create a `config.ts` file and export a `config` object. ::: code-group ```tsx [config.ts] import { http, createConfig } from '@wagmi/vue' import { base, mainnet, optimism } from '@wagmi/vue/chains' import { injected, metaMask, safe, walletConnect } from '@wagmi/vue/connectors' const projectId = '' export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), }, }) ``` ::: In the above configuration, we want to set up connectors for Injected (browser), WalletConnect (browser + mobile), MetaMask, and Safe wallets. This configuration uses the **Mainnet** and **Base** chains, but you can use whatever you want. ::: warning Make sure to replace the `projectId` with your own WalletConnect Project ID, if you wish to use WalletConnect! [Get your Project ID](https://cloud.walletconnect.com/) ::: ### 2. Inject the WagmiPlugin onto your App Next, we will need to inject our App with plugins so that our application is aware of Wagmi & Vue Query's reactive state and in-memory caching. ::: code-group ```ts [main.ts] // 1. Import modules. import { VueQueryPlugin } from '@tanstack/vue-query' import { WagmiPlugin } from '@wagmi/vue' import { createApp } from 'vue' import App from './App.vue' import { config } from './wagmi' createApp(App) // 2. Inject the Wagmi plugin. .use(WagmiPlugin, { config }) // 3. Inject the Vue Query plugin. .use(VueQueryPlugin, {}) .mount('#app') ``` ```vue [App.vue] ``` ```ts [config.ts] import { http, createConfig } from '@wagmi/vue' import { base, mainnet, optimism } from '@wagmi/vue/chains' import { injected, metaMask, safe, walletConnect } from '@wagmi/vue/connectors' const projectId = '' export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), }, }) ``` ::: ### 3. Display Wallet Options After that, we will create a `Connect` component that will display our connectors. This will allow users to select a wallet and connect. Below, we are rendering a list of `connectors` retrieved from `useConnect`. When the user clicks on a connector, the `connect` function will connect the users' wallet. ::: code-group ```vue [Connect.vue] ``` ```vue [App.vue] ``` ```ts [main.ts] // 1. Import modules. import { VueQueryPlugin } from '@tanstack/vue-query' import { WagmiPlugin } from '@wagmi/vue' import { createApp } from 'vue' import App from './App.vue' import { config } from './wagmi' createApp(App) // 2. Inject the Wagmi plugin. .use(WagmiPlugin, { config }) // 3. Inject the Vue Query plugin. .use(VueQueryPlugin, {}) .mount('#app') ``` ```ts [config.ts] import { http, createConfig } from '@wagmi/vue' import { base, mainnet, optimism } from '@wagmi/vue/chains' import { injected, metaMask, safe, walletConnect } from '@wagmi/vue/connectors' const projectId = '' export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), }, }) ``` ::: ### 4. Display Connection Lastly, if an connection is made, we want to show some basic information, like the connected address and ENS name and avatar. Below, we are using hooks like `useConnection`, `useEnsAvatar` and `useEnsName` to extract this information. We are also utilizing `useDisconnect` to show a "Disconnect" button so a user can disconnect their wallet. ::: code-group ```vue [Connection.vue] ``` ```vue [Connect.vue] ``` ```vue [App.vue] ``` ```ts [main.ts] // 1. Import modules. import { VueQueryPlugin } from '@tanstack/vue-query' import { WagmiPlugin } from '@wagmi/vue' import { createApp } from 'vue' import App from './App.vue' import { config } from './wagmi' createApp(App) // 2. Inject the Wagmi plugin. .use(WagmiPlugin, { config }) // 3. Inject the Vue Query plugin. .use(VueQueryPlugin, {}) .mount('#app') ``` ```ts [config.ts] import { http, createConfig } from '@wagmi/vue' import { base, mainnet, optimism } from '@wagmi/vue/chains' import { injected, metaMask, safe, walletConnect } from '@wagmi/vue/connectors' const projectId = '' export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), }, }) ``` ::: ### 5. Wire it up! Finally, we can wire up our Connect and Connection components to our application's entrypoint. ::: code-group ```vue [App.vue] ``` ```vue [Connection.vue] ``` ```vue [Connect.vue] ``` ```ts [main.ts] // 1. Import modules. import { VueQueryPlugin } from '@tanstack/vue-query' import { WagmiPlugin } from '@wagmi/vue' import { createApp } from 'vue' import App from './App.vue' import { config } from './wagmi' createApp(App) // 2. Inject the Wagmi plugin. .use(WagmiPlugin, { config }) // 3. Inject the Vue Query plugin. .use(VueQueryPlugin, {}) .mount('#app') ``` ```ts [config.ts] import { http, createConfig } from '@wagmi/vue' import { base, mainnet, optimism } from '@wagmi/vue/chains' import { injected, metaMask, safe, walletConnect } from '@wagmi/vue/connectors' const projectId = '' export const config = createConfig({ chains: [mainnet, base], connectors: [ injected(), walletConnect({ projectId }), metaMask(), safe(), ], transports: { [mainnet.id]: http(), [base.id]: http(), }, }) ``` ::: ### Playground Want to see the above steps all wired up together in an end-to-end example? Check out the below StackBlitz playground.
================================================ FILE: site/vue/guides/error-handling.md ================================================ # Error Handling The `error` property in Wagmi Composables is strongly typed with it's corresponding error type. This enables you to have granular precision with handling errors in your application. You can discriminate the error type by using the `name` property on the error object. ::: code-group ```vue twoslash [index.vue] // @twoslash-cache: {"v":1,"hash":"26fedaeea151ddba71fa403843f00ead34374f64e5dd13dafc27e1465b3af479","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgAhVhBEBrAHKCAtgCMyAHhGT+7AOa86NMFDi8AwoZO8AvLfvGKvEfmbswASShm9DCW1gZgRsbIADognt5gcDEAushgmjqkKTHsUMlOHq7RsV4+iSApadpkWSA5ye6yrDBiACLMa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IELIjKYt5+Tr6J6tbJS7696sJbgcLBY8Iax8Km4Rb3gW7RbW7iK24wj26GRyJATO5mRKLiJpYZb2Q6J6LOTJJ5ZB6eTeSV6UTS5BTYEOI1ZkJygEHK4b5yjJ5d5AG+YZ6gED59aRIDazpTY5r45Q7yqGFDYlozZ1JzaNILYHa1oraNr9I4xDIjKzqdo+B7ZoYfInYVKjow4DqnIPaLqc4novZQDPKvLvYA45D7rfbRHhFA6hElIg4IrXLIrg63oYoQZPqo4xBw62oI5I5Pa45074YM4DqlEmE5HY6zrE7JExBmaSpk5eFU6zpYbM5lG1F3YdEkYGreDkYc4VFc4NEgA843YfIfQEg1yeAeFgB875xyhmKC6sZEyXSoHUIzhhqYF8Y4Hy4hryjKGUJxRFzEHSZaE65sJu5UHEKni0HXj0GsBRaaQvg26SJ24JZGRcEu4pbKL8Fe6Za+7CEB5GISHi7h5v64KVaf4sSx4HHUKlaEFxRihnFp5pR946FH4GCwCzBITChq5mJ0QbHCguJz7lZIC7EOLYnBrOJ6hq5t48Sijq4aFCTgx75yaH7Z7Um4n4lmKEnEmkkyG9iL7ojUlx70l/5UJMmomkHon77ybZ4QE55n7QHsBX56a34IH35IGP7EnthCkf78Zf54HwkFzV5ImMkCyGjQBSZ/AiAHRYDJhvBYAJjgTGCOAxDYTrxfwQg8oWx/xG4OwWgCA7gaC8AADkRIJI7A4ZoIoIkk/ppYzA7g2kwZzgRCaCZAjA3AcZa8oYHCUwZIQauZJZeZuguI60Dp/QuZugNAEIiYNAII10ugTmvARASEIEHpjiBZRZWwTgjgzg4ZQ+12NqMSsZIATZoMCSypnwawbuOkaY7wNIUA+cX0Y+OIFswAbuo+xevAFoFok05ZTmTZh5rZ7ZpwsgHZ/AXZkEhZQa/Zg5BR76iOn6wq45k5LUzwGyCYeKUkRRn6+cdgOJm5251Je5B5zZuIx5oI5ZdZw6GyfQSItUzASAoA5gwQcAqKeARAdYIA+5QAA==="} ``` <<< @/snippets/vue/config.ts[config.ts] ::: ================================================ FILE: site/vue/guides/faq.md ================================================ # FAQ / Troubleshooting Collection of frequently asked questions with ideas on how to troubleshoot and resolve them. ================================================ FILE: site/vue/guides/read-from-contract.md ================================================ # Read from Contract ## Overview The [`useReadContract` Composable](/vue/api/composables/useReadContract) allows you to read data on a smart contract, from a `view` or `pure` (read-only) function. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas. The component below shows how to retrieve the token balance of an address from the [Wagmi Example](https://etherscan.io/token/0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2) contract :::code-group ```vue [ReadContract.vue] ``` ```ts [contracts.ts] export const wagmiContractConfig = { address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: [ { type: 'function', name: 'balanceOf', stateMutability: 'view', inputs: [{ name: 'account', type: 'address' }], outputs: [{ type: 'uint256' }], }, { type: 'function', name: 'totalSupply', stateMutability: 'view', inputs: [], outputs: [{ name: 'supply', type: 'uint256' }], }, ], } as const ``` ::: If `useReadContract` depends on another value (`address` in the example below), you can use the [`query.enabled`](/vue/api/composables/useReadContract#enabled) option to prevent the query from running until the dependency is ready. ```tsx const { data: balance } = useReadContract({ ...wagmiContractConfig, functionName: 'balanceOf', args: [address], query: { // [!code focus] enabled: !!address, // [!code focus] }, // [!code focus] }) ``` ## Loading & Error States The [`useReadContract` Composable](/vue/api/composables/useReadContract) also returns loading & error states, which can be used to display a loading indicator while the data is being fetched, or an error message if contract execution reverts. :::code-group ```vue [ReadContract.vue] ``` ::: ================================================ FILE: site/vue/guides/send-transaction.md ================================================ # Send Transaction The following guide teaches you how to send transactions in Wagmi. The example below builds on the [Connect Wallet guide](/vue/guides/connect-wallet) and uses the [useSendTransaction](/vue/api/composables/useSendTransaction) & [useWaitForTransactionReceipt](/vue/api/composables/useWaitForTransactionReceipt) composables. ## Example Feel free to check out the example before moving on: ## Steps ### 1. Connect Wallet Follow the [Connect Wallet guide](/vue/guides/connect-wallet) guide to get this set up. ### 2. Create a new component Create your `SendTransaction` component that will contain the send transaction logic. ::: code-group ```tsx [SendTransaction.vue] ``` ::: ### 3. Add a form handler Next, we will need to add a handler to the form that will send the transaction when the user hits "Send". This will be a basic handler in this step. ::: code-group ```vue [SendTransaction.vue] ``` ::: ### 4. Hook up the `useSendTransaction` Composable Now that we have the form handler, we can hook up the [`useSendTransaction` Composable](/vue/api/composables/useSendTransaction) to send the transaction. ::: code-group ```vue [SendTransaction.vue] ``` ::: ### 5. Add loading state (optional) We can optionally add a loading state to the "Send" button while we are waiting confirmation from the user's wallet. ::: code-group ```vue [SendTransaction.vue] ``` ::: ### 6. Wait for transaction receipt (optional) We can also display the transaction confirmation status to the user by using the [`useWaitForTransactionReceipt` Composable](/vue/api/composables/useWaitForTransactionReceipt). ::: code-group ```vue [SendTransaction.vue] ``` ::: ### 7. Handle errors (optional) If the user rejects the transaction, or the user does not have enough funds to cover the transaction, we can display an error message to the user. ::: code-group ```vue [SendTransaction.vue] ``` ::: ### 8. Wire it up! Finally, we can wire up our Send Transaction component to our application's entrypoint. :::code-group ```vue [App.vue] ``` ```vue [SendTransaction.vue] ``` ::: [See the Example.](#example) ================================================ FILE: site/vue/guides/ssr.md ================================================ --- outline: deep --- # SSR Wagmi uses client-only external stores (such as `localStorage` and `mipd`) to show the user the most relevant data as quickly as possible on first render. However, the caveat of using these external client stores is that frameworks which incorporate SSR (such as Next.js) will throw hydration warnings on the client when it identifies mismatches between the server-rendered HTML and the client-rendered HTML. To stop this from happening, you can toggle on the [`ssr`](/vue/api/createConfig#ssr) property in the Wagmi Config. ```tsx import { createConfig, http } from '@wagmi/vue' import { mainnet, sepolia } from '@wagmi/vue/chains' const config = createConfig({ // [!code focus:99] chains: [mainnet, sepolia], ssr: true, // [!code ++] transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` Turning on the `ssr` property means that content from the external stores will be hydrated on the client after the initial mount. ## Persistence using Cookies As a result of turning on the `ssr` property, external persistent stores like `localStorage` will be hydrated on the client **after the initial mount**. This means that you will still see a flash of "empty" data on the client (e.g. a `"disconnected"` account instead of a `"reconnecting"` account, or an empty address instead of the last connected address) until after the first mount, when the store hydrates. In order to persist data between the server and the client, you can use cookies. ### 1. Set up cookie storage First, we will set up cookie storage in the Wagmi Config. ```tsx import { createConfig, http, cookieStorage, // [!code ++] createStorage // [!code ++] } from '@wagmi/vue' import { mainnet, sepolia } from '@wagmi/vue/chains' export const config = createConfig({ chains: [mainnet, sepolia], ssr: true, storage: createStorage({ // [!code ++] storage: cookieStorage, // [!code ++] }), // [!code ++] transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` ### 2. Hydrate the cookie Next, we will need to add some mechanisms to hydrate the stored cookie in Wagmi. #### Nuxt.js Would you like to contribute this content? Feel free to [open a Pull Request](https://github.com/wevm/wagmi/pulls)! #### Vanilla SSR Would you like to contribute this content? Feel free to [open a Pull Request](https://github.com/wevm/wagmi/pulls)! ================================================ FILE: site/vue/guides/tanstack-query.md ================================================ # TanStack Query Wagmi Composables are not only a wrapper around the core [Wagmi Actions](/core/api/actions), but they also utilize [TanStack Query](https://tanstack.com/query/v5) to enable trivial and intuitive fetching, caching, synchronizing, and updating of asynchronous data in your Vue applications. Without an asynchronous data fetching abstraction, you would need to handle all the negative side-effects that comes as a result, such as: representing finite states (loading, error, success), handling race conditions, caching against a deterministic identifier, etc. ## Queries & Mutations Wagmi Composables represent either a **Query** or a **Mutation**. **Queries** are used for fetching data (e.g. fetching a block number, reading from a contract, etc), and are typically invoked on mount by default. All queries are coupled to a unique [Query Key](#query-keys), and can be used for further operations such as refetching, prefetching, or modifying the cached data. **Mutations** are used for mutating data (e.g. connecting/disconnecting accounts, writing to a contract, switching chains, etc), and are typically invoked in response to a user interaction. Unlike **Queries**, they are not coupled with a query key. ## Terms - **Query**: An asynchronous data fetching (e.g. read data) operation that is tied against a unique Query Key. - **Mutation**: An asynchronous mutating (e.g. create/update/delete data or side-effect) operation. - **Query Key**: A unique identifier that is used to deterministically identify a query. It is typically a tuple of the query name and the query arguments. - **Stale Data**: Data that is unused or inactive after a certain period of time. - **Query Fetching**: The process of invoking an async query function. - **Query Refetching**: The process of refetching **rendered** queries. - **[Query Invalidation](https://tanstack.com/query/v5/docs/vue/guides/query-invalidation)**: The process of marking query data as stale (e.g. inactive/unused), and refetching **rendered** queries. - **[Query Prefetching](https://tanstack.com/query/v5/docs/vue/guides/prefetching)**: The process of prefetching queries and seeding the cache. ## Query Keys Query Keys are typically used to perform advanced operations on the query such as: invalidation, refetching, prefetching, etc. Wagmi exports Query Keys for every Composable, and they can be retrieved via the [Composable (Vue)](#composable-vue) or via an [Import (Vanilla JS)](#import-vanilla-js). Read more about **Query Keys** on the [TanStack Query docs.](https://tanstack.com/query/v5/docs/vue/guides/query-keys) ### Composable (Vue) Each Composable returns a `queryKey` value. You would use this approach when you want to utilize the query key in a Vue component as it handles reactivity for you, unlike the [Import](#import-vanilla-js) method below. ```vue [index.vue] ``` ### Import (Vanilla JS) Each Hook has a corresponding `getQueryOptions` function that returns a query key. You would use this method when you want to utilize the query key outside of a Vue component in a Vanilla JS context, like in a utility function. ```ts import { getBalanceQueryOptions } from '@wagmi/vue/query' // [!code hl] import { config } from './config' function perform() { const { queryKey } = getBalanceQueryOptions(config, { // [!code hl] chainId: config.state.chainId // [!code hl] }) // [!code hl] } ``` ::: warning The caveat of this method is that it does not handle reactivity for you (e.g. active account/chain changes, argument changes, etc). You would need to handle this yourself by explicitly passing through the arguments to `getQueryOptions`. ::: ## Invalidating Queries Invalidating a query is the process of marking the query data as stale (e.g. inactive/unused), and refetching the queries that are already rendered. Read more about **Invalidating Queries** on the [TanStack Query docs.](https://tanstack.com/query/v5/docs/vue/guides/query-invalidation) #### Example: Watching a Users' Balance You may want to "watch" a users' balance, and invalidate the balance after each incoming block. We can invoke `invalidateQueries` inside a `watchEffect` – this will refetch all rendered balance queries when the `blockNumber` changes. ```vue ``` #### Example: After User Interaction Maybe you want to invalidate a users' balance after some interaction. This would mark the balance as stale, and consequently refetch all rendered balance queries. ```vue ``` ```vue ``` ## Fetching Queries Fetching a query is the process of invoking the query function to retrieve data. If the query exists and the data is not invalidated or older than a given `staleTime`, then the data from the cache will be returned. Otherwise, the query will fetch for the latest data. ::: code-group ```tsx [example.tsx] import { getBlockQueryOptions } from '@wagmi/vue/query' import { queryClient } from './main' import { config } from './config' export async function fetchBlockData() { return queryClient.fetchQuery( // [!code hl] getBlockQueryOptions(config, { // [!code hl] chainId: config.state.chainId, // [!code hl] } // [!code hl] )) // [!code hl] } ``` <<< @/snippets/vue/main.ts[main.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ## Retrieving & Updating Query Data You can retrieve and update query data imperatively with `getQueryData` and `setQueryData`. This is useful for scenarios where you want to retrieve or update a query outside of a Vue component. Note that these functions do not invalidate or refetch queries. ::: code-group ```tsx [example.tsx] import type { GetBalanceReturnType } from '@wagmi/vue/actions' import { getBalanceQueryOptions } from '@wagmi/vue/query' import { queryClient } from './app' import { config } from './config' export function getBalanceData() { return queryClient.getQueryData( // [!code hl] getBalanceQueryOptions(config, { // [!code hl] chainId: config.state.chainId, // [!code hl] } // [!code hl] )) // [!code hl] } export function setBalanceData(parameters: Partial) { return queryClient.setQueryData( // [!code hl] getBalanceQueryOptions(config, { // [!code hl] chainId: config.state.chainId, // [!code hl] }, // [!code hl] data => ({ ...data, ...parameters }) // [!code hl] )) // [!code hl] } ``` <<< @/snippets/vue/main.ts[main.ts] <<< @/snippets/vue/config.ts[config.ts] ::: ## Prefetching Queries Prefetching a query is the process of fetching the data ahead of time and seeding the cache with the returned data. This is useful for scenarios where you want to fetch data before the user navigates to a page, or fetching data on the server to be reused on client hydration. Read more about **Prefetching Queries** on the [TanStack Query docs.](https://tanstack.com/query/v5/docs/vue/guides/prefetching) #### Example: Prefetching in Event Handler ```vue ``` ## SSR It is possible to utilize TanStack Query's SSR strategies with Wagmi Composables & Query Keys. Check out the [SSR guide](https://tanstack.com/query/latest/docs/framework/vue/guides/ssr). ## Devtools TanStack Query includes dedicated [Devtools](https://tanstack.com/query/latest/docs/framework/vue/devtools) that assist in visualizing and debugging your queries, their cache states, and much more. You will have to pass a custom `queryKeyFn` to your `QueryClient` for Devtools to correctly serialize BigInt values for display. Alternatively, You can use the `hashFn` from `@wagmi/core/query`, which already handles this serialization. #### Install ::: code-group ```bash [pnpm] pnpm i @tanstack/vue-query-devtools ``` ```bash [npm] npm i @tanstack/vue-query-devtools ``` ```bash [yarn] yarn add @tanstack/vue-query-devtools ``` ```bash [bun] bun i @tanstack/vue-query-devtools ``` ::: #### Usage ::: code-group ```vue [App.vue] ``` ```vue [main.vue] ``` ::: ================================================ FILE: site/vue/guides/viem.md ================================================ # Viem [Viem](https://viem.sh) is a low-level TypeScript Interface for Ethereum that enables developers to interact with the Ethereum blockchain, including: JSON-RPC API abstractions, Smart Contract interaction, wallet & signing implementations, coding/parsing utilities and more. **Wagmi Core** is essentially a wrapper over **Viem** that provides multi-chain functionality via [Wagmi Config](/react/api/createConfig) and automatic account management via [Connectors](/react/api/connectors). ## Leveraging Viem Actions All of the core [Wagmi Composables](/vue/api/composables) are friendly wrappers around [Viem Actions](https://viem.sh/docs/actions/public/introduction) that inject a multi-chain and connector aware [Wagmi Config](/vue/api/createConfig). There may be cases where you might want to dig deeper and utilize Viem Actions directly (maybe a Composable doesn't exist in Wagmi yet). In these cases, you can create your own custom Wagmi Composable by importing Viem Actions directly via `viem/actions` and plugging in a Viem Client returned by the [`useClient` Composable](/vue/api/composables/useClient). There are two categories of Viem Actions: - **[Public Actions](https://viem.sh/docs/actions/public/introduction):** Actions that are "read-only" and do not require a wallet connection. - **[Wallet Actions](https://viem.sh/docs/actions/wallet/introduction):** Actions that interface with a Wallet and require a wallet connection. While it is not mandatory, it is also recommended to pair Actions with either `useQuery` or `useMutation` to effectively leverage the reactivity and caching capabilities of [Tanstack Query](/vue/guides/tanstack-query). ### Public Actions The example below demonstrates how to utilize Viem's `getLogs` Action with a `useQuery` Composable to create your own abstraction akin to a `useLogs` Composable. ```vue ``` ### Wallet Actions The example below demonstrates how to utilize Viem's `watchAsset` Action with a `useMutation` Composable to create your own abstraction akin to a `useWatchAsset` Composable. ```vue ``` ## Private Key & Mnemonic Accounts It is possible to utilize Viem's [Private Key & Mnemonic Accounts](https://viem.sh/docs/accounts/local) with Wagmi by explicitly passing through the account via the `account` argument on Wagmi Actions. ```vue ``` ::: info Wagmi currently does not support hoisting Private Key & Mnemonic Accounts to the top-level Wagmi Config – meaning you have to explicitly pass through the account to every Action. If you feel like this is a feature that should be added, please [open an discussion](https://github.com/wevm/wagmi/discussions/new?category=ideas). ::: ================================================ FILE: site/vue/guides/write-to-contract.md ================================================ # Write to Contract The [`useWriteContract` Composable](/vue/api/composables/useWriteContract) allows you to mutate data on a smart contract, from a `payable` or `nonpayable` (write) function. These types of functions require gas to be executed, hence a transaction is broadcasted in order to change the state. In the guide below, we will teach you how to implement a "Mint NFT" form that takes in a dynamic argument (token ID) using Wagmi. The example below builds on the [Connect Wallet guide](/vue/guides/connect-wallet) and uses the [useWriteContract](/vue/api/composables/useWriteContract) & [useWaitForTransactionReceipt](/vue/api/composables/useWaitForTransactionReceipt) composables. If you have already completed the [Sending Transactions guide](/vue/guides/send-transaction), this guide will look very similar! That's because writing to a contract internally broadcasts & sends a transaction. ## Example Feel free to check out the example before moving on: ## Steps ### 1. Connect Wallet Follow the [Connect Wallet guide](/vue/guides/connect-wallet) guide to get this set up. ### 2. Create a new component Create your `MintNft` component that will contain the Mint NFT logic. ::: code-group ```vue [MintNft.vue] ``` ::: ### 3. Add a form handler Next, we will need to add a handler to the form that will send the transaction when the user hits "Mint". This will be a basic handler in this step. ::: code-group ```vue [MintNft.vue] ``` ::: ### 4. Hook up the `useWriteContract` Composable Now that we have the form handler, we can hook up the [`useWriteContract` Composable](/vue/api/composables/useWriteContract) to send the transaction. ::: code-group ```vue [MintNft.vue] ``` ```ts [abi.ts] export const abi = [ { name: 'mint', type: 'function', stateMutability: 'nonpayable', inputs: [{ internalType: 'uint32', name: 'tokenId', type: 'uint32' }], outputs: [], }, ] as const ``` ::: ### 5. Add loading state (optional) We can optionally add a loading state to the "Mint" button while we are waiting confirmation from the user's wallet. ::: code-group ```vue [MintNft.vue] ``` ```ts [abi.ts] export const abi = [ { name: 'mint', type: 'function', stateMutability: 'nonpayable', inputs: [{ internalType: 'uint32', name: 'tokenId', type: 'uint32' }], outputs: [], }, ] as const ``` ::: ### 6. Wait for transaction receipt (optional) We can also display the transaction confirmation status to the user by using the [`useWaitForTransactionReceipt` Composable](/vue/api/composables/useWaitForTransactionReceipt). ::: code-group ```vue [MintNft.vue] ``` ```ts [abi.ts] export const abi = [ { name: 'mint', type: 'function', stateMutability: 'nonpayable', inputs: [{ internalType: 'uint32', name: 'tokenId', type: 'uint32' }], outputs: [], }, ] as const ``` ::: ### 7. Handle errors (optional) If the user rejects the transaction, or the user does not have enough funds to cover the transaction, we can display an error message to the user. ::: code-group ```vue [MintNft.vue] ``` ```ts [abi.ts] export const abi = [ { name: 'mint', type: 'function', stateMutability: 'nonpayable', inputs: [{ internalType: 'uint32', name: 'tokenId', type: 'uint32' }], outputs: [], }, ] as const ``` ::: ### 8. Wire it up! Finally, we can wire up our Send Transaction component to our application's entrypoint. :::code-group ```vue [App.vue] ``` ```vue [MintNft.vue] ``` ```ts [abi.ts] export const abi = [ { name: 'mint', type: 'function', stateMutability: 'nonpayable', inputs: [{ internalType: 'uint32', name: 'tokenId', type: 'uint32' }], outputs: [], }, ] as const ``` ::: [See the Example.](#example) ================================================ FILE: site/vue/installation.md ================================================ # Installation Install Wagmi via your package manager, a ` # TypeScript ## Requirements Wagmi is designed to be as type-safe as possible! Things to keep in mind: - Types currently require using TypeScript {{typescriptVersion}}. - [TypeScript doesn't follow semver](https://www.learningtypescript.com/articles/why-typescript-doesnt-follow-strict-semantic-versioning) and often introduces breaking changes in minor releases. - Changes to types in this repository are considered non-breaking and are usually released as patch changes (otherwise every type enhancement would be a major version!). - It is highly recommended that you lock your `wagmi` and `typescript` versions to specific patch releases and upgrade with the expectation that types may be fixed or upgraded between any release. - The non-type-related public API of Wagmi still follows semver very strictly. To ensure everything works correctly, make sure your `tsconfig.json` has [`strict`](https://www.typescriptlang.org/tsconfig#strict) mode set to `true`. ::: code-group ```json [tsconfig.json] { "compilerOptions": { "strict": true } } ``` ::: ## Config Types By default Vue Plugins does not work well with type inference. To support strong type-safety across the Vue Plugins boundary, there are two options available: - Declaration merging to "register" your `config` globally with TypeScript. - `config` property to pass your `config` directly to composables. ### Declaration Merging [Declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) allows you to "register" your `config` globally with TypeScript. The `Register` type enables Wagmi to infer types in places that wouldn't normally have access to type info via a Vue Plugin alone. To set this up, add the following declaration to your project. Below, we co-locate the declaration merging and the `config` set up. ```ts import { createConfig, http } from '@wagmi/vue' import { mainnet, sepolia } from 'wagmi/chains' declare module '@wagmi/vue' { // [!code focus] interface Register { // [!code focus] config: typeof config // [!code focus] } // [!code focus] } // [!code focus] export const config = createConfig({ chains: [mainnet, sepolia], transports: { [mainnet.id]: http(), [sepolia.id]: http(), }, }) ``` Since the `Register` type is global, you only need to add it once in your project. Once set up, you will get strong type-safety across your entire project. For example, query composables will type `chainId` based on your `config`'s `chains`. ```ts twoslash // @twoslash-cache: {"v":1,"hash":"21ee40fb2fb12112e58ba8b16f5d7f9ef29efdee74e4bd47b38d17e1aa2e8800","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgAhVhBEBrAHKCAtgCMyAHhGT+7AOa86NMFDi8AwoZO8AvLfvHdpGMyiTWGXqgAdKV4QrUUVAFFaLEUPUjhEXmAgkNTUjy8fP1h+ZkFWNETk4LTS3gzvMF9eMGYNGESAkAi0fDI4EWYwJoBuFLLSiqzpUlZGgjQ0LASAehmYVvbOsAA6CV7+gfTPSurmLHYAVVHx/EnpxDn99hWFtvjltYgZ642S0oBfPvevzd4wpTKAAq7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Py7sjae+aPujh2Gpdj2we8KHofTrX46TjhfzzouK4tVZW47uwe6JDYh5oMew4ESZn6uQ+T692+H43t+Th/gBQEgUl4GQV0MG8PBwg5KRqHoZhfxd2AHz4ee4IH6OMZ2jG4LnnpxgGUZM8rxZVmhbtEWOVIM5We7RJ4rGCtZAq41AHRVivFRKYDMpEj6rlT6/99rkCoGVCqpMar1UajcFqbUOpsx6kBfqg14AjSgd9QBk1pqzT5BqBaeJlr4FWnydaV5NqzRADtQqE0FonyQJCM6xELq3hOjdagd1KpkEApgkAU0ryzULCwpaK1ECCjOtAXAiBFSQlESAIwi1Px4FIrAWgKwZYlT4ngeRABaAxkIHF+wVA4wUT1zB4ASjgXgAByKECp/G8BAjUCAeUuBwBMLUMIMBeBoAgAkxKAT1JciwAAWWYBgHQFJ+C6DvvBZ+T8Yz3yPkhE+UATz+JWIdGAJBWD2NIAow6wj9FiI/JdcgiAyzSMwDge6xADrrW8ZVYygEcAzQwHwLyFErJpJgJk7JuSkIFPvsUjUz8ymIWQqhE89CVFIDUSARabCkDaOoNwralVZlQFacddp4lxHSyur03COjYDmJQTNJIaCBGAObgIQCGgAkAAF8HAWITAfxQQgj8OgVxRgwBCLEVIhRCEipm7cBKjeZgSBQDmCVhIMAeAbEfA+EAA"} // @errors: 2322 import { type Config } from '@wagmi/vue' import { mainnet, sepolia } from 'wagmi/chains' declare module '@wagmi/vue' { interface Register { config: Config } } // ---cut--- import { useBlockNumber } from '@wagmi/vue' useBlockNumber({ chainId: 123 }) ``` You just saved yourself a runtime error and you didn't even need to pass your `config`. 🎉 ### Hook `config` Property For cases where you have more than one Wagmi `config` or don't want to use the declaration merging approach, you can pass a specific `config` directly to composables via the `config` property. ```ts import { createConfig, http } from '@wagmi/vue' import { mainnet, optimism } from '@wagmi/vue/chains' export const configA = createConfig({ // [!code focus] chains: [mainnet], // [!code focus] transports: { // [!code focus] [mainnet.id]: http(), // [!code focus] }, // [!code focus] }) // [!code focus] export const configB = createConfig({ // [!code focus] chains: [optimism], // [!code focus] transports: { // [!code focus] [optimism.id]: http(), // [!code focus] }, // [!code focus] }) // [!code focus] ``` As you expect, `chainId` is inferred correctly for each `config`. ```ts twoslash // @twoslash-cache: {"v":1,"hash":"9b5b0298b470a179bc3ea33df03ba8ced7d88ec92e62fe07acf70060b35435dd","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgAhVhBEBrAHKCAtgCMyAHhGT+7AOa86NMFDi8AwoZO8AvLfvGKvEfmbswASShm9DCW1gZgRsbIADognt5gcDEAushgmjqkKTHsUMlOHq7RsV4+iSApadpkWSA5ye6yrDBiACLMaMz5WiY+aAB8jFjMpMwaMDSkcAD6APyIvACqsgpKaulkAArDo+NkcPqu7nE+/g0wTa3tzH3c80vyiirqVaQASuOCpGAAKtgwuo1mmg2h0+lEwOwNFgIKQ0NJlo81i9KCAoEoEIgCGg0Fg4IgAPT4gDuzGMGnYADo4Ph8URBDB8cwsOx8QYoRA4MwtE04PiZA9Vs8Mii4B1YUgAJxUJpgYxofBIACMABYqGLjOM8PyVk91uRpT5cIgAAxUOIjMRkSUAXwo6D+eEIJH11HMTDYnB48IFupeujs4RMulIMGYaLArAwvFQ4N4cd43NWAFFaFhFCHJvNgLH47mQ2HJJHeLB+MxBKw0Fmc7ma7x8+Gi2AdvMYkn5XsRMwwDEANzV2vx+uFqOfVgtrE4vGE8b4DtdikSXv9gd10MNqNM9gLUhj3gxfDY3EExnMikzudgBcQE/sJdSAfWvv3uOP/uJlTfSEweaKgBMxoAp9czCNALTQPFeGzZ8ayHCMo2COAFghZ1OVYd44AgVhnSraCV1goswygEM4AgmJjVoGBKKoyiVSgAB2RUAA4RF/LRlToqAJQlX8AGZYC5RUeJ4gBWGAVWVai7xXPM12HBNERsfMaCgeZeONRjhM0xigIfHTa3wqMNHLcRO1YVgeJw6TB1kuDeEI4jSJAcjO0VRUtFgY1hIlOi6K0HiADYeNc/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9p/PtoduIv8mdt3yHUopHWahougknR4pnS2R2UvzGjYo4vv14HOUuS2j4r2Ff0Ev3U/zeTEqCLkqkrAEvQUvFh4nvXkLvmfSfhllMuMDkE0riJELRQlC+iUKSNwJhDhGAAJnlj1EmQED3STgAAFyCWRqDE5wRwQ+DUDGBZ6GiDUhCBiTB5h+6SVJluAd6YC96D6cj/Aj6jhXAz7XA5BL6UQlpmAkBQBzAEIJAwA8BvZrRrQgA"} // @errors: 2322 import { type Config } from '@wagmi/vue' import { mainnet, optimism } from '@wagmi/vue/chains' declare const configA: Config declare const configB: Config // ---cut--- import { useBlockNumber } from '@wagmi/vue' useBlockNumber({ chainId: 123, config: configA }) useBlockNumber({ chainId: 123, config: configB }) ``` This approach is more explicit, but works well for advanced use-cases, if you don't want to use a Vue Plugin or declaration merging, etc. ## Const-Assert ABIs & Typed Data Wagmi can infer types based on [ABIs](https://docs.soliditylang.org/en/latest/abi-spec.html#json) and [EIP-712](https://eips.ethereum.org/EIPS/eip-712) Typed Data definitions, powered by [Viem](https://viem.sh) and [ABIType](https://github.com/wevm/abitype). This achieves full end-to-end type-safety from your contracts to your frontend and enlightened developer experience by autocompleting ABI item names, catching misspellings, inferring argument and return types (including overloads), and more. For this to work, you must either [const-assert](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions) ABIs and Typed Data (more info below) or define them inline. For example, `useReadContract`'s `abi` configuration parameter: ```ts const { data } = useReadContract({ abi: […], // <--- defined inline // [!code focus] }) ``` ```ts const abi = […] as const // <--- const assertion // [!code focus] const { data } = useReadContract({ abi }) ``` If type inference isn't working, it's likely you forgot to add a `const` assertion or define the configuration parameter inline. Also, make sure your ABIs, Typed Data definitions, and [TypeScript configuration](#requirements) are valid and set up correctly. ::: tip Unfortunately [TypeScript doesn't support importing JSON `as const` yet](https://github.com/microsoft/TypeScript/issues/32063). Check out the [Wagmi CLI](/cli/getting-started) to help with this! It can automatically fetch ABIs from Etherscan and other block explorers, resolve ABIs from your Foundry/Hardhat projects, generate Vue Composables, and more. ::: Anywhere you see the `abi` or `types` configuration property, you can likely use const-asserted or inline ABIs and Typed Data to get type-safety and inference. These properties are also called out in the docs. Here's what [`useReadContract`](/vue/api/composables/useReadContract) looks like with and without a const-asserted `abi` property. ::: code-group ```ts twoslash [Const-Asserted] // @twoslash-cache: {"v":1,"hash":"c81ecea55f2b27ad2c18ae6e5fc3ad6aed33ef72a35b2bb465243c2101cb267c","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgAlGMygBhSWlLMxAHhGS4aXswBG7XnRpgocXgEETvAD69SiqJNYZpYANaQA7mDIALoUAsJiEmAAcswAtjBm9DCW1qpg6ppoAGLh4pIx8VrG7KEAOiBYgi7ljrzlROwwfuUAfKHMpADm1ubJVrxpGWI5onlgNl1wRSZlFVUwNU71jc2UYaORBTBtvLpg/OydiRb9aQdHALwDkuehsqwwYgAizGjMvFcKSoMaz6/M0xK6wi+TiMHakxaLUYWA6YJopDgAH0APyIXgAVVkXxUal+aAACnD4gipsVQkINqD4hDuqE9rdePdHmgXm8Wtx0Vj5K4fpkFGgqmAACrYGCAim5TZg2lwO4wB5/dmlMDsWJYCCkAwyHnfPGZSggNwiBCIAhoNBYOCIAD0Nr8zE6sXYADo4PgbURBDAbcwsOwbYQIN44DadTi+WJDfoOgxEABOKgPMCdND4JAARgArFQ3l0YHGQOHefqo0n2GBcIgAAxUET4OFiMhIeMAXwo6DFeEIJHIufMeD2+l4UH+6IU/C0wlgB0rUBatQnWhMnQraBahuNppAwvwCVYXAMcEEIhE8DgQlYHmc8AgrBIUBH/wEmt4aYSAEdvaQMC7o3m4yzAAWJNklTdNEBA6gOk6As8FHN5DQ4SskAAJjrBt8WbRAAA5207HBu2IZt+3oJg2E4HhpGxEt0nxLQXCUdxPFQFVeHYm8mLAa8wDBdFyiMNhmFEGAAHl+HKABuNiOMYtxuM8TAcH4kBKRBMApJ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3eO+JGB41keiYHq8N5bx3nvA+R8oAnzPhfK+t976P2fq/d+n9v6/2BxQGSxR0QNtBeCpnNkb3JOB5O+9jPYcaSF+xRTsHse0EQ8h1D6HMPYdwxpvTxHSPkco9R2j9HGMwGByEcx3BBdBZVIaEkzAkCgF6GAOAkQ8BORAK2VsQA"} const erc721Abi = [ { name: 'balanceOf', type: 'function', stateMutability: 'view', inputs: [{ type: 'address', name: 'owner' }], outputs: [{ type: 'uint256' }], }, { name: 'isApprovedForAll', type: 'function', stateMutability: 'view', inputs: [ { type: 'address', name: 'owner' }, { type: 'address', name: 'operator' }, ], outputs: [{ type: 'bool' }], }, { name: 'getApproved', type: 'function', stateMutability: 'view', inputs: [{ type: 'uint256', name: 'tokenId' }], outputs: [{ type: 'address' }], }, { name: 'ownerOf', type: 'function', stateMutability: 'view', inputs: [{ type: 'uint256', name: 'tokenId' }], outputs: [{ type: 'address' }], }, { name: 'tokenURI', type: 'function', stateMutability: 'pure', inputs: [{ type: 'uint256', name: 'tokenId' }], outputs: [{ type: 'string' }], }, ] as const // ---cut--- import { useReadContract } from '@wagmi/vue' const { data } = useReadContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: erc721Abi, functionName: 'balanceOf', // ^? args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'], // ^? }) data // ^? ``` ```ts twoslash [Not Const-Asserted] // @twoslash-cache: {"v":1,"hash":"fd8f5c57d72097f21d1a246c1505fe478b32857ce6eeba0f9c882f247122d11d","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgAlGMygBhSWlLMxAHhGS4aXswBG7XnRpgocXgEETvAD69SiqJNYZpYANaQA7mDIALoUAsJiEmAAcswAtjBm9DCW1qpg6ppoAGLh4pIx8VrG7KEAOiBYgi7ljrzlROwwfuUAfKHMpADm1ubJVrxpGWI5onlgNl1wRSZlFVUwNU71jc2UYaORBT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ArNsJEbDAOlmAUIAUST6tsPjSXDf4ZQw/4aWs0N+MRBQ8o/1jJBsNlkBkzApBDdzaDYLNF23YQctkMQKu9cw8hEBQk2DMI3tDRoUibawO2HcwZ2TBRsbzKJqG0YmxefreKSZP+9gFIx7zgb61H3PR1ewaY97d423zEacxbtNP18IZP6ar/8suJcQDNANravQIVzuG5VngYomsO6QW7pkLC/cOymwIubIifYrZj11noAwZARCGxQhmOw7A57MXPk/Aaj9vrWV+pvOS29OoX2YvvXBpkvrDVmvPWGBDmII1UkjW+y06FEIYZjF+wQ35xk/krGuf9EzKxgoWNBGCsEmBAVWMBGEIG92NtAwecDh4kULLbe2ZBp7AjGFsGqgjFbYTlrXD+Os8ySLwJSEE0QwTyKQErcBTZe5QPwlWEAn4yAYBHtbEAOip5OwMdKZhsUTEf2juYv+QcAE2LNHYwxjj25VhcUotxqEB5mwIPA/xSCgl6JCdBLSi8BFUHFkI+M39RHgUgtYpuIASlOITOhfWkDsmwO8V+PxWimAT10Y7Z2kwarlLFv+TM1SYl1PiY05pqSWxtJ7lktROSLYINHoWIcBh4LMHHDASc04Dla3nIuA5y5UrpQ3BAE0eAdx7gPEyY8p53YXivG7W895HxvGfKQV8u5eA+O/L+CpEy+6ATMT/eWMyJGNN2S0uJusMkGxrJ0rxQLemIK2Sg75ezeBLiObOGApynAEoulchmNytz3N4PuYcR4TxnjeZ4D5d5iW4t+f8j8PSQXjPLuCyFtSkD1MboWeFCzLFLOUUgasrYQjINgHgSmmoDDABphGUsBhWwCDtrEXgAByAAAg6J0AZub6pVCqbZ2kOXaquGrYW+JGDLRbmedE+qva+39oHYOodw6R2jrHeOicU5pwzlnHOgE84FyLihfVFA+LFHRNIzB2CE1iSSWEia+rcb7X4PGy1YBC1MRKeiZAHraA2GrMofghdsLYQzJLJ4gEjDxlbdhSWksjBZmltLasKdmCAUlswDMldsIoX4ChLMGYYD6pCH5bghbdkqkNCSZgSBQC9DAHASIeBNIgFbK2IAA==="} declare const erc721Abi: { name: string; type: string; stateMutability: string; inputs: { type: string; name: string; }[]; outputs: { type: string; }[]; }[] // ---cut--- import { useReadContract } from '@wagmi/vue' const { data } = useReadContract({ address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', abi: erc721Abi, functionName: 'balanceOf', // ^? args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'], // ^? }) data // ^? ``` :::

You can prevent runtime errors and be more productive by making sure your ABIs and Typed Data definitions are set up appropriately. 🎉 ```ts twoslash // @twoslash-cache: {"v":1,"hash":"a8bdf07964e5e57f195e43b7354ec3ed1fdcf454f5eca95c72e560cff7e4b73d","data":"N4Igdg9gJgpgziAXAbVAFwJ4AcZJACwgDcYAnEAGhDRgA808AKAQwBsBLZuASgAIAzAK5gAxmnYQwvQXBgAlGMygBhSWlLMxAHhGS4aXswBG7XnRpgocXgEETvAD69SiqJNYZpYANaQA7mDIALoUAsJiEmAAcswAtjBm9DCW1qpg6ppoAGLh4pIx8VrG7KEAOiBYgi7ljrzlROwwfuUAfKHMpADm1ubJVrxpGWI5onlgNl1wRSZlFVUwNU71jc2UYaORBTBtvLpg/OydiRb9aQdHALwDkuehsqwwYgAizGjMvFcKSoMaz6/M0xK6wi+TiMHakxaLUYWA6YJopDgAH0APyIXgAVVkXxUal+aAACnD4gipsVQkINqD4hDuqE9rdePdHmgXm8Wtx0Vj5K4fpkFGgqmAACrYGCAim5TZg2lwO4wB5/dmlMDsWJYCCkAwyHnfPGZSggNwiBCIAhoNBYOCIAD0Nr8zE6sXYADo4PgbURBDAbcwsOwbYQIN44DadTi+WJDfoOgxEABOKgPMCdND4JAARgArFQ3l0YHGQOHefqo0n2GBcIgAAxUET4OFiMhIeMAXwo6DFeEIJHIufMTDYnB40mxJfS+K0LiU7k8qBVvEXzlcs94YDB6PKRjYzFEMAA8vxygBuBdL6duMAeXiYHCbkCUkFgE9nxcX1cxmgAWUEbxMHEwe8GiaF8pHPFcr08CtKjQa1lxnSDeHnMCl3AhDr1vGB7yUKAXDgOBQ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p/NuyxtoyJugAkha9B5tU3qg/KikCGYJPuUWB1VcnLSIX3QuhSKl31UuUIS6Qd61KUeohey1oln1YZNQypBjLULEdXTeyTeETMbukwRm0f45Nmd5CR8ijrNIYZwtpIBSnoJXtEmp8DlGIOKVwvZf8WmeEOdgyqcCaHzyubwBp4SuKbIwa0+8lCurdK0ScrZxUqkgCDufSaCSa7TISQI5yizsmiL6aufJCjTp1MIXI4hyL7pqMKZo+hi5cVBB0bGJAASMxexTGmFsZig54DIIE4JoSrGR0QLY+xcdyCIACc4zCtLSC6TTi7OMAAON25LjF+2jnY6AVYRJCpErWB8LlkhgjwBWWAtAXSwUNOwKAvLSAAFpZXyv1RmasEkTUiUNDQLxZp5YJAAORbnLo8SuIB7W8A0muCABguBwEOOuIwDwbwQESQ6p4MAYBYC/MwDARgeT8C0E636FdAa1HKIMial8RljMWGpEFQzL65uqclV1aa4aUzAIjFGQMnDCFgAcSsUAWj2pdLwJ4OreAYFYhDRQUhHUxPLv9V19qUThxgCQVgerNRMqrKKuxsdMjxxEty1xBBU5WoziALOZUyC52BGMLYXznUiFdUS12iARVispRK6lBY8DTK2DO92McHFLronWaVqr1SagMMADWEZSwGFbAIXSsReD2oAAIm2dBbGAjrnxgBDlrfEjA3r5z8fSkJMwzwPpKva2JlYT38HtRQfq3BDQkmYEgUAvQwB+skHgLVrZWxAA="} // @errors: 2820 const erc721Abi = [ { name: 'balanceOf', type: 'function', stateMutability: 'view', inputs: [{ type: 'address', name: 'owner' }], outputs: [{ type: 'uint256' }], }, { name: 'isApprovedForAll', type: 'function', stateMutability: 'view', inputs: [ { type: 'address', name: 'owner' }, { type: 'address', name: 'operator' }, ], outputs: [{ type: 'bool' }], }, { name: 'getApproved', type: 'function', stateMutability: 'view', inputs: [{ type: 'uint256', name: 'tokenId' }], outputs: [{ type: 'address' }], }, { name: 'ownerOf', type: 'function', stateMutability: 'view', inputs: [{ type: 'uint256', name: 'tokenId' }], outputs: [{ type: 'address' }], }, { name: 'tokenURI', type: 'function', stateMutability: 'pure', inputs: [{ type: 'uint256', name: 'tokenId' }], outputs: [{ type: 'string' }], }, ] as const // ---cut--- import { useReadContract } from '@wagmi/vue' useReadContract({ abi: erc721Abi, functionName: 'balanecOf', }) ``` ## Configure Internal Types For advanced use-cases, you may want to configure Wagmi's internal types. Most of Wagmi's types relating to ABIs and EIP-712 Typed Data are powered by [ABIType](https://github.com/wevm/abitype). See the [ABIType docs](https://abitype.dev) for more info on how to configure types. ================================================ FILE: site/vue/why.md ================================================ # Why Wagmi ## The Problems Building Ethereum applications is hard. Apps need to support connecting wallets, multiple chains, signing messages and data, sending transactions, listening for events and state changes, refreshing stale blockchain data, and much more. This is all on top of solving for app-specific use-cases and providing polished user experiences. The ecosystem is also continuously evolving, meaning you need to adapt to new improvements or get left behind. App developers should not need to worry about connecting tens of different wallets, the intricacies of multi-chain support, typos accidentally sending an order of magnitude more ETH or calling a misspelled contract function, or accidentally spamming their RPC provider, costing thousands in compute units. Wagmi solves all these problems and more — allowing app developers to focus on building high-quality and performant experiences for Ethereum — by focusing on **developer experience**, **performance**, **feature coverage**, and **stability.** ## Developer Experience Wagmi delivers a great developer experience through modular and composable APIs, automatic type safety and inference, and comprehensive documentation. It provides developers with intuitive building blocks to build their Ethereum apps. While Wagmi's APIs might seem more verbose at first, it makes Wagmi's modular building blocks extremely flexible. Easy to move around, change, and remove. It also allows developers to better understand Ethereum concepts as well as understand _what_ and _why_ certain properties are being passed through. Learning how to use Wagmi is a great way to learn how to interact with Ethereum in general. Wagmi also provides [strongly typed APIs](/vue/typescript), allowing consumers to get the best possible experience through [autocomplete](https://twitter.com/awkweb/status/1555678944770367493), [type inference](https://twitter.com/jakemoxey/status/1570244174502588417?s=20), as well as static validation. You often just need to provide an ABI and Wagmi can help you autocomplete your way to success, identify type errors before your users do, drill into blockchain errors [at compile and runtimes](/vue/guides/error-handling) with surgical precision, and much more. The API documentation is comprehensive and contains usage info for _every_ module in Wagmi. The core team uses a [documentation](https://gist.github.com/zsup/9434452) and [test driven](https://en.wikipedia.org/wiki/Test-driven_development#:~:text=Test%2Ddriven%20development%20(TDD),software%20against%20all%20test%20cases.) development approach to building modules, which leads to predictable and stable APIs. ## Performance Performance is critical for applications on all sizes. Slow page load and interactions can cause users to stop using applications. Wagmi uses and is built by the same team behind [Viem](https://viem.sh), the most performant production-ready Ethereum library. End users should not be required to download a module of over 100kB in order to interact with Ethereum. Wagmi is optimized for tree-shaking and dead-code elimination, allowing apps to minimize bundle size for fast page load times. Data layer performance is also critical. Slow, unnecessary, and manual data fetching can make apps unusable and cost thousands in RPC compute units. Wagmi supports caching, deduplication, persistence, and much more through [TanStack Query](/vue/guides/tanstack-query). ## Feature Coverage Wagmi supports the most popular and commonly-used Ethereum features out of the box with 40+ Vue Composables for accounts, wallets, contracts, transactions, signing, ENS, and more. Wagmi also supports just about any wallet out there through it's official [connectors](/vue/api/connectors), [EIP-6963 support](/vue/api/createConfig#multiinjectedproviderdiscovery), and [extensible API](/dev/creating-connectors). If you need lower-level control, you can always drop down to [Wagmi Core](/core/getting-started) or [Viem](https://viem.sh), which Wagmi uses internally to perform blockchain operations. Wagmi also manages multi-chain support automatically so developers can focus on their applications instead of adding custom code. Finally, Wagmi has a [CLI](/cli/getting-started) to manage ABIs as well as a robust ecosystem of third-party libraries, like [ConnectKit](https://docs.family.co/connectkit), [Dynamic](https://www.dynamic.xyz), [Privy](https://privy.io), and many more, so you can get started quickly without needing to build everything from scratch. ## Stability Stability is a fundamental principle for Wagmi. Many organizations, large and small, rely heavily on Wagmi and expect it to be entirely stable for their users and applications. Wagmi's test suite runs against forked Ethereum nodes to make sure functions work across chains. The test suite also runs type tests against many different versions of peer dependencies, like TypeScript, to ensure compatibility with the latest releases of other popular software. Wagmi follows semver so developers can upgrade between versions with confidence. Starting with Wagmi v2, new functionality will be opt-in with old functionality being deprecated alongside the new features. This means upgrading to the latest major versions will not require immediate changes. Lastly, the core team works full-time on Wagmi and [related projects](https://github.com/wevm), and is constantly improving Wagmi and keeping it up-to-date with industry trends and changes. ================================================ FILE: tsconfig.base.json ================================================ { // This tsconfig file contains the shared config for the build (tsconfig.build.json) and type checking (tsconfig.json) config. "include": [], "compilerOptions": { // Incremental builds // NOTE: Enabling incremental builds speeds up `tsc`. Keep in mind though that it does not reliably bust the cache when the `tsconfig.json` file changes. "incremental": true, // Type checking "strict": true, // "exactOptionalPropertyTypes": true, // Enabled once supported in tanstack query https://github.com/TanStack/query/issues/7641 "noFallthroughCasesInSwitch": true, // Not enabled by default in `strict` mode. "noImplicitOverride": true, // Not enabled by default in `strict` mode. "noImplicitReturns": true, // Not enabled by default in `strict` mode. "noUncheckedIndexedAccess": true, "noUnusedLocals": true, // Not enabled by default in `strict` mode. "noUnusedParameters": true, // Not enabled by default in `strict` mode. "useDefineForClassFields": true, // Not enabled by default in `strict` mode unless we bump `target` to ES2022. "useUnknownInCatchVariables": true, // JavaScript support "allowJs": false, "checkJs": false, // Interop constraints "forceConsistentCasingInFileNames": true, "verbatimModuleSyntax": true, // Language and environment "moduleResolution": "NodeNext", "module": "NodeNext", "target": "ES2021", // Setting this to `ES2021` enables native support for `Node v16+`: https://github.com/microsoft/TypeScript/wiki/Node-Target-Mapping. "lib": [ "ES2022", // By using ES2022 we get access to the `.cause` property on `Error` instances. "DOM" // We are adding `DOM` here to get the `fetch`, etc. types. This should be removed once these types are available via DefinitelyTyped. ], // Skip type checking for node modules "skipLibCheck": true, "noErrorTruncation": true } } ================================================ FILE: tsconfig.json ================================================ { "extends": "./tsconfig.base.json", "include": ["scripts/**/*.ts", "vitest.config.ts"], "exclude": [] } ================================================ FILE: vitest.config.ts ================================================ import path from 'node:path' import { playwright } from '@vitest/browser-playwright' import reactFallbackThrottlePlugin from 'vite-plugin-react-fallback-throttle' import solid from 'vite-plugin-solid' import { defaultExclude, defineConfig } from 'vitest/config' const alias = { '@wagmi/connectors': path.resolve( __dirname, './packages/connectors/src/exports', ), '@wagmi/core': path.resolve(__dirname, './packages/core/src/exports'), '@wagmi/test': path.resolve(__dirname, './packages/test/src/exports'), '@wagmi/vue': path.resolve(__dirname, './packages/vue/src/exports'), '@wagmi/solid': path.resolve(__dirname, './packages/solid/src/exports'), wagmi: path.resolve(__dirname, './packages/react/src/exports'), } export default defineConfig({ server: { watch: { ignored: ['**/templates/**'], }, }, test: { coverage: { reporter: process.env.CI ? ['lcov'] : ['text', 'json', 'html'], exclude: [ '**/dist/**', '**/*.test.ts', '**/*.test-d.ts', 'packages/cli/**', 'packages/test/**', // ignore third-party connectors 'packages/connectors/**', 'packages/core/src/connectors/injected.ts', 'packages/core/src/tempo/**', 'packages/react/src/tempo/**', ], }, globalSetup: process.env.TYPES ? ['./packages/test/src/setup.global.types.ts'] : ['./packages/test/src/setup.global.ts'], projects: [ { test: { name: 'cli', environment: 'node', include: ['./packages/cli/src/**/*.test.ts'], testTimeout: 20_000, setupFiles: ['./packages/cli/test/setup.ts'], }, }, { test: { name: 'connectors', include: ['./packages/connectors/src/**/*.test.ts'], environment: 'happy-dom', }, resolve: { alias }, }, { test: { name: 'core', include: [ ...(process.env.TYPES ? ['**/*.bench-d.ts'] : []), './packages/core/src/**/*.test.ts', ], exclude: [ './packages/core/src/tempo/**/*.test.ts', ...defaultExclude, ], environment: 'happy-dom', testTimeout: 20_000, setupFiles: ['./packages/core/test/setup.ts'], }, resolve: { alias }, }, { test: { name: 'create-wagmi', include: ['./packages/create-wagmi/src/**/*.test.ts'], environment: 'node', testTimeout: 20_000, }, }, { plugins: [reactFallbackThrottlePlugin()], resolve: { alias }, test: { name: 'tempo', browser: { enabled: true, headless: true, instances: [{ browser: 'chromium' }], provider: playwright(), screenshotFailures: false, }, include: [ './packages/core/src/tempo/**/*.test.ts', './packages/react/src/tempo/**/*.test.ts', ], fileParallelism: false, hookTimeout: 20_000, testTimeout: 30_000, globalSetup: process.env.TYPES ? ['./packages/test/src/setup.global.types.ts'] : ['./packages/test/src/tempo/setup.global.ts'], setupFiles: ['./packages/test/src/tempo/setup.ts'], }, }, { plugins: [reactFallbackThrottlePlugin()], resolve: { alias }, test: { name: 'react', browser: { enabled: true, headless: true, instances: [{ browser: 'chromium' }], provider: playwright(), screenshotFailures: false, }, include: ['./packages/react/src/**/*.test.ts?(x)'], exclude: [ './packages/react/src/tempo/**/*.test.ts', ...defaultExclude, ], testTimeout: 20_000, setupFiles: ['./packages/react/test/setup.ts'], }, }, { test: { name: 'vue', include: ['./packages/vue/src/**/*.test.ts?(x)'], environment: 'happy-dom', testTimeout: 20_000, setupFiles: ['./packages/vue/test/setup.ts'], }, resolve: { alias }, }, { plugins: [solid()], resolve: { alias }, test: { name: 'solid', browser: { enabled: true, headless: true, instances: [{ browser: 'chromium' }], provider: playwright(), screenshotFailures: false, }, include: ['./packages/solid/src/**/*.test.ts?(x)'], testTimeout: 20_000, setupFiles: ['./packages/solid/test/setup.ts'], }, }, { test: { name: 'test', include: ['./packages/test/src/**/*.test.ts'], }, resolve: { alias }, }, ], setupFiles: ['./packages/test/src/setup.ts'], }, })