> ## Documentation Index
> Fetch the complete documentation index at: https://docs.blockradar.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Interact with Any Smart Contract

> Use Blockradar's Smart Contract API to read from and write to any onchain contract — DeFi protocols, custom tokens, RWAs, and more.

Blockradar's core APIs cover the most common fintech flows: stablecoin deposits, payouts, swaps, and settlements. But what if you need to go beyond what's natively supported? What if you need to interact with a DeFi protocol, your own token contract, or an onchain service unique to your business?

That's where the **Smart Contract API** comes in. It lets you interact with any smart contract directly from your Blockradar wallet without managing RPC endpoints, signing flows, or node infrastructure yourself.

With it, you can:

* Connect to **DeFi protocols** for yield or liquidity management
* Automate **stablecoin lending, staking, or treasury operations**
* Integrate **tokenized real-world assets (RWAs)** into your product flows
* Power **programmable settlements, payouts, or compliance checks** using onchain logic
* Extend your platform with **custom tokens, reward systems, or fee rules**

The Smart Contract API gives you three capabilities: read contract state, write to contracts, and estimate gas before execution.

***

## Prerequisites

<Steps>
  <Step title="API Key">
    Get your API key from the [Blockradar Dashboard](https://dashboard.blockradar.co). Navigate to **Developers** to generate one.
  </Step>

  <Step title="Wallet Created">
    You'll need a `walletId` for all smart contract operations.
  </Step>

  <Step title="Contract ABI">
    You need the ABI (Application Binary Interface) for the contract function you want to call. This is publicly available for verified contracts on block explorers like Etherscan.
  </Step>

  <Step title="Contract Address">
    The onchain address of the smart contract you want to interact with.
  </Step>
</Steps>

***

## How It Works

In this guide, we'll walk through a real example: swapping an unsupported token into USDT using Uniswap V2. The same pattern applies to any smart contract interaction.

The flow:

1. **Read** the token balance from the contract
2. **Approve** Uniswap to spend the token
3. **Estimate** the network fee for the swap
4. **Execute** the swap
5. **Confirm** via webhook

***

## Step 1: Understand the Contract

We'll use Uniswap V2 Router's `swapExactTokensForTokens` method.

**Method signature:**

```solidity theme={null}
function swapExactTokensForTokens(
  uint amountIn,
  uint amountOutMin,
  address[] calldata path,
  address to,
  uint deadline
) external returns (uint[] memory amounts);
```

| Parameter      | Description                                                        |
| -------------- | ------------------------------------------------------------------ |
| `amountIn`     | Amount of the token you want to sell                               |
| `amountOutMin` | Minimum amount of output token you'll accept (slippage protection) |
| `path`         | Token addresses for the swap route                                 |
| `to`           | Your Blockradar wallet address (receives the output token)         |
| `deadline`     | Unix timestamp after which the transaction expires                 |

***

## Step 2: Read the Token Balance

Before swapping, check how much of the token your wallet holds using `contracts/read`.

```javascript theme={null}
const res = await fetch(
  'https://api.blockradar.co/v1/wallets/{walletId}/contracts/read',
  {
    method: 'POST',
    headers: {
      'x-api-key': '<api-key>',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      abi: [{
        "constant": true,
        "inputs": [{ "name": "_owner", "type": "address" }],
        "name": "balanceOf",
        "outputs": [{ "name": "balance", "type": "uint256" }],
        "stateMutability": "view",
        "type": "function"
      }],
      address: "0xUnsupportedTokenAddress",
      method: "balanceOf",
      parameters: ["0xYourWalletAddress"]
    })
  }
).then(r => r.json());

// Response:
// { "data": "1000000000000000000", "message": "Contract read successfully" }
```

| Parameter    | Description                                     |
| ------------ | ----------------------------------------------- |
| `abi`        | The ABI of the contract function you're calling |
| `address`    | The token's smart contract address              |
| `method`     | The function name to call                       |
| `parameters` | Arguments for the function                      |

<Tip>
  Use the balance returned here as the `amountIn` value for your swap call.
</Tip>

***

## Step 3: Approve the Contract to Spend Your Token

Before Uniswap can move your token, you need to grant it permission using the token contract's `approve` function.

```javascript theme={null}
await fetch(
  'https://api.blockradar.co/v1/wallets/{walletId}/contracts/write',
  {
    method: 'POST',
    headers: {
      'x-api-key': '<api-key>',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      abi: [{
        "inputs": [
          { "name": "_spender", "type": "address" },
          { "name": "_value", "type": "uint256" }
        ],
        "name": "approve",
        "outputs": [],
        "stateMutability": "nonpayable",
        "type": "function"
      }],
      address: "0xUnsupportedTokenAddress",
      method: "approve",
      parameters: ["0xUniswapRouterAddress", "1000000000000000000"]
    })
  }
);
```

<Warning>
  Do not proceed to the swap immediately after submitting the approval. Wait for the `custom-smart-contract.success` webhook confirming the approval transaction was mined before moving to the next step.
</Warning>

**Approval webhook payload:**

```json theme={null}
{
  "event": "custom-smart-contract.success",
  "data": {
    "status": "SUCCESS",
    "type": "CUSTOM_SMART_CONTRACT",
    "hash": "0xfedcba098765...",
    "tokenAddress": "0xUnsupportedTokenAddress"
  }
}
```

***

## Step 4: Estimate the Network Fee

Before executing the swap, estimate the gas cost to ensure your wallet has enough native token to cover it.

```javascript theme={null}
const fee = await fetch(
  'https://api.blockradar.co/v1/wallets/{walletId}/contracts/network-fee',
  {
    method: 'POST',
    headers: {
      'x-api-key': '<api-key>',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      abi: [ /* ABI of swapExactTokensForTokens */ ],
      address: "0xUniswapRouterAddress",
      method: "swapExactTokensForTokens",
      parameters: [
        "1000000000000000000",
        "990000",
        ["0xUnsupportedTokenAddress", "0xUSDTAddress"],
        "0xYourWalletAddress",
        Math.floor(Date.now() / 1000) + 60 * 20
      ]
    })
  }
).then(r => r.json());

// Response:
// { "data": { "balance": "1.0123", "fee": "0.00422" } }
```

***

## Step 5: Execute the Swap

Once the approval is confirmed and you've reviewed the fee, execute the swap.

```javascript theme={null}
const swap = await fetch(
  'https://api.blockradar.co/v1/wallets/{walletId}/contracts/write',
  {
    method: 'POST',
    headers: {
      'x-api-key': '<api-key>',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      abi: [ /* ABI of swapExactTokensForTokens */ ],
      address: "0xUniswapRouterAddress",
      method: "swapExactTokensForTokens",
      parameters: [
        "1000000000000000000",
        "990000",
        ["0xUnsupportedTokenAddress", "0xUSDTAddress"],
        "0xYourWalletAddress",
        Math.floor(Date.now() / 1000) + 60 * 20
      ]
    })
  }
).then(r => r.json());

// Response:
// { "message": "Contract write initiated successfully", "data": { "status": "PENDING" } }
```

Listen for the webhook to confirm completion:

```json theme={null}
{
  "event": "custom-smart-contract.success",
  "data": {
    "status": "SUCCESS",
    "type": "CUSTOM_SMART_CONTRACT",
    "hash": "0xfedcba098765...",
    "tokenAddress": "0xUniswapRouterAddress"
  }
}
```

***

## Webhook Events

| Event                           | Description                       |
| ------------------------------- | --------------------------------- |
| `custom-smart-contract.success` | Contract write confirmed on-chain |
| `custom-smart-contract.failed`  | Contract write failed             |

***

## Other Endpoints

| Endpoint                                            | Description                             |
| --------------------------------------------------- | --------------------------------------- |
| `POST /v1/wallets/{walletId}/contracts/read`        | Read state from any contract            |
| `POST /v1/wallets/{walletId}/contracts/write`       | Execute any contract function           |
| `POST /v1/wallets/{walletId}/contracts/network-fee` | Estimate gas before execution           |
| `POST /v1/wallets/{walletId}/contracts/write/sign`  | Sign a transaction without broadcasting |

***

## Security Notes

* All transactions are signed and broadcast through Blockradar's infrastructure — no need to manage private keys or RPC nodes
* Native AML and compliance checks apply where possible
* Every contract interaction is a real on-chain transaction and requires gas in the native token of the chain

***

## API Reference

| Endpoint                                                                                | Description                                  |
| --------------------------------------------------------------------------------------- | -------------------------------------------- |
| [Master Wallet Read](/en/api-reference/smart-contract/master-wallet-read)               | Read contract state from master wallet       |
| [Master Wallet Write](/en/api-reference/smart-contract/master-wallet-write)             | Execute contract function from master wallet |
| [Master Wallet Network Fee](/en/api-reference/smart-contract/master-wallet-network-fee) | Estimate gas from master wallet              |
| [Child Address Read](/en/api-reference/smart-contract/child-address-read)               | Read contract state from child address       |
| [Child Address Write](/en/api-reference/smart-contract/child-address-write)             | Execute contract function from child address |
| [Child Address Network Fee](/en/api-reference/smart-contract/child-address-network-fee) | Estimate gas from child address              |
