diff --git a/.ai/categories/smart-contracts.md b/.ai/categories/smart-contracts.md index acec68f8e..ebdc9477a 100644 --- a/.ai/categories/smart-contracts.md +++ b/.ai/categories/smart-contracts.md @@ -2690,9 +2690,6 @@ Add the Solidity compiler so you can generate standard EVM bytecode: npm install --save-dev solc ``` -!!! tip - The sample scripts use ECMAScript modules. Add `"type": "module"` to your `package.json` (or rename the files to `.mjs`) so that `node` can run the `import` statements. - ## Set Up the Web3 Provider The provider configuration is the foundation of any Web3.js application. It serves as a bridge between your application and the blockchain, allowing you to query blockchain data and interact with smart contracts. @@ -2749,7 +2746,7 @@ With the provider set up, you can start querying the blockchain. For instance, t const PROVIDER_RPC = { rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', chainId: 420420422, - name: 'polkadot-hub-testnet', + name: 'polkadotTestNet', }; const main = async () => { @@ -3012,7 +3009,7 @@ You can create a `deploy.js` script in the `scripts` directory of your project t const providerConfig = { rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', // TODO: replace to `https://services.polkadothub-rpc.com/testnet` when ready chainId: 420420422, - name: 'polkadot-hub-testnet', + name: 'polkadotTestNet', }; const privateKey = 'INSERT_PRIVATE_KEY'; @@ -3120,7 +3117,7 @@ You can create a `deploy.js` script in the `scripts` directory of your project t const providerConfig = { rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', // TODO: replace to `https://services.polkadothub-rpc.com/testnet` when ready chainId: 420420422, - name: 'polkadot-hub-testnet', + name: 'polkadotTestNet', }; const privateKey = 'INSERT_PRIVATE_KEY'; @@ -3140,7 +3137,7 @@ After running this script, your contract will be deployed to Polkadot Hub, and i ## Interact with the Contract -Once the contract is deployed, you can interact with it by calling its functions. For example, to set a number, read it and then modify that number by its double, you can create a file named `updateStorage.js` in the `scripts` directory of your project and add the following code: +Once the contract is deployed, you can interact with it by calling its functions. For example, to read the current stored value and then update it to a new value, you can create a file named `updateStorage.js` in the `scripts` directory of your project and add the following code: ```js title="scripts/updateStorage.js" const { readFileSync } = require('fs'); @@ -3210,7 +3207,7 @@ updateStorage(config) .catch((error) => console.error('Update error')); ``` -Ensure you replace the `INSERT_MNEMONIC`, `INSERT_CONTRACT_ADDRESS`, and `INSERT_ADDRESS_TO_CHECK` placeholders with actual values. Also, ensure the contract ABI file (`Storage.json`) is correctly referenced. The script prints the balance for `ADDRESS_TO_CHECK` before it writes and doubles the stored value, so pick any account you want to monitor. +Ensure you replace the `INSERT_PRIVATE_KEY` and `INSERT_CONTRACT_ADDRESS` placeholders with actual values. Also, ensure the contract ABI file (`Storage.json`) is correctly referenced. The script reads the current stored value, sets it to 1, and then displays the updated value. To interact with the contract, run: @@ -6218,165 +6215,6 @@ The system maintains precise conversion mechanisms between: This ensures accurate fee calculation while maintaining compatibility with existing Ethereum tools and workflows. ---- - -Page Title: Troubleshooting Remix IDE - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-remix-troubleshooting-faq.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/dev-environments/remix/troubleshooting-faq/ -- Summary: Common issues related to developing, compiling, and deploying smart contracts using Remix IDE on Polkadot Hub paired with troubleshooting suggestions. - -# Remix IDE Troubleshooting - -This guide provides solutions to common issues you may encounter when using Remix IDE with Polkadot Hub. If you're experiencing problems with compilation, deployment, or contract interaction, you'll likely find the solution here. - -## Contract fails to compile or shows errors in the terminal - -- **Check Solidity version compatibility**: - - Ensure your contract's pragma statement matches the compiler version selected in the **Solidity Compiler** tab. - - Example: If your contract uses `pragma solidity ^0.8.0;`, select compiler version 0.8.x or higher. - -- **Review syntax errors**: - - Carefully read error messages in the terminal panel at the bottom of the screen. - - Common issues include missing semicolons, incorrect function visibility, or mismatched brackets. - -- **Clear cache and recompile**: - - Delete the `artifacts` folder in the **File Explorer**. - - Try compiling again with `Ctrl+S` or click the **Compile** button. - -## The `artifacts` folder doesn't appear after compilation - -- Ensure compilation completed successfully without errors. -- Refresh the **File Explorer** by clicking away and back to the **File Explorer** tab. -- Check that your `.sol` file is saved before compiling. - -## Remix doesn't detect your wallet extension (MetaMask, Talisman, etc.) - -- **Verify wallet installation**: - - Ensure your wallet extension is properly installed and enabled in your browser. - - Check that the extension icon appears in your browser toolbar. - -- **Refresh the page**: - - Reload the Remix IDE page and try reconnecting. - -- **Check browser permissions**: - - Ensure Remix has permission to interact with the wallet extension. - - Check your browser's extension settings. - -- **Use correct environment**: - - In the **Deploy & Run Transactions** tab, select **Browser Extension** from the **Environment** dropdown. - - Choose **Injected Provider - MetaMask** (works with most wallet providers). - -## Wallet is connected but to the wrong network - -1. Open your wallet extension. -2. Switch to the Polkadot Hub network. -3. Refresh the Remix IDE if the network change isn't detected automatically. -4. Verify the network name and chain ID match Polkadot Hub's configuration. - -## Deployment fails with "insufficient funds" or similar error - -- **Check your balance**: - - Verify you have enough test tokens in your connected wallet. - - Visit the [Polkadot faucet](/smart-contracts/faucet/){target=\_blank} to obtain test tokens. - -- **Wait for faucet tokens**: - - Allow a few minutes for faucet transactions to complete. - - Refresh your wallet to see the updated balance. - -## Deployment transaction is rejected or fails - -- **Increase gas limit**: - - In the **Deploy & Run Transactions** tab, adjust the **Gas Limit** field. - - Try increasing it by 20-30% from the estimated amount. - -- **Check contract constructor parameters**: - - Ensure any required constructor parameters are provided correctly. - - Verify parameter types match the contract's constructor signature. - -- **Verify contract selection**: - - Ensure you've selected the correct contract from the **Contract** dropdown. - - If you have multiple contracts, make sure you're deploying the intended one. - -## The "Injected Provider - MetaMask" option doesn't appear in the Environment dropdown - -- Select **Browser Extension** from the **Environment** dropdown to populate the **Injected Provider - Metamask** option. -- Ensure your wallet extension is unlocked and active. -- Try disabling and re-enabling the wallet extension. -- Refresh the Remix IDE page. - -## Wallet rejects transactions when trying to interact with deployed contracts - -- **Check wallet unlock status**: - - Ensure your wallet is unlocked. - - Verify you're approving the transaction in the wallet pop-up. - -- **Verify sufficient gas**: - - Ensure you have enough tokens to cover the transaction fee. - - The wallet pop-up should show the estimated gas cost. - -- **Network mismatch**: - - Confirm your wallet is still connected to Polkadot Hub. - - Check that Remix is using the same network. - -## Deployed contract doesn't show in the **Deployed/Unpinned Contracts** section - -- Wait for the transaction to be confirmed on-chain. -- Check the Remix terminal for deployment confirmation. -- Scroll down in the **Deploy & Run Transactions** panel to find the deployed contracts section. -- If the deployment transaction failed, check the terminal for error messages. - -## Blue buttons (read functions) don't display return values - -- **Check the terminal**: - - Return values appear in the terminal panel at the bottom. - - Look for the decoded output section. - -- **Verify contract state**: - - Ensure the contract has been properly initialized. - - Check if the function requires a specific contract state to return values. - -- **Network connection**: - - Verify you're still connected to the correct network. - - Try refreshing the connection to your wallet. - - -## Orange/red buttons (write functions) execute, but the state doesn't change - -- **Wait for transaction confirmation**: - - Transactions need to be mined before state changes are reflected. - - Check the terminal for transaction status. - - Wait a few seconds and try rereading the state. - -- **Transaction failed**: - - Check if the transaction was actually successful in the terminal. - - Look for revert reasons or error messages. - - Verify you approved the transaction in your wallet. - -- **Check transaction parameters**: - - Ensure you're passing the correct parameters to the function. - - For payable functions (red buttons), verify you're sending the correct amount. - -## Remix takes a long time to load or becomes unresponsive - -- **Clear browser cache**: - - Clear your browser's cache and cookies. - - Restart your browser. - -- **Disable unnecessary plugins**: - - In Remix, deactivate plugins you're not using via the Plugin Manager. - -- **Use a supported browser**: - - Use Chrome, Firefox, or Brave for the best compatibility. - - Ensure your browser is up to date. - -## Changes to files or folders don't appear in the File Explorer - -- Click the refresh icon in the **File Explorer**. -- Switch to a different tab and back to **File Explorer**. -- Save your work and reload the Remix IDE page. - - --- Page Title: Troubleshooting Hardhat @@ -6907,6 +6745,165 @@ This guide provides solutions to common issues you may encounter when using Hard ``` +--- + +Page Title: Troubleshooting Remix IDE + +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-remix-troubleshooting-faq.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/dev-environments/remix/troubleshooting-faq/ +- Summary: Common issues related to developing, compiling, and deploying smart contracts using Remix IDE on Polkadot Hub paired with troubleshooting suggestions. + +# Remix IDE Troubleshooting + +This guide provides solutions to common issues you may encounter when using Remix IDE with Polkadot Hub. If you're experiencing problems with compilation, deployment, or contract interaction, you'll likely find the solution here. + +## Contract fails to compile or shows errors in the terminal + +- **Check Solidity version compatibility**: + - Ensure your contract's pragma statement matches the compiler version selected in the **Solidity Compiler** tab. + - Example: If your contract uses `pragma solidity ^0.8.0;`, select compiler version 0.8.x or higher. + +- **Review syntax errors**: + - Carefully read error messages in the terminal panel at the bottom of the screen. + - Common issues include missing semicolons, incorrect function visibility, or mismatched brackets. + +- **Clear cache and recompile**: + - Delete the `artifacts` folder in the **File Explorer**. + - Try compiling again with `Ctrl+S` or click the **Compile** button. + +## The `artifacts` folder doesn't appear after compilation + +- Ensure compilation completed successfully without errors. +- Refresh the **File Explorer** by clicking away and back to the **File Explorer** tab. +- Check that your `.sol` file is saved before compiling. + +## Remix doesn't detect your wallet extension (MetaMask, Talisman, etc.) + +- **Verify wallet installation**: + - Ensure your wallet extension is properly installed and enabled in your browser. + - Check that the extension icon appears in your browser toolbar. + +- **Refresh the page**: + - Reload the Remix IDE page and try reconnecting. + +- **Check browser permissions**: + - Ensure Remix has permission to interact with the wallet extension. + - Check your browser's extension settings. + +- **Use correct environment**: + - In the **Deploy & Run Transactions** tab, select **Browser Extension** from the **Environment** dropdown. + - Choose **Injected Provider - MetaMask** (works with most wallet providers). + +## Wallet is connected but to the wrong network + +1. Open your wallet extension. +2. Switch to the Polkadot Hub network. +3. Refresh the Remix IDE if the network change isn't detected automatically. +4. Verify the network name and chain ID match Polkadot Hub's configuration. + +## Deployment fails with "insufficient funds" or similar error + +- **Check your balance**: + - Verify you have enough test tokens in your connected wallet. + - Visit the [Polkadot faucet](/smart-contracts/faucet/){target=\_blank} to obtain test tokens. + +- **Wait for faucet tokens**: + - Allow a few minutes for faucet transactions to complete. + - Refresh your wallet to see the updated balance. + +## Deployment transaction is rejected or fails + +- **Increase gas limit**: + - In the **Deploy & Run Transactions** tab, adjust the **Gas Limit** field. + - Try increasing it by 20-30% from the estimated amount. + +- **Check contract constructor parameters**: + - Ensure any required constructor parameters are provided correctly. + - Verify parameter types match the contract's constructor signature. + +- **Verify contract selection**: + - Ensure you've selected the correct contract from the **Contract** dropdown. + - If you have multiple contracts, make sure you're deploying the intended one. + +## The "Injected Provider - MetaMask" option doesn't appear in the Environment dropdown + +- Select **Browser Extension** from the **Environment** dropdown to populate the **Injected Provider - Metamask** option. +- Ensure your wallet extension is unlocked and active. +- Try disabling and re-enabling the wallet extension. +- Refresh the Remix IDE page. + +## Wallet rejects transactions when trying to interact with deployed contracts + +- **Check wallet unlock status**: + - Ensure your wallet is unlocked. + - Verify you're approving the transaction in the wallet pop-up. + +- **Verify sufficient gas**: + - Ensure you have enough tokens to cover the transaction fee. + - The wallet pop-up should show the estimated gas cost. + +- **Network mismatch**: + - Confirm your wallet is still connected to Polkadot Hub. + - Check that Remix is using the same network. + +## Deployed contract doesn't show in the **Deployed/Unpinned Contracts** section + +- Wait for the transaction to be confirmed on-chain. +- Check the Remix terminal for deployment confirmation. +- Scroll down in the **Deploy & Run Transactions** panel to find the deployed contracts section. +- If the deployment transaction failed, check the terminal for error messages. + +## Blue buttons (read functions) don't display return values + +- **Check the terminal**: + - Return values appear in the terminal panel at the bottom. + - Look for the decoded output section. + +- **Verify contract state**: + - Ensure the contract has been properly initialized. + - Check if the function requires a specific contract state to return values. + +- **Network connection**: + - Verify you're still connected to the correct network. + - Try refreshing the connection to your wallet. + + +## Orange/red buttons (write functions) execute, but the state doesn't change + +- **Wait for transaction confirmation**: + - Transactions need to be mined before state changes are reflected. + - Check the terminal for transaction status. + - Wait a few seconds and try rereading the state. + +- **Transaction failed**: + - Check if the transaction was actually successful in the terminal. + - Look for revert reasons or error messages. + - Verify you approved the transaction in your wallet. + +- **Check transaction parameters**: + - Ensure you're passing the correct parameters to the function. + - For payable functions (red buttons), verify you're sending the correct amount. + +## Remix takes a long time to load or becomes unresponsive + +- **Clear browser cache**: + - Clear your browser's cache and cookies. + - Restart your browser. + +- **Disable unnecessary plugins**: + - In Remix, deactivate plugins you're not using via the Plugin Manager. + +- **Use a supported browser**: + - Use Chrome, Firefox, or Brave for the best compatibility. + - Ensure your browser is up to date. + +## Changes to files or folders don't appear in the File Explorer + +- Click the refresh icon in the **File Explorer**. +- Switch to a different tab and back to **File Explorer**. +- Save your work and reload the Remix IDE page. + + --- Page Title: Use Hardhat with Polkadot Hub @@ -7700,8 +7697,6 @@ Page Title: Wagmi for Polkadot Hub Smart Contracts # Wagmi -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. ## Introduction [Wagmi](https://wagmi.sh/){target=\_blank} is a collection of [React Hooks](https://wagmi.sh/react/api/hooks){target=\_blank} for interacting with Ethereum-compatible blockchains, focusing on developer experience, feature richness, and reliability. @@ -7713,9 +7708,8 @@ This guide demonstrates how to use Wagmi to interact with and deploy smart contr To start working with Wagmi, create a new React project and initialize it by running the following commands in your terminal: ```bash -# Create a new React project using Next.js -npx create-next-app@latest wagmi-asset-hub -cd wagmi-asset-hub +npx create-next-app@latest wagmi-polkadot-hub +cd wagmi-polkadot-hub ``` ## Install Dependencies @@ -7723,15 +7717,14 @@ cd wagmi-asset-hub Install Wagmi and its peer dependencies: ```bash -# Install Wagmi and its dependencies npm install wagmi viem @tanstack/react-query ``` ## Configure Wagmi for Polkadot Hub -Create a configuration file to initialize Wagmi with Polkadot Hub. In your project, create a file named `src/lib/wagmi.ts` and add the code below. Be sure to replace `INSERT_RPC_URL`, `INSERT_CHAIN_ID`, `INSERT_CHAIN_NAME`, `INSERT_NETWORK_NAME`, `INSERT_CHAIN_DECIMALS`, `INSERT_CURRENCY_NAME`, and `INSERT_CURRENCY_SYMBOL` with your specific values. +Create a configuration file to initialize Wagmi with Polkadot Hub. In your project, create a file named `app/lib/wagmi.ts` and add the code below. Be sure to replace `INSERT_RPC_URL`, `INSERT_CHAIN_ID`, `INSERT_CHAIN_NAME`, `INSERT_NETWORK_NAME`, `INSERT_CHAIN_DECIMALS`, `INSERT_CURRENCY_NAME`, and `INSERT_CURRENCY_SYMBOL` with your specific values. -```typescript title="src/lib/wagmi.ts" +```typescript title="app/lib/wagmi.ts" import { http, createConfig } from 'wagmi' // Configure the Polkadot Hub chain @@ -7777,7 +7770,7 @@ export const config = createConfig({ }, rpcUrls: { default: { - http: ['https://testnet-passet-hub-eth-rpc.polkadot.io'], + http: ['https://testnet-passet-hub-eth-rpc.polkadot.io'], // TODO: change to paseo asset hub once ready }, }, } as const; @@ -7917,7 +7910,7 @@ This component uses the following React hooks: ## Interact with Deployed Contract -This guide uses a simple Storage contract already deployed to the Polkadot Hub TestNet (`0x58053f0e8ede1a47a1af53e43368cd04ddcaf66f`). The code of that contract is: +This guide uses a simple Storage contract already deployed to the Polkadot Hub TestNet. The code of that contract is: ??? code "Storage.sol" @@ -7958,7 +7951,7 @@ import { } from "wagmi"; const CONTRACT_ADDRESS = - "0xabBd46Ef74b88E8B1CDa49BeFb5057710443Fd29" as `0x${string}`; + "INSERT_CONTRACT_ADDRESS" as `0x${string}`; export function StorageContract() { const [number, setNumber] = useState("42"); diff --git a/.ai/categories/tooling.md b/.ai/categories/tooling.md index afb47225a..d3e44e3e6 100644 --- a/.ai/categories/tooling.md +++ b/.ai/categories/tooling.md @@ -1736,9 +1736,6 @@ Add the Solidity compiler so you can generate standard EVM bytecode: npm install --save-dev solc ``` -!!! tip - The sample scripts use ECMAScript modules. Add `"type": "module"` to your `package.json` (or rename the files to `.mjs`) so that `node` can run the `import` statements. - ## Set Up the Web3 Provider The provider configuration is the foundation of any Web3.js application. It serves as a bridge between your application and the blockchain, allowing you to query blockchain data and interact with smart contracts. @@ -1795,7 +1792,7 @@ With the provider set up, you can start querying the blockchain. For instance, t const PROVIDER_RPC = { rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', chainId: 420420422, - name: 'polkadot-hub-testnet', + name: 'polkadotTestNet', }; const main = async () => { @@ -2058,7 +2055,7 @@ You can create a `deploy.js` script in the `scripts` directory of your project t const providerConfig = { rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', // TODO: replace to `https://services.polkadothub-rpc.com/testnet` when ready chainId: 420420422, - name: 'polkadot-hub-testnet', + name: 'polkadotTestNet', }; const privateKey = 'INSERT_PRIVATE_KEY'; @@ -2166,7 +2163,7 @@ You can create a `deploy.js` script in the `scripts` directory of your project t const providerConfig = { rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', // TODO: replace to `https://services.polkadothub-rpc.com/testnet` when ready chainId: 420420422, - name: 'polkadot-hub-testnet', + name: 'polkadotTestNet', }; const privateKey = 'INSERT_PRIVATE_KEY'; @@ -2186,7 +2183,7 @@ After running this script, your contract will be deployed to Polkadot Hub, and i ## Interact with the Contract -Once the contract is deployed, you can interact with it by calling its functions. For example, to set a number, read it and then modify that number by its double, you can create a file named `updateStorage.js` in the `scripts` directory of your project and add the following code: +Once the contract is deployed, you can interact with it by calling its functions. For example, to read the current stored value and then update it to a new value, you can create a file named `updateStorage.js` in the `scripts` directory of your project and add the following code: ```js title="scripts/updateStorage.js" const { readFileSync } = require('fs'); @@ -2256,7 +2253,7 @@ updateStorage(config) .catch((error) => console.error('Update error')); ``` -Ensure you replace the `INSERT_MNEMONIC`, `INSERT_CONTRACT_ADDRESS`, and `INSERT_ADDRESS_TO_CHECK` placeholders with actual values. Also, ensure the contract ABI file (`Storage.json`) is correctly referenced. The script prints the balance for `ADDRESS_TO_CHECK` before it writes and doubles the stored value, so pick any account you want to monitor. +Ensure you replace the `INSERT_PRIVATE_KEY` and `INSERT_CONTRACT_ADDRESS` placeholders with actual values. Also, ensure the contract ABI file (`Storage.json`) is correctly referenced. The script reads the current stored value, sets it to 1, and then displays the updated value. To interact with the contract, run: @@ -6339,165 +6336,6 @@ The system maintains precise conversion mechanisms between: This ensures accurate fee calculation while maintaining compatibility with existing Ethereum tools and workflows. ---- - -Page Title: Troubleshooting Remix IDE - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-remix-troubleshooting-faq.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/dev-environments/remix/troubleshooting-faq/ -- Summary: Common issues related to developing, compiling, and deploying smart contracts using Remix IDE on Polkadot Hub paired with troubleshooting suggestions. - -# Remix IDE Troubleshooting - -This guide provides solutions to common issues you may encounter when using Remix IDE with Polkadot Hub. If you're experiencing problems with compilation, deployment, or contract interaction, you'll likely find the solution here. - -## Contract fails to compile or shows errors in the terminal - -- **Check Solidity version compatibility**: - - Ensure your contract's pragma statement matches the compiler version selected in the **Solidity Compiler** tab. - - Example: If your contract uses `pragma solidity ^0.8.0;`, select compiler version 0.8.x or higher. - -- **Review syntax errors**: - - Carefully read error messages in the terminal panel at the bottom of the screen. - - Common issues include missing semicolons, incorrect function visibility, or mismatched brackets. - -- **Clear cache and recompile**: - - Delete the `artifacts` folder in the **File Explorer**. - - Try compiling again with `Ctrl+S` or click the **Compile** button. - -## The `artifacts` folder doesn't appear after compilation - -- Ensure compilation completed successfully without errors. -- Refresh the **File Explorer** by clicking away and back to the **File Explorer** tab. -- Check that your `.sol` file is saved before compiling. - -## Remix doesn't detect your wallet extension (MetaMask, Talisman, etc.) - -- **Verify wallet installation**: - - Ensure your wallet extension is properly installed and enabled in your browser. - - Check that the extension icon appears in your browser toolbar. - -- **Refresh the page**: - - Reload the Remix IDE page and try reconnecting. - -- **Check browser permissions**: - - Ensure Remix has permission to interact with the wallet extension. - - Check your browser's extension settings. - -- **Use correct environment**: - - In the **Deploy & Run Transactions** tab, select **Browser Extension** from the **Environment** dropdown. - - Choose **Injected Provider - MetaMask** (works with most wallet providers). - -## Wallet is connected but to the wrong network - -1. Open your wallet extension. -2. Switch to the Polkadot Hub network. -3. Refresh the Remix IDE if the network change isn't detected automatically. -4. Verify the network name and chain ID match Polkadot Hub's configuration. - -## Deployment fails with "insufficient funds" or similar error - -- **Check your balance**: - - Verify you have enough test tokens in your connected wallet. - - Visit the [Polkadot faucet](/smart-contracts/faucet/){target=\_blank} to obtain test tokens. - -- **Wait for faucet tokens**: - - Allow a few minutes for faucet transactions to complete. - - Refresh your wallet to see the updated balance. - -## Deployment transaction is rejected or fails - -- **Increase gas limit**: - - In the **Deploy & Run Transactions** tab, adjust the **Gas Limit** field. - - Try increasing it by 20-30% from the estimated amount. - -- **Check contract constructor parameters**: - - Ensure any required constructor parameters are provided correctly. - - Verify parameter types match the contract's constructor signature. - -- **Verify contract selection**: - - Ensure you've selected the correct contract from the **Contract** dropdown. - - If you have multiple contracts, make sure you're deploying the intended one. - -## The "Injected Provider - MetaMask" option doesn't appear in the Environment dropdown - -- Select **Browser Extension** from the **Environment** dropdown to populate the **Injected Provider - Metamask** option. -- Ensure your wallet extension is unlocked and active. -- Try disabling and re-enabling the wallet extension. -- Refresh the Remix IDE page. - -## Wallet rejects transactions when trying to interact with deployed contracts - -- **Check wallet unlock status**: - - Ensure your wallet is unlocked. - - Verify you're approving the transaction in the wallet pop-up. - -- **Verify sufficient gas**: - - Ensure you have enough tokens to cover the transaction fee. - - The wallet pop-up should show the estimated gas cost. - -- **Network mismatch**: - - Confirm your wallet is still connected to Polkadot Hub. - - Check that Remix is using the same network. - -## Deployed contract doesn't show in the **Deployed/Unpinned Contracts** section - -- Wait for the transaction to be confirmed on-chain. -- Check the Remix terminal for deployment confirmation. -- Scroll down in the **Deploy & Run Transactions** panel to find the deployed contracts section. -- If the deployment transaction failed, check the terminal for error messages. - -## Blue buttons (read functions) don't display return values - -- **Check the terminal**: - - Return values appear in the terminal panel at the bottom. - - Look for the decoded output section. - -- **Verify contract state**: - - Ensure the contract has been properly initialized. - - Check if the function requires a specific contract state to return values. - -- **Network connection**: - - Verify you're still connected to the correct network. - - Try refreshing the connection to your wallet. - - -## Orange/red buttons (write functions) execute, but the state doesn't change - -- **Wait for transaction confirmation**: - - Transactions need to be mined before state changes are reflected. - - Check the terminal for transaction status. - - Wait a few seconds and try rereading the state. - -- **Transaction failed**: - - Check if the transaction was actually successful in the terminal. - - Look for revert reasons or error messages. - - Verify you approved the transaction in your wallet. - -- **Check transaction parameters**: - - Ensure you're passing the correct parameters to the function. - - For payable functions (red buttons), verify you're sending the correct amount. - -## Remix takes a long time to load or becomes unresponsive - -- **Clear browser cache**: - - Clear your browser's cache and cookies. - - Restart your browser. - -- **Disable unnecessary plugins**: - - In Remix, deactivate plugins you're not using via the Plugin Manager. - -- **Use a supported browser**: - - Use Chrome, Firefox, or Brave for the best compatibility. - - Ensure your browser is up to date. - -## Changes to files or folders don't appear in the File Explorer - -- Click the refresh icon in the **File Explorer**. -- Switch to a different tab and back to **File Explorer**. -- Save your work and reload the Remix IDE page. - - --- Page Title: Troubleshooting Hardhat @@ -7028,6 +6866,165 @@ This guide provides solutions to common issues you may encounter when using Hard ``` +--- + +Page Title: Troubleshooting Remix IDE + +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-remix-troubleshooting-faq.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/dev-environments/remix/troubleshooting-faq/ +- Summary: Common issues related to developing, compiling, and deploying smart contracts using Remix IDE on Polkadot Hub paired with troubleshooting suggestions. + +# Remix IDE Troubleshooting + +This guide provides solutions to common issues you may encounter when using Remix IDE with Polkadot Hub. If you're experiencing problems with compilation, deployment, or contract interaction, you'll likely find the solution here. + +## Contract fails to compile or shows errors in the terminal + +- **Check Solidity version compatibility**: + - Ensure your contract's pragma statement matches the compiler version selected in the **Solidity Compiler** tab. + - Example: If your contract uses `pragma solidity ^0.8.0;`, select compiler version 0.8.x or higher. + +- **Review syntax errors**: + - Carefully read error messages in the terminal panel at the bottom of the screen. + - Common issues include missing semicolons, incorrect function visibility, or mismatched brackets. + +- **Clear cache and recompile**: + - Delete the `artifacts` folder in the **File Explorer**. + - Try compiling again with `Ctrl+S` or click the **Compile** button. + +## The `artifacts` folder doesn't appear after compilation + +- Ensure compilation completed successfully without errors. +- Refresh the **File Explorer** by clicking away and back to the **File Explorer** tab. +- Check that your `.sol` file is saved before compiling. + +## Remix doesn't detect your wallet extension (MetaMask, Talisman, etc.) + +- **Verify wallet installation**: + - Ensure your wallet extension is properly installed and enabled in your browser. + - Check that the extension icon appears in your browser toolbar. + +- **Refresh the page**: + - Reload the Remix IDE page and try reconnecting. + +- **Check browser permissions**: + - Ensure Remix has permission to interact with the wallet extension. + - Check your browser's extension settings. + +- **Use correct environment**: + - In the **Deploy & Run Transactions** tab, select **Browser Extension** from the **Environment** dropdown. + - Choose **Injected Provider - MetaMask** (works with most wallet providers). + +## Wallet is connected but to the wrong network + +1. Open your wallet extension. +2. Switch to the Polkadot Hub network. +3. Refresh the Remix IDE if the network change isn't detected automatically. +4. Verify the network name and chain ID match Polkadot Hub's configuration. + +## Deployment fails with "insufficient funds" or similar error + +- **Check your balance**: + - Verify you have enough test tokens in your connected wallet. + - Visit the [Polkadot faucet](/smart-contracts/faucet/){target=\_blank} to obtain test tokens. + +- **Wait for faucet tokens**: + - Allow a few minutes for faucet transactions to complete. + - Refresh your wallet to see the updated balance. + +## Deployment transaction is rejected or fails + +- **Increase gas limit**: + - In the **Deploy & Run Transactions** tab, adjust the **Gas Limit** field. + - Try increasing it by 20-30% from the estimated amount. + +- **Check contract constructor parameters**: + - Ensure any required constructor parameters are provided correctly. + - Verify parameter types match the contract's constructor signature. + +- **Verify contract selection**: + - Ensure you've selected the correct contract from the **Contract** dropdown. + - If you have multiple contracts, make sure you're deploying the intended one. + +## The "Injected Provider - MetaMask" option doesn't appear in the Environment dropdown + +- Select **Browser Extension** from the **Environment** dropdown to populate the **Injected Provider - Metamask** option. +- Ensure your wallet extension is unlocked and active. +- Try disabling and re-enabling the wallet extension. +- Refresh the Remix IDE page. + +## Wallet rejects transactions when trying to interact with deployed contracts + +- **Check wallet unlock status**: + - Ensure your wallet is unlocked. + - Verify you're approving the transaction in the wallet pop-up. + +- **Verify sufficient gas**: + - Ensure you have enough tokens to cover the transaction fee. + - The wallet pop-up should show the estimated gas cost. + +- **Network mismatch**: + - Confirm your wallet is still connected to Polkadot Hub. + - Check that Remix is using the same network. + +## Deployed contract doesn't show in the **Deployed/Unpinned Contracts** section + +- Wait for the transaction to be confirmed on-chain. +- Check the Remix terminal for deployment confirmation. +- Scroll down in the **Deploy & Run Transactions** panel to find the deployed contracts section. +- If the deployment transaction failed, check the terminal for error messages. + +## Blue buttons (read functions) don't display return values + +- **Check the terminal**: + - Return values appear in the terminal panel at the bottom. + - Look for the decoded output section. + +- **Verify contract state**: + - Ensure the contract has been properly initialized. + - Check if the function requires a specific contract state to return values. + +- **Network connection**: + - Verify you're still connected to the correct network. + - Try refreshing the connection to your wallet. + + +## Orange/red buttons (write functions) execute, but the state doesn't change + +- **Wait for transaction confirmation**: + - Transactions need to be mined before state changes are reflected. + - Check the terminal for transaction status. + - Wait a few seconds and try rereading the state. + +- **Transaction failed**: + - Check if the transaction was actually successful in the terminal. + - Look for revert reasons or error messages. + - Verify you approved the transaction in your wallet. + +- **Check transaction parameters**: + - Ensure you're passing the correct parameters to the function. + - For payable functions (red buttons), verify you're sending the correct amount. + +## Remix takes a long time to load or becomes unresponsive + +- **Clear browser cache**: + - Clear your browser's cache and cookies. + - Restart your browser. + +- **Disable unnecessary plugins**: + - In Remix, deactivate plugins you're not using via the Plugin Manager. + +- **Use a supported browser**: + - Use Chrome, Firefox, or Brave for the best compatibility. + - Ensure your browser is up to date. + +## Changes to files or folders don't appear in the File Explorer + +- Click the refresh icon in the **File Explorer**. +- Switch to a different tab and back to **File Explorer**. +- Save your work and reload the Remix IDE page. + + --- Page Title: Use Hardhat with Polkadot Hub @@ -7821,8 +7818,6 @@ Page Title: Wagmi for Polkadot Hub Smart Contracts # Wagmi -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. ## Introduction [Wagmi](https://wagmi.sh/){target=\_blank} is a collection of [React Hooks](https://wagmi.sh/react/api/hooks){target=\_blank} for interacting with Ethereum-compatible blockchains, focusing on developer experience, feature richness, and reliability. @@ -7834,9 +7829,8 @@ This guide demonstrates how to use Wagmi to interact with and deploy smart contr To start working with Wagmi, create a new React project and initialize it by running the following commands in your terminal: ```bash -# Create a new React project using Next.js -npx create-next-app@latest wagmi-asset-hub -cd wagmi-asset-hub +npx create-next-app@latest wagmi-polkadot-hub +cd wagmi-polkadot-hub ``` ## Install Dependencies @@ -7844,15 +7838,14 @@ cd wagmi-asset-hub Install Wagmi and its peer dependencies: ```bash -# Install Wagmi and its dependencies npm install wagmi viem @tanstack/react-query ``` ## Configure Wagmi for Polkadot Hub -Create a configuration file to initialize Wagmi with Polkadot Hub. In your project, create a file named `src/lib/wagmi.ts` and add the code below. Be sure to replace `INSERT_RPC_URL`, `INSERT_CHAIN_ID`, `INSERT_CHAIN_NAME`, `INSERT_NETWORK_NAME`, `INSERT_CHAIN_DECIMALS`, `INSERT_CURRENCY_NAME`, and `INSERT_CURRENCY_SYMBOL` with your specific values. +Create a configuration file to initialize Wagmi with Polkadot Hub. In your project, create a file named `app/lib/wagmi.ts` and add the code below. Be sure to replace `INSERT_RPC_URL`, `INSERT_CHAIN_ID`, `INSERT_CHAIN_NAME`, `INSERT_NETWORK_NAME`, `INSERT_CHAIN_DECIMALS`, `INSERT_CURRENCY_NAME`, and `INSERT_CURRENCY_SYMBOL` with your specific values. -```typescript title="src/lib/wagmi.ts" +```typescript title="app/lib/wagmi.ts" import { http, createConfig } from 'wagmi' // Configure the Polkadot Hub chain @@ -7898,7 +7891,7 @@ export const config = createConfig({ }, rpcUrls: { default: { - http: ['https://testnet-passet-hub-eth-rpc.polkadot.io'], + http: ['https://testnet-passet-hub-eth-rpc.polkadot.io'], // TODO: change to paseo asset hub once ready }, }, } as const; @@ -8038,7 +8031,7 @@ This component uses the following React hooks: ## Interact with Deployed Contract -This guide uses a simple Storage contract already deployed to the Polkadot Hub TestNet (`0x58053f0e8ede1a47a1af53e43368cd04ddcaf66f`). The code of that contract is: +This guide uses a simple Storage contract already deployed to the Polkadot Hub TestNet. The code of that contract is: ??? code "Storage.sol" @@ -8079,7 +8072,7 @@ import { } from "wagmi"; const CONTRACT_ADDRESS = - "0xabBd46Ef74b88E8B1CDa49BeFb5057710443Fd29" as `0x${string}`; + "INSERT_CONTRACT_ADDRESS" as `0x${string}`; export function StorageContract() { const [number, setNumber] = useState("42"); diff --git a/.ai/pages/smart-contracts-libraries-wagmi.md b/.ai/pages/smart-contracts-libraries-wagmi.md index 8b4ffe803..1dd23362e 100644 --- a/.ai/pages/smart-contracts-libraries-wagmi.md +++ b/.ai/pages/smart-contracts-libraries-wagmi.md @@ -7,8 +7,6 @@ url: https://docs.polkadot.com/smart-contracts/libraries/wagmi/ # Wagmi -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. ## Introduction [Wagmi](https://wagmi.sh/){target=\_blank} is a collection of [React Hooks](https://wagmi.sh/react/api/hooks){target=\_blank} for interacting with Ethereum-compatible blockchains, focusing on developer experience, feature richness, and reliability. @@ -20,9 +18,8 @@ This guide demonstrates how to use Wagmi to interact with and deploy smart contr To start working with Wagmi, create a new React project and initialize it by running the following commands in your terminal: ```bash -# Create a new React project using Next.js -npx create-next-app@latest wagmi-asset-hub -cd wagmi-asset-hub +npx create-next-app@latest wagmi-polkadot-hub +cd wagmi-polkadot-hub ``` ## Install Dependencies @@ -30,15 +27,14 @@ cd wagmi-asset-hub Install Wagmi and its peer dependencies: ```bash -# Install Wagmi and its dependencies npm install wagmi viem @tanstack/react-query ``` ## Configure Wagmi for Polkadot Hub -Create a configuration file to initialize Wagmi with Polkadot Hub. In your project, create a file named `src/lib/wagmi.ts` and add the code below. Be sure to replace `INSERT_RPC_URL`, `INSERT_CHAIN_ID`, `INSERT_CHAIN_NAME`, `INSERT_NETWORK_NAME`, `INSERT_CHAIN_DECIMALS`, `INSERT_CURRENCY_NAME`, and `INSERT_CURRENCY_SYMBOL` with your specific values. +Create a configuration file to initialize Wagmi with Polkadot Hub. In your project, create a file named `app/lib/wagmi.ts` and add the code below. Be sure to replace `INSERT_RPC_URL`, `INSERT_CHAIN_ID`, `INSERT_CHAIN_NAME`, `INSERT_NETWORK_NAME`, `INSERT_CHAIN_DECIMALS`, `INSERT_CURRENCY_NAME`, and `INSERT_CURRENCY_SYMBOL` with your specific values. -```typescript title="src/lib/wagmi.ts" +```typescript title="app/lib/wagmi.ts" import { http, createConfig } from 'wagmi' // Configure the Polkadot Hub chain @@ -84,7 +80,7 @@ export const config = createConfig({ }, rpcUrls: { default: { - http: ['https://testnet-passet-hub-eth-rpc.polkadot.io'], + http: ['https://testnet-passet-hub-eth-rpc.polkadot.io'], // TODO: change to paseo asset hub once ready }, }, } as const; @@ -224,7 +220,7 @@ This component uses the following React hooks: ## Interact with Deployed Contract -This guide uses a simple Storage contract already deployed to the Polkadot Hub TestNet (`0x58053f0e8ede1a47a1af53e43368cd04ddcaf66f`). The code of that contract is: +This guide uses a simple Storage contract already deployed to the Polkadot Hub TestNet. The code of that contract is: ??? code "Storage.sol" @@ -265,7 +261,7 @@ import { } from "wagmi"; const CONTRACT_ADDRESS = - "0xabBd46Ef74b88E8B1CDa49BeFb5057710443Fd29" as `0x${string}`; + "INSERT_CONTRACT_ADDRESS" as `0x${string}`; export function StorageContract() { const [number, setNumber] = useState("42"); diff --git a/.ai/pages/smart-contracts-libraries-web3-js.md b/.ai/pages/smart-contracts-libraries-web3-js.md index dbfdfc037..adb4957e1 100644 --- a/.ai/pages/smart-contracts-libraries-web3-js.md +++ b/.ai/pages/smart-contracts-libraries-web3-js.md @@ -73,9 +73,6 @@ Add the Solidity compiler so you can generate standard EVM bytecode: npm install --save-dev solc ``` -!!! tip - The sample scripts use ECMAScript modules. Add `"type": "module"` to your `package.json` (or rename the files to `.mjs`) so that `node` can run the `import` statements. - ## Set Up the Web3 Provider The provider configuration is the foundation of any Web3.js application. It serves as a bridge between your application and the blockchain, allowing you to query blockchain data and interact with smart contracts. @@ -132,7 +129,7 @@ With the provider set up, you can start querying the blockchain. For instance, t const PROVIDER_RPC = { rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', chainId: 420420422, - name: 'polkadot-hub-testnet', + name: 'polkadotTestNet', }; const main = async () => { @@ -395,7 +392,7 @@ You can create a `deploy.js` script in the `scripts` directory of your project t const providerConfig = { rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', // TODO: replace to `https://services.polkadothub-rpc.com/testnet` when ready chainId: 420420422, - name: 'polkadot-hub-testnet', + name: 'polkadotTestNet', }; const privateKey = 'INSERT_PRIVATE_KEY'; @@ -503,7 +500,7 @@ You can create a `deploy.js` script in the `scripts` directory of your project t const providerConfig = { rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', // TODO: replace to `https://services.polkadothub-rpc.com/testnet` when ready chainId: 420420422, - name: 'polkadot-hub-testnet', + name: 'polkadotTestNet', }; const privateKey = 'INSERT_PRIVATE_KEY'; @@ -523,7 +520,7 @@ After running this script, your contract will be deployed to Polkadot Hub, and i ## Interact with the Contract -Once the contract is deployed, you can interact with it by calling its functions. For example, to set a number, read it and then modify that number by its double, you can create a file named `updateStorage.js` in the `scripts` directory of your project and add the following code: +Once the contract is deployed, you can interact with it by calling its functions. For example, to read the current stored value and then update it to a new value, you can create a file named `updateStorage.js` in the `scripts` directory of your project and add the following code: ```js title="scripts/updateStorage.js" const { readFileSync } = require('fs'); @@ -593,7 +590,7 @@ updateStorage(config) .catch((error) => console.error('Update error')); ``` -Ensure you replace the `INSERT_MNEMONIC`, `INSERT_CONTRACT_ADDRESS`, and `INSERT_ADDRESS_TO_CHECK` placeholders with actual values. Also, ensure the contract ABI file (`Storage.json`) is correctly referenced. The script prints the balance for `ADDRESS_TO_CHECK` before it writes and doubles the stored value, so pick any account you want to monitor. +Ensure you replace the `INSERT_PRIVATE_KEY` and `INSERT_CONTRACT_ADDRESS` placeholders with actual values. Also, ensure the contract ABI file (`Storage.json`) is correctly referenced. The script reads the current stored value, sets it to 1, and then displays the updated value. To interact with the contract, run: diff --git a/.ai/site-index.json b/.ai/site-index.json index 2fe21850a..add9764c1 100644 --- a/.ai/site-index.json +++ b/.ai/site-index.json @@ -5265,7 +5265,7 @@ ], "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-libraries-wagmi.md", "html_url": "https://docs.polkadot.com/smart-contracts/libraries/wagmi/", - "preview": "!!! smartcontract \"PolkaVM Preview Release\" PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. ## Introduction", + "preview": "[Wagmi](https://wagmi.sh/){target=\\_blank} is a collection of [React Hooks](https://wagmi.sh/react/api/hooks){target=\\_blank} for interacting with Ethereum-compatible blockchains, focusing on developer experience, feature richness, and reliability.", "outline": [ { "depth": 2, @@ -5319,12 +5319,12 @@ } ], "stats": { - "chars": 13604, - "words": 1515, + "chars": 13340, + "words": 1488, "headings": 10, - "estimated_token_count_total": 3250 + "estimated_token_count_total": 3240 }, - "hash": "sha256:bc771f912627fa09cad64adab1bc81c052f650d6c5a3b4f0c91883a98f6628da", + "hash": "sha256:031259a4d4f3755c9f5c04ed78126abd90831a5fe9fae3a45913e2560a91db6e", "token_estimator": "heuristic-v1" }, { @@ -5401,12 +5401,12 @@ } ], "stats": { - "chars": 20325, - "words": 2290, + "chars": 20056, + "words": 2249, "headings": 12, - "estimated_token_count_total": 4600 + "estimated_token_count_total": 4523 }, - "hash": "sha256:7cf1e07d1b8ef4e7b893398976907159a932f23f708d4e1d7ac1d09b80881787", + "hash": "sha256:ac33422a87258d65a70e63f388279cc2afa4a1e3eec9c1b1aff52ac1ebf9e1a8", "token_estimator": "heuristic-v1" }, { diff --git a/.snippets/code/smart-contracts/libraries/wagmi/StorageContract.tsx b/.snippets/code/smart-contracts/libraries/wagmi/StorageContract.tsx index cd6fa7c72..ee357e311 100644 --- a/.snippets/code/smart-contracts/libraries/wagmi/StorageContract.tsx +++ b/.snippets/code/smart-contracts/libraries/wagmi/StorageContract.tsx @@ -8,7 +8,7 @@ import { } from "wagmi"; const CONTRACT_ADDRESS = - "0xabBd46Ef74b88E8B1CDa49BeFb5057710443Fd29" as `0x${string}`; + "INSERT_CONTRACT_ADDRESS" as `0x${string}`; export function StorageContract() { const [number, setNumber] = useState("42"); diff --git a/.snippets/code/smart-contracts/libraries/wagmi/wagmi-testnet.ts b/.snippets/code/smart-contracts/libraries/wagmi/wagmi-testnet.ts index 7b4f060a0..ec9354be8 100644 --- a/.snippets/code/smart-contracts/libraries/wagmi/wagmi-testnet.ts +++ b/.snippets/code/smart-contracts/libraries/wagmi/wagmi-testnet.ts @@ -12,7 +12,7 @@ const assetHub = { }, rpcUrls: { default: { - http: ['https://testnet-passet-hub-eth-rpc.polkadot.io'], + http: ['https://testnet-passet-hub-eth-rpc.polkadot.io'], // TODO: change to paseo asset hub once ready }, }, } as const; diff --git a/llms-full.jsonl b/llms-full.jsonl index c59e67fab..2e2ddf08c 100644 --- a/llms-full.jsonl +++ b/llms-full.jsonl @@ -712,28 +712,28 @@ {"page_id": "smart-contracts-libraries-viem", "page_title": "viem for Polkadot Hub Smart Contracts", "index": 11, "depth": 2, "title": "Deploy the Contract", "anchor": "deploy-the-contract", "start_char": 10480, "end_char": 12665, "estimated_token_count": 504, "token_estimator": "heuristic-v1", "text": "## Deploy the Contract\n\nCreate a new file at `src/deploy.ts` for handling contract deployment:\n\n```typescript title=\"src/deploy.ts\"\nimport { readFileSync } from 'fs';\nimport { join } from 'path';\nimport { createWallet } from './createWallet';\nimport { publicClient } from './createClient';\n\nconst deployContract = async (\n contractName: string,\n privateKey: `0x${string}`\n) => {\n try {\n console.log(`Deploying ${contractName}...`);\n\n // Read contract artifacts\n const abi = JSON.parse(\n readFileSync(\n join(__dirname, '../artifacts', `${contractName}.json`),\n 'utf8'\n )\n );\n const bytecode = `0x${readFileSync(\n join(__dirname, '../artifacts', `${contractName}.polkavm`)\n ).toString('hex')}` as `0x${string}`;\n\n // Create wallet\n const wallet = createWallet(privateKey);\n\n // Deploy contract\n const hash = await wallet.deployContract({\n abi,\n bytecode,\n args: [], // Add constructor arguments if needed\n });\n\n // Wait for deployment\n const receipt = await publicClient.waitForTransactionReceipt({ hash });\n const contractAddress = receipt.contractAddress;\n\n console.log(`Contract deployed at: ${contractAddress}`);\n return contractAddress;\n } catch (error) {\n console.error('Deployment failed:', error);\n throw error;\n }\n};\n\nconst privateKey = 'INSERT_PRIVATE_KEY';\ndeployContract('Storage', privateKey);\n```\n\nEnsure to replace `INSERT_PRIVATE_KEY` with the proper value. For further details on private key exportation, refer to the article [How to export an account's private key](https://support.metamask.io/configure/accounts/how-to-export-an-accounts-private-key/){target=\\_blank}.\n\n!!! warning\n Never commit or share your private key. Exposed keys can lead to immediate theft of all associated funds. Use environment variables instead.\n\nTo deploy, run the following command:\n\n```bash\nnpm run deploy\n```\n\nIf everything is successful, you will see the address of your deployed contract displayed in the terminal. This address is unique to your contract on the network you defined in the chain configuration, and you'll need it for any future interactions with your contract."} {"page_id": "smart-contracts-libraries-viem", "page_title": "viem for Polkadot Hub Smart Contracts", "index": 12, "depth": 2, "title": "Interact with the Contract", "anchor": "interact-with-the-contract", "start_char": 12665, "end_char": 14831, "estimated_token_count": 455, "token_estimator": "heuristic-v1", "text": "## Interact with the Contract\n\nCreate a new file at `src/interact.ts` for interacting with your deployed contract:\n\n```typescript title=\"src/interact.ts\"\nimport { publicClient } from './createClient';\nimport { createWallet } from './createWallet';\nimport { readFileSync } from 'fs';\n\nconst STORAGE_ABI = JSON.parse(\n readFileSync('./artifacts/Storage.json', 'utf8')\n);\n\nconst interactWithStorage = async (\n contractAddress: `0x${string}`,\n privateKey: `0x${string}`\n) => {\n try {\n const wallet = createWallet(privateKey);\n const currentNumber = await publicClient.readContract({\n address: contractAddress,\n abi: STORAGE_ABI,\n functionName: 'storedNumber',\n args: [],\n });\n console.log(`Stored number: ${currentNumber}`);\n\n const newNumber = BigInt(42);\n const { request } = await publicClient.simulateContract({\n address: contractAddress,\n abi: STORAGE_ABI,\n functionName: 'setNumber',\n args: [newNumber],\n account: wallet.account,\n });\n\n const hash = await wallet.writeContract(request);\n await publicClient.waitForTransactionReceipt({ hash });\n console.log(`Number updated to ${newNumber}`);\n\n const updatedNumber = await publicClient.readContract({\n address: contractAddress,\n abi: STORAGE_ABI,\n functionName: 'storedNumber',\n args: [],\n });\n console.log('Updated stored number:', updatedNumber);\n } catch (error) {\n console.error('Interaction failed:', error);\n }\n};\n\nconst PRIVATE_KEY = 'INSERT_PRIVATE_KEY';\nconst CONTRACT_ADDRESS = 'INSERT_CONTRACT_ADDRESS';\n\ninteractWithStorage(CONTRACT_ADDRESS, PRIVATE_KEY);\n\n```\n\nEnsure to replace `INSERT_PRIVATE_KEY` and `INSERT_CONTRACT_ADDRESS` with the proper values.\n\nTo interact with the contract:\n\n```bash\nnpm run interact\n```\n\nFollowing a successful interaction, you will see the stored value before and after the transaction. The output will show the initial stored number (0 if you haven't modified it yet), confirm when the transaction to set the number to 42 is complete, and then display the updated stored number value. This demonstrates both reading from and writing to your smart contract."} {"page_id": "smart-contracts-libraries-viem", "page_title": "viem for Polkadot Hub Smart Contracts", "index": 13, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 14831, "end_char": 16600, "estimated_token_count": 545, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\nNow that you have the foundation for using viem with Polkadot Hub, consider exploring:\n\n
\n\n- External __Advanced viem Features__\n\n ---\n Explore viem's documentation:\n
    \n
  • [:octicons-arrow-right-24: Multi call](https://viem.sh/docs/contract/multicall#multicall){target=\\_blank}
  • \n\n
  • [:octicons-arrow-right-24: Batch transactions](https://viem.sh/docs/clients/transports/http#batch-json-rpc){target=\\_blank}
  • \n\n
  • [:octicons-arrow-right-24: Custom actions](https://viem.sh/docs/clients/custom#extending-with-actions-or-configuration){target=\\_blank}
  • \n
\n\n- External __Test Frameworks__\n\n ---\n\n Integrate viem with the following frameworks for comprehensive testing:\n
    \n
  • [:octicons-arrow-right-24: Hardhat](https://hardhat.org/){target=\\_blank}
  • \n\n
  • [:octicons-arrow-right-24: Foundry](https://getfoundry.sh/){target=\\_blank}
  • \n
\n\n- External __Event Handling__\n\n ---\n\n Learn how to subscribe to and process contract events:\n
    \n
  • [:octicons-arrow-right-24: Event subscription](https://viem.sh/docs/actions/public/watchEvent#watchevent){target=\\_blank}
  • \n
\n\n- External __Building dApps__\n\n ---\n\n Combine viem the following technologies to create full-stack applications:\n
    \n
  • [:octicons-arrow-right-24: Next.js](https://nextjs.org/docs){target=\\_blank}
  • \n\n
  • [:octicons-arrow-right-24: Node.js](https://nodejs.org/en){target=\\_blank}
  • \n
\n\n
"} -{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 179, "end_char": 607, "estimated_token_count": 97, "token_estimator": "heuristic-v1", "text": "## Introduction\n\n[Wagmi](https://wagmi.sh/){target=\\_blank} is a collection of [React Hooks](https://wagmi.sh/react/api/hooks){target=\\_blank} for interacting with Ethereum-compatible blockchains, focusing on developer experience, feature richness, and reliability.\n\nThis guide demonstrates how to use Wagmi to interact with and deploy smart contracts to Polkadot Hub, providing a seamless frontend integration for your dApps."} -{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 1, "depth": 2, "title": "Set Up the Project", "anchor": "set-up-the-project", "start_char": 607, "end_char": 875, "estimated_token_count": 65, "token_estimator": "heuristic-v1", "text": "## Set Up the Project\n\nTo start working with Wagmi, create a new React project and initialize it by running the following commands in your terminal:\n\n```bash\n# Create a new React project using Next.js\nnpx create-next-app@latest wagmi-asset-hub\ncd wagmi-asset-hub\n```"} -{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 2, "depth": 2, "title": "Install Dependencies", "anchor": "install-dependencies", "start_char": 875, "end_char": 1037, "estimated_token_count": 34, "token_estimator": "heuristic-v1", "text": "## Install Dependencies\n\nInstall Wagmi and its peer dependencies:\n\n```bash\n# Install Wagmi and its dependencies\nnpm install wagmi viem @tanstack/react-query\n```"} -{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 3, "depth": 2, "title": "Configure Wagmi for Polkadot Hub", "anchor": "configure-wagmi-for-polkadot-hub", "start_char": 1037, "end_char": 2725, "estimated_token_count": 381, "token_estimator": "heuristic-v1", "text": "## Configure Wagmi for Polkadot Hub\n\nCreate a configuration file to initialize Wagmi with Polkadot Hub. In your project, create a file named `src/lib/wagmi.ts` and add the code below. Be sure to replace `INSERT_RPC_URL`, `INSERT_CHAIN_ID`, `INSERT_CHAIN_NAME`, `INSERT_NETWORK_NAME`, `INSERT_CHAIN_DECIMALS`, `INSERT_CURRENCY_NAME`, and `INSERT_CURRENCY_SYMBOL` with your specific values.\n\n```typescript title=\"src/lib/wagmi.ts\"\nimport { http, createConfig } from 'wagmi'\n\n// Configure the Polkadot Hub chain\nconst assetHub = {\n id: INSERT_CHAIN_ID,\n name: 'INSERT_CHAIN_NAME',\n network: 'INSERT_NETWORK_NAME',\n nativeCurrency: {\n decimals: INSERT_CHAIN_DECIMALS,\n name: 'INSERT_CURRENCY_NAME',\n symbol: 'INSERT_CURRENCY_SYMBOL',\n },\n rpcUrls: {\n default: {\n http: ['INSERT_RPC_URL'],\n },\n },\n} as const;\n\n// Create Wagmi config\nexport const config = createConfig({\n chains: [assetHub],\n transports: {\n [assetHub.id]: http(),\n },\n})\n```\n\n??? code \"Example Polkadot Hub TestNet Configuration\"\n\n ```typescript title=\"src/lib/wagmi.ts\"\n import { http, createConfig } from 'wagmi';\n\n // Configure the Polkadot Hub chain\n const assetHub = {\n id: 420420422,\n name: 'polkadot-hub-testnet',\n network: 'polkadot-hub-testnet',\n nativeCurrency: {\n decimals: 18,\n name: 'PAS',\n symbol: 'PAS',\n },\n rpcUrls: {\n default: {\n http: ['https://testnet-passet-hub-eth-rpc.polkadot.io'],\n },\n },\n } as const;\n\n // Create wagmi config\n export const config = createConfig({\n chains: [assetHub],\n transports: {\n [assetHub.id]: http(),\n },\n });\n ```"} -{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 4, "depth": 2, "title": "Set Up the Wagmi Provider", "anchor": "set-up-the-wagmi-provider", "start_char": 2725, "end_char": 3769, "estimated_token_count": 263, "token_estimator": "heuristic-v1", "text": "## Set Up the Wagmi Provider\n\nTo enable Wagmi in your React application, you need to wrap your app with the [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider#wagmiprovider){target=\\_blank}. Update your `app/layout.tsx` file (for Next.js app router) with the following code:\n\n```typescript title=\"app/layout.tsx\"\n// For app router (src/app/layout.tsx)\n\"use client\";\n\nimport { WagmiProvider } from \"wagmi\";\nimport { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\nimport { config } from \"./lib/wagmi\";\n\n// Create a query client\nconst queryClient = new QueryClient();\n\nexport default function RootLayout({\n children,\n}: {\n children: React.ReactNode;\n}) {\n return (\n \n \n \n \n {children}\n \n \n \n \n );\n}\n\n```\n\n!!!note\n If you are using a Next.js pages router, you should modify the `src/pages/_app.tsx` instead."} -{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 5, "depth": 2, "title": "Connect a Wallet", "anchor": "connect-a-wallet", "start_char": 3769, "end_char": 5220, "estimated_token_count": 367, "token_estimator": "heuristic-v1", "text": "## Connect a Wallet\n\nCreate a component to connect wallets to your dApp. Create a file named `app/components/ConnectWallet.tsx`:\n\n```typescript title=\"app/components/ConnectWallet.tsx\"\n\"use client\";\n\nimport React from \"react\";\nimport { useConnect, useAccount, useDisconnect } from \"wagmi\";\nimport { injected } from \"wagmi/connectors\";\n\nexport function ConnectWallet() {\n const { connect } = useConnect();\n const { address, isConnected } = useAccount();\n const { disconnect } = useDisconnect();\n\n if (isConnected) {\n return (\n
\n
Connected to {address}
\n \n
\n );\n }\n\n return (\n \n );\n}\n\n```\n\nThis component uses the following React hooks:\n\n- **[`useConnect`](https://wagmi.sh/react/api/hooks/useConnect#useconnect){target=\\_blank}**: Provides functions and state for connecting the user's wallet to your dApp. The `connect` function initiates the connection flow with the specified connector.\n- **[`useDisconnect`](https://wagmi.sh/react/api/hooks/useDisconnect#usedisconnect){target=\\_blank}**: Provides a function to disconnect the currently connected wallet.\n- **[`useAccount`](https://wagmi.sh/react/api/hooks/useAccount#useaccount){target=\\_blank}**: Returns data about the connected account, including the address and connection status."} -{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 6, "depth": 2, "title": "Fetch Blockchain Data", "anchor": "fetch-blockchain-data", "start_char": 5220, "end_char": 6700, "estimated_token_count": 359, "token_estimator": "heuristic-v1", "text": "## Fetch Blockchain Data\n\nWagmi provides various hooks to fetch blockchain data. Here's an example component that demonstrates some of these hooks:\n\n```typescript title=\"app/components/BlockchainInfo.tsx\"\n\"use client\";\n\nimport { useBlockNumber, useBalance, useAccount } from \"wagmi\";\n\nexport function BlockchainInfo() {\n const { address } = useAccount();\n // Get the latest block number\n const { data: blockNumber } = useBlockNumber({ watch: true });\n\n // Get balance for the connected wallet\n const { data: balance } = useBalance({\n address,\n });\n\n return (\n
\n

Blockchain Information

\n
\n

Current Block: {blockNumber?.toString() || \"Loading...\"}

\n\n {address && balance && (\n

\n Balance:{\" \"}\n {(\n BigInt(balance.value) / BigInt(10 ** balance.decimals)\n ).toLocaleString()}{\" \"}\n {balance.symbol}\n

\n )}\n
\n
\n );\n}\n\n```\n\nThis component uses the following React hooks:\n\n- **[`useBlockNumber`](https://wagmi.sh/react/api/hooks/useBlockNumber#useBlockNumber){target=\\_blank}**: Fetches the current block number of the connected chain. The `watch` parameter enables real-time updates when new blocks are mined.\n- **[`useBalance`](https://wagmi.sh/react/api/hooks/useBalance#useBalance){target=\\_blank}**: Retrieves the native token balance for a specified address, including value, symbol, and decimals information."} -{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 7, "depth": 2, "title": "Interact with Deployed Contract", "anchor": "interact-with-deployed-contract", "start_char": 6700, "end_char": 11209, "estimated_token_count": 989, "token_estimator": "heuristic-v1", "text": "## Interact with Deployed Contract\n\nThis guide uses a simple Storage contract already deployed to the Polkadot Hub TestNet (`0x58053f0e8ede1a47a1af53e43368cd04ddcaf66f`). The code of that contract is:\n\n??? code \"Storage.sol\"\n\n ```solidity title=\"Storage.sol\"\n //SPDX-License-Identifier: MIT\n\n // Solidity files have to start with this pragma.\n // It will be used by the Solidity compiler to validate its version.\n pragma solidity ^0.8.9;\n\n contract Storage {\n // Public state variable to store a number\n uint256 public storedNumber;\n\n /**\n * Updates the stored number.\n *\n * The `public` modifier allows anyone to call this function.\n *\n * @param _newNumber - The new value to store.\n */\n function setNumber(uint256 _newNumber) public {\n storedNumber = _newNumber;\n }\n }\n ```\n\nCreate a component to interact with your deployed contract. Create a file named `app/components/StorageContract.tsx`:\n\n```typescript title=\"app/components/StorageContract.tsx\"\n\"use client\";\n\nimport { useState } from \"react\";\nimport {\n useReadContract,\n useWriteContract,\n useWaitForTransactionReceipt,\n} from \"wagmi\";\n\nconst CONTRACT_ADDRESS =\n \"0xabBd46Ef74b88E8B1CDa49BeFb5057710443Fd29\" as `0x${string}`;\n\nexport function StorageContract() {\n const [number, setNumber] = useState(\"42\");\n\n // Contract ABI (should match your compiled contract)\n const abi = [\n {\n inputs: [],\n name: \"storedNumber\",\n outputs: [{ internalType: \"uint256\", name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { internalType: \"uint256\", name: \"_newNumber\", type: \"uint256\" },\n ],\n name: \"setNumber\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n ];\n\n // Read the current stored number\n const { data: storedNumber, refetch } = useReadContract({\n address: CONTRACT_ADDRESS,\n abi,\n functionName: \"storedNumber\",\n });\n\n // Write to the contract\n const { writeContract, data: hash, error, isPending } = useWriteContract();\n\n // Wait for transaction to be mined\n const { isLoading: isConfirming, isSuccess: isConfirmed } =\n useWaitForTransactionReceipt({\n hash,\n });\n\n const handleSetNumber = () => {\n writeContract({\n address: CONTRACT_ADDRESS,\n abi,\n functionName: \"setNumber\",\n args: [BigInt(number)],\n });\n };\n\n return (\n
\n

Storage Contract Interaction

\n
\n

Contract Address: {CONTRACT_ADDRESS}

\n

Current Stored Number: {storedNumber?.toString() || \"Loading...\"}

\n
\n\n
\n setNumber(e.target.value)}\n disabled={isPending || isConfirming}\n />\n \n
\n\n {error &&
Error: {error.message}
}\n\n {isConfirmed && (\n
\n Successfully updated!{\" \"}\n \n
\n )}\n
\n );\n}\n\n```\n\nThis component demonstrates how to interact with a smart contract using Wagmi's hooks:\n\n- **[`useReadContract`](https://wagmi.sh/react/api/hooks/useReadContract#useReadContract){target=\\_blank}**: Calls a read-only function on your smart contract to retrieve data without modifying the blockchain state.\n- **[`useWriteContract`](https://wagmi.sh/react/api/hooks/useWriteContract#useWriteContract){target=\\_blank}**: Calls a state-modifying function on your smart contract, which requires a transaction to be signed and sent.\n- **[`useWaitForTransactionReceipt`](https://wagmi.sh/react/api/hooks/useWaitForTransactionReceipt#useWaitForTransactionReceipt){target=\\_blank}**: Tracks the status of a transaction after it's been submitted, allowing you to know when it's been confirmed.\n\nThe component also includes proper state handling to:\n\n- Show the current value stored in the contract.\n- Allow users to input a new value.\n- Display transaction status (pending, confirming, or completed).\n- Handle errors.\n- Provide feedback when a transaction is successful."} -{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 8, "depth": 2, "title": "Integrate Components", "anchor": "integrate-components", "start_char": 11209, "end_char": 11961, "estimated_token_count": 183, "token_estimator": "heuristic-v1", "text": "## Integrate Components\n\nUpdate your main page to combine all the components. Create or update the file `src/app/page.tsx`:\n\n```typescript title=\"src/app/page.tsx\"\n\"use client\";\n\nimport { BlockchainInfo } from \"./components/BlockchainInfo\";\nimport { ConnectWallet } from \"./components/ConnectWallet\";\nimport { StorageContract } from \"./components/StorageContract\";\nimport { useAccount } from \"wagmi\";\n\nexport default function Home() {\n const { isConnected } = useAccount();\n\n return (\n
\n

Wagmi - Polkadot Hub Smart Contracts

\n \n {isConnected ? : Connect your wallet}\n {isConnected ? : Connect your wallet}\n
\n );\n}\n\n```"} -{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 9, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 11961, "end_char": 13604, "estimated_token_count": 512, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\nNow that you have the foundational knowledge to use Wagmi with Polkadot Hub, consider exploring:\n\n
\n\n- External __Advanced Wagmi__\n\n ---\n\n Explore Wagmi's advanced features:\n\n
    \n
  • [:octicons-arrow-right-24: Watch Contract Events](https://wagmi.sh/core/api/actions/watchContractEvent#eventname){target=\\_blank}
  • \n
  • [:octicons-arrow-right-24: Different Transports](https://wagmi.sh/react/api/transports){target=\\_blank}
  • \n
  • [:octicons-arrow-right-24: Actions](https://wagmi.sh/react/api/actions){target=\\_blank}
  • \n
\n\n- External __Wallet Integration__\n\n ---\n\n Connect your dApp with popular wallet providers:\n\n
    \n
  • [:octicons-arrow-right-24: MetaMask](https://wagmi.sh/core/api/connectors/metaMask){target=\\_blank}
  • \n
  • [:octicons-arrow-right-24: WalletConnect](https://wagmi.sh/core/api/connectors/walletConnect){target=\\_blank}
  • \n
  • [:octicons-arrow-right-24: Coinbase Wallet](https://wagmi.sh/core/api/connectors/coinbaseWallet){target=\\_blank}
  • \n
\n\n- External __Testing & Development__\n\n ---\n\n Enhance your development workflow:\n\n
    \n
  • [:octicons-arrow-right-24: Test Suite](https://wagmi.sh/dev/contributing#_6-running-the-test-suite){target=\\_blank}
  • \n
  • [:octicons-arrow-right-24: Dev Playground](https://wagmi.sh/dev/contributing#_5-running-the-dev-playgrounds){target=\\_blank}
  • \n
\n
"} +{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 9, "end_char": 437, "estimated_token_count": 97, "token_estimator": "heuristic-v1", "text": "## Introduction\n\n[Wagmi](https://wagmi.sh/){target=\\_blank} is a collection of [React Hooks](https://wagmi.sh/react/api/hooks){target=\\_blank} for interacting with Ethereum-compatible blockchains, focusing on developer experience, feature richness, and reliability.\n\nThis guide demonstrates how to use Wagmi to interact with and deploy smart contracts to Polkadot Hub, providing a seamless frontend integration for your dApps."} +{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 1, "depth": 2, "title": "Set Up the Project", "anchor": "set-up-the-project", "start_char": 437, "end_char": 668, "estimated_token_count": 55, "token_estimator": "heuristic-v1", "text": "## Set Up the Project\n\nTo start working with Wagmi, create a new React project and initialize it by running the following commands in your terminal:\n\n```bash\nnpx create-next-app@latest wagmi-polkadot-hub\ncd wagmi-polkadot-hub\n```"} +{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 2, "depth": 2, "title": "Install Dependencies", "anchor": "install-dependencies", "start_char": 668, "end_char": 793, "estimated_token_count": 28, "token_estimator": "heuristic-v1", "text": "## Install Dependencies\n\nInstall Wagmi and its peer dependencies:\n\n```bash\nnpm install wagmi viem @tanstack/react-query\n```"} +{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 3, "depth": 2, "title": "Configure Wagmi for Polkadot Hub", "anchor": "configure-wagmi-for-polkadot-hub", "start_char": 793, "end_char": 2527, "estimated_token_count": 392, "token_estimator": "heuristic-v1", "text": "## Configure Wagmi for Polkadot Hub\n\nCreate a configuration file to initialize Wagmi with Polkadot Hub. In your project, create a file named `app/lib/wagmi.ts` and add the code below. Be sure to replace `INSERT_RPC_URL`, `INSERT_CHAIN_ID`, `INSERT_CHAIN_NAME`, `INSERT_NETWORK_NAME`, `INSERT_CHAIN_DECIMALS`, `INSERT_CURRENCY_NAME`, and `INSERT_CURRENCY_SYMBOL` with your specific values.\n\n```typescript title=\"app/lib/wagmi.ts\"\nimport { http, createConfig } from 'wagmi'\n\n// Configure the Polkadot Hub chain\nconst assetHub = {\n id: INSERT_CHAIN_ID,\n name: 'INSERT_CHAIN_NAME',\n network: 'INSERT_NETWORK_NAME',\n nativeCurrency: {\n decimals: INSERT_CHAIN_DECIMALS,\n name: 'INSERT_CURRENCY_NAME',\n symbol: 'INSERT_CURRENCY_SYMBOL',\n },\n rpcUrls: {\n default: {\n http: ['INSERT_RPC_URL'],\n },\n },\n} as const;\n\n// Create Wagmi config\nexport const config = createConfig({\n chains: [assetHub],\n transports: {\n [assetHub.id]: http(),\n },\n})\n```\n\n??? code \"Example Polkadot Hub TestNet Configuration\"\n\n ```typescript title=\"src/lib/wagmi.ts\"\n import { http, createConfig } from 'wagmi';\n\n // Configure the Polkadot Hub chain\n const assetHub = {\n id: 420420422,\n name: 'polkadot-hub-testnet',\n network: 'polkadot-hub-testnet',\n nativeCurrency: {\n decimals: 18,\n name: 'PAS',\n symbol: 'PAS',\n },\n rpcUrls: {\n default: {\n http: ['https://testnet-passet-hub-eth-rpc.polkadot.io'], // TODO: change to paseo asset hub once ready\n },\n },\n } as const;\n\n // Create wagmi config\n export const config = createConfig({\n chains: [assetHub],\n transports: {\n [assetHub.id]: http(),\n },\n });\n ```"} +{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 4, "depth": 2, "title": "Set Up the Wagmi Provider", "anchor": "set-up-the-wagmi-provider", "start_char": 2527, "end_char": 3571, "estimated_token_count": 263, "token_estimator": "heuristic-v1", "text": "## Set Up the Wagmi Provider\n\nTo enable Wagmi in your React application, you need to wrap your app with the [`WagmiProvider`](https://wagmi.sh/react/api/WagmiProvider#wagmiprovider){target=\\_blank}. Update your `app/layout.tsx` file (for Next.js app router) with the following code:\n\n```typescript title=\"app/layout.tsx\"\n// For app router (src/app/layout.tsx)\n\"use client\";\n\nimport { WagmiProvider } from \"wagmi\";\nimport { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\nimport { config } from \"./lib/wagmi\";\n\n// Create a query client\nconst queryClient = new QueryClient();\n\nexport default function RootLayout({\n children,\n}: {\n children: React.ReactNode;\n}) {\n return (\n \n \n \n \n {children}\n \n \n \n \n );\n}\n\n```\n\n!!!note\n If you are using a Next.js pages router, you should modify the `src/pages/_app.tsx` instead."} +{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 5, "depth": 2, "title": "Connect a Wallet", "anchor": "connect-a-wallet", "start_char": 3571, "end_char": 5022, "estimated_token_count": 367, "token_estimator": "heuristic-v1", "text": "## Connect a Wallet\n\nCreate a component to connect wallets to your dApp. Create a file named `app/components/ConnectWallet.tsx`:\n\n```typescript title=\"app/components/ConnectWallet.tsx\"\n\"use client\";\n\nimport React from \"react\";\nimport { useConnect, useAccount, useDisconnect } from \"wagmi\";\nimport { injected } from \"wagmi/connectors\";\n\nexport function ConnectWallet() {\n const { connect } = useConnect();\n const { address, isConnected } = useAccount();\n const { disconnect } = useDisconnect();\n\n if (isConnected) {\n return (\n
\n
Connected to {address}
\n \n
\n );\n }\n\n return (\n \n );\n}\n\n```\n\nThis component uses the following React hooks:\n\n- **[`useConnect`](https://wagmi.sh/react/api/hooks/useConnect#useconnect){target=\\_blank}**: Provides functions and state for connecting the user's wallet to your dApp. The `connect` function initiates the connection flow with the specified connector.\n- **[`useDisconnect`](https://wagmi.sh/react/api/hooks/useDisconnect#usedisconnect){target=\\_blank}**: Provides a function to disconnect the currently connected wallet.\n- **[`useAccount`](https://wagmi.sh/react/api/hooks/useAccount#useaccount){target=\\_blank}**: Returns data about the connected account, including the address and connection status."} +{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 6, "depth": 2, "title": "Fetch Blockchain Data", "anchor": "fetch-blockchain-data", "start_char": 5022, "end_char": 6502, "estimated_token_count": 359, "token_estimator": "heuristic-v1", "text": "## Fetch Blockchain Data\n\nWagmi provides various hooks to fetch blockchain data. Here's an example component that demonstrates some of these hooks:\n\n```typescript title=\"app/components/BlockchainInfo.tsx\"\n\"use client\";\n\nimport { useBlockNumber, useBalance, useAccount } from \"wagmi\";\n\nexport function BlockchainInfo() {\n const { address } = useAccount();\n // Get the latest block number\n const { data: blockNumber } = useBlockNumber({ watch: true });\n\n // Get balance for the connected wallet\n const { data: balance } = useBalance({\n address,\n });\n\n return (\n
\n

