From cb6c434cbeb0f31d5b04c767518388f5350dc427 Mon Sep 17 00:00:00 2001 From: your_username Date: Thu, 4 Jan 2024 20:11:51 +0000 Subject: [PATCH] changed all double-quotes to single-quotes --- .../custom_subscriptions.md | 16 +-- .../guides/getting_started/getting_started.md | 48 +++---- docs/docs/guides/getting_started/metamask.md | 44 +++--- .../migration_from_other_libs/ethers.md | 16 +-- docs/docs/guides/smart_contracts/index.md | 10 +- .../smart_contracts/infer_contract_types.md | 54 +++---- docs/docs/guides/wallet/index.md | 42 +++--- docs/docs/guides/wallet/local_wallet.md | 6 +- docs/docs/guides/wallet/promi_event.md | 2 +- docs/docs/guides/wallet/signing.md | 42 +++--- docs/docs/guides/wallet/transactions.md | 96 ++++++------- docs/docs/guides/web3_config/index.md | 52 +++---- docs/docs/guides/web3_eth/eth.md | 132 +++++++++--------- .../web3_plugin_guide/plugin_authors.md | 52 +++---- .../guides/web3_plugin_guide/plugin_users.md | 48 +++---- .../web3_providers_guide/events_listening.md | 20 +-- docs/docs/guides/web3_providers_guide/http.md | 18 +-- .../docs/guides/web3_providers_guide/index.md | 48 +++---- docs/docs/guides/web3_providers_guide/ipc.md | 20 +-- .../guides/web3_providers_guide/truffle.md | 58 ++++---- .../guides/web3_providers_guide/websocket.md | 24 ++-- 21 files changed, 424 insertions(+), 424 deletions(-) diff --git a/docs/docs/guides/events_subscriptions/custom_subscriptions.md b/docs/docs/guides/events_subscriptions/custom_subscriptions.md index fba6771cab0..6f5826fe902 100644 --- a/docs/docs/guides/events_subscriptions/custom_subscriptions.md +++ b/docs/docs/guides/events_subscriptions/custom_subscriptions.md @@ -50,7 +50,7 @@ You need to specify the exact data that will be passed to the provider. You do t ```ts protected _buildSubscriptionParams() { // the `someCustomSubscription` below is the name of the subscription provided by the node you are connected to. - return ["someCustomSubscription", this.args]; + return ['someCustomSubscription', this.args]; } ``` @@ -58,7 +58,7 @@ With the implementation above, the call that will be made to the provider will b ```ts { - id: "[GUID-STRING]", // something like: '3f839900-afdd-4553-bca7-b4e2b835c687' + id: '[GUID-STRING]', // something like: '3f839900-afdd-4553-bca7-b4e2b835c687' jsonrpc: '2.0', method: 'eth_subscribe', // The `someCustomSubscription` below is the name of the subscription provided by the node you are connected to. @@ -130,11 +130,11 @@ const web3 = new Web3({ // subscribe at the provider: // Note: this will internally initialize a new instance of `MyCustomSubscription`, // call `_buildSubscriptionParams`, and then send the `eth_subscribe` RPC call. -const sub = web3.subscriptionManager.subscribe("custom", args); +const sub = web3.subscriptionManager.subscribe('custom', args); // listen to the emitted event: // Note: the data will be optionally formatted at `formatSubscriptionResult`, before it is emitted here. -sub.on("data", (result) => { +sub.on('data', (result) => { // This will be called every time a new data arrived from the provider to this subscription }); ``` @@ -164,7 +164,7 @@ class MyCustomSubscription extends Web3Subscription< > { protected _buildSubscriptionParams() { // the `someCustomSubscription` below is the name of the subscription provided by the node your are connected to. - return ["someCustomSubscription", this.args]; + return ['someCustomSubscription', this.args]; } protected formatSubscriptionResult(data: string) { @@ -187,7 +187,7 @@ class MyCustomSubscription extends Web3Subscription< // Usage const args = { - customArg: "hello custom", + customArg: 'hello custom', }; const CustomSubscriptions = { @@ -204,9 +204,9 @@ const web3 = new Web3({ registeredSubscriptions: CustomSubscriptions, }); -const sub = web3.subscriptionManager.subscribe("custom", args); +const sub = web3.subscriptionManager.subscribe('custom', args); -sub.on("data", (result) => { +sub.on('data', (result) => { // New data }); diff --git a/docs/docs/guides/getting_started/getting_started.md b/docs/docs/guides/getting_started/getting_started.md index eb8cc9dbcc0..8d08c907904 100644 --- a/docs/docs/guides/getting_started/getting_started.md +++ b/docs/docs/guides/getting_started/getting_started.md @@ -62,7 +62,7 @@ After instantiating the `web3` instance with a `new Web3 provider`, we can acces ```ts // get the balance of an address -await web3.eth.getBalance("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"); +await web3.eth.getBalance('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'); // ↳ 114438180989009447638n // get last block number @@ -74,7 +74,7 @@ await web3.eth.getChainId(); // ↳ 1n // get the nonce of an address -await web3.eth.getTransactionCount("0x37826D8B5F4B175517A0f42c886f8Fca38C55Fe7"); +await web3.eth.getTransactionCount('0x37826D8B5F4B175517A0f42c886f8Fca38C55Fe7'); // ↳ 7n // get the current gas price @@ -118,7 +118,7 @@ Wallet(1) ```ts //the private key must start with the '0x' prefix -const account = web3.eth.accounts.wallet.add("0x50d349f5cf627d44858d6fcb6fbf15d27457d35c58ba2d5cfeaf455f25db5bec"); +const account = web3.eth.accounts.wallet.add('0x50d349f5cf627d44858d6fcb6fbf15d27457d35c58ba2d5cfeaf455f25db5bec'); console.log(account[0].address); //↳ 0xcE6A5235d6033341972782a15289277E85E5b305 @@ -131,21 +131,21 @@ console.log(account[0].privateKey); ```ts title='Sending value' //add an account to a wallet -const account = web3.eth.accounts.wallet.add("0x50d349f5cf627d44858d6fcb6fbf15d27457d35c58ba2d5cfeaf455f25db5bec"); +const account = web3.eth.accounts.wallet.add('0x50d349f5cf627d44858d6fcb6fbf15d27457d35c58ba2d5cfeaf455f25db5bec'); //create transaction object to send 1 eth to '0xa32...c94' address from the account[0] const tx = { from: account[0].address, - to: "0xa3286628134bad128faeef82f44e99aa64085c94", - value: web3.utils.toWei("1", "ether") + to: '0xa3286628134bad128faeef82f44e99aa64085c94', + value: web3.utils.toWei('1', 'ether') }; //the `from` address must match the one previously added with wallet.add //send the transaction const txReceipt = await web3.eth.sendTransaction(tx); -console.log("Tx hash:", txReceipt.transactionHash) +console.log('Tx hash:', txReceipt.transactionHash) // ↳ Tx hash: 0x03c844b069646e08af1b6f31519a36e3e08452b198ef9f6ce0f0ccafd5e3ae0e ``` @@ -157,20 +157,20 @@ The first step to interact with a contract is to instantiate the contract, for w ```ts //Uniswap token address in mainnet -const address = "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984" +const address = '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984' //you can find the complete ABI in etherscan.io const ABI = [ { - name: "symbol", - outputs: [{ type: "string" }], - type: "function", + name: 'symbol', + outputs: [{ type: 'string' }], + type: 'function', }, { - name: "totalSupply", - outputs: [{ type: "uint256" }], - type: "function", + name: 'totalSupply', + outputs: [{ type: 'uint256' }], + type: 'function', }, ]; @@ -184,17 +184,17 @@ const uniswapToken = new web3.eth.Contract(abi, address); //make the call to the contract const symbol = await uniswapToken.methods.symbol().call(); -console.log("Uniswap symbol:",symbol); +console.log('Uniswap symbol:',symbol); // ↳ Uniswap symbol: UNI //make the call to the contract const totalSupply = await uniswapToken.methods.totalSupply().call(); -console.log("Uniswap Total supply:", totalSupply); +console.log('Uniswap Total supply:', totalSupply); // ↳ Uniswap Total Supply: 1000000000000000000000000000n //use web3 utils to format the units -console.log(web3.utils.fromWei(totalSupply, "ether")) +console.log(web3.utils.fromWei(totalSupply, 'ether')) // ↳ 1000000000 ``` @@ -202,15 +202,15 @@ console.log(web3.utils.fromWei(totalSupply, "ether")) ```ts //address to send the token -const to = "0xcf185f2F3Fe19D82bFdcee59E3330FD7ba5f27ce"; +const to = '0xcf185f2F3Fe19D82bFdcee59E3330FD7ba5f27ce'; //value to transfer (1 with 18 decimals) -const value = web3.utils.toWei("1","ether"); +const value = web3.utils.toWei('1','ether'); //send the transaction => return the Tx receipt const txReceipt = await uniswapToken.methods.transfer(to,value).send({from: account[0].address}); -console.log("Tx hash:",txReceipt.transactionHash); +console.log('Tx hash:',txReceipt.transactionHash); // ↳ Tx hash: 0x14273c2b5781cc8f1687906c68bfc93482c603026d01b4fd37a04adb6217ad43 ``` @@ -218,7 +218,7 @@ console.log("Tx hash:",txReceipt.transactionHash); ```ts //get past `Transfer` events from block 18850576 -const eventTransfer = await uniswapToken.getPastEvents("Transfer", { fromBlock: 18850576 }); +const eventTransfer = await uniswapToken.getPastEvents('Transfer', { fromBlock: 18850576 }); console.log(eventTransfer); // ↳ [{...},{...}, ...] array with all the events emitted @@ -235,15 +235,15 @@ You MUST initialize the `Web3 provider` with a WebSocket endpoint to subscribe t import { Web3 } from 'web3'; //WebSocket provider -const web3 = new Web3("wss://ethereum.publicnode.com"); +const web3 = new Web3('wss://ethereum.publicnode.com'); //instantiate contract const uniswapToken = new web3.eth.Contract(abi, address) -//create the subcription to all the "Transfer" events +//create the subcription to all the 'Transfer' events const subscription = uniswapToken.events.Transfer(); //listen to the events -subscription.on("data",console.log); +subscription.on('data',console.log); // ↳ [{...},{...}, ...] live events will be printed in the console ``` \ No newline at end of file diff --git a/docs/docs/guides/getting_started/metamask.md b/docs/docs/guides/getting_started/metamask.md index 480852f2b24..714360b9665 100644 --- a/docs/docs/guides/getting_started/metamask.md +++ b/docs/docs/guides/getting_started/metamask.md @@ -10,8 +10,8 @@ sidebar_label: Connecting to Metamask After creating your react app `npx create-react-app app-name`, and installing web3 `npm i web3` you can go to `src/app.js`, you can clean up the code and import `{Web3}`. It should look like this: ```jsx -import { useState } from "react"; -import { Web3 } from "web3"; +import { useState } from 'react'; +import { Web3 } from 'web3'; function App() { return <> ; @@ -26,13 +26,13 @@ Let's divide this into 2 small steps: In this step, we'll add a button to the front end for users to connect to Metamask. We'll also include an `

` element to display the connected address once the connection is established. ```jsx -import { useState } from "react"; -import { Web3 } from "web3"; +import { useState } from 'react'; +import { Web3 } from 'web3'; function App() { //highlight-start //react state to store and show the connected account - const [connectedAccount, setConnectedAccount] = useState("null"); + const [connectedAccount, setConnectedAccount] = useState('null'); //highlight-end return ( @@ -55,12 +55,12 @@ export default App; In this step, we'll implement the function that triggers Metamask to prompt the user to connect their wallet. ```jsx {} -import { useState } from "react"; -import { Web3 } from "web3"; +import { useState } from 'react'; +import { Web3 } from 'web3'; function App() { //state to store and show the connected account - const [connectedAccount, setConnectedAccount] = useState("null"); + const [connectedAccount, setConnectedAccount] = useState('null'); //highlight-start async function connectMetamask() { @@ -70,7 +70,7 @@ function App() { const web3 = new Web3(window.ethereum); //request user to connect accounts (Metamask will prompt) - await window.ethereum.request({ method: "eth_requestAccounts" }); + await window.ethereum.request({ method: 'eth_requestAccounts' }); //get the connected accounts const accounts = await web3.eth.getAccounts(); @@ -78,7 +78,7 @@ function App() { //show the first connected account in the react page setConnectedAccount(accounts[0]); } else { - alert("Please download metamask"); + alert('Please download metamask'); } } //highlight-end @@ -108,7 +108,7 @@ export default App; //highlight-start Metamask Connection - + //highlight-end @@ -124,17 +124,17 @@ export default App; Metamask Connection - + //highlight-start

Metamask Connection

- + -

null

+

null

//highlight-end @@ -148,35 +148,35 @@ export default App; Metamask Connection - +

Metamask Connection

- + -

null

+

null

//highlight-start - diff --git a/docs/docs/guides/migration_from_other_libs/ethers.md b/docs/docs/guides/migration_from_other_libs/ethers.md index 5623b2792db..3d924499972 100644 --- a/docs/docs/guides/migration_from_other_libs/ethers.md +++ b/docs/docs/guides/migration_from_other_libs/ethers.md @@ -52,7 +52,7 @@ blockNumber.then(console.log); :::tip 📝 web3.js uses `bigint` as the default type for all big numbers returned. For, this you see above the blocknumber has the `n` at its end (`18561956n`). However, you can change the returned type by passing an optional parameter like: ::: -```ts title="BigInt Tip" +```ts title='BigInt Tip' import { Web3, DEFAULT_RETURN_FORMAT, FMT_NUMBER } from 'web3'; const blockNumber = web3.eth.getBlockNumber({ @@ -292,7 +292,7 @@ To deploy a contract in ethers.js you might have something like: ```typescript const signer = provider.getSigner(); const factory = new ethers.ContractFactory(abi, bytecode, signer); -const contract = await factory.deploy("constructor param"); +const contract = await factory.deploy('constructor param'); console.log('contract address', contract.address); // wait for contract creation transaction to be mined @@ -305,9 +305,9 @@ In web3.js: const contractObject = new web3.eth.Contract(abi); const deployedContract = await contractObject.deploy({ data: bytecode, - arguments: ["constructor param"] + arguments: ['constructor param'] }).send({ - from: "0x12598d2Fd88B420ED571beFDA8dD112624B5E730", + from: '0x12598d2Fd88B420ED571beFDA8dD112624B5E730', gas: '1000000', // other transaction's params }); @@ -348,8 +348,8 @@ In ethers.js: ```typescript // ethers const abi = [ - "function getMessage(string) public view returns (string)", - "function getMessage() public view returns (string)" + 'function getMessage(string) public view returns (string)', + 'function getMessage() public view returns (string)' ] const contract = new ethers.Contract(address, abi, signer); @@ -460,12 +460,12 @@ console.log(fromEtherToWie); With web3.js: ```typescript -// the second parameter is "the unit to convert to" +// the second parameter is 'the unit to convert to' const fromWieToEther = Web3.utils.fromWei('1000000000000000000', 'ether'); // outputs: 1 console.log(fromWieToEther); -// the second parameter is "the unit of the number passed" +// the second parameter is 'the unit of the number passed' const fromEtherToWie = Web3.utils.toWei('1.0', 'ether'); // outputs: 1000000000000000000 console.log(fromEtherToWie); diff --git a/docs/docs/guides/smart_contracts/index.md b/docs/docs/guides/smart_contracts/index.md index 2fd784429e5..6e73975a550 100644 --- a/docs/docs/guides/smart_contracts/index.md +++ b/docs/docs/guides/smart_contracts/index.md @@ -21,7 +21,7 @@ Here's an example of importing from each: ```ts // Importing from web3-eth-contract package -import { Contract } from "web3-eth-contract"; +import { Contract } from 'web3-eth-contract'; const contract = new Contract(...); // Importing from the main web3 package @@ -30,7 +30,7 @@ const contract = new Contract(...); // Importing from the main web3 package from inside `web3.eth` namespace import { Web3 } from 'web3'; -const web3 = new Web3("http://127.0.0.1:8545"); +const web3 = new Web3('http://127.0.0.1:8545'); const contract = new web3.eth.Contract(...); // to set the provider for the contract instance: @@ -53,13 +53,13 @@ Actually, the `web3.eth.Contract` is typically how you access the class through Examples: ```ts -import { Contract } from "web3-eth-contract"; +import { Contract } from 'web3-eth-contract'; // instantiating Contract directly with provider URL from Contract package // alternatively, you can instantiate the Contract without a provider and set it later using contract.setProvider() const abi = [{...}]; const address = '0x...'; -const contract = new Contract(abi, address { provider: "http://127.0.0.1:8545" }); +const contract = new Contract(abi, address { provider: 'http://127.0.0.1:8545' }); // the provider can be set like this if not provided at the constructor: contract.setProvider('http://127.0.0.1:7545'); @@ -168,7 +168,7 @@ myContract.options.jsonInterface = [{...}]; // ABI // to call a method by sending a transaction contract.methods.METHOD_NAME(METHOD_PARAMETERS).send(); // you need to specify the account (from) that will be used to sign and send the transaction -contract.methods.METHOD_NAME(METHOD_PARAMETERS).send({from: "0x..."}); +contract.methods.METHOD_NAME(METHOD_PARAMETERS).send({from: '0x...'}); // to call a view or pure method that does not send a transaction contract.methods.METHOD_NAME(METHOD_PARAMETERS).call(); diff --git a/docs/docs/guides/smart_contracts/infer_contract_types.md b/docs/docs/guides/smart_contracts/infer_contract_types.md index 74b8a553d09..8dcd006e2e4 100644 --- a/docs/docs/guides/smart_contracts/infer_contract_types.md +++ b/docs/docs/guides/smart_contracts/infer_contract_types.md @@ -14,18 +14,18 @@ Web3.js is a popular library used for interacting with EVM blockchains. One of i Before we dive into the problem, let's take a quick look at the problem. Web3.js provides a simple and convenient way to interact with Solidity contracts. To use Web3.js to interact with a Solidity contract, you need to know the contract's address and the ABI (Application Binary Interface) of the contract. The ABI is JSON data that contains the definition of the functions in the contract, including their, name, input parameters and return values. -Web3.js uses ABI type to dynamically load available methods and events but Typescript currently [doesn't support loading JSON as const](https://github.com/microsoft/TypeScript/issues/32063). If you go to the [Playground Link](https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgIwJYwLwwNoCga5gbxz1wCIkwAHAVyghIC5MjjdCWWywoBTAJzDgAbACoBPCtwYwS0XuQDmJADTN20gQFtJjEpu4B9ZavYko47dNkKSxvAF8VagreKce-IWIlSZUOWEVHJ3U4LR8IUQ0EEEFDIKdTc3C-axcYO1sAXXi8XzgeAFkaRCRBJDMfMHAKOFFEQUkc0jNvHVBIPypgKBBeG2IHVTYOOCqwSJAqOkYAMyEIbibpcmpaKWwnYYTyABNuAA9uHalOxbTScncBESSdOB2d3m4IOiXXPR8QAHcwPiNg6QtCwke6PZ50NKDTbnZZgPaHY6MU5vXKXPjXLzA0FPF7-YK6ULAiASOF-FHNW7SbHg-pqKFqLZqTjwo5SOaCBbk2FXTyUkhUS4AJgArAA2PEJD46ABuQiojRhiVa0gFXBF4shWSWBLCOgAghQKLwQLLBBLckCfNxpdwuLTcPTWLYQWMJlM2fMziYVjRpkxoQDmQdWUjePKuW50bzlSCHjjXoqpdIZsaNOaTJa7nGaZCUYzvaSESc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cjTuY90Y52xgWB+HUCZF0BA2N+Id4xIXsH7aq7Do7ENnrZeybV4K4NWuwVcAserAmZpAPcnsODD2vFgthk9NYgCvvg9WvDpBl1IQo8hbEoa13-g3E2ZtgF73btbQRECgJQM0awyBIi6r8K4SQFMIA0xGNjOTP8Qi87Ow4T4gxOgeiEOCfwimithE6PInTaJVI7KtTiUHL+Z8bLKN3HwAAYqmbOt8PGuK8aFPRZpfFxJMXI9aEMKGWL-ntdQmUm52LoQ40BTiHREEyPACAMB2jQAANxAA) and choose ".d.ts" you can check type difference with and without `as const`. +Web3.js uses ABI type to dynamically load available methods and events but Typescript currently [doesn't support loading JSON as const](https://github.com/microsoft/TypeScript/issues/32063). If you go to the [Playground Link](https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgIwJYwLwwNoCga5gbxz1wCIkwAHAVyghIC5MjjdCWWywoBTAJzDgAbACoBPCtwYwS0XuQDmJADTN20gQFtJjEpu4B9ZavYko47dNkKSxvAF8VagreKce-IWIlSZUOWEVHJ3U4LR8IUQ0EEEFDIKdTc3C-axcYO1sAXXi8XzgeAFkaRCRBJDMfMHAKOFFEQUkc0jNvHVBIPypgKBBeG2IHVTYOOCqwSJAqOkYAMyEIbibpcmpaKWwnYYTyABNuAA9uHalOxbTScncBESSdOB2d3m4IOiXXPR8QAHcwPiNg6QtCwke6PZ50NKDTbnZZgPaHY6MU5vXKXPjXLzA0FPF7-YK6ULAiASOF-FHNW7SbHg-pqKFqLZqTjwo5SOaCBbk2FXTyUkhUS4AJgArAA2PEJD46ABuQiojRhiVa0gFXBF4shWSWBLCOgAghQKLwQLLBBLckCfNxpdwuLTcPTWLYQWMJlM2fMziYVjRpkxoQDmQdWUjePKuW50bzlSCHjjXoqpdIZsaNOaTJa7nGaZCUYzvaSEScw178WiPDcY9TcRGk6YQOmOJmqdncbm0vmOLtg4iYOzOYryxi+aqoOrG+9CT5TfKJxaR0KxfaWBl2NlnXXhLxRhAZmTnc2SNbbVBl47nAXVn6NgzB1wo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gF73btbQRECgJQM0awyBIi6r8K4SQFMIA0xGNjOTP8Qi87Ow4T4gxOgeiEOCfwimithE6PInTaJVI7KtTiUHL+Z8bLKN3HwAAYqmbOt8PGuK8aFPRZpfFxJMXI9aEMKGWL-ntdQmUm52LoQ40BTiHREEyPACAMB2jQAANxAA) and choose '.d.ts' you can check type difference with and without `as const`. ```typescript -import { Contract, Web3 } from "web3"; -import ERC20 from "./node_modules/@openzeppelin/contracts/build/contracts/ERC20.json"; +import { Contract, Web3 } from 'web3'; +import ERC20 from './node_modules/@openzeppelin/contracts/build/contracts/ERC20.json'; (async function () { - const web3 = new Web3("rpc url"); + const web3 = new Web3('rpc url'); - const contract = new Contract(ERC20.abi, "0x7af963cF6D228E564e2A0aA0DdBF06210B38615D", web3); + const contract = new Contract(ERC20.abi, '0x7af963cF6D228E564e2A0aA0DdBF06210B38615D', web3); - const holder = "0xa8F6eB216e26C1F7d924A801E46eaE0CE8ed1A0A"; + const holder = '0xa8F6eB216e26C1F7d924A801E46eaE0CE8ed1A0A'; //Error because Contract doesn't know what methods exists const balance = await contract.methods.balanceOf(holder).call(); @@ -35,19 +35,19 @@ import ERC20 from "./node_modules/@openzeppelin/contracts/build/contracts/ERC20. To work around it you need to copy abi into a Typescript file like this: ```typescript -import {Contract, Web3} from "web3"; +import {Contract, Web3} from 'web3'; const ERC20 = [ ... - // "as const" is important part, without it typescript would create generic type and remove available methods from type + // 'as const' is important part, without it typescript would create generic type and remove available methods from type ] as const; (async function () { - const web3 = new Web3("rpc url"); + const web3 = new Web3('rpc url'); - const contract = new Contract(ERC20, "0x7af963cF6D228E564e2A0aA0DdBF06210B38615D", web3); + const contract = new Contract(ERC20, '0x7af963cF6D228E564e2A0aA0DdBF06210B38615D', web3); - const holder = "0xa8F6eB216e26C1F7d924A801E46eaE0CE8ed1A0A"; + const holder = '0xa8F6eB216e26C1F7d924A801E46eaE0CE8ed1A0A'; //Works now const balance = await contract.methods.balanceOf(holder).call(); @@ -59,15 +59,15 @@ To solve this problem, you can use a custom script that copies the JSON artifact Script: -```typescript title="gen.ts" -import fs from "fs"; -import path from "path"; +```typescript title='gen.ts' +import fs from 'fs'; +import path from 'path'; //read destination directory submitted as first param var destination = process.argv.slice(2)[0]; //read all contract artifacts from artifacts.json which should be in the directoy from where script should be executed -const artifactContent = fs.readFileSync("./artifacts.json", "utf-8"); +const artifactContent = fs.readFileSync('./artifacts.json', 'utf-8'); const artifacts: string[] = JSON.parse(artifactContent); @@ -79,22 +79,22 @@ const artifacts: string[] = JSON.parse(artifactContent); content = JSON.stringify(await import(artifact)); } catch (e) { //try to read as path on disc - content = fs.readFileSync(artifact, "utf-8"); + content = fs.readFileSync(artifact, 'utf-8'); } - const filename = path.basename(artifact, ".json"); + const filename = path.basename(artifact, '.json'); //create and write typescript file - fs.writeFileSync(path.join(destination, filename + ".ts"), `const artifact = ${content.trimEnd()} as const; export default artifact;`); + fs.writeFileSync(path.join(destination, filename + '.ts'), `const artifact = ${content.trimEnd()} as const; export default artifact;`); } })(); ``` To use this script, just create an `artifacts.json` file at the root of your project with all the artifacts you are using. -```json title="artifacts.json" +```json title='artifacts.json' [ - "@openzeppelin/contracts/build/contracts/ERC20.json", - "@openzeppelin/contracts/build/contracts/ERC1155.json", - "./build/contracts/MyContract.json" + '@openzeppelin/contracts/build/contracts/ERC20.json', + '@openzeppelin/contracts/build/contracts/ERC1155.json', + './build/contracts/MyContract.json' ] ``` @@ -105,15 +105,15 @@ node -r ts-node/register + - + +```html title='E.g, Metamask' + + @@ -187,14 +187,14 @@ npm i express 8. Copy and paste the following code into `server.js`, and save it after: ```js -const express = require("express"); +const express = require('express'); const app = express(); -const path = require("path"); +const path = require('path'); -app.use(express.static(path.join(__dirname, "."))); +app.use(express.static(path.join(__dirname, '.'))); app.listen(8097, () => { - console.log("Server started on port 8097"); + console.log('Server started on port 8097'); }); ``` diff --git a/docs/docs/guides/web3_providers_guide/websocket.md b/docs/docs/guides/web3_providers_guide/websocket.md index 10678f3a851..acf8d7b9d4c 100644 --- a/docs/docs/guides/web3_providers_guide/websocket.md +++ b/docs/docs/guides/web3_providers_guide/websocket.md @@ -1,6 +1,6 @@ --- sidebar_position: 4 -sidebar_label: "Tutorial: WebSocket Provider" +sidebar_label: 'Tutorial: WebSocket Provider' --- # Tutorial: WebSocket Provider @@ -57,29 +57,29 @@ npm i web3 5. Copy and paste the following code into your `web3-websocket-provider.js` file and save it: -```typescript title="WebSocket Provider" -import { Web3 } from "web3"; +```typescript title='WebSocket Provider' +import { Web3 } from 'web3'; // Connect to the Ethereum network using WebSocket provider -const ganacheUrl = "ws://localhost:8545"; +const ganacheUrl = 'ws://localhost:8545'; const wsProvider = new Web3.providers.WebsocketProvider(ganacheUrl); const web3 = new Web3(wsProvider); async function main() { try { - console.log("Does the provider support subscriptions?:", wsProvider.supportsSubscriptions()); + console.log('Does the provider support subscriptions?:', wsProvider.supportsSubscriptions()); // Subscribe to new block headers - const subscription = await web3.eth.subscribe("newBlockHeaders"); + const subscription = await web3.eth.subscribe('newBlockHeaders'); - subscription.on("data", async (blockhead) => { - console.log("New block header: ", blockhead); + subscription.on('data', async (blockhead) => { + console.log('New block header: ', blockhead); // You do not need the next line if you like to keep being notified for every new block await subscription.unsubscribe(); - console.log("Unsubscribed from new block headers."); + console.log('Unsubscribed from new block headers.'); }); - subscription.on("error", (error) => console.log("Error when subscribing to New block header: ", error)); + subscription.on('error', (error) => console.log('Error when subscribing to New block header: ', error)); // Get the list of accounts in the connected node which is in this case: Ganache. const accounts = await web3.eth.getAccounts(); @@ -87,9 +87,9 @@ async function main() { const transactionReceipt = await web3.eth.sendTransaction({ from: accounts[0], to: accounts[1], - value: web3.utils.toWei("0.001", "ether"), + value: web3.utils.toWei('0.001', 'ether'), }); - console.log("Transaction Receipt:", transactionReceipt); + console.log('Transaction Receipt:', transactionReceipt); } catch (error) { console.error(error); }