Skip to main content

Smart Contracts

Read from and write to smart contracts on EVM-compatible chains.

Reading Contract State

Programmatic

import { erc20Abi } from "@fluxkitdev/onchain";

// Read a single value
const name = await app.onchain.contracts.read({
address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
abi: erc20Abi,
method: "name",
chain: "ethereum",
});
// => "USD Coin"

// Read with arguments
const balance = await app.onchain.contracts.read({
address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
abi: erc20Abi,
method: "balanceOf",
args: ["0x1234...5678"],
chain: "ethereum",
});
// => 1000000000n (BigInt, 1000 USDC)

REST API

curl -X POST http://localhost:3000/onchain/contracts/read \
-H "Content-Type: application/json" \
-H "Authorization: Bearer eyJhbGci..." \
-d '{
"address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
"abi": "erc20",
"method": "balanceOf",
"args": ["0x1234...5678"],
"chain": "ethereum"
}'

Response (200):

{
"result": "1000000000",
"method": "balanceOf",
"address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
}

Writing to Contracts

Programmatic

const tx = await app.onchain.contracts.write({
address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
abi: erc20Abi,
method: "transfer",
args: ["0xrecipient...", 1000000n], // 1 USDC
chain: "ethereum",
walletId: "65a1b2c3...", // Wallet to sign with
});

console.log(tx.hash); // Transaction hash
console.log(tx.status); // "pending"

REST API

curl -X POST http://localhost:3000/onchain/contracts/write \
-H "Content-Type: application/json" \
-H "Authorization: Bearer eyJhbGci..." \
-d '{
"address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
"abi": "erc20",
"method": "transfer",
"args": ["0xrecipient...", "1000000"],
"chain": "ethereum",
"walletId": "65a1b2c3d4e5f6a7b8c9d0e1"
}'

Response (200):

{
"hash": "0xabc123...",
"status": "pending",
"chain": "ethereum"
}

Built-in ABIs

FluxKit includes commonly used ABIs:

import {
erc20Abi,
erc721Abi,
erc1155Abi,
} from "@fluxkitdev/onchain";

Or pass "erc20", "erc721", or "erc1155" as the abi field in REST requests.

Custom ABI

const abi = [
{
name: "getValue",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ type: "uint256" }],
},
];

const value = await app.onchain.contracts.read({
address: "0xcontract...",
abi,
method: "getValue",
chain: "ethereum",
});

Contract Events

Listen for contract events:

app.onchain.contracts.on({
address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
abi: erc20Abi,
event: "Transfer",
chain: "ethereum",
handler: async (from, to, value, log) => {
console.log(`Transfer: ${from} -> ${to}: ${value}`);
},
});

Gas Estimation

const gas = await app.onchain.contracts.estimateGas({
address: "0xcontract...",
abi: erc20Abi,
method: "transfer",
args: ["0xrecipient...", 1000000n],
chain: "ethereum",
});

console.log(gas.gasLimit); // Estimated gas units
console.log(gas.gasPrice); // Current gas price
console.log(gas.totalCost); // Total cost in ETH