Blockchain Information

\n
\n

Current Block: {blockNumber?.toString() || \"Loading...\"}

\n\n {address && balance && (\n

\n Balance:{\" \"}\n {(\n BigInt(balance.value) / BigInt(10 ** balance.decimals)\n ).toLocaleString()}{\" \"}\n {balance.symbol}\n

\n )}\n
\n
\n );\n}\n\n```\n\nThis component uses the following React hooks:\n\n- **[`useBlockNumber`](https://wagmi.sh/react/api/hooks/useBlockNumber#useBlockNumber){target=\\_blank}**: Fetches the current block number of the connected chain. The `watch` parameter enables real-time updates when new blocks are mined.\n- **[`useBalance`](https://wagmi.sh/react/api/hooks/useBalance#useBalance){target=\\_blank}**: Retrieves the native token balance for a specified address, including value, symbol, and decimals information."} +{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 7, "depth": 2, "title": "Interact with Deployed Contract", "anchor": "interact-with-deployed-contract", "start_char": 6502, "end_char": 10945, "estimated_token_count": 984, "token_estimator": "heuristic-v1", "text": "## Interact with Deployed Contract\n\nThis guide uses a simple Storage contract already deployed to the Polkadot Hub TestNet. The code of that contract is:\n\n??? code \"Storage.sol\"\n\n ```solidity title=\"Storage.sol\"\n //SPDX-License-Identifier: MIT\n\n // Solidity files have to start with this pragma.\n // It will be used by the Solidity compiler to validate its version.\n pragma solidity ^0.8.9;\n\n contract Storage {\n // Public state variable to store a number\n uint256 public storedNumber;\n\n /**\n * Updates the stored number.\n *\n * The `public` modifier allows anyone to call this function.\n *\n * @param _newNumber - The new value to store.\n */\n function setNumber(uint256 _newNumber) public {\n storedNumber = _newNumber;\n }\n }\n ```\n\nCreate a component to interact with your deployed contract. Create a file named `app/components/StorageContract.tsx`:\n\n```typescript title=\"app/components/StorageContract.tsx\"\n\"use client\";\n\nimport { useState } from \"react\";\nimport {\n useReadContract,\n useWriteContract,\n useWaitForTransactionReceipt,\n} from \"wagmi\";\n\nconst CONTRACT_ADDRESS =\n \"INSERT_CONTRACT_ADDRESS\" as `0x${string}`;\n\nexport function StorageContract() {\n const [number, setNumber] = useState(\"42\");\n\n // Contract ABI (should match your compiled contract)\n const abi = [\n {\n inputs: [],\n name: \"storedNumber\",\n outputs: [{ internalType: \"uint256\", name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { internalType: \"uint256\", name: \"_newNumber\", type: \"uint256\" },\n ],\n name: \"setNumber\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n ];\n\n // Read the current stored number\n const { data: storedNumber, refetch } = useReadContract({\n address: CONTRACT_ADDRESS,\n abi,\n functionName: \"storedNumber\",\n });\n\n // Write to the contract\n const { writeContract, data: hash, error, isPending } = useWriteContract();\n\n // Wait for transaction to be mined\n const { isLoading: isConfirming, isSuccess: isConfirmed } =\n useWaitForTransactionReceipt({\n hash,\n });\n\n const handleSetNumber = () => {\n writeContract({\n address: CONTRACT_ADDRESS,\n abi,\n functionName: \"setNumber\",\n args: [BigInt(number)],\n });\n };\n\n return (\n
\n

