# Guides

#### On this page

* [<mark style="color:blue;">Wallet Integration</mark>](#wallet-integration)
  * [<mark style="color:blue;">Implementation Checklist</mark>](#implementation-checklist)
  * [<mark style="color:blue;">Frontend</mark>](#frontend)
  * [<mark style="color:blue;">Transactions</mark>](#transactions)
  * [<mark style="color:blue;">Connections</mark>](#connections)
* [<mark style="color:blue;">DApp Store Contract Registration</mark>](#dapp-store-contract-registration)
  * [<mark style="color:blue;">Requirements</mark>](#requirements)
  * [<mark style="color:blue;">Register Contract</mark>](#register-contract)
  * [<mark style="color:blue;">Deployed Factory Pattern</mark>](#deployed-factory-pattern)
  * [<mark style="color:blue;">Update Contract</mark>](#update-contract)
  * [<mark style="color:blue;">Cancel Contract</mark>](#cancel-contract)
* [<mark style="color:blue;">ERC-20 Registration</mark>](#erc-20-registration)
  * [<mark style="color:blue;">Drafting the ERC-20 Proposal</mark>](#drafting-the-erc-20-proposal)
  * [<mark style="color:blue;">Submitting the ERC-20 Proposal</mark>](#submitting-the-erc-20-proposal)
  * [<mark style="color:blue;">Formatting the Proposal’s Text</mark>](#formatting-the-proposals-text)
  * [<mark style="color:blue;">Submit the Proposal to Testnet</mark>](#submit-the-proposal-to-testnet)
  * [<mark style="color:blue;">The On-Chain ERC-20 Proposal</mark>](#the-on-chain-erc-20-proposal)
  * [<mark style="color:blue;">The Deposit Period</mark>](#the-deposit-period)
  * [<mark style="color:blue;">The Voting Period</mark>](#the-voting-period)
* [<mark style="color:blue;">Query Balances</mark>](#query-balances)
  * [<mark style="color:blue;">`ICPlazad`</mark> <mark style="color:blue;"></mark><mark style="color:blue;">& Tendermint RPC</mark>](#icplazad--tendermint-rpc)
  * [<mark style="color:blue;">JSON-RPC</mark>](#json-rpc)
  * [<mark style="color:blue;">gRPC</mark>](#grpc)
* [<mark style="color:blue;">Trace Transactions</mark>](#trace-transactions)
  * [<mark style="color:blue;">Basic EVM Tracing with JS</mark>](#basic-evm-tracing-with-js)
  * [<mark style="color:blue;">Tracing Prerequisites</mark>](#tracing-prerequisites)
  * [<mark style="color:blue;">Basic Traces</mark>](#basic-traces)
  * [<mark style="color:blue;">Limits of Basic Traces</mark>](#limits-of-basic-traces)
  * [<mark style="color:blue;">Filtered EVM Tracing with JS</mark>](#filtered-evm-tracing-with-js)
  * [<mark style="color:blue;">Running a Simple Trace</mark>](#running-a-simple-trace)
  * [<mark style="color:blue;">How Does it Work?</mark>](#how-does-it-work)
  * [<mark style="color:blue;">Actual Filtering</mark>](#actual-filtering)
  * [<mark style="color:blue;">Stack Information</mark>](#stack-information)
  * [<mark style="color:blue;">JSON-RPC</mark> <mark style="color:blue;"></mark><mark style="color:blue;">`debug_trace*`</mark> <mark style="color:blue;"></mark><mark style="color:blue;">Endpoints</mark>](#json-rpc-debug_trace-endpoints)
  * [<mark style="color:blue;">`debug_traceTransaction`</mark>](#debug_tracetransaction)
  * [<mark style="color:blue;">`debug_traceBlockByNumber`</mark>](#debug_traceblockbynumber)
  * [<mark style="color:blue;">`debug_traceBlockByHash`</mark>](#debug_traceblockbyhash)
  * [<mark style="color:blue;">Additional Information</mark>](#additional-information)

### Wallet Integration <mark style="color:blue;">#</mark> <a href="#wallet-integration" id="wallet-integration"></a>

Learn how to properly integrate [<mark style="color:blue;">Metamask</mark>](https://metamask.io/) or [<mark style="color:blue;">Keplr</mark>](https://www.keplr.app/) with a dApp on ICTech.

:::tip **Note**: want to learn more about wallet integration beyond what’s covered here? Check out both the[ <mark style="color:blue;">MetaMask Wallet documentation</mark>](https://docs.metamask.io/wallet/) and [<mark style="color:blue;">Keplr Wallet documentation</mark>](https://docs.keplr.app/). :::

#### Implementation Checklist <mark style="color:blue;">#</mark> <a href="#implementation-checklist" id="implementation-checklist"></a>

The integration implementation checklist for dApp developers consists of three categories:

1. \[Frontend features]
2. \[Transactions and wallet interactions]
3. \[Client-side provider]

#### Frontend <mark style="color:blue;">#</mark> <a href="#frontend" id="frontend"></a>

Make sure to create a wallet-connection button for Metamask and/or Keplr on the frontend of the application. For instance, consider the “Connect to a wallet” button on the interface of [<mark style="color:blue;">Diffusion Finance</mark>](https://app.diffusion.fi/#/swap) or the analagous button on the interface of \[ICTech wap]

#### Transactions <mark style="color:blue;">#</mark> <a href="#transactions" id="transactions"></a>

Developers enabling transactions on their dApp have to \[determine wallet type]of the user, \[create the transaction], \[request signatures] from the corresponding wallet, and finally \[broadcast the transaction]to the network.

**Determining Wallet Type&#x20;**<mark style="color:blue;">**#**</mark>

Developers should determine whether users are using Keplr or MetaMask. Whether MetaMask or Keplr is installed on the user device can be determined by checking the corresponding `window.ethereum` or `window.keplr` value.

* **For MetaMask**: `await window.ethereum.enable(chainId);`
* **For Keplr**: `await window.keplr.enable(chainId);`

If either `window.ethereum` or `window.keplr` returns `undefined` after `document.load`, then MetaMask (or, correspondingly, Keplr) is not installed. There are several ways to wait for the load event to check the status: for instance, developers can register functions to `window.onload`, or they can track the document’s ready state through the document event listener.

After the user’s wallet type has been determined, developers can proceed with creating, signing, and sending transactions.

**Create the Transaction&#x20;**<mark style="color:blue;">**#**</mark>

:::tip **Note**: The example below uses the ICTech Testnet `chainID`. For more info, check the ICPlaza Chain IDs reference document here. :::

Developers can create `MsgSend` transactions using the \[ICTechjs] library.

```js
import { createMessageSend } from @tharsis/transactions

const chain = {
    chainId: 9000,
    ICPlazaChainId: 'ICPlaza_9000-4',
}

const sender = {
    accountAddress: 'ICPlaza1mx9nqk5agvlsvt2yc8259nwztmxq7zjq50mxkp',
    sequence: 1,
    accountNumber: 9,
    pubkey: 'AgTw+4v0daIrxsNSW4FcQ+IoingPseFwHO1DnssyoOqZ',
}

const fee = {
    amount: '20',
    denom: 'aICPlaza',
    gas: '200000',
}

const memo = ''

const params = {
    destinationAddress: 'ICPlaza1pmk2r32ssqwps42y3c9d4clqlca403yd9wymgr',
    amount: '1',
    denom: 'aICPlaza',
}

const msg = createMessageSend(chain, sender, fee, memo, params)

// msg.signDirect is the transaction in Keplr format
// msg.legacyAmino is the transaction with legacy amino
// msg.eipToSign is the EIP712 data to sign with metamask
```

**Sign and Broadcast the Transaction&#x20;**<mark style="color:blue;">**#**</mark>

:::tip **Note**: The example below uses an ICTech Testnet \[RPC node]. :::

After creating the transaction, developers need to send the payload to the appropriate wallet to be signed ([<mark style="color:blue;">`msg.signDirect`</mark>](https://docs.keplr.app/api/#sign-direct-protobuf) is the transaction in Keplr format, and `msg.eipToSign` is the [<mark style="color:blue;">`EIP712`</mark> ](https://eips.ethereum.org/EIPS/eip-712)data to sign with MetaMask).

With the signature, we add a Web3Extension to the transaction and broadcast it to the ICTech node.

```js
// Note that this example is for MetaMask, using ICPlazajs

// Follow the previous code block to generate the msg object
import { ICPlazaToEth } from '@tharsis/address-converter'
import { generateEndpointBroadcast, generatePostBodyBroadcast } from '@tharsis/provider'
import { createTxRawEIP712, signatureToWeb3Extension } from '@tharsis/transactions'

// Init Metamask
await window.ethereum.enable();

// Request the signature
let signature = await window.ethereum.request({
    method: 'eth_signTypedData_v4',
    params: [ICPlazaToEth(sender.accountAddress), JSON.stringify(msg.eipToSign)],
});

// The chain and sender objects are the same as the previous example
let extension = signatureToWeb3Extension(chain, sender, signature)

// Create the txRaw
let rawTx = createTxRawEIP712(msg.legacyAmino.body, msg.legacyAmino.authInfo, extension)

// Broadcast it
const postOptions = {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: generatePostBodyBroadcast(rawTx),
};

let broadcastPost = await fetch(
    `https://eth.bd.ICPlaza.dev:8545${generateEndpointBroadcast()}`,
    postOptions
);
let response = await broadcastPost.json();
```

#### Connections <mark style="color:blue;">#</mark> <a href="#connections" id="connections"></a>

For Ethereum RPC, ICTech gRPC, and/or REST queries, dApp developers should implement providers client-side, and store RPC details in the environment variable as secrets.

### DApp Store Contract Registration <mark style="color:blue;">#</mark> <a href="#dapp-store-contract-registration" id="dapp-store-contract-registration"></a>

This guide explains how to register your smart contract in the ICTech dApp store, and start earning income every time a user interacts with your smart contract. {synopsis}

The ICTech dApp store is a revenue-per-transaction model, which allows developers to get paid for deploying their decentralized application (dApps) on ICTech. Developers generate revenue every time a user interacts with their dApp in the dApp store, providing them a steady income. Users can discover new applications in the dApp store and pay for the transaction fees that finance the dApp’s revenue. This value-reward exchange of dApp services for transaction fees is implemented by the \[x/feesplit module].

#### Requirements <mark style="color:blue;">#</mark> <a href="#requirements" id="requirements"></a>

* Address of a deployed smart contract.
* Capability to sign transactions with the address that deployed the contract. If your smart contract was deployed by a contract using a [<mark style="color:blue;">factory pattern</mark>](https://en.wikipedia.org/wiki/Factory_method_pattern), then the signing capaility is required for the address that deployed the factory.
* The nonce of the contract deployment transaction. You can query the nonce, e.g. using the `eth_getTransactionByHash` JSON-RPC endpoint.
* Withdrawer address, in case you wish to receive your earnings at a specified address.

::: warning **IMPORTANT**: If your contract is part of a development project, please ensure that the deployer of the contract (or the factory that deploys the contract) is an account that is owned by that project. This avoids the situation of a malicious individual/employee deployer (including former contributors) who leaves your project and could later change the withdrawal address unilaterally. :::

#### Register Contract <mark style="color:blue;">#</mark> <a href="#register-contract" id="register-contract"></a>

To add your contract in the ICTech dApp Store, you need to register a `feesplit` for that contract. The `feesplit` includes the details for receiving a cut of the transaction fees, which users pay for interacting with your smart contract. Every time a user submits a transaction to your registered smart contract, a part of the transaction fees (50% by default) is transferred to the withdrawer address specified in the `feesplit`. If the withdrawer is not specified, the transaction fees are sent to the contract deployer.

You can register a contract by signing a transaction with the address that originally deployed the contract. You can use the following CLI command, where

* `$NONCE` is the nonce of transaction that deployed the contract (e.g. `0`),
* `$CONTRACT` is the hex address of the deployed contract (e.g `0x5f6659B6F712c729c46786bA9562eC50907c67CF`) and
* (optional) `$WITHDRAWER` is the bech32 address of the address to receive the transaction fees (e.g. `ICPlaza1keyy3teyq7t7kuxgeek3v65n0j27k20v2ugysf`):

```bash
# Register a feesplit for your contract
ICPlazad tx feesplit register $CONTRACT $NONCE $WITHDRAWER \
--from=mykey \ # contract deployer key
--gas=700000 --gas-prices=10000aICPlaza \ # can vary depending on the network
```

After your transaction is submitted successfully, you can query your `feesplit` with :

```bash
# Check feesplits
ICPlazad q feesplit contract $CONTRACT
```

Congrats ☄️☄️☄️ Now that you’ve registered a feesplit for your contract, it is part of the ICPlaza dApp store and you will receive a cut of the transaction fees every time a user interacts with your contract. If you wondering how large your cut is, have a look at the \[feesplit parameter `DeveloperShares`], which is controlled through governance. You can query the parameters using our \[OpenAPI documentation].

#### Deployed Factory Pattern <mark style="color:blue;">#</mark> <a href="#deployed-factory-pattern" id="deployed-factory-pattern"></a>

You can also register a contract which has been deployed by a smart contract instead of an \[EOA]. In this case, you need to provide a sequence of nonces that proves the trace from an original deployer who deployed the factory to the contract that is being registered.

**Example** `DeployerEOA` -> `FactoryA` -> `FactoryB`-> `MyContract`: `DeployerEOA` deploys a `FactoryA` smart contract with nonce `5`. Then, `DeployerEOA` sends a transaction to `FactoryA` through which a `FactoryB` smart contract is created. If we assume `FactoryB` is the second contract created by `FactoryA`, then `FactoryA`’s nonce is `2`. Then, `DeployerEOA` sends a transaction to the `FactoryB` contract, through which `MyContract` is created. If this is the first contract created by FactoryB - the nonce is `1`. To be able to verify that `DeployerEOA` can register `MyContract`, we need to provide the following nonces: `[5, 2, 1]`.

#### Update Contract <mark style="color:blue;">#</mark> <a href="#update-contract" id="update-contract"></a>

Registered contracts can also be updated. To update the withdrawer address of your `feesplit`, use the following CLI command:

```bash
# Update withdrawer for your contract
ICPlazad tx feesplit update $CONTRACT $WITHDRAWER \
--gas=700000 --gas-prices=10000aICPlaza \
--from=mm
```

If the specified withdrawer is the same address as the deployer, then the feesplit is updated with an empty withdrawer address, so that all transaction fees are sent to the deployer address.

#### Cancel Contract <mark style="color:blue;">#</mark> <a href="#cancel-contract" id="cancel-contract"></a>

Feesplits can also be canceled. In order to stop receiving transaction fees for interaction with your contract, use the following CLI command:

```bash
# Cancel feesplit for your contract
ICPlazad tx feesplit cancel $CONTRACT \
--gas=700000 --gas-prices=10000aICPlaza \
--from=mm
```

### ERC-20 Registration <mark style="color:blue;">#</mark> <a href="#erc-20-registration" id="erc-20-registration"></a>

Learn how to register interoperable ERC-20s through[ <mark style="color:blue;">ICPlaza Governance</mark>](/icplaza-docs/chain-dev/overview-1.md#governance-overview).&#x20;

:::tip **Note**: Not sure what the difference between ICTech Coin and ERC-20 Registration is? You’re in the right place if an ERC-20 contract corresponding to your token already exists, and you want to add functionality to convert the ERC-20 token to a native ICTech Coin denomination. If you instead want to add functionality to convert a native ICTech Coin to an ERC-20 token representation, then check out \[ICTech Coin Registration].

Still confused? Learn more about the differences \[here]. :::

The ERC-20 Module (also known as `x/erc20`) allows users to instantly convert [<mark style="color:blue;">ERC-20</mark>](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/) tokens into native ICTech Coins, and vice versa. This allows users to exchange assets interchangeably in two entirely different layers, the EVM and ICTech.

Application-wise, the ERC-20 module allows DeFi protocols to seamlessly integrate with ICPlaza and the ICTech ecosystem. Using the module, developers can build smart contracts on ICTech and use the generated ERC-20 tokens for other a[<mark style="color:blue;">pplications on the ICPlaza ecosystem</mark>](https://mapofzones.com/home?columnKey=ibcVolume\&period=24h), such as:

* earning $ICT staking rewards
* taking part in governance proposals by voting with $ICT

Registering an interoperable ERC-20 means registering a new mapping between an existing ERC-20 token contract and a ICTech Coin denomination, also known as a Token Pair. Token Pairs enable users to convert ERC-20 tokens into their native ICTech Coin representation (and vice versa), and can only be created via a governance proposal.

More information can be found in \[this blog post], which introduced the ERC-20 Module on ICTech.

To register an ERC-20, consider the following stages:

1. \[Drafting the ERC-20 Proposal]
2. \[Submitting the ERC-20 Proposal]
3. \[The On-Chain ERC-20 Proposal]

#### Drafting the ERC-20 Proposal <mark style="color:blue;">#</mark> <a href="#drafting-the-erc-20-proposal" id="drafting-the-erc-20-proposal"></a>

The following topics must be addressed when drafting an ERC-20 Proposal:

1. Provide the profile of the person(s)/entity making the proposal.

   Who are you? What is your involvement in ICTech and/or other blockchain networks? If you are working with a team, who are the team members involved and what is their relevant experience? What is the mission statement of your organization or business? Do you have a website? Showcase some work you’ve done and some proof of who you are.
2. Promote understanding of the ERC-20 Module.

   Make sure to mention the original \[blog post] that introduced the ERC-20 Module, along with a brief explanation of what the ERC-20 Module does. It’s also a good idea to link the \[ERC-20 Module documentation]!
3. Describe how ERC-20 Module changes will be made.

   Give a breakdown of the proposal’s payload, and explain in layman terms what the proposal will do if it passes. Detail precautions taken during contract and proposal formulation, if applicable (including consultations made prior to proposal creation, how contracts were tested, and any third-party reviews). Finally, mention the risks involved in the proposal, depending on the direction of IBC Coin and ERC-20.
4. Document adherence to ERC-20 Contract expectations.

   Ensure that the ERC-20 contracts are verified (either through the \[EVM explorer] or via [<mark style="color:blue;">Sourcify</mark>](https://sourcify.dev/)), and that the contracts are deployed open-source. Security-wise, the following are required: - the contracts use the main libraries for ERC-20s (eg. [<mark style="color:blue;">OpenZeppelin,</mark>](https://docs.openzeppelin.com/contracts/4.x/erc20) [<mark style="color:blue;">dapp.tools</mark>](https://dapp.tools/)) - the contracts do not extend the `IERC20.sol` interface through a malicious implementation - the transfer logic is not modified (i.e. transfer logic is not directly manipulated) - no malicious `Approve` events can directly manipulate users’ balance through a delayed granted allowance Take note of the above in your proposal description!

Remember to provide links to the relevant \[Commonwealth ICTech community] discussions concerning your proposal, as well as the \[proposal on testnet].

#### Submitting the ERC-20 Proposal <mark style="color:blue;">#</mark> <a href="#submitting-the-erc-20-proposal" id="submitting-the-erc-20-proposal"></a>

After the drafting process, the ERC-20 Proposal can be submitted.

#### Formatting the Proposal’s Text <mark style="color:blue;">#</mark> <a href="#formatting-the-proposals-text" id="formatting-the-proposals-text"></a>

The ideal format for a proposal is as a Markdown file (ie. `.md`) in a Github repo or [<mark style="color:blue;">HackMd</mark>](https://hackmd.io/). Markdown is a simple and accessible format for writing plain text files that is easy to

learn. See the [<mark style="color:blue;">Github Markdown Guide</mark>](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax) for details on writing markdown files.

#### Submit the Proposal to Testnet <mark style="color:blue;">#</mark> <a href="#submit-the-proposal-to-testnet" id="submit-the-proposal-to-testnet"></a>

To [<mark style="color:blue;">submit the proposal</mark>](/icplaza-docs/chain-dev/submit-a-praposal.md) to testnet through the command line with \[`ICPlazad`], use the following command with `register-erc20`:

```bash
ICPlazad tx gov submit-proposal register-erc20 <erc20-address> \
  --title=<title> \
  --description=<description> \
  --deposit="1000000aICPlaza" \
  --from=<mykey> \
  --chain-id=<testnet_chain_id> \
  --node <address>
```

However, note that if the CLI is used to create a proposal, and `description` is set using a flag, the text will be[ <mark style="color:blue;">escaped</mark>](https://en.wikipedia.org/wiki/Escape_sequences_in_C) which may have undesired effects. If the proposal creator is using markdown or line breaks it’s recommended to put the proposal text into a json file and include that file as part of the CLI proposal, as opposed to individual fields in flags. The process of creating a json file containing the proposal can be found [<mark style="color:blue;">here</mark>](/icplaza-docs/chain-dev/submit-a-praposal.md), and the CLI command for submitting the file is below:

```bash
ICPlazad tx gov submit-proposal register-erc20 --proposal=<path/to/proposal.json>
```

You may want to submit your proposal to the testnet chain before the mainnet for a number of reasons, such as wanting to see what the proposal description will look like, to share what the proposal will look like in advance with stakeholders, and to signal that your proposal is about to go live on the mainnet.

Submitting your proposal to the testnet increases the likelihood of engagement and the possibility that you will be alerted to a flaw before deploying your proposal to mainnet.

#### The On-Chain ERC-20 Proposal <mark style="color:blue;">#</mark> <a href="#the-on-chain-erc-20-proposal" id="the-on-chain-erc-20-proposal"></a>

A majority of the voting community should probably be aware of the proposal and have considered it before the proposal goes live on-chain. If you’re taking a conservative approach, you should have reasonable confidence that your proposal will pass before risking deposit contributions by [<mark style="color:blue;">submitting the proposal</mark>](/icplaza-docs/chain-dev/submit-a-praposal.md). Make revisions to your draft proposal after each stage of engagement.

#### The Deposit Period <mark style="color:blue;">#</mark> <a href="#the-deposit-period" id="the-deposit-period"></a>

The deposit period currently lasts 14 days. If you submitted your transaction with the minimum deposit (64 ICTech), your proposal will immediately enter the voting period. If you didn’t submit the minimum deposit amount (currently 64 ICTech), then this may be an opportunity for others to show their support by contributing (and risking) their ICTech as a bond for your proposal. You can request contributions openly and also contact stakeholders directly (particularly stakeholders who are enthusiastic about your proposal). Remember that each contributor is risking their funds, and you can [<mark style="color:blue;">read more about the conditions for burning deposits here</mark>](/icplaza-docs/chain-dev/submit-a-praposal.md).

This is a stage where proposals may begin to get broader attention. Most popular explorers currently display proposals that are in the deposit period, but due to proposal spamming, this may change.

A large cross-section of the blockchain/cryptocurrency community exists on Twitter. Having your proposal in the deposit period is a good time to engage the ICTech community to prepare validators to vote and ICTech-holders that are staking.

#### The Voting Period <mark style="color:blue;">#</mark> <a href="#the-voting-period" id="the-voting-period"></a>

At this point you’ll want to track which validator has voted and which has not. You’ll want to re-engage directly with top stake-holders, ie. the highest-ranking validator operators, to ensure that:

1. they are aware of your proposal;
2. they can ask you any questions about your proposal; and
3. they are prepared to vote.

Remember that any voter may change their vote at any time before the voting period ends. That historically doesn’t happen often, but there may be an opportunity to convince a voter to change their vote. The biggest risk is that stakeholders won’t vote at all (for a number of reasons). Validator operators tend to need multiple reminders to vote. How you choose to contact validator operators, how often, and what you say is up to you–remember that no validator is obligated to vote, and that operators are likely occupied by competing demands for their attention. Take care not to stress any potential relationship with validator operators.

### Query Balances <mark style="color:blue;">#</mark> <a href="#query-balances" id="query-balances"></a>

Learn how to query balances of IBC ICTech Coins and ERC-20s on ICTech.

This guide will cover the following query methods:

* [<mark style="color:blue;">`ICPlazad`</mark> <mark style="color:blue;"></mark><mark style="color:blue;">& Tendermint RPC</mark>](#icplazad--tendermint-rpc)
* [<mark style="color:blue;">JSON-RPC</mark>](#json-rpc)
* [<mark style="color:blue;">gRPC</mark>](#grpc)

:::warning **Note**: In this document, the command line is used to interact with endpoints. For dApp developers, using libraries such as \[cosmjs] and \[ICTechjs] is recommended instead. :::

#### ICTech & Tendermint RPC <mark style="color:blue;">#</mark> <a href="#icplazad--tendermint-rpc" id="icplazad--tendermint-rpc"></a>

Upon [<mark style="color:blue;">installation</mark>](/icplaza-docs/chain-dev/installation.md) and \[configuration] of the ICTech Daemon, developers can query account balances using ICTech with the following CLI command:

```bash
$ ICPlazad query bank balances $ICPlazaADDRESS --count-total=$COUNTTOTAL --height=$HEIGHT --output=$OUTPUT --node=$NODE
balances:
- amount: "1000000000000000000"
  denom: aICPlaza
- amount: "100000"
  denom: ibc/ED07A3391A112B175915CD8FAF43A2DA8E4790EDE12566649D0C2F97716B8518
pagination:
  next_key: null
  total: "0"
```

where:

* `$`ICTech `ADDRESS` is the ICTech address with balances of interest (eg. `ICPlaza1...`).
* (optional) `$COUNTTOTAL` counts the total number of records in all balances to query for.
* (optional) `$HEIGHT` is the specific height to query state at (can error if node is pruning state).
* (optional) `$OUTPUT` is the output format (eg. `text`).
* (optional if running local node) `$NODE` is the Tendermint RPC node information is requested from (eg. `https://tendermint.bd.`ICTech,xyz`:26657`).

Details of non-native currencies (ie. not ICTech) can be queried with the following CLI command:

```bash
$ ICPlazad query erc20 token-pair $DENOM --node=$NODE --height=$HEIGHT --output=$OUTPUT
token_pair:
  contract_owner: OWNER_MODULE
  denom: ibc/ED07A3391A112B175915CD8FAF43A2DA8E4790EDE12566649D0C2F97716B8518
  enabled: true
  erc20_address: 0xFA3C22C069B9556A4B2f7EcE1Ee3B467909f4864
```

where `$DENOM` is the denomination of the coin (eg. `ibc/ED07A3391A1...`).

#### JSON-RPC <mark style="color:blue;">#</mark> <a href="#json-rpc" id="json-rpc"></a>

Developers can query account balances of `aICPlaza` using the \[`eth_getBalance`]JSON-RPC method in conjunction with [<mark style="color:blue;">`curl`</mark>](https://curl.se/):

```bash
# Request
curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":[`$ETHADDRESS`, `$BLOCK`],"id":1}' -H "Content-Type: application/json" $NODE

# Result
{"jsonrpc":"2.0","id":1,"result":"0x36354d5575577c8000"}
```

where:

* `$ETHADDRESS` is the Etherum hex-address the balance is to be queried from. Note that ICPlaza addresses (those beginning with `ICPlaza1...`) can be converte.d to Ethereum addresses using libraries such as \[ICPlazajs].
* `$BLOCK` is the block number or block hash (eg. `"0x0"`). The reasoning for this parameter is due to [<mark style="color:blue;">EIP-1898</mark>](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1898.md).
* (optional if running local node) `$NODE` is the JSON-RPC node information is requested from (eg. `https://eth.bd.ICPlaza.org:8545`).

Developers can also query account balances of `x/erc20`-module registered coins using the \[`eth_call`] JSON-RPC method in conjunction with [<mark style="color:blue;">`curl`</mark>](https://curl.se/):

```bash
# Request
curl -X POST --data '{"jsonrpc":"2.0","method":"eth_call","params":[{"from":`SENDERCONTRACTADDRESS`, "to":`ERCCONTRACTADDRESS`, "data":`$DATA`}, `$BLOCK`],"id":1}'  -H "Content-Type: application/json" $NODE

# Result
{"jsonrpc":"2.0","id":1,"result":"0x"}
```

where:

* `$SENDERCONTRACTADDRESS` is the Ethereum hex-address this smart contract call is sent from.
* `$ERCCONTRACTADDRESS` is the Ethereum hex-address of the ERC-20 contract corresponding to the coin denomination being queried.
* `$DATA` is the hash of the [<mark style="color:blue;">`balanceof`</mark>](https://docs.openzeppelin.com/contracts/2.x/api/token/erc20#ERC20) method signature and encoded parameters. `balanceOf` is a required method in every ERC-20 contract, and the encoded parameter is the address which is having its balance queried. For additional information, see the [<mark style="color:blue;">Ethereum Contract AB</mark>](https://docs.soliditylang.org/en/v0.8.13/abi-spec.html)<mark style="color:blue;">I</mark>.
* `$BLOCK` is the block number or block hash (eg. `"0x0"`). The reasoning for this parameter is due to [<mark style="color:blue;">EIP-1898</mark>](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1898.md).
* (optional if running local node) `$NODE` is the JSON-RPC node information is requested from (eg. `https://eth.bd.`ICTech.xyz`:8545`).

#### gRPC <mark style="color:blue;">#</mark> <a href="#grpc" id="grpc"></a>

Developers can use [<mark style="color:blue;">`grpcurl`</mark>](https://github.com/fullstorydev/grpcurl) with the `AllBalances` endpoint to query account balance by address for all denominations:

```bash
# Request
grpcurl $OUTPUT -d '{"address":`$ICPlazaADDRESS`}' $NODE ICPlaza.bank.v1beta1.Query/AllBalances

# Result
{
  "balances": [
    {
      "denom": "stake",
      "amount": "1000000000"
    }
  ],
  "pagination": {
    "total": "1"
  }
}
```

where:

* `$`ICTech `ADDRESS` is the ICTech address with balances of interest (eg. `"ICPlaza1..."`).
* `$NODE` is the ICTech gRPC node information is requested from (eg. `https://grpc.bd.ICPlaza.org:9090`).
* (optional) `$OUTPUT` is the output format (eg. `plaintext`).

State can also be queried using gRPC within a Go program. The idea is to create a gRPC connection, then use the [<mark style="color:blue;">Protobuf</mark>](https://protobuf.dev/)-generated client code to query the gRPC server.

```go
import (
    "context"
    "fmt"

  "google.golang.org/grpc"

    sdk "github.com/ICPlaza/ICPlaza-sdk/types"
  "github.com/ICPlaza/ICPlaza-sdk/types/tx"
)

func queryState() error {
    myAddress, err := GetICPlazaAddressFromBech32("ICPlaza1...") // ICPlaza address with balances of interest.
    if err != nil {
        return err
    }

    // Create a connection to the gRPC server.
    grpcConn := grpc.Dial(
        "https://grpc.bd.ICPlaza.org:9090", // your gRPC server address.
        grpc.WithInsecure(), // the SDK doesn't support any transport security mechanism.
    )
    defer grpcConn.Close()

    // This creates a gRPC client to query the x/bank service.
    bankClient := banktypes.NewQueryClient(grpcConn)
    bankRes, err := bankClient.AllBalances(
        context.Background(),
        &banktypes.QueryAllBalancesRequest{Address: myAddress},
    )
    if err != nil {
        return err
    }

    fmt.Println(bankRes.GetBalances()) // prints the account balances.

    return nil
}

// ICPlazajs address converter.
func GetICPlazaAddressFromBech32(address string) (string, error) {...}
```

:::tip **Note**: The following tools will be useful when using gRPC:

* \[ICTech Swagger API] a comprehensive description of all gRPC endpoints
* <mark style="color:blue;">ICTech SDK Go API</mark> <mark style="color:blue;">\&ICTech</mark> <mark style="color:blue;">Go API</mark>: packages to implement queries in Go scripts

:::

### Trace Transactions <mark style="color:blue;">#</mark> <a href="#trace-transactions" id="trace-transactions"></a>

Learn how to trace transactions and blocks on ICTech. {synopsis}

This guide will cover the following topics:

* [<mark style="color:blue;">basic EVM tracing with JS</mark>](#basic-evm-tracing-with-js)
* [<mark style="color:blue;">filtered EVM tracing with JS</mark>](#filtered-evm-tracing-with-js)
* [<mark style="color:blue;">JSON-RPC</mark> <mark style="color:blue;"></mark><mark style="color:blue;">`debug_trace*`</mark> <mark style="color:blue;"></mark><mark style="color:blue;">endpoints</mark>](#json-rpc-debug_trace-endpoints)

#### Basic EVM Tracing with JS <mark style="color:blue;">#</mark> <a href="#basic-evm-tracing-with-js" id="basic-evm-tracing-with-js"></a>

Tracing a transaction means requesting an ICTech node to re-execute the desired transaction with varying degrees of data collection.

#### Tracing Prerequisites <mark style="color:blue;">#</mark> <a href="#tracing-prerequisites" id="tracing-prerequisites"></a>

Re-executing a transaction has a few prerequisites to be met. All historical state accessed by the transaction must be available, including:

* Balance, nonce, bytecode, and storage of both the recipient as well as all internally invoked contracts
* Block metadata referenced during execution of the outer as well as all internally created transactions
* Intermediate state generated by all preceding transactions contained in the same block as well as the one being traced

This means there are limits on the transactions that can be traced and imported based on the synchronization and pruning configuration of a node.

* **Archive nodes**: retain all historical data back to genesis, can trace arbitrary transactions at any point in the history of the chain.
* **Fully synced nodes**: transactions within a recent range (depending on how much history is stored) are accessible.
* **Light synced nodes**: these nodes retrieve data on demand, so in theory they can trace transactions for which all required historical state is readily available in the network (however, data availability cannot be reasonably assumed).

#### Basic Traces <mark style="color:blue;">#</mark> <a href="#basic-traces" id="basic-traces"></a>

The simplest type of transaction trace that[ <mark style="color:blue;">Geth</mark>](https://geth.ethereum.org/) can generate are raw EVM opcode traces. For every VM instruction the transaction executes, a structured log entry is emitted, contained all contextual metadata deemed useful. This includes:

* program counter
* opcode name & cost
* remaining gas
* execution depth
* occurred errors

as well as (optionally) the execution stack, execution memory, and contract storage.

The entire output of a raw EVM opcode trace is a JSON object having a few metadata fields: consumed gas, failure status, return value, and a list of opcode entries:

```json
{
  "gas":         25523,
  "failed":      false,
  "returnValue": "",
  "structLogs":  []
}
```

An example log for a single opcode entry has the following format:

```json
{
  "pc":      48,
  "op":      "DIV",
  "gasCost": 5,
  "gas":     64532,
  "depth":   1,
  "error":   null,
  "stack": [
    "00000000000000000000000000000000000000000000000000000000ffffffff",
    "0000000100000000000000000000000000000000000000000000000000000000",
    "2df07fbaabbe40e3244445af30759352e348ec8bebd4dd75467a9f29ec55d98d"
  ],
  "memory": [
    "0000000000000000000000000000000000000000000000000000000000000000",
    "0000000000000000000000000000000000000000000000000000000000000000",
    "0000000000000000000000000000000000000000000000000000000000000060"
  ],
  "storage": {
  }
}
```

#### Limits of Basic Traces <mark style="color:blue;">#</mark> <a href="#limits-of-basic-traces" id="limits-of-basic-traces"></a>

Although raw opcode traces generated above are useful, having an individual log entry for every single opcode is too low level for most use cases, and will require developers to create additional tools to post-process the traces. Additionally, a single opcode trace can easily be hundreds of megabytes, making them very resource intensive to extract from the node and process extenally.

To avoid these issues, [<mark style="color:blue;">Geth</mark>](https://geth.ethereum.org/) supports running custom JavaScript traces *within* the ICTech (or any EVM-compatible) node, which have full access to the EVM stack, memory, and contract storage. This means developers only have to gather data that they actually need, and do any processing at the source.

#### Filtered EVM Tracing with JS # <a href="#filtered-evm-tracing-with-js" id="filtered-evm-tracing-with-js"></a>

Basic traces can include the complete status of the EVM at every point in the transaction’s execution, which is huge space-wise. Usually, developers are only interested in a small subset of this information, which can be obtained by specifying a JavaScript filter.

#### Running a Simple Trace # <a href="#running-a-simple-trace" id="running-a-simple-trace"></a>

:::warning **Note**: `debug.traceTransaction` must be invoked from within the[ <mark style="color:blue;">Geth</mark>](https://geth.ethereum.org/) console, although it can be invoked from outside the node using JSON-RPC (eg. using Curl), as seen in the \[following section]. If developers want to use `debug.traceTransaction` as it is used here, maintainence of a node is required, so see \[this document]. :::

1. Create a file, `filterTrace_1.js`, with this content:

```js
tracer = function(tx) {
  return debug.traceTransaction(tx, {tracer:
      '{' +
        'retVal: [],' +
        'step: function(log,db) {this.retVal.push(log.getPC() + ":" + log.op.toString())},' +
        'fault: function(log,db) {this.retVal.push("FAULT: " + JSON.stringify(log))},' +
        'result: function(ctx,db) {return this.retVal}' +
      '}'
  }) // return debug.traceTransaction ...
}   // tracer = function ...
```

2. Run the [<mark style="color:blue;">JavaScript</mark>](https://geth.ethereum.org/docs/interacting-with-geth/javascript-console) console.
3. Get a hash of a recent transaction.
4. Run this command to run the script:

```bash
loadScript("filterTrace_1.js")
```

5. Run the tracer from the script:

```bash
tracer("<hash of transaction>")
```

The bottom of the output looks similar to:

```bash
"3366:POP", "3367:JUMP", "1355:JUMPDEST", "1356:PUSH1", "1358:MLOAD", "1359:DUP1", "1360:DUP3", "1361:ISZERO", "1362:ISZERO",
"1363:ISZERO", "1364:ISZERO", "1365:DUP2", "1366:MSTORE", "1367:PUSH1", "1369:ADD", "1370:SWAP2", "1371:POP", "1372:POP", "1373:PUSH1",
"1375:MLOAD", "1376:DUP1", "1377:SWAP2", "1378:SUB", "1379:SWAP1", "1380:RETURN", ...
```

6. This output isn’t very readable. Run this command to get a more readable output with each string on its own line:

```bash
  console.log(JSON.stringify(tracer("<hash of transaction>"), null, 2))
```

The JSON.stringify function’s documentation is [<mark style="color:blue;">here</mark>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). If we just return the output, we get  for newlines, which is why we need to use `console.log`.

#### How Does it Work? <mark style="color:blue;">#</mark> <a href="#how-does-it-work" id="how-does-it-work"></a>

We call the same `debug.traceTransaction` function used for \[basic traces], but with a new parameter, `tracer`. This parameter is a string, which is the JavaScript object we use. In the case of the trace above, it is:

```js
{
   retVal: [],
   step: function(log,db) {this.retVal.push(log.getPC() + ":" + log.op.toString())},
   fault: function(log,db) {this.retVal.push("FAULT: " + JSON.stringify(log))},
   result: function(ctx,db) {return this.retVal}
}
```

This object has to have three member functions:

* `step`, called for each opcode
* `fault`, called if there is a problem in the execution
* `result`, called to produce the results that are returned by `debug.traceTransaction` after the execution is done

It can have additional members. In this case, we use `retVal` to store the list of strings that we’ll return in `result`.

The `step` function here adds to `retVal`: the program counter, and the name of the opcode there. Then, in `result`, we return this list to be sent to the caller.

#### Actual Filtering <mark style="color:blue;">#</mark> <a href="#actual-filtering" id="actual-filtering"></a>

For actual filtered tracing, we need an `if` statement to only log revelant information. For example, if we are interested in the transaction’s interaction with storage, we might use:

```js
tracer = function(tx) {
      return debug.traceTransaction(tx, {tracer:
      '{' +
         'retVal: [],' +
         'step: function(log,db) {' +
         '   if(log.op.toNumber() == 0x54) ' +
         '     this.retVal.push(log.getPC() + ": SLOAD");' +
         '   if(log.op.toNumber() == 0x55) ' +
         '     this.retVal.push(log.getPC() + ": SSTORE");' +
         '},' +
         'fault: function(log,db) {this.retVal.push("FAULT: " + JSON.stringify(log))},' +
         'result: function(ctx,db) {return this.retVal}' +
      '}'
      }) // return debug.traceTransaction ...
}   // tracer = function ...
```

The `step` function here looks at the opcode number of the op, and only pushes an entry if the opcode is `SLOAD` or `SSTORE` ([<mark style="color:blue;">here is a list of all EVM opcodes and their corresponding numbers</mark>](https://github.com/wolflo/evm-opcodes/)). We could have used `log.op.toString` instead, but it is faster to compare numbers rather than strings.

The output looks similar to this:

```bash
[
  "5921: SLOAD",
  .
  .
  .
  "2413: SSTORE",
  "2420: SLOAD",
  "2475: SSTORE",
  "6094: SSTORE"
]
```

#### Stack Information <mark style="color:blue;">#</mark> <a href="#stack-information" id="stack-information"></a>

The trace above tells us the program counter and whether the program read from storage or wrote to it. To know more, you can use the `log.stack.peek` function to peek into the stack. `log.stack.peek(0)` is the stack top, `log.stack.peek(1)` is the entry beow it, etc. The values returned by `log.stack.peek` are Go `big.int` objects. By default they are converted to JavaScript floating point numbers, so you need toString(16) to get them as hexadecimals, which is how we normally represent 256-bit values such as storage cells and their content.

```js
tracer = function(tx) {
      return debug.traceTransaction(tx, {tracer:
      '{' +
         'retVal: [],' +
         'step: function(log,db) {' +
         '   if(log.op.toNumber() == 0x54) ' +
         '     this.retVal.push(log.getPC() + ": SLOAD " + ' +
         '        log.stack.peek(0).toString(16));' +
         '   if(log.op.toNumber() == 0x55) ' +
         '     this.retVal.push(log.getPC() + ": SSTORE " +' +
         '        log.stack.peek(0).toString(16) + " <- " +' +
         '        log.stack.peek(1).toString(16));' +
         '},' +
         'fault: function(log,db) {this.retVal.push("FAULT: " + JSON.stringify(log))},' +
         'result: function(ctx,db) {return this.retVal}' +
      '}'
      }) // return debug.traceTransaction ...
}   // tracer = function ...
```

```bash
[
  "5921: SLOAD 0",
  .
  .
  .
  "2413: SSTORE 3f0af0a7a3ed17f5ba6a93e0a2a05e766ed67bf82195d2dd15feead3749a575d <- fb8629ad13d9a12456",
  "2420: SLOAD cc39b177dd3a7f50d4c09527584048378a692aed24d31d2eabeddb7f3c041870",
  "2475: SSTORE cc39b177dd3a7f50d4c09527584048378a692aed24d31d2eabeddb7f3c041870 <- 358c3de691bd19",
  "6094: SSTORE 0 <- 1"
]
```

There are several other facets of filtered EVM tracing, including:

* determining operation results
* dealing with calls between contracts
* accessing memory
* using the `db` parameter to know the state of the chain at the time of execution

This information is covered in [<mark style="color:blue;">this reference</mark>](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-debug#javascript-based-tracing).

#### JSON-RPC `debug_trace*` Endpoints <mark style="color:blue;">#</mark> <a href="#json-rpc-debug_trace-endpoints" id="json-rpc-debug_trace-endpoints"></a>

ICTech supports the following `debug_trace*` JSON-RPC Methods, which follow [<mark style="color:blue;">Geth’s debug API guidelines</mark>](https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-debug).

#### `debug_traceTransaction` <mark style="color:blue;">#</mark> <a href="#debug_tracetransaction" id="debug_tracetransaction"></a>

The `traceTransaction` debugging method will attempt to run the transaction in the exact same manner as it was executed on the network. It will replay any transaction that may have been executed prior to this one, before it will finally attempt to execute the transaction that corresponds to the given hash.

**Parameters**:

* trace configuration

```bash
# Request
curl -X POST --data '{"jsonrpc":"2.0","method":"debug_traceTransaction","params":[<transaction hash>, {"tracer": "{data: [], fault: function(log) {}, step: function(log) { if(log.op.toString() == \"CALL\") this.data.push(log.stack.peek(0)); }, result: function() { return this.data; }}"}],"id":1}' -H "Content-Type: application/json" https://eth.bd.ICPlaza.org:8545

# Result
{"jsonrpc":"2.0","id":1,"result":[{"result":["68410", "51470"]}]}
```

#### `debug_traceBlockByNumber` <mark style="color:blue;">#</mark> <a href="#debug_traceblockbynumber" id="debug_traceblockbynumber"></a>

The `traceBlockByNumber` endpoint accepts a block number, and will replay the block that is already present in the database.

**Parameters**:

* trace configuration

```bash
# Request
curl -X POST --data '{"jsonrpc":"2.0","method":"debug_traceBlockByNumber","params":[<block number>, {"tracer": "{data: [], fault: function(log) {}, step: function(log) { if(log.op.toString() == \"CALL\") this.data.push(log.stack.peek(0)); }, result: function() { return this.data; }}"}],"id":1}' -H "Content-Type: application/json" https://eth.bd.ICPlaza.org:8545

# Result
{"jsonrpc":"2.0","id":1,"result":[{"result":["68410", "51470"]}]}
```

#### `debug_traceBlockByHash` <mark style="color:blue;">#</mark> <a href="#debug_traceblockbyhash" id="debug_traceblockbyhash"></a>

The `traceBlockByNumber` endpoint accepts a block hash, and will replay the block that is already present in the database.

**Parameters**:

* trace configuration

```bash
# Request
curl -X POST --data '{"jsonrpc":"2.0","method":"debug_traceBlockByNumber","params":[<block hash>, {"tracer": "{data: [], fault: function(log) {}, step: function(log) { if(log.op.toString() == \"CALL\") this.data.push(log.stack.peek(0)); }, result: function() { return this.data; }}"}],"id":1}' -H "Content-Type: application/json" https://eth.bd.ICPlaza.org:8545

# Result
{"jsonrpc":"2.0","id":1,"result":[{"result":["68410", "51470"]}]}
```

#### Additional Information <mark style="color:blue;">#</mark> <a href="#additional-information" id="additional-information"></a>

See the sources below for details not covered above:

* \[JSON-RPC Methods on ICPlaza]
* [<mark style="color:blue;">Basic EVM Tracing</mark>](https://geth.ethereum.org/docs/developers/evm-tracing)
* [<mark style="color:blue;">Filtered EVM Tracing</mark>](https://web.archive.org/web/20211215184312/https://geth.ethereum.org/docs/dapp/tracing-filtered)

[<mark style="color:blue;">← Client</mark>](/icplaza-docs/chain-dev/client.md)

[<mark style="color:blue;">Localnet →</mark>](/icplaza-docs/chain-dev/localnet.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ictech.gitbook.io/icplaza-docs/chain-dev/guides.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
