# 0xWeb

### 1. CLI Toolkit for EVM compatibale blockchains&#x20;

By using [dequanto](https://github.com/0xweb-org/dequanto) library we export the most common WEB3 commands to be accessible straight from your command line interface. &#x20;

### 2. Interacting with EVM Smart Contracts in Node.js done in seconds.&#x20;

Generate <img src="/files/thDW8DPvv58vx0geBAtR" alt="" data-size="line">TypeScript classes for validated smart contracts and import them as regular modules. **Read** methods, **Write** methods, **Event** listeners, and **Log** parsers — everything is already included. Access **private storage** variables with auto-generated getter functions.

`0xWeb` is built on top of [dequanto](https://github.com/0xweb-org/dequanto) library — the blockchain communication layer, which is integrated under the hood.&#x20;

We believe in the openness and transparency of the web.  And we want to provide anybody with a **quick** and **easy** way to integrate blockchain solutions.

An example of what you will get

> Lets get an ETH price from the [onchain oracle](https://data.chain.link/ethereum/mainnet/crypto-usd/eth-usd) by chainlink.

* <img src="/files/MXzTXAzHZisC2yksMg7O" alt="" data-size="line"> Install the contract

```bash
0xweb install 0x5f4ec3df9cbd43714fe2740f5e3616155c5b8419 --name chainlink/oracle-eth --chain eth
```

* <img src="/files/WfkVlc3xfbofnTCEIeBd" alt="" data-size="line"> Get the price

```typescript
const oracle = new ChainlinkOracleEth();
const price: bigint = await oracle.latestAnswer();
```


# Installation

The `CLI` tool is installed as global npm package

```
npm i 0xweb -g
0xweb --help
```

Right away you can start using available commands.  Like getting the <img src="/files/UOOF4tTUVcNafjiZvmb8" alt="" data-size="line"> Gas Price for a chain.

```
> 0xweb gas -c polygon

Chain polygon
Price 60 gwei
```

⚠️ We ship our public **API keys** and **Node Endpoints** for Ethereum, Polygon, Gnosis Chain, etc. So we would like you to ask to create your keys and **replace** them in the configuration.

### Configuration

```
0xweb config --edit
```

This creates the configuration file (`%APPDATA%/.dequanto/config.yml`) with the default values, and you are free to add/replace the values. After you saved the file, you can check the configuration with

```
0xweb config --view
```

### Additional Common Flags

<table><thead><tr><th></th><th></th><th data-hidden></th></tr></thead><tbody><tr><td><code>--color none</code></td><td>Doesn't print colored output</td><td></td></tr><tr><td><code>--silent</code></td><td>Doesn't print information logs</td><td></td></tr><tr><td><code>--endpoint http://some:port</code></td><td>Overrides the RPC Url loaded from config</td><td></td></tr></tbody></table>


# Blockchains

[#predefined-blockchain-configurations](#predefined-blockchain-configurations "mention")

[#modify-the-configuration](#modify-the-configuration "mention")

[#add-custom-evm-compatible-chain](#add-custom-evm-compatible-chain "mention")

[#node-rate-limit-guard](#node-rate-limit-guard "mention")

## Predefined blockchain configurations

`0xWeb` includes some blockchain configurations and default public RPC endpoints for:

| Chain slug        | Name                              |
| ----------------- | --------------------------------- |
| `aurora`          | Aurora                            |
| `arbitrum`        | Arbitrum One                      |
| `avalanche`       | Avalanche                         |
| `bsc`             | Binance Smart Chain               |
| `celo`            | Celo Platform                     |
| `cronos`          | Cronos                            |
| `eth`             | Ethereum                          |
| `eth:goerli`      | Ethereum Testnet                  |
| `fantom`          | Fantom                            |
| `gnosis` ; `xdai` | Gnosis Chain                      |
| `hardhat`         | Local Hardhat Development Network |
| `heco`            | HECO Chain                        |
| `polygon`         | Polygon Network                   |
| `metis`           | Metis                             |
| `optimism`        | Optimism                          |

## Modify the configuration

[🙏](https://emojipedia.org/folded-hands/) Change the RPC endpoints for those chains in configuration. &#x20;

Edit the configuration `yml` by running:

```bash
0xweb config -e
```

A default configuration will be copied into the new configuration file, which should be opened with your default editor for `yml` files, if the file is not opened automatically, open the file manually, the file path will be printed in the terminal.

## Add custom EVM-compatible chain

* **1** Add a new platform to the `web3` section, for example:

```yaml
web3:
  foo:
    chainId: 5555
    chainToken: FOO
    endpoints:
      - url: 'https://foo-rpc-example'
      - url: 'wss://foo-socket-url-example'
      - url: 'https://some-other-url'
```

* **2** Add the Blockchain Explorer configuration optionally to read the ABI and the sources.

`0xWeb` supports `Etherscan` and `Blockscout` forks, if there is one for your custom chain, add that information to the `blockchainExplorer` section

```yaml
blockchainExplorer:
  foo:
    key: YOUR_KEY
    host: 'https://api.bscscan.com'
    www: 'https://bscscan.com'
```

### AD

## Node Rate Limit Guard

The Endpoints accept the rate limit configuration so that the clients' pool hander can handle better select and manage the Web3 Clients and Requests.  For example: \`100/1s\`  - means 100 requests per 1 second. You can also set multiple guards. Example:

### AD

```yaml
web3:
  eth:
    endpoints:
      - url: 'https://myendpoint-url'
        rateLimit: 100/1s;5000/1m
      # - ... other urls
```

### AD

### ## AD

### AD


# Folder structure

> See the [Demo](https://github.com/0xweb-org/0xweb-sample)🔗 project

For the installed contract you'll get:

* Generated TypeScript classes
* ABI json source file
* Solidity source file(s)

The files are saved under `0xweb` folder in the project's root directory, additionally the `0xweb.json` will include all installed contracts (similar to `package.json`)

```
my-project/
├── 0xweb/
│   └── eth/
│       └── %package-name%/
│           ├── %class-name%.ts
│           ├── %class-name%.json
│           └── %class-name%/
│               └── %sources%.sol
└── 0xweb.json
```


# Dequanto dependency

The generated classes will include `Dequanto` dependencies for the Blockchain communication. See the `Dequanto` section to read more about the library.

#### Automatically

To automatically install required dependencies run the initialization command inside your project root

```
0xweb init
```

#### Manually

You can perform the same steps manually

* Clone the [dequanto](https://github.com/0xweb-org/dequanto) [🔗](https://emojipedia.org/link/) repository

  `git submodule add` [`https://github.com/0xweb-org/dequanto`](https://github.com/0xweb-org/dequanto)&#x20;
* Add `@dequanto` alias to your `tsconfig.json` file

```json
{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@dequanto/*": "dequanto/src/*"
    }
  }
}
```


# Installing contracts

The TypeScript class are generated from ABI, which will be resolved from various sources.

### Blockchain Explorer

By providing the contract address and the chain (default is `Ethereum`). **Proxy contracts** will be automatically followed to the implementation contract, to resolve the implementation ABI&#x20;

> ❗To prevent blockchain API request throttling, provide your keys in config file:
>
> &#x20;`0xweb config --edit`

```bash
0xweb i 0x5f4ec3df9cbd43714fe2740f5e3616155c5b8419 --name chainlink/oracle-eth
```

### ABI json

Specify a local ABI JSON file, for example that one generated by solidity compiler

```bash
0xweb i ./artifacts/contracts/FooBar.sol/FooBar.json --name foobar
```


# Versioning

#### Contract versions

Blockchain is immutable, therefore the versioning is not supported. There is always only **one version** on the blockchain.&#x20;

#### Upgradable Proxies

Even by upgrading the implementation for a contract. The previous implementation gets obsolete, so you have to reinstall the contract to regenerate the code.

#### Git versioning of the `0xweb/` folder

Unlike `node_modules` we suggest adding `0xweb` folder with the generated classes to the project's repository. You can track later the changes made to the dAPPs (*in case of proxies*).&#x20;

But you can also add `0xweb` to `.gitignore`, as you can reinstall all contracts listed in `0xweb.json` file any time later.


# Keys notice

We use **encrypted storage** to store private keys. The root storage password is a cryptographically strong key derived from the **machine key** plus a **`pin`**, which must be provided every time the accounts store should be accessed. The **`pin`** can be provided via CLI or Environment variable.&#x20;

* [🖥️](https://emojipedia.org/desktop-computer/) **Machine Key** — the storage file can't be decrypted on other machines (*unless your machine is compromised and a hacker has full access to it, and even then, he must listen to your actions - see the next requirement, the **`pin`**)*
* [🔑](https://emojipedia.org/key/) **PIN** — must be provided every time you want to decrypt the storage. This key won't be stored anywhere

This combination of keys makes the storage file safe from various attack vectors.&#x20;

The **pin** is set on the first storage write — *when you add or create an account*. So you must:

* remember the **PIN** - it won't be possible to decrypt the storage without it.
* do not reset the operating system — the **machine key** will be lost and the storage won't be accessible.

> If you forgot the `pin` or the machine key was changed — you can **reset the storage**, and this means - it will be completely cleared.

To summarize: **ALWAYS** back up your keys.


# Accounts

You can add or create an account with the assigned name to it, and save the account to local ecrypted storage.  This will make it easier and safer to list and access the keys.&#x20;

> **`WRITE`** methods of a contract, do not depened on accounts storage, you can also load and provide account data (the `key`) on your own.&#x20;

### Manage accounts via CLI

See the help for `accounts` command to get full and up-to-date information

```
0xweb accounts --help
```

* **`add`** — adds an account

```bash
0xweb accounts add --key PRIVATE_KEY --name FOOBAR --pin YOUR_PASSWORD
```

* **`remove`** — removed the account

```bash
0xweb accounts remove --name FOOBAR --pin YOUR_PASSWORD
```

* **`list`** — show account names saved in storage

```bash
0xweb accounts list --pin YOUR_PASSWORD
```

* **`new`** — generates a new account. Remember to back-up the KEY [❗](https://emojipedia.org/exclamation-mark/)

```bash
0xweb accounts new --name FOOBAR --pin YOUR_PASSWORD
```

### Use the account in CLI

Provide the `name` and `pin` to retrieve the account from storage. For example, if you want to transfer a token:

```
0xweb token transfer USDC --from FOOBAR --to 0x.... --amount 10 --pin YOUR_PASSWORD
```

### Use the account in code

```typescript
import { USDC } from '@0xweb/eth/USDC/USDC'

async function example () {
    // read the configuration, safe to call multiple times, but can be called once at application start
    await Config.fetch();
    
    let usdcContract = new USDC();
    let decimals = await usdcContract.decimals();
    // 10$ to wei
    let wei = 10n * 10n**BigInt(decimals);
    let tx = await usdcContract.transfer('FOOBAR', '0x....', wei);
    let receipt = await tx.wait();
}
example();
```


# Commands Overview

Here is the list of available commands. To get the detailed description and arguments of a command or a sub-command run&#x20;

#### `0xweb COMMAND --help, 0xweb COMMAND SUBCOMMAND --help`

e.g. `0xweb install --help`

### `i, install`

Download contracts ABI and generates the TS class for it.

### `init`

Clone dequanto sources and configure aliases in tsconfig.

### `c, contract`

Contract actions

* **`abi`** - List of the available READ and WRITE methods for the contract
* **`read`** - READ contract. Parameters are resolved by CLI flags or will be prompted.
* **`write`** - Send a Transaction. Parameters are resolved by cli flags or will be prompted.
* **`logs`** - Load contract events
* **`dump`** - Dump the storage of the contract
* **`slot`** - Read the contract's single slot value
* **`var`** - Read the contract's variable value
* **`vars`** - Get the list of state variables and their values

### `accounts`

Manage accounts.

* **`add`** - Add existing account
* **`remove`** - Remove account
* **`list`** - List account names
* **`new`** - Create new account

### `account`

Account tools.

* **`balance`** - Get account balance for ETH or any ERC20 token

### `safe`

Multi-sig account tools.

* **`add`** - Add existing safe
* **`list`** - List safe account names
* **`new`** - Deploy new safe

### `token`

ERC20 Token tools.

* **`price`** - Get a token price

### `tokens`

Manage known tokens.

* **`add`** - Add a new token to the known list.
* **`find`** - Get a token by Symbol or Address, and print the info
* **`for`** - Get ERC20 tokens and the balances for a specific EOA

### `transfer`

Transfer ETH or ERC20

### `tx`

Transaction utils.

* **`view`** - Load transaction by hash
* **`sign`** - Sign the transaction in a JSON file
* **`send`** - Send the transaction from a JSON

### `block`

Block utils

* **`get`** - Get block info

### `gas`

Print the current GAS price for a chain

### `config`

View and edit dequanto web3 configuration

### `reset`

Reset various things.

* **`accounts`** - Remove all accounts
* **`config`** - Reset all config modifications

### `help`

Prints help overview.


# Zero Trust Wallet

2FA or N-Factor-Authorization for the wallet

Any transaction can be emitted by providing the MultiSig Address and a member (executor) account.  In this case, all the assets can be stored in the multi-signature wallet.&#x20;

This is the most secure way to protect assets, even in compromised environments, as the attacker won't have access to other accounts from the multi-sig.

To make it even more secure, you can rotate the executor account periodically.

✨ Easy-to-use — You have to do nothing special to emit multi-sig transactions, provide the `Safe Interface` for the `Sender`

```typescript
interface ISafeAccount {
   safeAddress: TAddress
   operator: ChainAccount
}
```

If `SafeAccount` is detected, we automatically wrap the execution into Safes Transaction Proposal, and wait until the required amount of confirmations has been received, afterwards the tx is submitted to the mempool.

#### Supported MultiSig Wallets

![](/files/dmGWmTSdFqf92a2rrL5I)

For the first integration, we have chosen the Gnosis Safe, as it is really a great multi-signature platform. It has mobile and web applications, to easily review and confirm transactions.


# Info

Dequanto library **simplifies blockchain development**. It is built on top of [ethersproject ](https://github.com/ethers-io)and [web3.js](https://github.com/ChainSafe/web3.js), but includes additional features, like [Nodes Pool](/dequanto/rpc-client-pool), [Tx Builder](/dequanto/tx-builder), [Tx Writer](/dequanto/tx-writer), [Indexer](/dequanto/indexer), and others.

### 0xWeb and Dequanto

To understand the relationship - `0xWeb` uses `dequanto` as its dependency, and not vice-versa. Dequanto is a **standalone** library you can use in any blockchain-related project.

## Install

**`📃 Distributed as Source Code`**

Though we have published the npm package - [dequanto](https://www.npmjs.com/package/dequanto). But we advise using dequanto as a **git submodule.**&#x20;

```bash
git submodule add https://github.com/0xweb-org/dequanto
```

You should use raw TypeScript source code files.  You can browse, view, and modify any classes on your need.

#### Configuring Imports

[‼️](https://emojipedia.org/double-exclamation-mark/) Add `@dequanto` alias to your `tsconfig.json`&#x20;

```json
{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@dequanto/*": ["dequanto/src/*"]
    }
  }
}

```

> If you have installed via npm, the path would be `"node_modules/dequanto/src/*`

## Configure

There is a bunch of things in configuration to be loaded at application start - like Node URLs, API Keys. The most simple is to use `0xweb` to create a default config file, which you can edit

```bash
0xweb config -e
```

Load that configuration on startup

```typescript
import { Config } from '@dequanto/Config'

await Config.fetch();
```

> It is safe to call the method multiple time, but enough only once.&#x20;


# RPC Client Pool

Provide multiple RPC Node URLs per chain, this will make your application much more reliable. Even if one of the Nodes goes down or for some reason is not in sync, all your RPC calls will still work.

[Web3Client](https://github.com/0xweb-org/dequanto/blob/master/src/clients/Web3Client.ts)🔗 is the base class for all the EVM Platforms. This wraps web3 to provide pool-based communication with the nodes. It handles also `gas` and `nonce` values.

We provide pre-configured clients for&#x20;

* Ethereum - [EthWeb3Client](https://github.com/0xweb-org/dequanto/blob/master/src/clients/EthWeb3Client.ts)🔗
* Polygon - [PolyWeb3Client](https://github.com/0xweb-org/dequanto/blob/master/src/clients/PolyWeb3Client.ts)🔗
* Binance Smart Chain - [BscWeb3Client](https://github.com/0xweb-org/dequanto/blob/master/src/clients/BscWeb3Client.ts)🔗
* Hardhat - [HardhatWeb3Client](https://github.com/0xweb-org/dequanto/blob/master/src/clients/HardhatWeb3Client.ts)🔗
* Gnosis - [XDaiWeb3Client](https://github.com/0xweb-org/dequanto/blob/master/src/chains/xdai/XDaiWeb3Client.ts)🔗
* Arbitrum - [ArbWeb3Client](https://github.com/0xweb-org/dequanto/blob/master/src/chains/arbitrum/ArbWeb3Client.ts)🔗

The endpoint configuration can be defined in the constructor, or it will be read from the application [configuration](/dequanto/info#configure)🔗.&#x20;

#### An example, how to get the balance for an address

```typescript
import { PolyWeb3Client } from '@dequanto/clients/PolyWeb3Client';

let client = new PolyWeb3Client();
let balance: bigint = client.getBalance('0x....');
```


# Tx Builder

> You won't need to use this class directly. In `0xWeb` generated classes `TxDataBuilder` and `TxWriter` are used under the hood to send transactions.

Prepares the [Tx Data](https://github.com/0xweb-org/dequanto/blob/master/src/txs/TxDataBuilder.ts)🔗 to be submitted to the chain.&#x20;

```typescript
import { TxDataBuilder } from '@dequanto/txs/TxDataBulder'

let builder = new TxDataBuilder(client, account?)
let txData = builder
    // demo with types
    .setInputDataWithTypes(types: any[], paramaters: any[])
    .setInputDataWithABI(fnAbi: string | AbiItem, ...params)
    .setValue(wei: bigint)
    .setNonce(nonceConfig?: TNonceConfig)
    .setGas(gasConfig?: TGasConfig)
    .signToString(privateKey: string);

    
type TNonceConfig {
    // sets the nonce of the first tx in pending state
    overriding?: boolean
    // set the nonce of the N-th tx in pending state
    noncePending?: number
    // custom nonce value
    nonce?: number
}
type TGasConfig {
    price?: bigint
    priceRatio?: number
    gasLimitRatio?: number
    gasLimit?: string | number
    gasEstimation?: boolean
    from?: TAddress
    type?: 1 | 2
}
```


# Tx Writer

> You won't need to use this class directly. In `0xWeb` generated classes `TxDataBuilder` and `TxWriter` are used under the hood to send transactions.

#### [TxWriter](https://github.com/0xweb-org/dequanto/blob/master/src/txs/TxWriter.ts)🔗

#### Retryable `sendTransaction`  for:

* `Time-out` — if not mined within a time, will resubmit the tx with increased gas.
* `NonceTooLow` — resets the nonce automatically
* `InsufficientFunds` — a funder account can be set. If the sender doesn't have the required amount to cover the `gaslimit`, the account will be funded before sending the transaction

#### Logger

Adds [TxLogger](https://github.com/0xweb-org/dequanto/blob/master/src/txs/TxLogger.ts)🔗 to write transaction states to a log file using [everlog](https://github.com/atmajs/everlog)🔗

#### Transaction Events Parser

Automatically parses known Events, like `Transfer`. If ABI is used to build the transaction, then it will parse also all events which were defined in the ABI


# Blockchain Explorers

With [BlockChainExplorerFactory](https://github.com/0xweb-org/dequanto/blob/master/src/BlockchainExplorer/BlockChainExplorerFactory.ts)🔗 different Blockchain Explorer Clients are created:

* [Etherscan](https://github.com/0xweb-org/dequanto/blob/master/src/BlockchainExplorer/Etherscan.ts)🔗
* [Polyscan](https://github.com/0xweb-org/dequanto/blob/master/src/BlockchainExplorer/Polyscan.ts)🔗
* [Bscscan](https://github.com/0xweb-org/dequanto/blob/master/src/BlockchainExplorer/Bscscan.ts)🔗
* [XDaiscan](https://github.com/0xweb-org/dequanto/blob/master/src/chains/xdai/XDaiscan.ts)🔗 (Gnosis Chain)
* [Arbiscan](https://github.com/0xweb-org/dequanto/blob/master/src/chains/arbitrum/Arbiscan.ts)🔗
* *...more to come*

The clients allow to (see the interface [IBlockChainExplorer](https://github.com/0xweb-org/dequanto/blob/master/src/BlockchainExplorer/IBlockChainExplorer.ts)🔗)

* receive ABIs and sources for the validated contracts. *`0xweb` uses extensively this feature.*
* load transactions, internal transactions, and erc20 transactions for an address

Basically, the public [APIs](https://docs.etherscan.io/)🔗 are or will be implemented.&#x20;

> With `0xweb config -e` save your API keys to configuration. The API keys are free, though the requests will be throttled, but the client can handle the throttling by queuing the requests


# Token Services

### Token Data

Dequanto includes JSONs with `>5000` popular tokens - names, addresses, chains, decimals.&#x20;

```typescript
import { TokensService } from '@dequanto/tokens/TokensService';

let service = new TokensService('eth');
let usdc = await service.getKnownToken('USDC');

console.log(usdc);

/* output
{
  symbol: 'USDC',
  name: 'USD Coin',
  platform: 'eth',
  address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
  decimals: 6
}
*/

        
```

### ERC20 Contracts

Ready to use strongly-typed erc20 contract class.

```typescript
import { TokensService } from '@dequanto/tokens/TokensService';

let service = new TokensService('eth');
let usdc = await service.erc20('USDC');

let balance: bigint = await usdc.balanceOf('0x....')
```

### Token Price&#x20;

> An article regarding token prices - [get-token-price-at-a-specific-block-onchain](https://dev.kit.eco/ethereum-get-token-price-at-a-specific-block-onchain)🔗

### Token Swap

See [TokenSwapService](https://github.com/0xweb-org/dequanto/blob/master/src/tokens/TokenSwapService.ts)🔗 for details.

> [Paraswap ](https://www.paraswap.io/)is implemented as the default exchange

```typescript
import { TokenSwapService } from '@dequanto/tokens/TokenSwapService'
import { EthWeb3Client } from '@dequanto/clients/EthWeb3Client';

let client = new EthWeb3Client();
let exchange = new TokenSwapService(client);

let account = { key: '' }
let tx = await exchange.swap(account, {
    from: 'USDC',
    to: 'WETH',
    amount: 1000
});
let receipt = await tx.wait();
```

### Token Transfer

Transfer tokens by a **specific amount**, **all** or with the **remainder**.

See [TokenTransferService](https://github.com/0xweb-org/dequanto/blob/master/src/tokens/TokenTransferService.ts)🔗 for details.

```typescript
import { TokenTransferService} from '@dequanto/tokens/TokenTransferService'
import { EthWeb3Client } from '@dequanto/clients/EthWeb3Client';

let client = new EthWeb3Client();
let service = new TokenTransferService(client);

let account = { key: '' }
let tx = await service.transferAll(account, '0x...', 'USDC');
let receipt = await tx.wait();
```


# Indexer

See [BlocksTxIndexer](https://github.com/0xweb-org/dequanto/blob/master/src/indexer/BlocksTxIndexer.ts)🔗 for details.

With the indexer, you can go through a range of blocks and handle the transactions.

A range can be specified by block numbers or dates. The Indexer can also listen for incoming block headers and transactions.

```typescript
import { BlocksTxIndexer } from '@dequanto/indexer/BlocksTxIndexer'

let indexer = new BlocksTxIndexer(platform, {
    name: 'foo worker',
    // loads also transactions from the mined blocks
    loadTransactions: true,
    // saves blockNumbers of already processed blocks
    persistance: true,
});

indexer.onBlock(async (
    client: Web3Client, 
    block: BlockTransactionString, 
    txs: Transaction[]
) => {
    // process txs
});

// starts indexing from the block at specified date
// as no end date is provided, after indexer is ready, it will listen for incomming blocks
indexer.start(new Date('2022-04-22T00:00:00Z'));

// gets current status 
let status = indexer.stats();

```


# Utilities

There is a bunch of utility functions you can use:

&#x20;<https://github.com/0xweb-org/dequanto/tree/master/src/utils>&#x20;

* [$bigint](https://github.com/0xweb-org/dequanto/blob/master/src/utils/%24bigint.ts)  - `bigint` helper to convert `wei`, `gwei`, `ether` ;  float multiplying and division
* [$date](https://github.com/0xweb-org/dequanto/blob/master/src/utils/%24date.ts) - lots of date methods - replaces `moment.js` and `date.js` libraries
* [$require](https://github.com/0xweb-org/dequanto/blob/master/src/utils/%24require.ts) - assertion utilities. *You should use assertions in the blockchain development much more often, as any small error can lead to huge losses*
* *...*

Please, go through the code, maybe you'll find something for your needs.


# Info

`0xWeb` can be used also by blockchain developers. We provide the <img src="/files/fWH1IsqUNoti6zGFlQ8X" alt="" data-size="line"> [Hardhat plugin](https://github.com/0xweb-org/hardhat), which generates the classes after the solidity contracts are compiled.


# Installation

#### Automatically

The command ensures all manual steps

```bash
$ 0xweb init --hardhat
```

#### Manually

* Install [dequanto 📦](/package-manager/dequanto-dependency) library
* Install [hardhat](https://www.npmjs.com/package/hardhat)

  ```
  npm i hardhat
  ```
* Install [@0xweb/hardhat](https://www.npmjs.com/package/@0xweb/hardhat) plugin

  ```
  npm i @0xweb/hardhat
  ```
* `hardhat.config.js` should look like this:

  ```
  require("@0xweb/hardhat");

  module.exports = {
      solidity: {
          version: "0.8.2",
          settings: {
              optimizer: {
                  enabled: true,
                  runs: 200
              }
          }
      },
      networks: {
          hardhat: {
              chainId: 1337
          },
          localhost: {
              chainId: 1337
          },
          mainnet: {
              url: ``,
              accounts: [``]
          }
      },
      etherscan: {
          // One at https://etherscan.io/
          apiKey: ""
      }
  };


  ```


# Compile

You would use the Hardhat as usual. Client classes will be generated for the compiled contracts automatically

```
npx hardhat compile
```

#### Additional CLI parameters

### `--sources`&#x20;

Override the default sources folder (`/contracts`)

```
npx hardhat compile --sources /other/folder/in/projects/root
```

***

### `--artifacts`&#x20;

Override the default output folder

```
npx hardhat compile --artifacts /foo/bar
```

***

### `--watch true`&#x20;

Compile the contracts, watch `*.sol` files for changes and automatically recompile

```
npx hardhat compile --watch true
```

***

### `--package`

Enables the mono-repo structure for the project. The contracts can now be organized into separate package folders within the repository

```

project/
├─ packages/
│  ├─ Foo/
│  │  ├─ contracts/
│  │  │  ├─ Foo.sol
│  ├─ Bar/
│  │  ├─ contracts/
│  │  │  ├─ Bar.sol
```

Every package can be implemented separately, but still **reference the contracts and interfaces** of each other. To compile the package:

```
npx hardhat compile --package packages/Bar
```


# Deploy

The Dequanto library provides services for deploying newly generated TypeScript classes derived from Solidity contracts. It tracks all deployments and bytecode changes and manages proxy deployments.


# Openzeppelin contracts

We include the pre-built [OpenZeppelin](https://www.openzeppelin.com/contracts) contracts, so you can access deployed contracts based on those interfaces with ease.

List of contracts:&#x20;

<https://github.com/0xweb-org/dequanto/tree/master/contracts/openzeppelin>

### e.g. ERC20 contract

```typescript
import { ERC20 } from '@dequanto-contracts/openzeppelin/ERC20';
import { Web3ClientFactory } from '@dequanto/clients/Web3ClientFactory';

let client = Web3ClientFactory.get('eth');
let token = new ERC20('0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', client);
let balance: bigint = await token.balanceOf('0x....');
```