Storage Contract Interaction

\n
\n

Contract Address: {CONTRACT_ADDRESS}

\n

Current Stored Number: {storedNumber?.toString() || \"Loading...\"}

\n
\n\n
\n setNumber(e.target.value)}\n disabled={isPending || isConfirming}\n />\n \n
\n\n {error &&
Error: {error.message}
}\n\n {isConfirmed && (\n
\n Successfully updated!{\" \"}\n \n
\n )}\n
\n );\n}\n\n```\n\nThis component demonstrates how to interact with a smart contract using Wagmi's hooks:\n\n- **[`useReadContract`](https://wagmi.sh/react/api/hooks/useReadContract#useReadContract){target=\\_blank}**: Calls a read-only function on your smart contract to retrieve data without modifying the blockchain state.\n- **[`useWriteContract`](https://wagmi.sh/react/api/hooks/useWriteContract#useWriteContract){target=\\_blank}**: Calls a state-modifying function on your smart contract, which requires a transaction to be signed and sent.\n- **[`useWaitForTransactionReceipt`](https://wagmi.sh/react/api/hooks/useWaitForTransactionReceipt#useWaitForTransactionReceipt){target=\\_blank}**: Tracks the status of a transaction after it's been submitted, allowing you to know when it's been confirmed.\n\nThe component also includes proper state handling to:\n\n- Show the current value stored in the contract.\n- Allow users to input a new value.\n- Display transaction status (pending, confirming, or completed).\n- Handle errors.\n- Provide feedback when a transaction is successful."} +{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 8, "depth": 2, "title": "Integrate Components", "anchor": "integrate-components", "start_char": 10945, "end_char": 11697, "estimated_token_count": 183, "token_estimator": "heuristic-v1", "text": "## Integrate Components\n\nUpdate your main page to combine all the components. Create or update the file `src/app/page.tsx`:\n\n```typescript title=\"src/app/page.tsx\"\n\"use client\";\n\nimport { BlockchainInfo } from \"./components/BlockchainInfo\";\nimport { ConnectWallet } from \"./components/ConnectWallet\";\nimport { StorageContract } from \"./components/StorageContract\";\nimport { useAccount } from \"wagmi\";\n\nexport default function Home() {\n const { isConnected } = useAccount();\n\n return (\n
\n

