### Initialize Web3Eth and Get Block (Individual Package) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Web3Eth.md Shows how to initialize the Web3Eth class directly from the 'web3-eth' package for a more modular and lightweight setup. It connects to an Ethereum node and fetches the genesis block (block 0). Requires installing the 'web3-eth' package. ```TypeScript import { Web3Eth } from 'web3-eth'; const eth = new Web3Eth('https://mainnet.infura.io/v3/'); const block = await eth.getBlock(0); ``` -------------------------------- ### Initialize Web3 and Get Block (Full Package) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Web3Eth.md Demonstrates how to initialize the Web3 library using the full 'web3' package and connect to an Ethereum node (e.g., Infura). It then shows how to fetch the genesis block (block 0) using the 'eth' property. Requires installing the 'web3' package. ```TypeScript import { Web3 } from 'web3'; const web3 = new Web3('https://mainnet.infura.io/v3/'); const block = await web3.eth.getBlock(0); ``` -------------------------------- ### Example Getting Provider in TypeScript Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Web3.md Demonstrates how to instantiate a `Web3Context` and access its `provider` property to see the current provider configuration. ```TypeScript const web3 = new Web3Context("http://localhost:8545"); console.log(web3.provider); ``` -------------------------------- ### Converting Iban Instance to String in web3-eth-iban (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Iban.md Demonstrates how to create an Iban instance and then use the `toString()` method to get its string representation. This is a basic usage example for an Iban object. ```ts const iban = new web3.eth.Iban('XE7338O073KYGTWWZN0F2WZ0R8PX5ZPPZS'); iban.toString(); ``` -------------------------------- ### Get Account and Storage Proof with web3.js (Formatted Output) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Web3Eth.md This example illustrates calling `web3.eth.getProof` while providing formatting options for the returned data. By passing `undefined` for the block parameter and an options object, you can control how numbers and bytes are represented in the output proof object. ```TypeScript web3.eth.getProof( "0x1234567890123456789012345678901234567890", ["0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000001"], undefined, { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } ).then(console.log); ``` -------------------------------- ### Installing Velora SDK with Yarn Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/README.md Command to add the Velora SDK package to a project using the Yarn package manager. This is the standard way to install the SDK dependency. ```bash yarn add @velora-dex/sdk ``` -------------------------------- ### Get Accounts using Web3 (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Personal.md Demonstrates how to use the full 'web3' package to connect to an Ethereum node and retrieve a list of accounts using the 'eth.personal.getAccounts' method. Requires installing the 'web3' package. ```TypeScript import { Web3 } from 'web3'; const web3 = new Web3('http://127.0.0.1:7545'); console.log(await web3.eth.personal.getAccounts()); ``` -------------------------------- ### Getting Account Proof with Viem Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/type-aliases/PublicActions.md This example shows how to retrieve the account and storage proof for a specific address using the `getProof` function in Viem. It sets up a public client for the mainnet and then calls `getProof` with the target address and storage keys. This is useful for verifying state. ```typescript import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' const client = createPublicClient({ chain: mainnet, transport: http(), }) const block = await client.getProof({ address: '0x...', storageKeys: ['0x...'], }) ``` -------------------------------- ### Get Accounts using web3-eth-personal (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Personal.md Shows how to use the specific 'web3-eth-personal' package to connect to an Ethereum node and retrieve a list of accounts using the 'personal.getAccounts' method. Requires installing the 'web3-eth-personal' package. ```TypeScript import {Personal} from 'web3-eth-personal'; const personal = new Personal('http://127.0.0.1:7545'); console.log(await personal.getAccounts()); ``` -------------------------------- ### Querying Balance (BigInt) with Web3.js (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Web3Eth.md Shows how to get the balance of a specific address using `web3.eth.getBalance()`. This example demonstrates the default return format, which is a BigInt representing the balance in wei. ```TypeScript web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); ``` -------------------------------- ### Example using EventEmitter emit method (JavaScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/interfaces/WritableStream.md This JavaScript example demonstrates how to create an EventEmitter instance, register multiple listeners for the same event ('event'), and then emit the event with arguments. It shows how different listeners receive and process the arguments. ```JavaScript import { EventEmitter } from 'node:events'; const myEmitter = new EventEmitter(); // First listener myEmitter.on('event', function firstListener() { console.log('Helloooo! first listener'); }); // Second listener myEmitter.on('event', function secondListener(arg1, arg2) { console.log(`event with parameters ${arg1}, ${arg2} in second listener`); }); // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(`event with parameters ${parameters} in third listener`); }); console.log(myEmitter.listeners('event')); myEmitter.emit('event', 1, 2, 3, 4, 5); // Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // Helloooo! first listener // event with parameters 1, 2 in second listener // event with parameters 1, 2, 3, 4, 5 in third listener ``` -------------------------------- ### Estimating Transaction Gas with web3.eth.estimateGas (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/interfaces/Web3EthInterface.md This example shows how to use the `web3.eth.estimateGas` method to simulate a transaction and estimate the gas required for its execution. It includes examples for a basic transaction and for specifying the return format for the gas estimate. ```typescript const transaction = { from: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', to: '0xe899f0130FD099c0b896B2cE4E5E15A25b23139a', value: '0x1', nonce: '0x1', type: '0x0' } web3.eth.estimateGas(transaction).then(console.log); web3.eth.estimateGas(transaction, { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX }).then(console.log); ``` -------------------------------- ### Get Network ID using web3-net package (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Net.md Initializes a `Net` instance from the `web3-net` package with an Infura provider and retrieves the network ID using `net.getId()`. Requires the `web3-net` package to be installed. ```TypeScript import {Net} from 'web3-net'; const net = new Net('https://mainnet.infura.io/v3/'); console.log(await net.getId()); ``` -------------------------------- ### Getting EventEmitter Listeners (JavaScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/internal.md This JavaScript example demonstrates how to use the `listeners()` method on an EventEmitter instance (`server`) to retrieve an array of functions currently listening for a specific event (`'connection'`). It then uses `util.inspect` to print the array to the console. ```JavaScript server.on('connection', (stream) => { console.log('someone connected!'); }); console.log(util.inspect(server.listeners('connection'))); // Prints: [ [Function] ] ``` -------------------------------- ### Getting the currentProvider in Web3Context (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Web3PluginBase.md This example demonstrates how to retrieve the current provider instance from a Web3Context object after initialization. It shows accessing the `provider` property and logging its details, illustrating the type of provider currently in use. ```typescript const web3Context = new Web3Context("http://localhost:8545"); console.log(web3Context.provider); > HttpProvider { clientUrl: 'http://localhost:8545', httpProviderOptions: undefined } ``` -------------------------------- ### Querying Max Priority Fee Per Gas with Web3.eth (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Web3Eth.md Shows how to get the current max priority fee per gas in wei using `web3.eth.getMaxPriorityFeePerGas()`. Includes examples for default (BigInt) and hex string output. ```typescript web3.eth.getMaxPriorityFeePerGas().then(console.log); > 20000000000n web3.eth.getMaxPriorityFeePerGas({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); > "0x4a817c800" ``` -------------------------------- ### Getting Block Transaction Count with web3.eth (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Web3Eth.md Shows how to use `web3.eth.getBlockTransactionCount()` to get the number of transactions in a specific block identified by its hash. Examples include the default BigInt return and requesting a standard number format. ```TypeScript web3.eth.getBlockTransactionCount("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); > 1n web3.eth.getBlockTransactionCount( "0x407d73d8a49eeb85d32cf465507dd71d507100c1", { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } ).then(console.log); > 1 ``` -------------------------------- ### Using Simple Velora SDK for Swaps (ethers) Source: https://github.com/veloradex/paraswap-sdk/blob/master/README.md Demonstrates how to initialize the simple SDK with a fetcher (axios or fetch) and perform a token swap by fetching a price route and building the transaction parameters using an ethers signer. ```typescript import { constructSimpleSDK } from '@velora-dex/sdk'; import axios from 'axios'; // construct minimal SDK with fetcher only const minSDK = constructSimpleSDK({chainId: 1, axios}); // or const minSDK = constructSimpleSDK({chainId: 1, fetch: window.fetch, version: '5'}); const ETH = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'; const DAI = '0x6B175474E89094C44Da98b954EedeAC495271d0F'; async function swapExample() { // or any other signer/provider const signer: JsonRpcSigner = ethers.Wallet.fromMnemonic('__your_mnemonic__'); const senderAddress = signer.address; const priceRoute = await minSDK.swap.getRate({ srcToken: ETH, destToken: DAI, amount: srcAmount, userAddress: senderAddress, side: SwapSide.SELL, }); const txParams = await minSDK.swap.buildTx( { srcToken, destToken, srcAmount, destAmount, priceRoute, userAddress: senderAddress, partner: referrer, } ); const transaction = { ...txParams, gasPrice: '0x' + new BigNumber(txParams.gasPrice).toString(16), gasLimit: '0x' + new BigNumber(5000000).toString(16), value: '0x' + new BigNumber(txParams.value).toString(16), }; const txr = await signer.sendTransaction(transaction); } ``` -------------------------------- ### Example Usage of toHex - TypeScript Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/namespaces/Users_alexeyshchur_Desktop_Repos_paraswap-sdk_node_modules_web3-utils_lib_commonjs_index/functions/toHex.md This example demonstrates how to use the `toHex` function to convert a number to hex and how to use the optional `returnType` parameter with a hex string. ```TypeScript console.log(web3.utils.toHex(10)); > 0xa console.log(web3.utils.toHex('0x123', true)); > bytes ``` -------------------------------- ### Constructing Simple Velora SDK and Performing a Swap (Fetcher Only) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/README.md Demonstrates how to create a minimal Velora SDK instance using `constructSimpleSDK` with only a fetcher (axios or fetch). It then shows an example of fetching a price route and building a swap transaction using the constructed SDK instance. This configuration is suitable for API querying methods. ```typescript import { constructSimpleSDK } from '@velora-dex/sdk'; import axios from 'axios'; // construct minimal SDK with fetcher only const minSDK = constructSimpleSDK({chainId: 1, axios}); // or const minSDK = constructSimpleSDK({chainId: 1, fetch: window.fetch, version: '5'}); const ETH = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'; const DAI = '0x6B175474E89094C44Da98b954EedeAC495271d0F'; async function swapExample() { // or any other signer/provider const signer: JsonRpcSigner = ethers.Wallet.fromMnemonic('__your_mnemonic__'); const senderAddress = signer.address; const priceRoute = await minSDK.swap.getRate({ srcToken: ETH, destToken: DAI, amount: srcAmount, userAddress: senderAddress, side: SwapSide.SELL, }); const txParams = await minSDK.swap.buildTx( { srcToken, destToken, srcAmount, destAmount, priceRoute, userAddress: senderAddress, partner: referrer, } ); const transaction = { ...txParams, gasPrice: '0x' + new BigNumber(txParams.gasPrice).toString(16), gasLimit: '0x' + new BigNumber(5000000).toString(16), value: '0x' + new BigNumber(txParams.value).toString(16), }; const txr = await signer.sendTransaction(transaction); } ``` -------------------------------- ### Using EventEmitter.emit with Multiple Listeners - JavaScript Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/WritableBase.md This example demonstrates how to use the `EventEmitter.emit` method in Node.js. It shows how to register multiple listeners for the same event and how `emit` synchronously calls each listener in order, passing the provided arguments. The example logs the listeners and the output from each listener when the 'event' is emitted. ```js import { EventEmitter } from 'node:events'; const myEmitter = new EventEmitter(); // First listener myEmitter.on('event', function firstListener() { console.log('Helloooo! first listener'); }); // Second listener myEmitter.on('event', function secondListener(arg1, arg2) { console.log(`event with parameters ${arg1}, ${arg2} in second listener`); }); // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(`event with parameters ${parameters} in third listener`); }); console.log(myEmitter.listeners('event')); myEmitter.emit('event', 1, 2, 3, 4, 5); // Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // Helloooo! first listener // event with parameters 1, 2 in second listener // event with parameters 1, 2, 3, 4, 5 in third listener ``` -------------------------------- ### Initializing Web3.js Contract with Address and Options (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Contract.md An example demonstrating how to create a `web3.eth.Contract` instance by providing the contract's ABI, address, and an options object for default `from` address and `gasPrice`. ```typescript var myContract = new web3.eth.Contract([...], '0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe', { from: '0x1234567890123456789012345678901234567891', // default from address gasPrice: '20000000000' // default gas price in wei, 20 gwei in this case }); ``` -------------------------------- ### Getting Provider in Web3Context (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/interfaces/Web3EthInterface.md Demonstrates how to instantiate a Web3Context and retrieve the current provider instance using the provider getter. The example shows the expected output for an HttpProvider. ```ts const web3 = new Web3Context("http://localhost:8545"); console.log(web3.provider); > HttpProvider { clientUrl: 'http://localhost:8545', httpProviderOptions: undefined } ``` -------------------------------- ### Example: Using padLeft with web3.utils Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/namespaces/Users_alexeyshchur_Desktop_Repos_paraswap-sdk_node_modules_web3-utils_lib_commonjs_index/functions/padLeft.md Demonstrates how to use the padLeft function from web3.utils to pad a hexadecimal string to a specified length. ```TypeScript console.log(web3.utils.padLeft('0x123', 10)); >0x0000000123 ``` -------------------------------- ### Getting the current provider in TypeScript Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Web3Context.md This example demonstrates how to instantiate a Web3Context with an HTTP provider and then access its `provider` property to retrieve the current provider instance. ```ts const web3Context = new Web3Context("http://localhost:8545"); console.log(web3Context.provider); > HttpProvider { clientUrl: 'http://localhost:8545', httpProviderOptions: undefined } ``` -------------------------------- ### Constructing Partial Velora SDK (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/README.md Shows how to initialize a partial Velora SDK instance by selecting specific functions like `constructGetRate` and `constructGetBalances` to reduce bundle size. It requires a fetcher function and chain ID. The example demonstrates calling `getRate` and `getAllowance` on the partial SDK instance. ```typescript import { constructPartialSDK, constructFetchFetcher, constructGetRate, constructGetBalances } from '@velora-dex/sdk'; const fetcher = constructFetchFetcher(window.fetch); const sdk = constructPartialSDK({ chainId: 1, fetcher, }, constructGetRate, constructGetBalances); const priceRoute = await sdk.getRate(params); const allowance = await sdk.getAllowance(userAddress, tokenAddress); ``` -------------------------------- ### Constructing Full Velora SDK with Custom Fetcher and Contract Caller Source: https://github.com/veloradex/paraswap-sdk/blob/master/README.md Illustrates how to build the full SDK by separately constructing a fetcher (e.g., using axios or fetch) and a contract caller (e.g., using ethers, viem, or web3.js) and providing them to the `constructFullSDK` function for a more modular setup. ```typescript import { constructFullSDK, constructAxiosFetcher, constructEthersContractCaller } from '@velora-dex/sdk'; const signer = ethers.Wallet.fromMnmemonic('__your_mnemonic__'); // or any other signer/provider const account = '__signer_address__'; const contractCaller = constructEthersContractCaller({ ethersProviderOrSigner: signer, EthersContract: ethers.Contract, }, account); // alternatively constructViemContractCaller or constructWeb3ContractCaller const fetcher = constructAxiosFetcher(axios); // alternatively constructFetchFetcher const sdk = constructFullSDK({ chainId: 1, fetcher, contractCaller, }); ``` -------------------------------- ### Get Web3Context Provider (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Web3Eth.md Demonstrates how to instantiate a Web3Context and access its current provider property using the getter. The example shows the expected output when the provider is an HttpProvider. ```ts const web3 = new Web3Context("http://localhost:8545"); console.log(web3.provider); > HttpProvider { clientUrl: 'http://localhost:8545', httpProviderOptions: undefined } ``` -------------------------------- ### Getting Current Provider in Web3Context (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Contract.md This example demonstrates how to access the current provider instance associated with a Web3Context object using the 'provider' property, which is synonymous with 'currentProvider'. ```TypeScript const web3Context = new Web3Context("http://localhost:8545"); console.log(web3Context.provider); ``` -------------------------------- ### Configuring Simple SDK with Provider Options for Token Approval Source: https://github.com/veloradex/paraswap-sdk/blob/master/README.md Shows how to initialize the simple SDK with an optional second parameter, `providerOptions`, to enable functionalities like token approval using different libraries such as ethers (v5/v6), viem, or web3.js. ```typescript // with ethers@5 const providerOptionsEtherV5 = { ethersProviderOrSigner: provider, // JsonRpcProvider EthersContract: ethers.Contract, account: senderAddress, }; // with ethers@6 const providerOptionsEtherV6 = { ethersV6ProviderOrSigner: provider, // JsonRpcProvider EthersV6Contract: ethers.Contract, account: senderAddress, }; // or with viem (from wagmi or standalone) const providerOptionsViem = { viemClient, // made with createWalletClient() account: senderAddress, }; // or with web3.js const providerOptionsWeb3 = { web3, // new Web3(...) instance account: senderAddress, }; const sdk = constructSimpleSDK({chainId: 1, axios}, providerOptionsEtherV5); // approve token through sdk const txHash = await sdk.approveToken(amountInWei, DAI); // await tx somehow await provider.waitForTransaction(txHash); ``` -------------------------------- ### Installing Velora SDK via Yarn Source: https://github.com/veloradex/paraswap-sdk/blob/master/README.md Provides the command to add the Velora SDK package as a dependency to your project using the Yarn package manager. ```bash yarn add @velora-dex/sdk ``` -------------------------------- ### Get Network ID using Web3 package (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Net.md Initializes a Web3 instance with an Infura provider and retrieves the network ID using `web3.eth.net.getId()`. Requires the `web3` package to be installed. ```TypeScript import { Web3 } from 'web3'; const web3 = new Web3('https://mainnet.infura.io/v3/'); console.log(await web3.eth.net.getId()); ``` -------------------------------- ### Initializing Web3 Contract and Calling Method (Full Package) - TypeScript Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Contract.md Demonstrates initializing a Web3 instance and a smart contract instance using the full `web3` package. It shows how to call a read-only contract method (`balanceOf`) using `.call()`. Requires installing `web3`. ```TypeScript import { Web3 } from 'web3'; const web3 = new Web3('https://127.0.0.1:4545'); const abi = [...] as const; // your contract ABI let contract = new web3.eth.Contract(abi,'0xdAC17F958D2ee523a2206206994597C13D831ec7'); await contract.methods.balanceOf('0xdAC17F958D2ee523a2206206994597C13D831ec7').call(); ``` -------------------------------- ### Initializing Web3 Contract (Individual Packages) - TypeScript Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Contract.md Illustrates how to initialize a smart contract instance using the more lightweight approach with individual `web3-core` and `web3-eth-contract` packages. It also shows calling a read-only method. Requires installing `web3-eth-contract` and `web3-core`. ```TypeScript import { Web3Context } from 'web3-core'; import { Contract } from 'web3-eth-contract'; const abi = [...] as const; // your contract ABI let contract = new web3.eth.Contract( abi, '0xdAC17F958D2ee523a2206206994597C13D831ec7' new Web3Context('http://127.0.0.1:8545')); await contract.methods.balanceOf('0xdAC17F958D2ee523a2206206994597C13D831ec7').call(); ``` -------------------------------- ### Get Node Hashrate (Deprecated and Current) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/interfaces/Web3EthInterface.md Demonstrates how to retrieve the current hashrate of the connected node using both the deprecated `getHashrate` method and the current `getHashRate` method. Examples show default and hexadecimal number/bytes formatting. ```JavaScript web3.eth.getHashrate().then(console.log); > 493736n ``` ```JavaScript web3.eth.getHashrate({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); > "0x788a8" ``` ```JavaScript web3.eth.getHashRate().then(console.log); > 493736n ``` ```JavaScript web3.eth.getHashRate({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); > "0x788a8" ``` -------------------------------- ### Constructing a Partial Velora SDK Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/README.md Demonstrates how to create a lightweight instance of the Velora SDK by including only specific functions like `getRate` and `getBalances` to reduce bundle size. Requires the `@velora-dex/sdk` package and a fetcher function. ```typescript import { constructPartialSDK, constructFetchFetcher, constructGetRate, constructGetBalances } from '@velora-dex/sdk'; const fetcher = constructFetchFetcher(window.fetch); const sdk = constructPartialSDK({ chainId: 1, fetcher, }, constructGetRate, constructGetBalances); const priceRoute = await sdk.getRate(params); const allowance = await sdk.getAllowance(userAddress, tokenAddress); ``` -------------------------------- ### Basic Velora SDK Usage with Quote and Swap Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/README.md Illustrates the basic trade flow using `constructSimpleSDK` and the `/quote` API endpoint. It covers initializing the SDK with Ethers, getting a quote, handling both Delta and Market trade paths, including token approval and transaction submission. ```typescript import axios from 'axios'; import { ethers } from 'ethersV5'; import { constructSimpleSDK } from '@velora-dex/sdk'; const ethersProvider = new ethers.providers.Web3Provider(window.ethereum); const accounts = await ethersProvider.listAccounts(); const account = accounts[0]!; const signer = ethersProvider.getSigner(account); const simpleSDK = constructSimpleSDK( { chainId: 1, axios }, { ethersProviderOrSigner: signer, EthersContract: ethers.Contract, account, } ); const amount = '1000000000000'; // wei const Token1 = '0x1234...' const Token2 = '0xabcde...' const quote = await simpleSDK.quote.getQuote({ srcToken: Token1, // Native token (ETH) is only supported in mode: 'market' destToken: Token2, amount, userAddress: account, srcDecimals: 18, destDecimals: 18, mode: 'all', // Delta quote if possible, with fallback to Market price side: 'SELL', // Delta mode only supports side: SELL currenly // partner: "..." // if available }); if ('delta' in quote) { const deltaPrice = quote.delta; const DeltaContract = await simpleSDK.delta.getDeltaContract(); // or sign a Permit1 or Permit2 TransferFrom for DeltaContract await simpleSDK.delta.approveTokenForDelta(amount, Token1); const slippagePercent = 0.5; const destAmountAfterSlippage = BigInt( // get rid of exponential notation +(+deltaPrice.destAmount * (1 - slippagePercent / 100)).toFixed(0) // get rid of decimals ).toString(10); const deltaAuction = await simpleSDK.delta.submitDeltaOrder({ deltaPrice, owner: account, // beneficiary: anotherAccount, // if need to send the output destToken to another account // permit: "0x1234...", // if signed a Permit1 or Permit2 TransferFrom for DeltaContract srcToken: Token1, destToken: Token2, srcAmount: amount, destAmount: destAmountAfterSlippage, // minimum acceptable destAmount }); // poll if necessary const auction = await simpleSDK.delta.getDeltaOrderById(deltaAuction.id); if (auction?.status === 'EXECUTED') { console.log('Auction was executed'); } } else { console.log( `Delta Quote failed: ${quote.fallbackReason.errorType} - ${quote.fallbackReason.details}` ); const priceRoute = quote.market; const TokenTransferProxy = await simpleSDK.swap.getSpender(); // or sign a Permit1 or Permit2 TransferFrom for TokenTransferProxy const approveTxHash = simpleSDK.swap.approveToken(amount, Token1); const txParams = await simpleSDK.swap.buildTx({ srcToken: Token1, destToken: Token2, srcAmount: amount, slippage: 250, // 2.5% priceRoute, userAddress: account, // partner: '...' // if available }); const swapTx = await signer.sendTransaction(txParams); } ``` -------------------------------- ### Getting the Current Web3 Provider Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Contract.md Illustrates how to retrieve the currently configured provider instance from a Web3Context object. The example shows initializing a Web3Context with an HTTP provider URL and then logging the provider object. ```TypeScript const web3 = new Web3Context("http://localhost:8545"); console.log(web3.provider); > HttpProvider { clientUrl: 'http://localhost:8545', httpProviderOptions: undefined } ``` -------------------------------- ### Example: Prepending a One-Time Connection Listener (JavaScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/WritableBase.md Demonstrates how to use `prependOnceListener` on a server instance to add a listener for the 'connection' event that executes only once when the first connection is established. ```JavaScript server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); }); ``` -------------------------------- ### Basic Velora SDK Trade Flow (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/README.md Illustrates the basic trade process using `constructSimpleSDK`. It covers obtaining a quote via the `/quote` endpoint, handling both Delta and Market quote responses. For Delta, it shows approving tokens, submitting the order, and polling for execution. For Market, it shows approving tokens, building the swap transaction, and sending it via an ethers signer. ```typescript import axios from 'axios'; import { ethers } from 'ethersV5'; import { constructSimpleSDK } from '@velora-dex/sdk'; const ethersProvider = new ethers.providers.Web3Provider(window.ethereum); const accounts = await ethersProvider.listAccounts(); const account = accounts[0]!; const signer = ethersProvider.getSigner(account); const simpleSDK = constructSimpleSDK( { chainId: 1, axios }, { ethersProviderOrSigner: signer, EthersContract: ethers.Contract, account, } ); const amount = '1000000000000'; // wei const Token1 = '0x1234...' const Token2 = '0xabcde...' const quote = await simpleSDK.quote.getQuote({ srcToken: Token1, // Native token (ETH) is only supported in mode: 'market' destToken: Token2, amount, userAddress: account, srcDecimals: 18, destDecimals: 18, mode: 'all', // Delta quote if possible, with fallback to Market price side: 'SELL', // Delta mode only supports side: SELL currenly // partner: "..." // if available }); if ('delta' in quote) { const deltaPrice = quote.delta; const DeltaContract = await simpleSDK.delta.getDeltaContract(); // or sign a Permit1 or Permit2 TransferFrom for DeltaContract await simpleSDK.delta.approveTokenForDelta(amount, Token1); const slippagePercent = 0.5; const destAmountAfterSlippage = BigInt( // get rid of exponential notation +(+deltaPrice.destAmount * (1 - slippagePercent / 100)).toFixed(0) // get rid of decimals ).toString(10); const deltaAuction = await simpleSDK.delta.submitDeltaOrder({ deltaPrice, owner: account, // beneficiary: anotherAccount, // if need to send the output destToken to another account // permit: "0x1234...", // if signed a Permit1 or Permit2 TransferFrom for DeltaContract srcToken: Token1, destToken: Token2, srcAmount: amount, destAmount: destAmountAfterSlippage, // minimum acceptable destAmount }); // poll if necessary const auction = await simpleSDK.delta.getDeltaOrderById(deltaAuction.id); if (auction?.status === 'EXECUTED') { console.log('Auction was executed'); } } else { console.log( `Delta Quote failed: ${quote.fallbackReason.errorType} - ${quote.fallbackReason.details}` ); const priceRoute = quote.market; const TokenTransferProxy = await simpleSDK.swap.getSpender(); // or sign a Permit1 or Permit2 TransferFrom for TokenTransferProxy const approveTxHash = simpleSDK.swap.approveToken(amount, Token1); const txParams = await simpleSDK.swap.buildTx({ srcToken: Token1, destToken: Token2, srcAmount: amount, slippage: 250, // 2.5% priceRoute, userAddress: account, // partner: '...' // if available }); const swapTx = await signer.sendTransaction(txParams); } ``` -------------------------------- ### Get Storage At Address with Format (Web3.js Eth) - TypeScript Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/interfaces/Web3EthInterface.md Shows how to use the `web3.eth.getStorageAt` method with a specified return format (`FMT_NUMBER.HEX`, `FMT_BYTES.UINT8ARRAY`) to control the output type of the storage value. This example retrieves the value and formats it as a Uint8Array. ```TypeScript web3.eth.getStorageAt( "0x033456732123ffff2342342dd12342434324234234fd234fd23fd4f23d4234", 0, undefined, { number: FMT_NUMBER.HEX , bytes: FMT_BYTES.UINT8ARRAY } ).then(console.log); ``` -------------------------------- ### Using Web3 Wallet for Account Management and Transactions (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Wallet.md This snippet demonstrates how to initialize Web3, create an in-memory wallet with a specified number of accounts, sign arbitrary data using one of the wallet's accounts, and send an Ethereum transaction where the signing is handled internally by the wallet using the specified 'from' address. It requires the 'web3' package to be installed. ```TypeScript import { Web3 } from 'web3'; const web3 = new Web3('http://127.0.0.1:7545'); const wallet = await web3.eth.accounts.wallet.create(2); const signature = wallet.at(0).sign("Test Data"); // use wallet // fund account before sending following transaction ... const receipt = await web3.eth.sendTransaction({ // internally sign transaction using wallet from: wallet.at(0).address, to: "0xdAC17F958D2ee523a2206206994597C13D831ec7", value: 1 //.... }); ``` -------------------------------- ### Get Max Priority Fee Per Gas Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/interfaces/Web3EthInterface.md Illustrates how to fetch the current maximum priority fee per gas in wei using the `getMaxPriorityFeePerGas` method. Examples show the default BigInt output and a hexadecimal string output. ```JavaScript web3.eth.getMaxPriorityFeePerGas().then(console.log); > 20000000000n ``` ```JavaScript web3.eth.getMaxPriorityFeePerGas({ number: FMT_NUMBER.HEX , bytes: FMT_BYTES.HEX }).then(console.log); > "0x4a817c800" ``` -------------------------------- ### Querying Balance (Hex String) with Web3.js (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Web3Eth.md Shows how to get the balance of a specific address using `web3.eth.getBalance()`. This example demonstrates a potential alternative return format, which is a hexadecimal string representing the balance in wei. ```TypeScript web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(console.log); ``` -------------------------------- ### Deploying Contract (viem, TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/type-aliases/WalletActions.md Shows how to deploy a smart contract using `viem`'s `deployContract` action. Requires a wallet client configured with an account and transport, the contract's ABI, and bytecode. ```TypeScript import { createWalletClient, http } from 'viem' import { privateKeyToAccount } from 'viem/accounts' import { mainnet } from 'viem/chains' const client = createWalletClient({ account: privateKeyToAccount('0x…'), chain: mainnet, transport: http(), }) const hash = await client.deployContract({ abi: [], account: '0x…', bytecode: '0x608060405260405161083e38038061083e833981016040819052610...' }) ``` -------------------------------- ### Constructing Simple Velora SDK with Provider Options (Ethers, Viem, Web3) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/README.md Shows how to configure `providerOptions` for `constructSimpleSDK` to enable methods requiring blockchain interaction (like token approval). Examples are provided for integrating with ethers v5, ethers v6, viem, and web3.js, demonstrating the flexibility in choosing a web3 library. ```typescript // with ethers@5 const providerOptionsEtherV5 = { ethersProviderOrSigner: provider, // JsonRpcProvider EthersContract: ethers.Contract, account: senderAddress, }; // with ethers@6 const providerOptionsEtherV6 = { ethersV6ProviderOrSigner: provider, // JsonRpcProvider EthersV6Contract: ethers.Contract, account: senderAddress, }; // or with viem (from wagmi or standalone) const providerOptionsViem = { viemClient, // made with createWalletClient() account: senderAddress, }; // or with web3.js const providerOptionsWeb3 = { web3, // new Web3(...) instance account: senderAddress, }; const sdk = constructSimpleSDK({chainId: 1, axios}, providerOptionsEtherV5); // approve token through sdk const txHash = await sdk.approveToken(amountInWei, DAI); // await tx somehow await provider.waitForTransaction(txHash); ``` -------------------------------- ### Get Transaction with Format (Web3.js Eth) - TypeScript Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/interfaces/Web3EthInterface.md Demonstrates retrieving a transaction using `web3.eth.getTransaction` and specifying a return format (`FMT_NUMBER.NUMBER`, `FMT_BYTES.HEX`) to format the numerical and byte fields in the transaction object. This example uses `web3.utils.hexToBytes` for the hash input. ```TypeScript web3.eth.getTransaction( web3.utils.hexToBytes("0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f9466d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be400"), { number: FMT_NUMBER.NUMBER , bytes: FMT_BYTES.HEX } ).then(console.log); ``` -------------------------------- ### Get Registered Event Names - Node.js EventEmitter - JavaScript Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/ReadableBase.md Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or `Symbol`s. This example demonstrates how to use `eventNames()` on a Node.js EventEmitter instance. ```JavaScript import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {}); const sym = Symbol('symbol'); myEE.on(sym, () => {}); console.log(myEE.eventNames()); // Prints: [ 'foo', 'bar', Symbol(symbol) ] ``` -------------------------------- ### Deploying Smart Contract using Web3.js Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Contract.md Demonstrates various ways to deploy a smart contract using the `deploy` method, including sending the transaction, handling events, encoding/decoding constructor data, and estimating gas. ```JavaScript myContract.deploy({ input: '0x12345...', // data keyword can be used, too. arguments: [123, 'My String'] }) .send({ from: '0x1234567890123456789012345678901234567891', gas: 1500000, gasPrice: '30000000000000' }, function(error, transactionHash){ ... }) .on('error', function(error){ ... }) .on('transactionHash', function(transactionHash){ ... }) .on('receipt', function(receipt){ console.log(receipt.contractAddress) // contains the new contract address }) .on('confirmation', function(confirmationNumber, receipt){ ... }) .then(function(newContractInstance){ console.log(newContractInstance.options.address) // instance with the new contract address }); // When the data is already set as an option to the contract itself myContract.options.data = '0x12345...'; myContract.deploy({ arguments: [123, 'My String'] }) .send({ from: '0x1234567890123456789012345678901234567891', gas: 1500000, gasPrice: '30000000000000' }) .then(function(newContractInstance){ console.log(newContractInstance.options.address) // instance with the new contract address }); // Simply encoding myContract.deploy({ input: '0x12345...', arguments: [123, 'My String'] }) .encodeABI(); > '0x12345...0000012345678765432' // decoding myContract.deploy({ input: '0x12345...', // arguments: [123, 'My Greeting'] if you just need to decode the data, you can skip the arguments }) .decodeData('0x12345...0000012345678765432'); > { __method__: 'constructor', __length__: 2, '0': '123', _id: '123', '1': 'My Greeting', _greeting: 'My Greeting', } // Gas estimation myContract.deploy({ input: '0x12345...', arguments: [123, 'My String'] }) .estimateGas(function(err, gas){ console.log(gas); }); ``` -------------------------------- ### Constructing Full Velora SDK with Composable Components Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/README.md Illustrates the construction of the full Velora SDK by composing individual fetcher and contract caller components. This approach allows for greater control and tree-shaking, enabling users to include only the necessary parts of the SDK. Examples show how to create fetchers and contract callers using axios and ethers. ```typescript import { constructFullSDK, constructAxiosFetcher, constructEthersContractCaller } from '@velora-dex/sdk'; const signer = ethers.Wallet.fromMnmemonic('__your_mnemonic__'); // or any other signer/provider const account = '__signer_address__'; const contractCaller = constructEthersContractCaller({ ethersProviderOrSigner: signer, EthersContract: ethers.Contract, }, account); // alternatively constructViemContractCaller or constructWeb3ContractCaller const fetcher = constructAxiosFetcher(axios); // alternatively constructFetchFetcher const sdk = constructFullSDK({ chainId: 1, fetcher, contractCaller, }); ``` -------------------------------- ### Getting Fee History with viem (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/type-aliases/PublicActions.md Illustrates fetching historical gas fee data using viem's `getFeeHistory` action. The example shows how to specify the number of blocks and percentile ranges for reward data. ```ts import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' const client = createPublicClient({ chain: mainnet, transport: http(), }) const feeHistory = await client.getFeeHistory({ blockCount: 4, rewardPercentiles: [25, 75], }) ``` -------------------------------- ### Getting EventEmitter event names (JavaScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/interfaces/EventEmitter.md This example shows how to create an EventEmitter instance, register listeners for different event names (including a Symbol), and then use the `myEE.eventNames()` method to retrieve an array of all unique event names with registered listeners. ```JavaScript import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {}); const sym = Symbol('symbol'); myEE.on(sym, () => {}); console.log(myEE.eventNames()); // Prints: [ 'foo', 'bar', Symbol(symbol) ] ``` -------------------------------- ### Getting Raw EventEmitter Listeners (JavaScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/internal.md Returns a copy of the array of listeners for the specified event name. This includes any wrappers, such as those created by `.once()`. The example demonstrates how to access the original listener function via the `listener` property of the wrapper. ```JavaScript import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once')); // Returns a new Array with a function `onceWrapper` which has a property // `listener` which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0]; // Logs "log once" to the console and does not unbind the `once` event logFnWrapper.listener(); // Logs "log once" to the console and removes the listener logFnWrapper(); emitter.on('log', () => console.log('log persistently')); // Will return a new Array with a single function bound by `.on()` above const newListeners = emitter.rawListeners('log'); // Logs "log persistently" twice newListeners[0](); emitter.emit('log'); ``` -------------------------------- ### Creating and Encrypting Web3 Wallet Source: https://github.com/veloradex/paraswap-sdk/blob/master/docs/md/-internal-/classes/Wallet.md This snippet demonstrates how to create a new wallet account using `web3.eth.accounts.wallet.create` and then encrypt the wallet using `web3.eth.accounts.wallet.encrypt` with a password. The result, an array of encrypted keystore JSON objects, is logged to the console. ```TypeScript web3.eth.accounts.wallet.create(1) web3.eth.accounts.wallet.encrypt("abc").then(console.log); ``` -------------------------------- ### Building and Sending Swap Transaction (TypeScript) Source: https://github.com/veloradex/paraswap-sdk/blob/master/README.md Builds the transaction parameters required for a swap using the `buildTx` method of the SDK's swap module. Requires source/destination tokens, amount, slippage, price route, and user address. Optionally includes partner or receiver. Then, sends the resulting transaction parameters using the connected signer's `sendTransaction` method. Returns the transaction hash. ```TypeScript const txParams = await simpleSDK.swap.buildTx({ srcToken: Token1, destToken: Token2, srcAmount: amount, slippage: 250, // 2.5% // can pass `destAmount` (adjusted for slippage) instead of `slippage` priceRoute, userAddress: account, // partner: '...' // if available // receiver: '0x123ae...' // if need to send the output destToken to another account }); const swapTxHash = await signer.sendTransaction(txParams); ```