### Install Graph CLI Source: https://docs.vechain.org/developer-resources/index-with-graph-node/index-with-openzeppelin/deploy-subgraph-and-start-indexing Installs the @graphprotocol/graph-cli package using npm, which is required for preparing subgraphs and interacting with the graph node. ```shell npm install --save @graphprotocol/graph-cli ``` -------------------------------- ### Create VeChain dApp with npx Source: https://docs.vechain.org/developer-resources/getting-started Starts a new VeChain dApp project using the create-vechain-dapp package via npx, ensuring the latest version is used. This command bootstraps a new dApp development environment. ```bash npx create-vechain-dapp@latest ``` -------------------------------- ### NPM Installation for Vechain DApp Kit Source: https://docs.vechain.org/developer-resources/sdks-and-providers/dapp-kit/dapp-kit-1/vanilla/installation Installs the Vechain DApp Kit UI and DApp Kit packages using NPM. This is the primary step for integrating Vechain's DApp development tools into your project. ```bash npm i @vechain/dapp-kit-ui @vechain/dapp-kit ``` -------------------------------- ### Create VeChain dApp with npm/yarn Source: https://docs.vechain.org/developer-resources/getting-started Initiates a new VeChain dApp project using the create-vechain-dapp package with npm or yarn. This command sets up a basic project structure and necessary configurations for dApp development. ```bash npm create vechain-dapp ``` ```bash yarn create vechain-dapp ``` -------------------------------- ### Example Output of `graph deploy` Source: https://docs.vechain.org/developer-resources/index-with-graph-node/index-with-openzeppelin/deploy-subgraph-and-start-indexing This output details the steps involved in deploying a subgraph, including skipping migrations, applying migrations, loading, compiling, and uploading the subgraph. It also shows the IPFS hashes for uploaded files and the final deployment endpoint. ```shell Skip migration: Bump mapping apiVersion from 0.0.1 to 0.0.2 Skip migration: Bump mapping apiVersion from 0.0.2 to 0.0.3 Skip migration: Bump mapping apiVersion from 0.0.3 to 0.0.4 Skip migration: Bump mapping apiVersion from 0.0.4 to 0.0.5 Skip migration: Bump mapping apiVersion from 0.0.5 to 0.0.6 Skip migration: Bump manifest specVersion from 0.0.1 to 0.0.2 Skip migration: Bump manifest specVersion from 0.0.2 to 0.0.4 ✔ Apply migrations ✔ Load subgraph from vebetterdao/tokens.subgraph.yaml Compile data source: erc20 => build/erc20/erc20.wasm Compile data source: erc20-1 => build/erc20/erc20.wasm (already compiled) ✔ Compile subgraph Copy schema file build/tokens.schema.graphql Write subgraph file build/node_modules/@openzeppelin/contracts/build/contracts/IERC20Metadata.json Write subgraph file build/node_modules/@openzeppelin/contracts/build/contracts/IERC20Metadata.json Write subgraph manifest build/subgraph.yaml ✔ Write compiled subgraph to build/ Add file to IPFS build/tokens.schema.graphql .. QmTJC228tSzgV6ano5uSgVkk4yq3tdpUAZ11xBBnqtKbmm Add file to IPFS build/node_modules/@openzeppelin/contracts/build/contracts/IERC20Metadata.json .. QmVkgbSMT9SrNoFcfxSdSmhghS2zz7Y6g3QxQ1xZ8HccrB Add file to IPFS build/node_modules/@openzeppelin/contracts/build/contracts/IERC20Metadata.json .. QmVkgbSMT9SrNoFcfxSdSmhghS2zz7Y6g3QxQ1xZ8HccrB (already uploaded) Add file to IPFS build/erc20/erc20.wasm .. QmWbi5wkYU15ksR7H4iMkQ7yZYXihPwb8qYfun7Ne1xcLn Add file to IPFS build/erc20/erc20.wasm .. QmWbi5wkYU15ksR7H4iMkQ7yZYXihPwb8qYfun7Ne1xcLn (already uploaded) ✔ Upload subgraph to IPFS Build completed: QmezwJ1bGUGAUXehjg1qsTrycRVxsw29vFqVuN5fdzsE98 Deployed to http://127.0.0.1:8000/subgraphs/name/vebetterdao/tokens/graphql Subgraph endpoints: Queries (HTTP): http://127.0.0.1:8000/subgraphs/name/vebetterdao/tokens ``` -------------------------------- ### Install VeChain Hardhat Libraries Source: https://docs.vechain.org/core-concepts/evm-compatibility/how-to-recreate Installs the required VeChain-specific Hardhat libraries using npm. These packages enable Hardhat to interact with the VeChain network. ```bash npm install @vechain/hardhat-vechain@0.0.1 --save-exact npm install @vechain/hardhat-web3@0.0.1 --save-exact npm install @vechain/web3-providers-connex@1.0.0 --save-exact ``` -------------------------------- ### Build Subgraph with `build` Source: https://docs.vechain.org/developer-resources/index-with-graph-node/index-with-openzeppelin/deploy-subgraph-and-start-indexing Generates the AssemblyScript code for the subgraph's indexing scripts. This command compiles the subgraph and prepares it for deployment. An example command and its output are provided. ```shell npx graph build vebetterdao/tokens.subgraph.yaml ``` -------------------------------- ### Run VeChain Thor Solo Node Source: https://docs.vechain.org/core-concepts/evm-compatibility/how-to-recreate Starts a VeChain Thor solo node. This is essential for local development and testing on the VeChain blockchain. The command includes options for on-demand operation and increased gas limits. ```bash bin/thor solo --on-demand --gas-limit 10000000000 ``` -------------------------------- ### Create Subgraph Namespace with `graph create` Source: https://docs.vechain.org/developer-resources/index-with-graph-node/index-with-openzeppelin/deploy-subgraph-and-start-indexing Creates the namespace on the Graph Node where subgraph data will be stored. This command only needs to be run once. It requires the Graph Node service URL and provides an example of usage and the resulting output. ```shell npx graph create vebetterdao/tokens --node http://127.0.0.1:8020 ``` -------------------------------- ### Starting Docker Compose Services Source: https://docs.vechain.org/developer-resources/index-with-graph-node/setup-with-docker This bash command initiates the Docker Compose setup defined in the `docker-compose.yml` file. The `-d` flag runs the containers in detached mode, allowing the terminal to be used for other tasks. The output shows the status of the network and container creation. ```bash docker compose up -d [+] Running 5/5 ✔ Network example_default Created 0.0s ✔ Container example-postgres-1 Started 3.8s ✔ Container example-ipfs-1 Started 3.8s ✔ Container rpc-proxy Started 3.8s ✔ Container example-graph-node-1 Started ``` -------------------------------- ### Install VeChain DApp-Kit using npm, yarn, or pnpm Source: https://docs.vechain.org/developer-resources/sdks-and-providers/dapp-kit/dapp-kit/installation Installs the VeChain DApp-Kit library using different package managers. This is the first step before utilizing the library in your project. ```npm npm i @vechain/dapp-kit ``` ```yarn yarn add @vechain/dapp-kit ``` ```pnpm pnpm i @vechain/dapp-kit ``` -------------------------------- ### Verify VeChain DApp Kit React Installation in TypeScript Source: https://docs.vechain.org/developer-resources/sdks-and-providers/dapp-kit/dapp-kit/react/installation A basic TypeScript import statement to verify the successful installation of the VeChain DApp Kit React library. This code snippet checks if the `DAppKitProvider` can be imported, indicating a correct setup. ```typescript import { DAppKitProvider } from '@vechain/dapp-kit-react'; ``` -------------------------------- ### Install OpenZeppelin Contracts and Hardhat Upgrades Plugin Source: https://docs.vechain.org/developer-resources/how-to-build-on-vechain/build-with-hardhat Commands to install OpenZeppelin contract libraries and the Hardhat Upgrades plugin. This setup facilitates the use of pre-built, secure smart contract components and enables upgradeability patterns. ```shell npm install --save @openzeppelin/contracts @openzeppelin/contracts-upgradeable @openzeppelin/hardhat-upgrades ``` -------------------------------- ### Install VeChain dApp-Kit and SDKs Source: https://docs.vechain.org/developer-resources/example-dapps/buy-me-a-coffee Installs the necessary VeChain dApp-Kit and SDK modules for React applications. These modules facilitate integration with the VeChain network, wallet connections, and UI components. ```shell npm install --save @vechain/dapp-kit-react @vechain/dapp-kit-ui @vechain/sdk-core @vechain/sdk-network ``` -------------------------------- ### Verify VeChain DApp-Kit Installation in TypeScript Source: https://docs.vechain.org/developer-resources/sdks-and-providers/dapp-kit/dapp-kit/installation A TypeScript code snippet to verify the successful installation of the VeChain DApp-Kit. It demonstrates how to initialize the DAppKit with necessary configuration, such as node URL and genesis. ```typescript import { DAppKit } from "@vechain/dapp-kit" const dappKit = new DAppKit({ //Required nodeUrl: 'https://sync-testnet.vechain.org/', // Required if not connecting to the mainnet genesis: 'test', }); ``` -------------------------------- ### Install VeChain DApp-Kit UI via NPM Source: https://docs.vechain.org/developer-resources/sdks-and-providers/dapp-kit/dapp-kit/vanilla/installation Installs the @vechain/dapp-kit-ui package using npm. This is the primary step for integrating the UI library into your project. ```bash npm i @vechain/dapp-kit-ui ``` -------------------------------- ### Install VeChain SDK Dependencies Source: https://docs.vechain.org/developer-resources/example-dapps/pwa-with-privy-and-account-abstraction This command installs the necessary VeChain SDK packages for your project, simplifying interaction with the VeChain network. It specifies versions for `@vechain/sdk-core` and `@vechain/sdk-network`. ```shell npm install --save @vechain/sdk-core@1.0.0-beta.16 @vechain/sdk-network@1.0.0-beta.16 ``` -------------------------------- ### Generate Subgraph Types with `codegen` Source: https://docs.vechain.org/developer-resources/index-with-graph-node/index-with-openzeppelin/deploy-subgraph-and-start-indexing Generates AssemblyScript types from the subgraph's GraphQL schema and contract ABIs. This command should be run whenever the schema or ABIs change. It includes an example of the command and its typical output. ```shell npx graph codegen vebetterdao/tokens.subgraph.yaml ``` -------------------------------- ### Clone openzeppelin-contracts Repository Source: https://docs.vechain.org/core-concepts/evm-compatibility/how-to-recreate Clones the specified openzeppelin-contracts repository to your local machine and navigates into the directory. This is a prerequisite for setting up the development environment. ```bash git clone git@github.com:OpenZeppelin/openzeppelin-contracts.git cd openzeppelin-contracts ``` ```bash git clone -b thor-compatibility git@github.com:vechain/openzeppelin-contracts.git cd openzeppelin-contracts ``` -------------------------------- ### Install VeChain Kit and Dependencies Source: https://docs.vechain.org/developer-resources/sdks-and-providers/vechain-kit This snippet shows how to install the VeChain Kit library along with necessary dependencies like React Query and Chakra UI using Yarn. Ensure you have Node.js and Yarn installed. ```bash yarn add @tanstack/react-query@"^5.64.2" @chakra-ui/react@"^2.8.2" @vechain/dapp-kit-react@"1.5.0" @vechain/vechain-kit ``` -------------------------------- ### Install VeChain SDK Core and Network Packages with npm Source: https://docs.vechain.org/developer-resources/sdks-and-providers/sdk This snippet demonstrates how to install the core and network packages of the VeChain SDK using npm. These packages are essential for interacting with the VeChain blockchain. Ensure you have Node.js and npm installed. ```bash npm install @vechain/sdk-core npm install @vechain/sdk-network ... ``` -------------------------------- ### Install Project Dependencies Source: https://docs.vechain.org/developer-resources/example-dapps/pwa-with-privy-and-account-abstraction This command installs the necessary dependencies for the project after cloning the template. It ensures all required packages are available for the Next.js PWA to run. It assumes the user is in the project's root directory. ```shell cd my-pwa-project npm install ``` -------------------------------- ### Initialize DAppKit Instance Source: https://docs.vechain.org/developer-resources/sdks-and-providers/dapp-kit/dapp-kit-1/core/usage Initializes the DAppKit instance with node URL, genesis network, and optional WalletConnect options. It also allows configuration for persistence, default wallet source, log level, certificate requirements, and allowed wallets. This setup is crucial for interacting with the VeChain blockchain. ```typescript import { DAppKit } from '@vechain/dapp-kit'; const {thor, vendor, wallet} = new DAppKit({ // Required - The URL of the node to connect to nodeUrl: "https://sync-testnet.vechain.org/", // OPTIONAL: "main" | "test" | Connex.Thor.Block genesis: "test", // OPTIONAL: Wallet connect options walletConnectOptions: walletConnectOptions, // OPTIONAL: Defaults to false. If true, account and source will be persisted in local storage usePersistence: true, // OPTIONAL: Use the first available wallet useFirstDetectedSource: false, // OPTIONAL: Log Level - To debug the library logLevel: "DEBUG", // OPTIONAL: every wallet has a connection certificate, but wallet connect doesn't connect with a certificate, it uses a session; if required, with this option, we will force the user to sign a certificate after he finishes the connection with wallet connect requireCertificate=false; // OPTIONAL: you can optionally provide a certificate to be signed during the login, otherwise a standard one will be used connectionCertificate={defaultContract} // OPTIONAL: you can choose which wallets to allow in your application between 'wallet-connect', 'veworld', 'sync2' or 'sync'. Default: all allowedWallets={[ 'veworld', 'wallet-connect' ]} }); ``` -------------------------------- ### Verify TypeScript Installation Source: https://docs.vechain.org/developer-resources/sdks-and-providers/dapp-kit/dapp-kit/vanilla/installation A simple TypeScript import statement to confirm that the DApp-Kit UI library has been successfully installed and can be recognized by the TypeScript compiler. ```typescript import { DAppKitUI } from '@vechain/dapp-kit-ui'; ``` -------------------------------- ### Verify thor-devkit.js Installation (TypeScript) Source: https://docs.vechain.org/developer-resources/sdks-and-providers/thor-devkit/installation A TypeScript code snippet to verify the successful installation of thor-devkit.js. It imports the keccak256 function and logs its output for the string 'hello world'. ```typescript import { keccak256 } from 'thor-devkit' console.log(keccak256('hello world').toString('hex')) // 47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad ``` -------------------------------- ### Install Connex via NPM for Browser Implementation Source: https://docs.vechain.org/developer-resources/sdks-and-providers/connex/installation Installs the Connex library using npm, a package manager for Node.js. This is the standard approach for dApp development in browser environments. ```bash npm i @vechain/connex ``` -------------------------------- ### Install Hardhat and VeChain Plugin Source: https://docs.vechain.org/developer-resources/frameworks-and-ides/hardhat Installs Hardhat development environment and the VeChain Hardhat plugin using yarn package manager. ```bash yarn add --dev hardhat npx hardhat yarn add @vechain/sdk-hardhat-plugin ``` -------------------------------- ### Install Hardhat and VeChain SDK Plugin Source: https://docs.vechain.org/developer-resources/how-to-build-on-vechain/build-with-hardhat Commands to install Hardhat and the VeChain SDK plugin for Hardhat. These are essential steps for setting up a VeChain development environment using Hardhat. ```shell npm install --save-dev hardhat npx hardhat init ``` ```bash npm install --save-dev @vechain/sdk-hardhat-plugin ``` -------------------------------- ### RPC Proxy Installation and Usage Source: https://docs.vechain.org/developer-resources/frameworks-and-ides/remix Instructions on how to install the RPC proxy and various ways to run it using CLI options. ```APIDOC ## Installation To install the RPC proxy, use the following command: ```bash yarn add @vechain/sdk-rpc-proxy ``` ## CLI Options The RPC proxy can be launched with various CLI options to customize its behavior. ### Basic Usage (Default Configuration) ```bash npx rpc-proxy ``` ### With Configuration File Use a configuration file to set default values. ```bash npx rpc-proxy -c /path/of/custom-config.json ``` ### With CLI Options Overriding Configuration CLI options take precedence over the configuration file. ```bash npx rpc-proxy -c /path/of/custom-config.json -p 8545 -v ``` ### CLI Options List #### Configuration File * `-c, --configurationFile `: The path to the configuration file. (e.g., `npx rpc-proxy -c custom-config.json`) #### Port * `-p, --port `: The port on which the proxy server will run. (e.g., `npx rpc-proxy -p 8545`) #### VeChain Thor Node URL * `-u, --url `: The URL of the VeChain Thor node. (e.g., `npx rpc-proxy -u http://testnet.vechain.org`) #### Verbose Logging * `-v, --verbose`: Enable verbose logging. (e.g., `npx rpc-proxy -v`) #### Accounts (Private Keys) * `-a, --accounts `: A space-separated list of private keys for signing transactions. (e.g., `npx rpc-proxy -a " "`) #### Mnemonic Phrase * `-m, --mnemonic `: The mnemonic phrase to derive accounts. * `-mc, --mnemonicCount `: The number of accounts to derive from the mnemonic. * `-mi, --mnemonicInitialIndex `: The starting index for deriving accounts. (e.g., `npx rpc-proxy -m "" -mc 10 -mi 1`) *Note*: `--mnemonic`, `--mnemonicCount`, and `--mnemonicInitialIndex` must be used together. #### Delegation Options * `-e, --enableDelegation`: Enable delegation for gas sponsorship. * `-dp, --gasPayerPrivateKey `: The private key of the gas payer. Mutually exclusive with `--gasPayerUrl`. * `-du, --gasPayerUrl `: The URL of the gas payer service. Mutually exclusive with `--gasPayerPrivateKey`. (e.g., `npx rpc-proxy -e -dp ` or `npx rpc-proxy -e -du `) *Note*: If `--enableDelegation` is used, either `--gasPayerPrivateKey` or `--gasPayerUrl` must be provided. ``` -------------------------------- ### Install VeChain DApp Kit React using NPM Source: https://docs.vechain.org/developer-resources/sdks-and-providers/dapp-kit/dapp-kit/react/installation Installs the VeChain DApp Kit React library via NPM. This command is suitable for both TypeScript and JavaScript projects. ```bash npm i @vechain/dapp-kit-react ``` -------------------------------- ### Install Account Abstraction Contract Dependencies Source: https://docs.vechain.org/developer-resources/example-dapps/pwa-with-privy-and-account-abstraction This command installs dependencies for the account abstraction contracts project, using the '--legacy-peer-deps' flag. This is necessary for compatibility with older versions of certain packages. Navigate to the contracts directory before running. ```shell cd docs-pwa-privy-account-abstraction/account-abstraction-contracts/ npm install --legacy-peer-deps ``` -------------------------------- ### Install VeChain SDK Core and Network Packages with Yarn Source: https://docs.vechain.org/developer-resources/sdks-and-providers/sdk This snippet shows how to install the core and network packages of the VeChain SDK using yarn. Yarn is another popular package manager for Node.js. Ensure you have Node.js and yarn installed. ```bash yarn add @vechain/sdk-core yarn add @vechain/sdk-network ... ``` -------------------------------- ### Example VeChain RPC Proxy Configuration (JSON) Source: https://docs.vechain.org/developer-resources/frameworks-and-ides/remix An example JSON configuration file for the RPC proxy. It specifies the VeChain Thor node URL, proxy port, account details (using a mnemonic), verbosity, and delegation settings. This configuration is essential for running the proxy with custom parameters. ```json { "url": "http://127.0.0.1:8669", "port": 8545, "accounts": { "mnemonic": "denial kitchen pet squirrel other broom bar gas better priority spoil cross", "count": 10 }, "verbose": true, "enableDelegation": false } ``` -------------------------------- ### Initialize Connex Framework Instance (NodeJS) Source: https://docs.vechain.org/developer-resources/sdks-and-providers/connex/installation Demonstrates the creation of a low-level Connex instance using the framework. It involves setting up a network, a driver, and then initializing the Framework with the driver. Outputs the genesis block ID. ```javascript import { Driver, SimpleNet } from '@vechain/connex-driver' import { Framework } from '@vechain/connex-framework' // Init newtork and driver const network = new SimpleNet('https://mainnet.veblocks.net/') const driver = await Driver.connect(network) // Init connex instance const connex = new Framework(driver) console.log(connex.thor.genesis.id) ``` -------------------------------- ### Connect to VeChain Wallet and Get Address Source: https://docs.vechain.org/developer-resources/sdks-and-providers/dapp-kit/dapp-kit/usage This function connects to the user's selected VeChain wallet, improving user experience by streamlining connection processes. It returns the wallet address and a 'verified' status, indicating if a certificate was signed. ```typescript import { ConnectResponse } from '@vechain/dapp-kit' const res: ConnectResponse = await wallet.connect() console.log(res) // { "address": "0x995711ADca070C8f6cC9ca98A5B9C5A99b8350b1","verified": true} ``` -------------------------------- ### Subscribe to a Single State Value by Key (TypeScript) Source: https://docs.vechain.org/developer-resources/sdks-and-providers/dapp-kit/dapp-kit-2/vanilla/usage This example demonstrates subscribing to a single, specific value in the state identified by a key. It includes a listener function, starts the subscription to the 'source' key, and shows how to unsubscribe. Requires the '@vechain/dapp-kit' library. ```typescript import { WalletSource } from '@vechain/dapp-kit' const myListener = (newWalletSource: WalletSource) => { console.log(newWalletSource) } //Start the subscription const subscription = wallet.subscribeToKey('source', myListener) //End the subscription subscription() ``` -------------------------------- ### Deploy Subgraph with `graph deploy` Command Source: https://docs.vechain.org/developer-resources/index-with-graph-node/index-with-openzeppelin/deploy-subgraph-and-start-indexing This command deploys a subgraph to a specified node and IPFS instance. It requires the subgraph name, node URL, IPFS URL, version label, and the subgraph definition file. The output shows the compilation and upload process. ```shell npx graph deploy vebetterdao/tokens --node http://127.0.0.1:8020 --ipfs http://127.0.0.1:5001 --version-label 1 vebetterdao/tokens.subgraph.yaml ``` -------------------------------- ### VeChain Fee Delegation Example Source: https://docs.vechain.org/developer-resources/sdks-and-providers/sdk/transactions Demonstrates how to set up fee delegation on the VeChainThor blockchain. This allows a sender to have another entity pay for transaction fees. It covers client creation, clause definition, gas estimation, transaction body setup, key generation, signing, and encoding/decoding. ```typescript // Sender account with private key const senderAccount = { privateKey: 'f9fc826b63a35413541d92d2bfb6661128cd5075fcdca583446d20c59994ba26', address: '0x7a28e7361fd10f4f058f9fefc77544349ecff5d6' }; // 1 - Create thor client for solo network const thorSoloClient = ThorClient.at(THOR_SOLO_URL, { isPollingEnabled: false }); // 2 - Define clause and estimate gas const clauses: TransactionClause[] = [ Clause.transferVET( Address.of('0x7567d83b7b8d80addcb281a71d54fc7b3364ffed'), VET.of(10000) ) as TransactionClause ]; // Get gas estimate const gasResult = await thorSoloClient.gas.estimateGas( clauses, senderAccount.address ); // 3 - Define transaction body const body: TransactionBody = { chainTag: networkInfo.mainnet.chainTag, blockRef: '0x0000000000000000', expiration: 0, clauses, gasPriceCoef: 0, gas: gasResult.totalGas, dependsOn: null, nonce: 1, reserved: { features: 1 // set the transaction to be delegated } }; // 4 - Create private keys of sender and delegate const nodeDelegate = HDKey.fromMnemonic(Mnemonic.of()); const gasPayerPrivateKey = nodeDelegate.privateKey; // 5 - Get address of delegate const gasPayerAddress = Address.ofPublicKey(nodeDelegate.publicKey).toString(); // 6 - Sign transaction as sender and delegate const signedTransaction = Transaction.of(body).signAsSenderAndGasPayer( HexUInt.of(senderAccount.privateKey).bytes, HexUInt.of(gasPayerPrivateKey).bytes ); // 7 - Encode transaction const encodedRaw = signedTransaction.encoded; // 8 - Decode transaction and check const decodedTx = Transaction.decode(encodedRaw, true); ``` -------------------------------- ### Initialize DAppKitProvider with WalletConnect Options (TypeScript) Source: https://docs.vechain.org/developer-resources/sdks-and-providers/dapp-kit/dapp-kit/react/usage Configures WalletConnect options and initializes the DAppKitProvider for a VeChain dApp. This setup requires a WalletConnect project ID and metadata for your application. It enables persistence and sets a node URL and genesis block for network configuration. ```tsx import type { WalletConnectOptions } from '@vechain/dapp-kit'; const walletConnectOptions: WalletConnectOptions = { // Create your project here: https://cloud.walletconnect.com/sign-up projectId: '', metadata: { name: 'My dApp', description: 'My dApp description', // Your app URL url: window.location.origin, // Your app Icon icons: [`${window.location.origin}/images/my-dapp-icon.png`], }, }; import { DAppKitProvider } from '@vechain/dapp-kit-react'; ReactDOM.createRoot(document.getElementById('root')!).render( , ); ``` -------------------------------- ### Get and Process Event Logs with VeChain SDK Source: https://docs.vechain.org/developer-resources/how-to-build-on-vechain/read-data/events-and-logs Retrieves event logs from the blockchain using a pre-defined filter and processes the results. This example shows how to fetch logs, iterate through them, and access decoded event data. It utilizes the `filterEventLogs` method and demonstrates decoding the raw log data. ```javascript const transferCriteria = contract.criteria // pass filters in the order of the input definition for the event // skip values by passing null or undefined .Transfer(null, '0x0000000000000000000000000000456e65726779'); const eventLogs = await thorClient.logs.filterEventLogs() eventLogs.forEach(log => { // Decode each event console.log('Decoded event', log.decodedData); }); ``` -------------------------------- ### Send Delegated Transaction with URL in VeChain Source: https://docs.vechain.org/developer-resources/sdks-and-providers/sdk/transactions This snippet demonstrates how to send a transaction with fee delegation enabled using a sponsor URL. It covers client initialization, account setup, transaction clause creation, gas estimation, transaction body building, signing with delegation, and sending the transaction. This example requires the VeChain SDK and assumes a testnet environment. ```javascript // 1 - Create the thor client const thorClient = ThorClient.at(TESTNET_URL, { isPollingEnabled: false }); // Sender account with private key const senderAccount: { mnemonic: string; privateKey: string; address: string; } = { mnemonic: 'fat draw position use tenant force south job notice soul time fruit', privateKey: '2153c1e49c14d92e8b558750e4ec3dc9b5a6ac4c13d24a71e0fa4f90f4a384b5', address: '0x571E3E1fBE342891778151f037967E107fb89bd0' }; // Gas-payer account with private key const gasPayerAccount = { URL: 'https://sponsor-testnet.vechain.energy/by/269' }; // Create the provider (used in this case to sign the transaction with getSigner() method) const providerWithDelegationEnabled = new VeChainProvider( // Thor client used by the provider thorClient, // Internal wallet used by the provider (needed to call the getSigner() method) new ProviderInternalBaseWallet( [ { privateKey: HexUInt.of(senderAccount.privateKey).bytes, address: senderAccount.address } ], { gasPayer: { gasPayerServiceUrl: gasPayerAccount.URL } } ), // Enable fee delegation true ); // 2 - Create the transaction clauses const transaction = { clauses: [ Clause.transferVET( Address.of('0xb717b660cd51109334bd10b2c168986055f58c1a'), VET.of(1) ) as TransactionClause ], simulateTransactionOptions: { caller: senderAccount.address } }; // 3 - Estimate gas const gasResult = await thorClient.gas.estimateGas( transaction.clauses, senderAccount.address ); // 4 - Build transaction body const txBody = await thorClient.transactions.buildTransactionBody( transaction.clauses, gasResult.totalGas, { isDelegated: true } ); // 4 - Sign the transaction const signer = await providerWithDelegationEnabled.getSigner( senderAccount.address ); const rawDelegateSigned = await signer.signTransaction( signerUtils.transactionBodyToTransactionRequestInput( txBody, senderAccount.address ) ); const delegatedSigned = Transaction.decode( HexUInt.of(rawDelegateSigned.slice(2)).bytes, true ); // 5 - Send the transaction const sendTransactionResult = await thorClient.transactions.sendTransaction(delegatedSigned); // 6 - Wait for transaction receipt const txReceipt = await thorClient.transactions.waitForTransaction( sendTransactionResult.id ); ``` -------------------------------- ### Configure Method Caching (Expire on Address Seen) Source: https://docs.vechain.org/developer-resources/sdks-and-providers/connex/api-specification This TypeScript example shows how to set up caching for a `balanceOf` method, configured to expire when a specific address is observed on the blockchain. It defines the ABI, gets the method, and applies `.cache()` with an array containing the address. This ensures the cache is invalidated if events related to that address occur. The balance for the specified address is then retrieved. ```typescript // Caching for method balanceOf, for my addresses // Solidity function balanceOf(address _owner) public view returns(uint256 balance) const balanceOfABI = {"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"} const balanceOfMethod = connex.thor.account('0x0000000000000000000000000000456E65726779').method(balanceOfABI) // Set this method to expire when my account being seen balanceOfMethod.cache(['0x7567d83b7b8d80addcb281a71d54fc7b3364ffed']) // Get balance of my account, we will get cached result on most blocks // Event Transfer(_from = '0x7567d83b7b8d80addcb281a71d54fc7b3364ffed', ....) would make cache expiredalanceOfMethod.call('0x7567d83b7b8d80addcb281a71d54fc7b3364ffed').then(output=>{ console.log(output) }) ``` -------------------------------- ### Thor Client Initialization Source: https://docs.vechain.org/developer-resources/sdks-and-providers/sdk/thor-client Demonstrates two ways to initialize the ThorClient: by first creating an HTTP client and then passing it, or by directly initializing from the network URL. ```APIDOC ## Thor Client Initialization ### Description Initializes the ThorClient for interacting with the VeChainThor blockchain. ### Method Constructor or static method ### Endpoint N/A ### Parameters None for direct initialization. Requires an HTTP client for the other method. ### Request Example ```javascript // First way to initialize thor client const httpClient = new SimpleHttpClient(TESTNET_URL); const thorClient = new ThorClient(httpClient); // Second way to initialize thor client const thorClient2 = ThorClient.at(TESTNET_URL); ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Execute Multicall for Token Balance and Decimals with Signer (TypeScript) Source: https://docs.vechain.org/developer-resources/how-to-build-on-vechain/utilities/bigint-and-unit-handling This example shows how to execute a multicall transaction to get a token's balance and decimals using a VeChain signer. It sets up a `ThorClient`, loads an ERC20 contract, defines clauses for `balanceOf` and `decimals`, and then uses `VeChainProvider` and `getSigner` to send the transaction. The output is the transaction response. ```typescript import { ThorClient, TESTNET_URL, Contract, VeChainAbstractSigner , VeChainProvider, ProviderInternalBaseWallet } from '@vechain/sdk-network'; import { HexUInt , ERC20_ABI} from '@vechain/sdk-core' const thor = ThorClient.at(TESTNET_URL+'/'); const contract = thor.contracts.load('0x0000000000000000000000000000456e65726779', ERC20_ABI ); const senderAccount = { privateKey: 'f9fc826b63a35413541d92d2bfb6661128cd5075fcdca583446d20c59994ba26', address: '0x7a28e7361fd10f4f058f9fefc77544349ecff5d6' }; let clauses = []; clauses.push(contract.clause.balanceOf('0x0000000000000000000000000000456e65726779')); clauses.push(contract.clause.decimals()); // Create the provider const provider = new VeChainProvider( // Thor client used by the provider thor, // Wallets used by the provider new ProviderInternalBaseWallet([ { privateKey: HexUInt.of(senderAccount.privateKey).bytes, address: senderAccount.address } ]), false ); const signer = await provider.getSigner(senderAccount.address); const response = await thor.contracts.executeMultipleClausesTransaction(clauses, signer); console.log(response); ``` -------------------------------- ### Run All OpenZeppelin Tests (OZ5) Source: https://docs.vechain.org/core-concepts/evm-compatibility/how-to-recreate Executes all OpenZeppelin tests using the `npm run test:solo` script, which is configured for running tests on a solo VeChain node. Be aware that this can take a significant amount of time. ```bash npm run test:solo ``` -------------------------------- ### Deploy Contracts on VeChain Testnet Source: https://docs.vechain.org/developer-resources/example-dapps/pwa-with-privy-and-account-abstraction This command uses the Hardhat deploy plugin to deploy example contracts to the VeChain testnet. The output will display the addresses of the deployed contracts, such as the SimpleAccountFactory. ```shell npx hardhat deploy --network vechain_testnet ``` -------------------------------- ### Run Specific Directory Tests (OZ5) Source: https://docs.vechain.org/core-concepts/evm-compatibility/how-to-recreate Executes OpenZeppelin tests within a specified directory on the solo VeChain node. This is useful for running tests in smaller batches. ```bash npm run test:solo:dir ``` -------------------------------- ### Install thor-devkit.js via NPM Source: https://docs.vechain.org/developer-resources/sdks-and-providers/thor-devkit/installation Installs the thor-devkit.js library using npm, the Node Package Manager. This is the recommended method for TypeScript projects. ```bash npm i thor-devkit ``` -------------------------------- ### Initialize Thor Client (JavaScript) Source: https://docs.vechain.org/developer-resources/sdks-and-providers/sdk/thor-client Demonstrates two methods for initializing the ThorClient. The first involves creating a SimpleHttpClient and passing it to ThorClient. The second uses a direct initialization from the network URL. ```javascript const httpClient = new SimpleHttpClient(TESTNET_URL); const thorClient = new ThorClient(httpClient); // Second way to initialize thor client const thorClient2 = ThorClient.at(TESTNET_URL); ``` -------------------------------- ### Install Connex Framework Dependencies Source: https://docs.vechain.org/developer-resources/sdks-and-providers/connex/installation Installs the necessary packages for using Connex within a framework, typically for NodeJS projects or CLI applications. Requires `@vechain/connex-framework` and `@vechain/connex-driver`. ```bash npm i @vechain/connex-framework @vechain/connex-driver ``` -------------------------------- ### Run OpenZeppelin Tests on VeChain Source: https://docs.vechain.org/core-concepts/evm-compatibility/how-to-recreate Executes OpenZeppelin tests on the configured VeChain network using Hardhat. This command can be used to run a specific test file or all tests within the project. ```bash npx hardhat test --network vechain test/access/AccessControlEnumerable.test.js ``` ```bash npx hardhat test --network vechain ``` -------------------------------- ### Initialize DAppKit Instance for VeChain Development Source: https://docs.vechain.org/developer-resources/sdks-and-providers/dapp-kit/dapp-kit/usage This code initializes the DAppKit instance, establishing a connection to a VeChain node. It includes configurations for the node URL, genesis block, WalletConnect options, persistence, and logging level. ```typescript import { DAppKit } from '@vechain/dapp-kit'; const {thor, vendor, wallet} = new DAppKit({ // Required - The URL of the node to connect to nodeUrl: "https://sync-testnet.vechain.org/", // Optional - "main" | "test" | Connex.Thor.Block genesis: "test", // Optional - Wallet connect options walletConnectOptions: walletConnectOptions, // Optional - Defaults to false. If true, account and source will be persisted in local storage usePersistence: true, // Optional - Use the first available wallet useFirstDetectedSource: false, // Optional - Log Level - To debug the library logLevel: "DEBUG", }); ``` -------------------------------- ### Use Connex with HTML (Browser Implementation - CDN) Source: https://docs.vechain.org/developer-resources/sdks-and-providers/connex/installation Shows a basic HTML structure that includes Connex via CDN and initializes it to interact with the VeChain mainnet. It logs the genesis block ID to the console. ```html Connex Test Project ``` -------------------------------- ### Implement Async Poll for DAPP Transactions with Vechain SDK (JavaScript) Source: https://docs.vechain.org/developer-resources/sdks-and-providers/sdk/polls This JavaScript code demonstrates how to implement an asynchronous poll for tracking transaction events in a Decentralized Application (DAPP) using the vechain SDK. It initializes a Thor client, sets up accounts to monitor, and configures a poll to fetch account details at regular intervals. The poll includes listeners for start, stop, data, and error events, with an example of stopping the poll after a specific number of iterations. ```javascript import { Poll, TESTNET_URL, ThorClient } from '@vechain/sdk-network'; import { expect } from 'expect'; import { Address } from '@vechain/sdk-core'; // 1 - Create thor client for testnet const thorClient = ThorClient.at(TESTNET_URL); // 2 - Init accounts const accounts = [ '0x2669514f9fe96bc7301177ba774d3da8a06cace4', '0x9e7911de289c3c856ce7f421034f66b6cde49c39' ]; // 3 - Monitor status for each account for (const account of accounts) { const monitoringPoll = Poll.createEventPoll( async () => await thorClient.accounts.getAccount(Address.of(account)), 1000 ) // Add listeners for start event .onStart((eventPoll) => { console.log(`Start monitoring account ${account}`, eventPoll); }) // Add listeners for stop event .onStop((eventPoll) => { console.log(`Stop monitoring account ${account}`, eventPoll); }) // Add listeners for data event. It intercepts the account details every 1 second .onData((accountDetails, eventPoll) => { console.log(`Account details of ${account}:`, accountDetails); // Stop after 3 iterations - EXIT CONDITION if (eventPoll.getCurrentIteration === 3) eventPoll.stopListen(); }) // Add listeners for error event .onError((error) => { console.log('Error:', error); }); monitoringPoll.startListen(); // It seems to be strange, BUT onData is called only after 1 second of the eventPoll.startListen() call. expect(monitoringPoll.getCurrentIteration).toBe(0); } ``` -------------------------------- ### Initialize VeChain DAppKit UI with WalletConnect Source: https://docs.vechain.org/developer-resources/sdks-and-providers/dapp-kit/dapp-kit-2/vanilla/usage Configures the DAppKit UI with specified options, including WalletConnect project ID and metadata. This setup prepares the application to interact with VeChain wallets. ```typescript import { DAppKitUI } from '@vechain/dapp-kit-ui'; import type { WalletConnectOptions, DAppKitUIOptions } from '@vechain/dapp-kit-ui'; const walletConnectOptions: WalletConnectOptions = { // Create your project here: https://cloud.walletconnect.com/sign-up projectId: '<PROJECT_ID>', metadata: { name: 'My dApp', description: 'My dApp description', // Your app URL url: window.location.origin, // Your app Icon icons: [`${window.location.origin}/images/my-dapp-icon.png`], }, }; const vechainWalletKitOptions: DAppKitUIOptions = { // Required - The URL of the node to connect to node: 'https://testnet.vechain.org/', // Optional - Wallet connect options walletConnectOptions, // Optional - Defaults to false. If true, the account and source will be persisted in local storage usePersistence: true, // Optional - Defaults to the first available wallet. Default value is false useFirstDetectedSource: true, // Optional - Set a log level to debug the library logLevel: 'DEBUG', // OPTIONAL: theme variables (check theme variables section) themeVariables=ThemeVariables // OPTIONAL: app current language language="en"; // OPTIONAL: i18n default object (check i18n section) i18n=defaultI18n // OPTIONAL: where to render the modal, document.body is the default modalParent=document.body // OPTIONAL: handle source click to customise wallet connect onSourceClick=source => void // OPTIONAL: every wallet has a connection certificate, but wallet connect doesn't connect with a certificate, it uses a session; if required, with this option, we will force the user to sign a certificate after he finishes the connection with wallet connect requireCertificate=false; // OPTIONAL: you can optionally provide a certificate to be signed during the login, otherwise a standard one will be used connectionCertificate=defaultContract // OPTIONAL: you can choose which wallets to allow in your application between 'wallet-connect', 'veworld', 'sync2' or 'sync'. Default: all allowedWallets={[ 'veworld', 'wallet-connect' ]} }; const dappKit = DAppKitUI.configure(vechainWalletKitOptions); const {thor, vendor, wallet, modal} = DAppKitUI console.log(`DAppKit configured`, dappKit.thor.genesis.id); ``` -------------------------------- ### Running VeChain RPC Proxy via npm Source: https://docs.vechain.org/developer-resources/evm-compatibility-for-developers/frequently-asked-questions-faqs This command installs and runs a local JSON-RPC proxy for a VeChain Testnet node using npm. This provides a convenient way to interact with the VeChain Testnet locally, similar to how one might interact with an Ethereum local development node. ```shell npx @vechain/sdk-rpc-proxy ``` -------------------------------- ### Get VeChain Blockchain Status (TypeScript) Source: https://docs.vechain.org/developer-resources/sdks-and-providers/connex/api-specification Fetches the current status of the VeChain Thor blockchain, including the latest block's head information and overall progress. It accesses `connex.thor.status` to get these details. ```typescript console.log(connex.thor.status) ```