Wagmi - Polkadot Hub Smart Contracts

\n \n {isConnected ? : Connect your wallet}\n {isConnected ? : Connect your wallet}\n
\n );\n}\n\n```"} +{"page_id": "smart-contracts-libraries-wagmi", "page_title": "Wagmi for Polkadot Hub Smart Contracts", "index": 9, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 11697, "end_char": 13340, "estimated_token_count": 512, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\nNow that you have the foundational knowledge to use Wagmi with Polkadot Hub, consider exploring:\n\n
\n\n- External __Advanced Wagmi__\n\n ---\n\n Explore Wagmi's advanced features:\n\n
    \n
  • [:octicons-arrow-right-24: Watch Contract Events](https://wagmi.sh/core/api/actions/watchContractEvent#eventname){target=\\_blank}
  • \n
  • [:octicons-arrow-right-24: Different Transports](https://wagmi.sh/react/api/transports){target=\\_blank}
  • \n
  • [:octicons-arrow-right-24: Actions](https://wagmi.sh/react/api/actions){target=\\_blank}
  • \n
\n\n- External __Wallet Integration__\n\n ---\n\n Connect your dApp with popular wallet providers:\n\n
    \n
  • [:octicons-arrow-right-24: MetaMask](https://wagmi.sh/core/api/connectors/metaMask){target=\\_blank}
  • \n
  • [:octicons-arrow-right-24: WalletConnect](https://wagmi.sh/core/api/connectors/walletConnect){target=\\_blank}
  • \n
  • [:octicons-arrow-right-24: Coinbase Wallet](https://wagmi.sh/core/api/connectors/coinbaseWallet){target=\\_blank}
  • \n
\n\n- External __Testing & Development__\n\n ---\n\n Enhance your development workflow:\n\n
    \n
  • [:octicons-arrow-right-24: Test Suite](https://wagmi.sh/dev/contributing#_6-running-the-test-suite){target=\\_blank}
  • \n
  • [:octicons-arrow-right-24: Dev Playground](https://wagmi.sh/dev/contributing#_5-running-the-dev-playgrounds){target=\\_blank}
  • \n
\n
"} {"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 298, "end_char": 857, "estimated_token_count": 102, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nInteracting with blockchains typically requires an interface between your application and the network. [Web3.js](https://web3js.readthedocs.io/){target=\\_blank} offers this interface through a comprehensive collection of libraries, facilitating seamless interaction with the nodes using HTTP or WebSocket protocols. This guide illustrates how to utilize Web3.js specifically for interactions with Polkadot Hub.\n\nThis guide is intended for developers who are familiar with JavaScript and want to interact with the Polkadot Hub using Web3.js."} {"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 1, "depth": 2, "title": "Prerequisites", "anchor": "prerequisites", "start_char": 857, "end_char": 1213, "estimated_token_count": 110, "token_estimator": "heuristic-v1", "text": "## Prerequisites\n\nBefore getting started, ensure you have the following installed:\n\n- **Node.js**: v22.13.1 or later, check the [Node.js installation guide](https://nodejs.org/en/download/current/){target=\\_blank}.\n- **npm**: v6.13.4 or later (comes bundled with Node.js).\n- **Solidity**: This guide uses Solidity `^0.8.9` for smart contract development."} {"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 2, "depth": 2, "title": "Project Structure", "anchor": "project-structure", "start_char": 1213, "end_char": 1691, "estimated_token_count": 135, "token_estimator": "heuristic-v1", "text": "## Project Structure\n\nThis project organizes contracts, scripts, and compiled artifacts for easy development and deployment.\n\n```text\nweb3js-project\n├── contracts\n│ ├── Storage.sol\n├── scripts\n│ ├── connectToProvider.js\n│ ├── fetchLastBlock.js\n│ ├── compile.js\n│ ├── deploy.js\n│ ├── updateStorage.js\n├── abis\n│ ├── Storage.json\n├── artifacts\n│ ├── Storage.bin\n├── contract-address.json\n├── node_modules/\n├── package.json\n├── package-lock.json\n└── README.md\n```"} {"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 3, "depth": 2, "title": "Set Up the Project", "anchor": "set-up-the-project", "start_char": 1691, "end_char": 1910, "estimated_token_count": 50, "token_estimator": "heuristic-v1", "text": "## Set Up the Project\n\nTo start working with Web3.js, create a new folder and initialize your project by running the following commands in your terminal:\n\n```bash\nmkdir web3js-project\ncd web3js-project\nnpm init -y\n```"} -{"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 4, "depth": 2, "title": "Install Dependencies", "anchor": "install-dependencies", "start_char": 1910, "end_char": 2323, "estimated_token_count": 107, "token_estimator": "heuristic-v1", "text": "## Install Dependencies\n\nNext, run the following command to install the Web3.js library:\n\n```bash\nnpm install web3\n```\n\nAdd the Solidity compiler so you can generate standard EVM bytecode:\n\n```bash\nnpm install --save-dev solc\n```\n\n!!! tip\n The sample scripts use ECMAScript modules. Add `\"type\": \"module\"` to your `package.json` (or rename the files to `.mjs`) so that `node` can run the `import` statements."} -{"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 5, "depth": 2, "title": "Set Up the Web3 Provider", "anchor": "set-up-the-web3-provider", "start_char": 2323, "end_char": 4522, "estimated_token_count": 504, "token_estimator": "heuristic-v1", "text": "## Set Up the Web3 Provider\n\nThe provider configuration is the foundation of any Web3.js application. It serves as a bridge between your application and the blockchain, allowing you to query blockchain data and interact with smart contracts.\n\nTo interact with Polkadot Hub, you must set up a Web3.js provider. This provider connects to a blockchain node, allowing you to query blockchain data and interact with smart contracts. In the `scripts` directory of your project, create a file named `connectToProvider.js` and add the following code:\n\n```js title=\"scripts/connectToProvider.js\"\nconst { Web3 } = require('web3');\n\nconst createProvider = (rpcUrl) => {\n const web3 = new Web3(rpcUrl);\n return web3;\n};\n\nconst PROVIDER_RPC = {\n rpc: 'INSERT_RPC_URL',\n chainId: 'INSERT_CHAIN_ID',\n name: 'INSERT_CHAIN_NAME',\n};\n\ncreateProvider(PROVIDER_RPC.rpc);\n\n```\n\n!!! note\n Replace `INSERT_RPC_URL`, `INSERT_CHAIN_ID`, and `INSERT_CHAIN_NAME` with the appropriate values. For example, to connect to Polkadot Hub TestNet's Ethereum RPC instance, you can use the following parameters:\n\n ```js\n const PROVIDER_RPC = {\n rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io',\n chainId: 420420422,\n name: 'polkadot-hub-testnet'\n };\n ```\n\nTo connect to the provider, execute:\n\n```bash\nnode scripts/connectToProvider.js\n```\n\nWith the provider set up, you can start querying the blockchain. For instance, to fetch the latest block number.\n\n??? code \"Fetch last block example\"\n\n ```js title=\"scripts/fetchLastBlock.js\"\n const { Web3 } = require('web3');\n\n const createProvider = (rpcUrl) => {\n const web3 = new Web3(rpcUrl);\n return web3;\n };\n\n const PROVIDER_RPC = {\n rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io',\n chainId: 420420422,\n name: 'polkadot-hub-testnet',\n };\n\n const main = async () => {\n try {\n const web3 = createProvider(PROVIDER_RPC.rpc);\n const latestBlock = await web3.eth.getBlockNumber();\n console.log('Last block: ' + latestBlock);\n } catch (error) {\n console.error('Error connecting to Polkadot Hub TestNet: ' + error.message);\n }\n };\n\n main();\n\n ```"} -{"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 6, "depth": 2, "title": "Compile Contracts", "anchor": "compile-contracts", "start_char": 4522, "end_char": 4849, "estimated_token_count": 74, "token_estimator": "heuristic-v1", "text": "## Compile Contracts\n\nPolkadot Hub exposes an Ethereum JSON-RPC endpoint, so you can compile Solidity contracts to familiar EVM bytecode with the upstream [`solc`](https://www.npmjs.com/package/solc){target=\\_blank} compiler. The resulting artifacts work with any EVM-compatible toolchain and can be deployed through Web3.js."} -{"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 7, "depth": 3, "title": "Sample Storage Smart Contract", "anchor": "sample-storage-smart-contract", "start_char": 4849, "end_char": 5554, "estimated_token_count": 145, "token_estimator": "heuristic-v1", "text": "### Sample Storage Smart Contract\n\nThis example demonstrates compiling a `Storage.sol` Solidity contract for deployment to Polkadot Hub. The contract's functionality stores a number and permits users to update it with a new value.\n\n```solidity title=\"contracts/Storage.sol\"\n//SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\ncontract Storage {\n // Public state variable to store a number\n uint256 public storedNumber;\n\n /**\n * Updates the stored number.\n *\n * The `public` modifier allows anyone to call this function.\n *\n * @param _newNumber - The new value to store.\n */\n function setNumber(uint256 _newNumber) public {\n storedNumber = _newNumber;\n }\n}\n```"} -{"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 8, "depth": 3, "title": "Compile the Smart Contract", "anchor": "compile-the-smart-contract", "start_char": 5554, "end_char": 9111, "estimated_token_count": 810, "token_estimator": "heuristic-v1", "text": "### Compile the Smart Contract\n\nTo compile this contract, use the following script:\n\n```js title=\"scripts/compile.js\"\nconst solc = require('solc');\nconst { readFileSync, writeFileSync, mkdirSync, existsSync } = require('fs');\nconst { basename, join } = require('path');\n\nconst ensureDir = (dirPath) => {\n if (!existsSync(dirPath)) {\n mkdirSync(dirPath, { recursive: true });\n }\n};\n\nconst compileContract = (solidityFilePath, abiDir, artifactsDir) => {\n try {\n // Read the Solidity file\n const source = readFileSync(solidityFilePath, 'utf8');\n const fileName = basename(solidityFilePath);\n \n // Construct the input object for the Solidity compiler\n const input = {\n language: 'Solidity',\n sources: {\n [fileName]: {\n content: source,\n },\n },\n settings: {\n outputSelection: {\n '*': {\n '*': ['abi', 'evm.bytecode'],\n },\n },\n },\n };\n \n console.log(`Compiling contract: ${fileName}...`);\n \n // Compile the contract\n const output = JSON.parse(solc.compile(JSON.stringify(input)));\n \n // Check for errors\n if (output.errors) {\n const errors = output.errors.filter(error => error.severity === 'error');\n if (errors.length > 0) {\n console.error('Compilation errors:');\n errors.forEach(err => console.error(err.formattedMessage));\n return;\n }\n // Show warnings\n const warnings = output.errors.filter(error => error.severity === 'warning');\n warnings.forEach(warn => console.warn(warn.formattedMessage));\n }\n \n // Ensure output directories exist\n ensureDir(abiDir);\n ensureDir(artifactsDir);\n\n // Process compiled contracts\n for (const [sourceFile, contracts] of Object.entries(output.contracts)) {\n for (const [contractName, contract] of Object.entries(contracts)) {\n console.log(`Compiled contract: ${contractName}`);\n \n // Write the ABI\n const abiPath = join(abiDir, `${contractName}.json`);\n writeFileSync(abiPath, JSON.stringify(contract.abi, null, 2));\n console.log(`ABI saved to ${abiPath}`);\n \n // Write the bytecode\n const bytecodePath = join(artifactsDir, `${contractName}.bin`);\n writeFileSync(bytecodePath, contract.evm.bytecode.object);\n console.log(`Bytecode saved to ${bytecodePath}`);\n }\n }\n } catch (error) {\n console.error('Error compiling contracts:', error);\n }\n};\n\nconst solidityFilePath = join(__dirname, '../contracts/Storage.sol');\nconst abiDir = join(__dirname, '../abis');\nconst artifactsDir = join(__dirname, '../artifacts');\n\ncompileContract(solidityFilePath, abiDir, artifactsDir);\n```\n\n!!! note \n The script above is tailored to the `Storage.sol` contract. It can be adjusted for other contracts by changing the file name or modifying the ABI and bytecode paths.\n\nThe ABI (Application Binary Interface) is a JSON representation of your contract's functions, events, and their parameters. It serves as the interface between your JavaScript code and the deployed smart contract, allowing your application to know how to format function calls and interpret returned data.\n\nExecute the script above by running:\n\n```bash\nnode scripts/compile.js\n```\n\nAfter executing the script, the Solidity contract is compiled into standard EVM bytecode. The ABI and bytecode are saved into files with `.json` and `.bin` extensions, respectively. You can now proceed with deploying the contract to Polkadot Hub, as outlined in the next section."} -{"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 9, "depth": 2, "title": "Deploy the Compiled Contract", "anchor": "deploy-the-compiled-contract", "start_char": 9111, "end_char": 17195, "estimated_token_count": 1801, "token_estimator": "heuristic-v1", "text": "## Deploy the Compiled Contract\n\nTo deploy your compiled contract to Polkadot Hub, you'll need a wallet with a private key to sign the deployment transaction.\n\nYou can create a `deploy.js` script in the `scripts` directory of your project to achieve this. The deployment script can be divided into key components:\n\n1. Set up the required imports and utilities:\n\n ```js title=\"scripts/deploy.js\"\n const { writeFileSync, existsSync, readFileSync } = require('fs');\n const { join } = require('path');\n const { Web3 } = require('web3');\n\n const scriptsDir = __dirname;\n const abisDir = join(__dirname, '../abis');\n const artifactsDir = join(__dirname, '../artifacts');\n ```\n\n2. Create a provider to connect to Polkadot Hub:\n\n ```js title=\"scripts/deploy.js\"\n const createProvider = (rpcUrl, chainId, chainName) => {\n const web3 = new Web3(rpcUrl);\n return web3;\n };\n ```\n\n3. Set up functions to read contract artifacts:\n\n ```js title=\"scripts/deploy.js\"\n const getAbi = (contractName) => {\n try {\n const abiPath = join(abisDir, `${contractName}.json`);\n return JSON.parse(readFileSync(abiPath, 'utf8'));\n } catch (error) {\n console.error(\n `Could not find ABI for contract ${contractName}:`,\n error.message,\n );\n throw error;\n }\n };\n\n const getByteCode = (contractName) => {\n try {\n const bytecodePath = join(artifactsDir, `${contractName}.bin`);\n const bytecode = readFileSync(bytecodePath, 'utf8').trim();\n return bytecode.startsWith('0x') ? bytecode : `0x${bytecode}`;\n } catch (error) {\n console.error(\n `Could not find bytecode for contract ${contractName}:`,\n error.message,\n );\n throw error;\n }\n };\n ```\n\n4. Create the main deployment function:\n\n ```js title=\"scripts/deploy.js\"\n const deployContract = async (contractName, privateKey, providerConfig) => {\n console.log(`Deploying ${contractName}...`);\n try {\n const web3 = createProvider(\n providerConfig.rpc,\n providerConfig.chainId,\n providerConfig.name,\n );\n\n const formattedPrivateKey = privateKey.startsWith('0x') ? privateKey : `0x${privateKey}`;\n const account = web3.eth.accounts.privateKeyToAccount(formattedPrivateKey);\n web3.eth.accounts.wallet.add(account);\n web3.eth.defaultAccount = account.address;\n\n const abi = getAbi(contractName);\n const bytecode = getByteCode(contractName);\n const contract = new web3.eth.Contract(abi);\n const deployTx = contract.deploy({\n data: bytecode,\n });\n\n const gas = await deployTx.estimateGas();\n const gasPrice = await web3.eth.getGasPrice();\n\n console.log(`Estimated gas: ${gas}`);\n console.log(`Gas price: ${web3.utils.fromWei(gasPrice, 'gwei')} gwei`);\n\n const deployedContract = await deployTx.send({\n from: account.address,\n gas: gas,\n gasPrice: gasPrice,\n });\n\n const address = deployedContract.options.address;\n console.log(`Contract ${contractName} deployed at: ${address}`);\n\n const addressesFile = join(scriptsDir, 'contract-address.json');\n const addresses = existsSync(addressesFile)\n ? JSON.parse(readFileSync(addressesFile, 'utf8'))\n : {};\n\n addresses[contractName] = address;\n writeFileSync(addressesFile, JSON.stringify(addresses, null, 2), 'utf8');\n } catch (error) {\n console.error(`Failed to deploy contract ${contractName}:`, error);\n }\n };\n ```\n\n5. Configure and execute the deployment:\n\n ```js title=\"scripts/deploy.js\"\n const providerConfig = {\n rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', // TODO: replace to `https://services.polkadothub-rpc.com/testnet` when ready\n chainId: 420420422,\n name: 'polkadot-hub-testnet',\n };\n\n const privateKey = 'INSERT_PRIVATE_KEY';\n\n deployContract('Storage', privateKey, providerConfig);\n ```\n\n !!! note\n\n A private key is a hexadecimal string that is used to sign and pay for the deployment transaction. **Always keep your private key secure and never share it publicly**.\n\n Ensure to replace the `INSERT_PRIVATE_KEY` placeholder with your actual private key.\n\n??? code \"View complete script\"\n\n ```js title=\"scripts/deploy.js\"\n const { writeFileSync, existsSync, readFileSync } = require('fs');\n const { join } = require('path');\n const { Web3 } = require('web3');\n\n const scriptsDir = __dirname;\n const abisDir = join(__dirname, '../abis');\n const artifactsDir = join(__dirname, '../artifacts');\n\n const createProvider = (rpcUrl, chainId, chainName) => {\n const web3 = new Web3(rpcUrl);\n return web3;\n };\n\n const getAbi = (contractName) => {\n try {\n const abiPath = join(abisDir, `${contractName}.json`);\n return JSON.parse(readFileSync(abiPath, 'utf8'));\n } catch (error) {\n console.error(\n `Could not find ABI for contract ${contractName}:`,\n error.message,\n );\n throw error;\n }\n };\n\n const getByteCode = (contractName) => {\n try {\n const bytecodePath = join(artifactsDir, `${contractName}.bin`);\n const bytecode = readFileSync(bytecodePath, 'utf8').trim();\n return bytecode.startsWith('0x') ? bytecode : `0x${bytecode}`;\n } catch (error) {\n console.error(\n `Could not find bytecode for contract ${contractName}:`,\n error.message,\n );\n throw error;\n }\n };\n\n const deployContract = async (contractName, privateKey, providerConfig) => {\n console.log(`Deploying ${contractName}...`);\n try {\n const web3 = createProvider(\n providerConfig.rpc,\n providerConfig.chainId,\n providerConfig.name,\n );\n\n const formattedPrivateKey = privateKey.startsWith('0x') ? privateKey : `0x${privateKey}`;\n const account = web3.eth.accounts.privateKeyToAccount(formattedPrivateKey);\n web3.eth.accounts.wallet.add(account);\n web3.eth.defaultAccount = account.address;\n\n const abi = getAbi(contractName);\n const bytecode = getByteCode(contractName);\n const contract = new web3.eth.Contract(abi);\n const deployTx = contract.deploy({\n data: bytecode,\n });\n\n const gas = await deployTx.estimateGas();\n const gasPrice = await web3.eth.getGasPrice();\n\n console.log(`Estimated gas: ${gas}`);\n console.log(`Gas price: ${web3.utils.fromWei(gasPrice, 'gwei')} gwei`);\n\n const deployedContract = await deployTx.send({\n from: account.address,\n gas: gas,\n gasPrice: gasPrice,\n });\n\n const address = deployedContract.options.address;\n console.log(`Contract ${contractName} deployed at: ${address}`);\n\n const addressesFile = join(scriptsDir, 'contract-address.json');\n const addresses = existsSync(addressesFile)\n ? JSON.parse(readFileSync(addressesFile, 'utf8'))\n : {};\n\n addresses[contractName] = address;\n writeFileSync(addressesFile, JSON.stringify(addresses, null, 2), 'utf8');\n } catch (error) {\n console.error(`Failed to deploy contract ${contractName}:`, error);\n }\n };\n\n const providerConfig = {\n rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', // TODO: replace to `https://services.polkadothub-rpc.com/testnet` when ready\n chainId: 420420422,\n name: 'polkadot-hub-testnet',\n };\n\n const privateKey = 'INSERT_PRIVATE_KEY';\n\n deployContract('Storage', privateKey, providerConfig);\n\n\n ```\n\nTo run the script, execute the following command:\n\n```bash\nnode scripts/deploy.js\n```\n\nAfter running this script, your contract will be deployed to Polkadot Hub, and its address will be saved in `contract-address.json` within your project directory. You can use this address for future contract interactions."} -{"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 10, "depth": 2, "title": "Interact with the Contract", "anchor": "interact-with-the-contract", "start_char": 17195, "end_char": 19945, "estimated_token_count": 659, "token_estimator": "heuristic-v1", "text": "## Interact with the Contract\n\nOnce the contract is deployed, you can interact with it by calling its functions. For example, to set a number, read it and then modify that number by its double, you can create a file named `updateStorage.js` in the `scripts` directory of your project and add the following code:\n\n```js title=\"scripts/updateStorage.js\"\nconst { readFileSync } = require('fs');\nconst { join } = require('path');\nconst { Web3 } = require('web3');\n\nconst abisDir = join(__dirname, '../abis');\n\nconst getAbi = (contractName) => {\n try {\n const abiPath = join(abisDir, `${contractName}.json`);\n return JSON.parse(readFileSync(abiPath, 'utf8'));\n } catch (error) {\n console.error(\n `Could not find ABI for contract ${contractName}:`,\n error.message,\n );\n throw error;\n }\n};\n\nconst updateStorage = async (config) => {\n try {\n const web3 = new Web3(config.rpcUrl);\n const formattedPrivateKey = config.privateKey.startsWith('0x') ? config.privateKey : `0x${config.privateKey}`;\n const account = web3.eth.accounts.privateKeyToAccount(formattedPrivateKey);\n web3.eth.accounts.wallet.add(account);\n\n const abi = getAbi('Storage');\n const contract = new web3.eth.Contract(abi, config.contractAddress);\n\n const initialValue = await contract.methods.storedNumber().call();\n console.log('Current stored value:', initialValue);\n\n const updateTransaction = contract.methods.setNumber(1);\n const gasEstimate = await updateTransaction.estimateGas({\n from: account.address,\n });\n const gasPrice = await web3.eth.getGasPrice();\n\n const receipt = await updateTransaction.send({\n from: account.address,\n gas: gasEstimate,\n gasPrice: gasPrice,\n });\n\n console.log(`Transaction hash: ${receipt.transactionHash}`);\n\n const newValue = await contract.methods.storedNumber().call();\n console.log('New stored value:', newValue);\n\n return receipt;\n } catch (error) {\n console.error('Update failed:', error);\n throw error;\n }\n};\n\nconst config = {\n rpcUrl: 'https://testnet-passet-hub-eth-rpc.polkadot.io',\n privateKey: 'INSERT_PRIVATE_KEY',\n contractAddress: 'INSERT_CONTRACT_ADDRESS',\n};\n\nupdateStorage(config)\n .then((receipt) => console.log('Update successful'))\n .catch((error) => console.error('Update error'));\n```\n\nEnsure you replace the `INSERT_MNEMONIC`, `INSERT_CONTRACT_ADDRESS`, and `INSERT_ADDRESS_TO_CHECK` placeholders with actual values. Also, ensure the contract ABI file (`Storage.json`) is correctly referenced. The script prints the balance for `ADDRESS_TO_CHECK` before it writes and doubles the stored value, so pick any account you want to monitor.\n\nTo interact with the contract, run:\n\n```bash\nnode scripts/updateStorage.js\n```"} -{"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 11, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 19945, "end_char": 20325, "estimated_token_count": 103, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\n
\n\n- External __Web3.js Docs__\n\n ---\n\n Explore the Web3.js documentation to learn how to use additional features, such as wallet management, signing messages, subscribing to events, etc.\n\n [:octicons-arrow-right-24: Get Started](https://web3js.readthedocs.io/en/v1.10.0/)\n\n
"} +{"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 4, "depth": 2, "title": "Install Dependencies", "anchor": "install-dependencies", "start_char": 1910, "end_char": 2141, "estimated_token_count": 55, "token_estimator": "heuristic-v1", "text": "## Install Dependencies\n\nNext, run the following command to install the Web3.js library:\n\n```bash\nnpm install web3\n```\n\nAdd the Solidity compiler so you can generate standard EVM bytecode:\n\n```bash\nnpm install --save-dev solc\n```"} +{"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 5, "depth": 2, "title": "Set Up the Web3 Provider", "anchor": "set-up-the-web3-provider", "start_char": 2141, "end_char": 4335, "estimated_token_count": 500, "token_estimator": "heuristic-v1", "text": "## Set Up the Web3 Provider\n\nThe provider configuration is the foundation of any Web3.js application. It serves as a bridge between your application and the blockchain, allowing you to query blockchain data and interact with smart contracts.\n\nTo interact with Polkadot Hub, you must set up a Web3.js provider. This provider connects to a blockchain node, allowing you to query blockchain data and interact with smart contracts. In the `scripts` directory of your project, create a file named `connectToProvider.js` and add the following code:\n\n```js title=\"scripts/connectToProvider.js\"\nconst { Web3 } = require('web3');\n\nconst createProvider = (rpcUrl) => {\n const web3 = new Web3(rpcUrl);\n return web3;\n};\n\nconst PROVIDER_RPC = {\n rpc: 'INSERT_RPC_URL',\n chainId: 'INSERT_CHAIN_ID',\n name: 'INSERT_CHAIN_NAME',\n};\n\ncreateProvider(PROVIDER_RPC.rpc);\n\n```\n\n!!! note\n Replace `INSERT_RPC_URL`, `INSERT_CHAIN_ID`, and `INSERT_CHAIN_NAME` with the appropriate values. For example, to connect to Polkadot Hub TestNet's Ethereum RPC instance, you can use the following parameters:\n\n ```js\n const PROVIDER_RPC = {\n rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io',\n chainId: 420420422,\n name: 'polkadot-hub-testnet'\n };\n ```\n\nTo connect to the provider, execute:\n\n```bash\nnode scripts/connectToProvider.js\n```\n\nWith the provider set up, you can start querying the blockchain. For instance, to fetch the latest block number.\n\n??? code \"Fetch last block example\"\n\n ```js title=\"scripts/fetchLastBlock.js\"\n const { Web3 } = require('web3');\n\n const createProvider = (rpcUrl) => {\n const web3 = new Web3(rpcUrl);\n return web3;\n };\n\n const PROVIDER_RPC = {\n rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io',\n chainId: 420420422,\n name: 'polkadotTestNet',\n };\n\n const main = async () => {\n try {\n const web3 = createProvider(PROVIDER_RPC.rpc);\n const latestBlock = await web3.eth.getBlockNumber();\n console.log('Last block: ' + latestBlock);\n } catch (error) {\n console.error('Error connecting to Polkadot Hub TestNet: ' + error.message);\n }\n };\n\n main();\n\n ```"} +{"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 6, "depth": 2, "title": "Compile Contracts", "anchor": "compile-contracts", "start_char": 4335, "end_char": 4662, "estimated_token_count": 74, "token_estimator": "heuristic-v1", "text": "## Compile Contracts\n\nPolkadot Hub exposes an Ethereum JSON-RPC endpoint, so you can compile Solidity contracts to familiar EVM bytecode with the upstream [`solc`](https://www.npmjs.com/package/solc){target=\\_blank} compiler. The resulting artifacts work with any EVM-compatible toolchain and can be deployed through Web3.js."} +{"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 7, "depth": 3, "title": "Sample Storage Smart Contract", "anchor": "sample-storage-smart-contract", "start_char": 4662, "end_char": 5367, "estimated_token_count": 145, "token_estimator": "heuristic-v1", "text": "### Sample Storage Smart Contract\n\nThis example demonstrates compiling a `Storage.sol` Solidity contract for deployment to Polkadot Hub. The contract's functionality stores a number and permits users to update it with a new value.\n\n```solidity title=\"contracts/Storage.sol\"\n//SPDX-License-Identifier: MIT\npragma solidity ^0.8.9;\n\ncontract Storage {\n // Public state variable to store a number\n uint256 public storedNumber;\n\n /**\n * Updates the stored number.\n *\n * The `public` modifier allows anyone to call this function.\n *\n * @param _newNumber - The new value to store.\n */\n function setNumber(uint256 _newNumber) public {\n storedNumber = _newNumber;\n }\n}\n```"} +{"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 8, "depth": 3, "title": "Compile the Smart Contract", "anchor": "compile-the-smart-contract", "start_char": 5367, "end_char": 8924, "estimated_token_count": 810, "token_estimator": "heuristic-v1", "text": "### Compile the Smart Contract\n\nTo compile this contract, use the following script:\n\n```js title=\"scripts/compile.js\"\nconst solc = require('solc');\nconst { readFileSync, writeFileSync, mkdirSync, existsSync } = require('fs');\nconst { basename, join } = require('path');\n\nconst ensureDir = (dirPath) => {\n if (!existsSync(dirPath)) {\n mkdirSync(dirPath, { recursive: true });\n }\n};\n\nconst compileContract = (solidityFilePath, abiDir, artifactsDir) => {\n try {\n // Read the Solidity file\n const source = readFileSync(solidityFilePath, 'utf8');\n const fileName = basename(solidityFilePath);\n \n // Construct the input object for the Solidity compiler\n const input = {\n language: 'Solidity',\n sources: {\n [fileName]: {\n content: source,\n },\n },\n settings: {\n outputSelection: {\n '*': {\n '*': ['abi', 'evm.bytecode'],\n },\n },\n },\n };\n \n console.log(`Compiling contract: ${fileName}...`);\n \n // Compile the contract\n const output = JSON.parse(solc.compile(JSON.stringify(input)));\n \n // Check for errors\n if (output.errors) {\n const errors = output.errors.filter(error => error.severity === 'error');\n if (errors.length > 0) {\n console.error('Compilation errors:');\n errors.forEach(err => console.error(err.formattedMessage));\n return;\n }\n // Show warnings\n const warnings = output.errors.filter(error => error.severity === 'warning');\n warnings.forEach(warn => console.warn(warn.formattedMessage));\n }\n \n // Ensure output directories exist\n ensureDir(abiDir);\n ensureDir(artifactsDir);\n\n // Process compiled contracts\n for (const [sourceFile, contracts] of Object.entries(output.contracts)) {\n for (const [contractName, contract] of Object.entries(contracts)) {\n console.log(`Compiled contract: ${contractName}`);\n \n // Write the ABI\n const abiPath = join(abiDir, `${contractName}.json`);\n writeFileSync(abiPath, JSON.stringify(contract.abi, null, 2));\n console.log(`ABI saved to ${abiPath}`);\n \n // Write the bytecode\n const bytecodePath = join(artifactsDir, `${contractName}.bin`);\n writeFileSync(bytecodePath, contract.evm.bytecode.object);\n console.log(`Bytecode saved to ${bytecodePath}`);\n }\n }\n } catch (error) {\n console.error('Error compiling contracts:', error);\n }\n};\n\nconst solidityFilePath = join(__dirname, '../contracts/Storage.sol');\nconst abiDir = join(__dirname, '../abis');\nconst artifactsDir = join(__dirname, '../artifacts');\n\ncompileContract(solidityFilePath, abiDir, artifactsDir);\n```\n\n!!! note \n The script above is tailored to the `Storage.sol` contract. It can be adjusted for other contracts by changing the file name or modifying the ABI and bytecode paths.\n\nThe ABI (Application Binary Interface) is a JSON representation of your contract's functions, events, and their parameters. It serves as the interface between your JavaScript code and the deployed smart contract, allowing your application to know how to format function calls and interpret returned data.\n\nExecute the script above by running:\n\n```bash\nnode scripts/compile.js\n```\n\nAfter executing the script, the Solidity contract is compiled into standard EVM bytecode. The ABI and bytecode are saved into files with `.json` and `.bin` extensions, respectively. You can now proceed with deploying the contract to Polkadot Hub, as outlined in the next section."} +{"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 9, "depth": 2, "title": "Deploy the Compiled Contract", "anchor": "deploy-the-compiled-contract", "start_char": 8924, "end_char": 16998, "estimated_token_count": 1793, "token_estimator": "heuristic-v1", "text": "## Deploy the Compiled Contract\n\nTo deploy your compiled contract to Polkadot Hub, you'll need a wallet with a private key to sign the deployment transaction.\n\nYou can create a `deploy.js` script in the `scripts` directory of your project to achieve this. The deployment script can be divided into key components:\n\n1. Set up the required imports and utilities:\n\n ```js title=\"scripts/deploy.js\"\n const { writeFileSync, existsSync, readFileSync } = require('fs');\n const { join } = require('path');\n const { Web3 } = require('web3');\n\n const scriptsDir = __dirname;\n const abisDir = join(__dirname, '../abis');\n const artifactsDir = join(__dirname, '../artifacts');\n ```\n\n2. Create a provider to connect to Polkadot Hub:\n\n ```js title=\"scripts/deploy.js\"\n const createProvider = (rpcUrl, chainId, chainName) => {\n const web3 = new Web3(rpcUrl);\n return web3;\n };\n ```\n\n3. Set up functions to read contract artifacts:\n\n ```js title=\"scripts/deploy.js\"\n const getAbi = (contractName) => {\n try {\n const abiPath = join(abisDir, `${contractName}.json`);\n return JSON.parse(readFileSync(abiPath, 'utf8'));\n } catch (error) {\n console.error(\n `Could not find ABI for contract ${contractName}:`,\n error.message,\n );\n throw error;\n }\n };\n\n const getByteCode = (contractName) => {\n try {\n const bytecodePath = join(artifactsDir, `${contractName}.bin`);\n const bytecode = readFileSync(bytecodePath, 'utf8').trim();\n return bytecode.startsWith('0x') ? bytecode : `0x${bytecode}`;\n } catch (error) {\n console.error(\n `Could not find bytecode for contract ${contractName}:`,\n error.message,\n );\n throw error;\n }\n };\n ```\n\n4. Create the main deployment function:\n\n ```js title=\"scripts/deploy.js\"\n const deployContract = async (contractName, privateKey, providerConfig) => {\n console.log(`Deploying ${contractName}...`);\n try {\n const web3 = createProvider(\n providerConfig.rpc,\n providerConfig.chainId,\n providerConfig.name,\n );\n\n const formattedPrivateKey = privateKey.startsWith('0x') ? privateKey : `0x${privateKey}`;\n const account = web3.eth.accounts.privateKeyToAccount(formattedPrivateKey);\n web3.eth.accounts.wallet.add(account);\n web3.eth.defaultAccount = account.address;\n\n const abi = getAbi(contractName);\n const bytecode = getByteCode(contractName);\n const contract = new web3.eth.Contract(abi);\n const deployTx = contract.deploy({\n data: bytecode,\n });\n\n const gas = await deployTx.estimateGas();\n const gasPrice = await web3.eth.getGasPrice();\n\n console.log(`Estimated gas: ${gas}`);\n console.log(`Gas price: ${web3.utils.fromWei(gasPrice, 'gwei')} gwei`);\n\n const deployedContract = await deployTx.send({\n from: account.address,\n gas: gas,\n gasPrice: gasPrice,\n });\n\n const address = deployedContract.options.address;\n console.log(`Contract ${contractName} deployed at: ${address}`);\n\n const addressesFile = join(scriptsDir, 'contract-address.json');\n const addresses = existsSync(addressesFile)\n ? JSON.parse(readFileSync(addressesFile, 'utf8'))\n : {};\n\n addresses[contractName] = address;\n writeFileSync(addressesFile, JSON.stringify(addresses, null, 2), 'utf8');\n } catch (error) {\n console.error(`Failed to deploy contract ${contractName}:`, error);\n }\n };\n ```\n\n5. Configure and execute the deployment:\n\n ```js title=\"scripts/deploy.js\"\n const providerConfig = {\n rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', // TODO: replace to `https://services.polkadothub-rpc.com/testnet` when ready\n chainId: 420420422,\n name: 'polkadotTestNet',\n };\n\n const privateKey = 'INSERT_PRIVATE_KEY';\n\n deployContract('Storage', privateKey, providerConfig);\n ```\n\n !!! note\n\n A private key is a hexadecimal string that is used to sign and pay for the deployment transaction. **Always keep your private key secure and never share it publicly**.\n\n Ensure to replace the `INSERT_PRIVATE_KEY` placeholder with your actual private key.\n\n??? code \"View complete script\"\n\n ```js title=\"scripts/deploy.js\"\n const { writeFileSync, existsSync, readFileSync } = require('fs');\n const { join } = require('path');\n const { Web3 } = require('web3');\n\n const scriptsDir = __dirname;\n const abisDir = join(__dirname, '../abis');\n const artifactsDir = join(__dirname, '../artifacts');\n\n const createProvider = (rpcUrl, chainId, chainName) => {\n const web3 = new Web3(rpcUrl);\n return web3;\n };\n\n const getAbi = (contractName) => {\n try {\n const abiPath = join(abisDir, `${contractName}.json`);\n return JSON.parse(readFileSync(abiPath, 'utf8'));\n } catch (error) {\n console.error(\n `Could not find ABI for contract ${contractName}:`,\n error.message,\n );\n throw error;\n }\n };\n\n const getByteCode = (contractName) => {\n try {\n const bytecodePath = join(artifactsDir, `${contractName}.bin`);\n const bytecode = readFileSync(bytecodePath, 'utf8').trim();\n return bytecode.startsWith('0x') ? bytecode : `0x${bytecode}`;\n } catch (error) {\n console.error(\n `Could not find bytecode for contract ${contractName}:`,\n error.message,\n );\n throw error;\n }\n };\n\n const deployContract = async (contractName, privateKey, providerConfig) => {\n console.log(`Deploying ${contractName}...`);\n try {\n const web3 = createProvider(\n providerConfig.rpc,\n providerConfig.chainId,\n providerConfig.name,\n );\n\n const formattedPrivateKey = privateKey.startsWith('0x') ? privateKey : `0x${privateKey}`;\n const account = web3.eth.accounts.privateKeyToAccount(formattedPrivateKey);\n web3.eth.accounts.wallet.add(account);\n web3.eth.defaultAccount = account.address;\n\n const abi = getAbi(contractName);\n const bytecode = getByteCode(contractName);\n const contract = new web3.eth.Contract(abi);\n const deployTx = contract.deploy({\n data: bytecode,\n });\n\n const gas = await deployTx.estimateGas();\n const gasPrice = await web3.eth.getGasPrice();\n\n console.log(`Estimated gas: ${gas}`);\n console.log(`Gas price: ${web3.utils.fromWei(gasPrice, 'gwei')} gwei`);\n\n const deployedContract = await deployTx.send({\n from: account.address,\n gas: gas,\n gasPrice: gasPrice,\n });\n\n const address = deployedContract.options.address;\n console.log(`Contract ${contractName} deployed at: ${address}`);\n\n const addressesFile = join(scriptsDir, 'contract-address.json');\n const addresses = existsSync(addressesFile)\n ? JSON.parse(readFileSync(addressesFile, 'utf8'))\n : {};\n\n addresses[contractName] = address;\n writeFileSync(addressesFile, JSON.stringify(addresses, null, 2), 'utf8');\n } catch (error) {\n console.error(`Failed to deploy contract ${contractName}:`, error);\n }\n };\n\n const providerConfig = {\n rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', // TODO: replace to `https://services.polkadothub-rpc.com/testnet` when ready\n chainId: 420420422,\n name: 'polkadotTestNet',\n };\n\n const privateKey = 'INSERT_PRIVATE_KEY';\n\n deployContract('Storage', privateKey, providerConfig);\n\n\n ```\n\nTo run the script, execute the following command:\n\n```bash\nnode scripts/deploy.js\n```\n\nAfter running this script, your contract will be deployed to Polkadot Hub, and its address will be saved in `contract-address.json` within your project directory. You can use this address for future contract interactions."} +{"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 10, "depth": 2, "title": "Interact with the Contract", "anchor": "interact-with-the-contract", "start_char": 16998, "end_char": 19676, "estimated_token_count": 646, "token_estimator": "heuristic-v1", "text": "## Interact with the Contract\n\nOnce the contract is deployed, you can interact with it by calling its functions. For example, to read the current stored value and then update it to a new value, you can create a file named `updateStorage.js` in the `scripts` directory of your project and add the following code:\n\n```js title=\"scripts/updateStorage.js\"\nconst { readFileSync } = require('fs');\nconst { join } = require('path');\nconst { Web3 } = require('web3');\n\nconst abisDir = join(__dirname, '../abis');\n\nconst getAbi = (contractName) => {\n try {\n const abiPath = join(abisDir, `${contractName}.json`);\n return JSON.parse(readFileSync(abiPath, 'utf8'));\n } catch (error) {\n console.error(\n `Could not find ABI for contract ${contractName}:`,\n error.message,\n );\n throw error;\n }\n};\n\nconst updateStorage = async (config) => {\n try {\n const web3 = new Web3(config.rpcUrl);\n const formattedPrivateKey = config.privateKey.startsWith('0x') ? config.privateKey : `0x${config.privateKey}`;\n const account = web3.eth.accounts.privateKeyToAccount(formattedPrivateKey);\n web3.eth.accounts.wallet.add(account);\n\n const abi = getAbi('Storage');\n const contract = new web3.eth.Contract(abi, config.contractAddress);\n\n const initialValue = await contract.methods.storedNumber().call();\n console.log('Current stored value:', initialValue);\n\n const updateTransaction = contract.methods.setNumber(1);\n const gasEstimate = await updateTransaction.estimateGas({\n from: account.address,\n });\n const gasPrice = await web3.eth.getGasPrice();\n\n const receipt = await updateTransaction.send({\n from: account.address,\n gas: gasEstimate,\n gasPrice: gasPrice,\n });\n\n console.log(`Transaction hash: ${receipt.transactionHash}`);\n\n const newValue = await contract.methods.storedNumber().call();\n console.log('New stored value:', newValue);\n\n return receipt;\n } catch (error) {\n console.error('Update failed:', error);\n throw error;\n }\n};\n\nconst config = {\n rpcUrl: 'https://testnet-passet-hub-eth-rpc.polkadot.io',\n privateKey: 'INSERT_PRIVATE_KEY',\n contractAddress: 'INSERT_CONTRACT_ADDRESS',\n};\n\nupdateStorage(config)\n .then((receipt) => console.log('Update successful'))\n .catch((error) => console.error('Update error'));\n```\n\nEnsure you replace the `INSERT_PRIVATE_KEY` and `INSERT_CONTRACT_ADDRESS` placeholders with actual values. Also, ensure the contract ABI file (`Storage.json`) is correctly referenced. The script reads the current stored value, sets it to 1, and then displays the updated value.\n\nTo interact with the contract, run:\n\n```bash\nnode scripts/updateStorage.js\n```"} +{"page_id": "smart-contracts-libraries-web3-js", "page_title": "Deploy Contracts to Polkadot Hub with Web3.js", "index": 11, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 19676, "end_char": 20056, "estimated_token_count": 103, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\n
\n\n- External __Web3.js Docs__\n\n ---\n\n Explore the Web3.js documentation to learn how to use additional features, such as wallet management, signing messages, subscribing to events, etc.\n\n [:octicons-arrow-right-24: Get Started](https://web3js.readthedocs.io/en/v1.10.0/)\n\n
"} {"page_id": "smart-contracts-libraries-web3-py", "page_title": "Web3.py", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 181, "end_char": 605, "estimated_token_count": 83, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nInteracting with blockchains typically requires an interface between your application and the network. [Web3.py](https://web3py.readthedocs.io/en/stable/index.html){target=\\_blank} offers this interface through a collection of libraries, facilitating seamless interaction with the nodes using HTTP or WebSocket protocols. \n\nThis guide illustrates how to utilize Web3.py for interactions with Polkadot Hub."} {"page_id": "smart-contracts-libraries-web3-py", "page_title": "Web3.py", "index": 1, "depth": 2, "title": "Set Up the Project", "anchor": "set-up-the-project", "start_char": 605, "end_char": 986, "estimated_token_count": 88, "token_estimator": "heuristic-v1", "text": "## Set Up the Project\n\n1. To start working with Web3.py, begin by initializing your project:\n\n ```bash\n mkdir web3py-project\n cd web3py-project\n ```\n\n2. Create and activate a virtual environment for your project:\n\n ```bash\n python -m venv venv\n source venv/bin/activate\n ```\n\n3. Next, install the Web3.py library:\n\n ```bash\n pip install web3\n ```"} {"page_id": "smart-contracts-libraries-web3-py", "page_title": "Web3.py", "index": 2, "depth": 2, "title": "Set Up the Web3 Provider", "anchor": "set-up-the-web3-provider", "start_char": 986, "end_char": 3080, "estimated_token_count": 423, "token_estimator": "heuristic-v1", "text": "## Set Up the Web3 Provider\n\nThe [provider](https://web3py.readthedocs.io/en/stable/providers.html){target=\\_blank} configuration is the foundation of any Web3.py application. The following example establishes a connection to Polkadot Hub. Follow these steps to use the provider configuration:\n\n1. Replace `INSERT_RPC_URL` with the appropriate value. For instance, to connect to Polkadot Hub TestNet, use the following parameter:\n\n ```python\n PROVIDER_RPC = 'https://testnet-passet-hub-eth-rpc.polkadot.io'\n ```\n\n The provider connection script should look something like this:\n\n ```python title=\"connect_to_provider.py\"\n from web3 import Web3\n\n def create_provider(rpc_url):\n web3 = Web3(Web3.HTTPProvider(rpc_url))\n return web3\n\n PROVIDER_RPC = 'INSERT_RPC_URL'\n\n create_provider(PROVIDER_RPC)\n ```\n\n1. With the Web3 provider set up, start querying the blockchain. For instance, you can use the following code snippet to fetch the latest block number of the chain:\n\n ```python title=\"fetch_last_block.py\"\n def main():\n try:\n web3 = create_provider(PROVIDER_RPC)\n latest_block = web3.eth.block_number\n print('Last block: ' + str(latest_block))\n except Exception as error:\n print('Error connecting to Polkadot Hub TestNet: ' + str(error))\n\n if __name__ == \"__main__\":\n main()\n ```\n\n ??? code \"View complete script\"\n\n ```python title=\"fetch_last_block.py\"\n from web3 import Web3\n\n def create_provider(rpc_url):\n web3 = Web3(Web3.HTTPProvider(rpc_url))\n return web3\n\n PROVIDER_RPC = 'https://testnet-passet-hub-eth-rpc.polkadot.io'\n\n def main():\n try:\n web3 = create_provider(PROVIDER_RPC)\n latest_block = web3.eth.block_number\n print('Last block: ' + str(latest_block))\n except Exception as error:\n print('Error connecting to Polkadot Hub TestNet: ' + str(error))\n\n if __name__ == \"__main__\":\n main()\n ```"} diff --git a/llms.txt b/llms.txt index 844f73706..28cb43f37 100644 --- a/llms.txt +++ b/llms.txt @@ -6,7 +6,7 @@ This directory lists URLs for raw Markdown pages that complement the rendered pages on the documentation site. Use these Markdown files to retain semantic context when prompting models while avoiding passing HTML elements. ## Metadata -- Documentation pages: 87 +- Documentation pages: 86 - Categories: 11 ## Docs @@ -120,6 +120,7 @@ Docs: Tooling - [Zero to Hero Smart Contract DApp](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-dapps-zero-to-hero.md): Learn how to build a decentralized application on Polkadot Hub using Viem and Next.js by creating a simple dApp that interacts with a smart contract. - [Deploying Uniswap V2 on Polkadot](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-eth-dapps-uniswap-v2.md): Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. - [Use Hardhat with Polkadot Hub](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-hardhat-get-started.md): Overview of Hardhat, a powerful development environment for creating, compiling, testing, and deploying smart contracts on Polkadot Hub. +- [Troubleshooting Hardhat](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-hardhat-troubleshooting-faq.md): Common issues related to developing, compiling, and deploying smart contracts using Hardhat on Polkadot Hub, paired with troubleshooting suggestions. - [Deploy Contracts Using Remix IDE](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-remix-deploy-a-contract.md): Learn how to deploy smart contracts to the Polkadot Hub network and interact with them using the Remix IDE and wallet providers, covering deployment and state. - [Use the Remix IDE on Polkadot Hub](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-remix-get-started.md): Explore the smart contract development and deployment process on Polkadot Hub using Remix IDE, a visual IDE for blockchain developers. - [Troubleshooting Remix IDE](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-remix-troubleshooting-faq.md): Common issues related to developing, compiling, and deploying smart contracts using Remix IDE on Polkadot Hub paired with troubleshooting suggestions. @@ -148,8 +149,6 @@ Docs: Uncategorized - [smart-contracts-dev-environments-hardhat-compile-and-test](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-hardhat-compile-and-test.md): No description available. - [smart-contracts-dev-environments-hardhat-deploy-a-contract](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-hardhat-deploy-a-contract.md): No description available. - [smart-contracts-dev-environments-hardhat-install-and-config](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-hardhat-install-and-config.md): No description available. -- [smart-contracts-dev-environments-hardhat-troubleshooting](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-hardhat-troubleshooting.md): No description available. -- [smart-contracts-dev-environments-hardhat-verify-a-contract](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-hardhat-verify-a-contract.md): No description available. - [Gas Model on the Polkadot Hub](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-gas-model.md): Learn how gas estimation, pricing, and weight mapping work in the Polkadot Hub. - [smart-contracts-integrations-.indexers](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-integrations-.indexers.md): No description available. - [smart-contracts-integrations-.oracles](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-integrations-.oracles.md): No description available. diff --git a/smart-contracts/libraries/wagmi.md b/smart-contracts/libraries/wagmi.md index 2228deef8..8a07d9582 100644 --- a/smart-contracts/libraries/wagmi.md +++ b/smart-contracts/libraries/wagmi.md @@ -6,8 +6,6 @@ categories: Smart Contracts, Tooling # Wagmi ---8<-- 'text/smart-contracts/polkaVM-warning.md' - ## Introduction [Wagmi](https://wagmi.sh/){target=\_blank} is a collection of [React Hooks](https://wagmi.sh/react/api/hooks){target=\_blank} for interacting with Ethereum-compatible blockchains, focusing on developer experience, feature richness, and reliability. @@ -19,9 +17,8 @@ This guide demonstrates how to use Wagmi to interact with and deploy smart contr To start working with Wagmi, create a new React project and initialize it by running the following commands in your terminal: ```bash -# Create a new React project using Next.js -npx create-next-app@latest wagmi-asset-hub -cd wagmi-asset-hub +npx create-next-app@latest wagmi-polkadot-hub +cd wagmi-polkadot-hub ``` ## Install Dependencies @@ -29,15 +26,14 @@ cd wagmi-asset-hub Install Wagmi and its peer dependencies: ```bash -# Install Wagmi and its dependencies npm install wagmi viem @tanstack/react-query ``` ## Configure Wagmi for Polkadot Hub -Create a configuration file to initialize Wagmi with Polkadot Hub. In your project, create a file named `src/lib/wagmi.ts` and add the code below. Be sure to replace `INSERT_RPC_URL`, `INSERT_CHAIN_ID`, `INSERT_CHAIN_NAME`, `INSERT_NETWORK_NAME`, `INSERT_CHAIN_DECIMALS`, `INSERT_CURRENCY_NAME`, and `INSERT_CURRENCY_SYMBOL` with your specific values. +Create a configuration file to initialize Wagmi with Polkadot Hub. In your project, create a file named `app/lib/wagmi.ts` and add the code below. Be sure to replace `INSERT_RPC_URL`, `INSERT_CHAIN_ID`, `INSERT_CHAIN_NAME`, `INSERT_NETWORK_NAME`, `INSERT_CHAIN_DECIMALS`, `INSERT_CURRENCY_NAME`, and `INSERT_CURRENCY_SYMBOL` with your specific values. -```typescript title="src/lib/wagmi.ts" +```typescript title="app/lib/wagmi.ts" --8<-- 'code/smart-contracts/libraries/wagmi/wagmi.ts' ``` @@ -87,7 +83,7 @@ This component uses the following React hooks: ## Interact with Deployed Contract -This guide uses a simple Storage contract already deployed to the Polkadot Hub TestNet (`0x58053f0e8ede1a47a1af53e43368cd04ddcaf66f`). The code of that contract is: +This guide uses a simple Storage contract already deployed to the Polkadot Hub TestNet. The code of that contract is: ??? code "Storage.sol"