### Automate Polygon Testnet Setup (TypeScript Script)
Source: https://context7.com/yearn/kalani/llms.txt
An automation script for configuring Polygon testnet environments. It utilizes the Tenderly client to set balances, transfer roles, and grant permissions to accounts. The script requires custom configurations for addresses and roles, and supports reverting to a previous state in case of errors. Dependencies include 'viem' and '@kalani/lib/tenderly'.
```typescript
// Run with: bun run packages/scripts/src/testnet/polygon_setup.ts
import { createTestnetClient } from '@kalani/lib/tenderly';
import { parseEther, parseUnits, getContract } from 'viem';
import abis from '@kalani/lib/abis';
const ALICE = '0x70997970C51812dc3A010C7d01b50e0d17dc79C8';
const yWMATIC = '0x28F53bA70E5c8ce8D03b1FaD41E9dF11Bb646c36';
const USDC = '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359';
const client = createTestnetClient(polygonChain);
const snapshot = await client.snapshot(); // Save state for revert
try {
// Fund test accounts
await client.setBalance(ALICE, parseEther('1000'));
await client.setErc20Balance(ALICE, USDC, parseUnits('100000', 6));
// Transfer vault role manager
const vault = getContract({ abi: abis.vault, address: yWMATIC, client });
await vault.write.transfer_role_manager([ALICE], {
account: currentRoleManager
});
await vault.write.accept_role_manager({ account: ALICE });
// Grant roles
await vault.write.set_role([ALICE, ROLES.DEBT_MANAGER], { account: ALICE });
console.log('Setup complete');
} catch (error) {
await client.revert(snapshot); // Restore on error
console.error('Setup failed:', error);
}
```
--------------------------------
### GET /api/kong/mq/job
Source: https://context7.com/yearn/kalani/llms.txt
Checks the status of background jobs in the message queue system. Requires queue name and job ID as query parameters.
```APIDOC
## GET /api/kong/mq/job
### Description
Checks the status of background jobs in the message queue system. Requires queue name and job ID as query parameters.
### Method
GET
### Endpoint
/api/kong/mq/job
### Parameters
#### Query Parameters
- **queueName** (string) - Required - The name of the message queue.
- **jobId** (string) - Required - The ID of the job to check.
### Response
#### Success Response (200)
- **id** (string) - The job ID.
- **name** (string) - The name of the job.
- **data** (object) - The data associated with the job.
- **finishedOn** (number) - The timestamp when the job finished, or null if pending.
- **failedReason** (string) - The reason for job failure, or null if successful.
- **returnvalue** (object) - The return value of the job.
#### Response Example
```json
{
"id": "abc123",
"name": "evmlog",
"data": {
"chainId": 137,
"address": "0x...",
"from": 45678900,
"to": 45678902
},
"finishedOn": 1672531250000,
"failedReason": null,
"returnvalue": {
"extracted": 15
}
}
```
```
--------------------------------
### GET /api/assets/token/[chainId]/[address]
Source: https://context7.com/yearn/kalani/llms.txt
Proxies token logo images. If a logo is unavailable for the given chain ID and token address, it returns a transparent PNG fallback.
```APIDOC
## GET /api/assets/token/[chainId]/[address]
### Description
Proxies token logo images. If a logo is unavailable for the given chain ID and token address, it returns a transparent PNG fallback.
### Method
GET
### Endpoint
/api/assets/token/[chainId]/[address]
### Parameters
#### Path Parameters
- **chainId** (number) - Required - The blockchain network ID.
- **address** (string) - Required - The address of the token.
### Response
#### Success Response (200)
- Content-Type: image/png
- The response is a PNG image file representing the token logo or a 1x1 transparent fallback.
#### Response Example
(Binary image data)
```
--------------------------------
### Kalani API: Get Message Queue Job Status
Source: https://context7.com/yearn/kalani/llms.txt
Retrieves the status of background jobs in the message queue system. This GET endpoint requires the queue name and job ID to query. It returns information about whether the job is completed, its return value, or any failure reason.
```typescript
// GET /api/kong/mq/job?queueName=extract-137&jobId=abc123
const queueName = 'extract-137';
const jobId = 'abc123';
const response = await fetch(
`https://api.kalani.com/api/kong/mq/job?queueName=${queueName}&jobId=${jobId}`,
{ headers: { 'Content-Type': 'application/json' } }
);
const job = await response.json();
console.log('Job status:', job.finishedOn ? 'completed' : 'pending');
console.log('Failed reason:', job.failedReason || 'none');
// Expected output:
// {
// id: 'abc123',
// name: 'evmlog',
// data: { chainId: 137, address: '0x...', from: 45678900n, to: 45678902n },
// finishedOn: 1672531250000,
// failedReason: null,
// returnvalue: { extracted: 15 }
// }
```
--------------------------------
### Kalani API: Token Asset Proxy Endpoint
Source: https://context7.com/yearn/kalani/llms.txt
Provides a proxied URL for token logo images, falling back to a transparent PNG if the logo is unavailable. This GET endpoint takes chain ID and token address as parameters. The response is a PNG image, typically 128x128 pixels.
```typescript
// GET /api/assets/token/[chainId]/[address]
const chainId = 137;
const tokenAddress = '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270';
const imageUrl = `https://api.kalani.com/api/assets/token/${chainId}/${tokenAddress}`;
// Usage in HTML/React
const tokenImage = ;
// Response: PNG image (128x128 logo or 1x1 transparent fallback)
// Content-Type: image/png
```
--------------------------------
### Configure EVM Chains and RPCs in TypeScript
Source: https://context7.com/yearn/kalani/llms.txt
Provides multi-chain support with RPC configurations for various EVM networks. It allows fetching chain details and creating viem clients for interacting with smart contracts. Requires '@kalani/lib/chains' and 'viem'.
```typescript
import { chains, getRpc } from '@kalani/lib/chains';
import { createPublicClient, http } from 'viem';
// Get configured chains
const polygonChain = chains[137]; // Polygon
const mainnetChain = chains[1]; // Ethereum mainnet
const arbitrumChain = chains[42161]; // Arbitrum
// Get RPC URL for chain
const rpcUrl = getRpc(137); // Returns process.env.RPC_137 or TESTNET_RPC_137
console.log(rpcUrl); // "https://polygon-rpc.com"
// Create viem client with chain config
const client = createPublicClient({
chain: chains[137],
transport: http(getRpc(137))
});
// Read vault data
const vaultAddress = '0x28F53bA70E5c8ce8D03b1FaD41E9dF11Bb646c36';
const totalAssets = await client.readContract({
address: vaultAddress,
abi: abis.vault,
functionName: 'totalAssets'
});
console.log('Total assets:', totalAssets); // 5000000000000000000n
```
--------------------------------
### Format Numbers and Tokens in TypeScript
Source: https://context7.com/yearn/kalani/llms.txt
Utilities for formatting USD values, percentages, and token amounts into human-readable strings. It handles different precision requirements and uses BigInt for token balances. Requires '@kalani/lib/format'.
```typescript
import { fUSD, fPercent, fTokens, fEvmAddress } from '@kalani/lib/format';
// Format USD amounts with K/M/B suffixes
const tvl = 15_750_000;
console.log(fUSD(tvl)); // "$ 15.75M"
console.log(fUSD(tvl, { full: true })); // "$ 15,750,000.00"
// Format percentages with precision
const apy = 0.0847; // 8.47%
console.log(fPercent(apy)); // "8.47%"
console.log(fPercent(0.125, { fixed: 1 })); // "12.5%"
// Format token amounts from BigInt
const balance = 1234567890000000000n; // 1.23456789 tokens
console.log(fTokens(balance, 18, { fixed: 2 })); // "1.23"
console.log(fTokens(balance, 18, { fixed: 4 })); // "1.2345"
// Format addresses
const vaultAddress = '0x28F53bA70E5c8ce8D03b1FaD41E9dF11Bb646c36';
console.log(fEvmAddress(vaultAddress)); // "0x28F5...c36"
console.log(fEvmAddress(vaultAddress, true)); // "0x28F5"
```
--------------------------------
### POST /api/kong/index/vault
Source: https://context7.com/yearn/kalani/llms.txt
Registers and indexes a new Yearn V3 vault into the platform's database and job queue system. This endpoint requires specific vault details and signature verification.
```APIDOC
## POST /api/kong/index/vault
### Description
Registers and indexes a new Yearn V3 vault into the platform's database and job queue system. This endpoint requires specific vault details and signature verification.
### Method
POST
### Endpoint
/api/kong/index/vault
### Parameters
#### Request Body
- **chainId** (number) - Required - The blockchain network ID.
- **address** (string) - Required - The address of the Yearn V3 vault.
- **asset** (string) - Required - The address of the underlying asset.
- **decimals** (number) - Required - The number of decimals for the asset.
- **apiVersion** (string) - Required - The API version of the vault.
- **category** (number) - Required - The category ID of the vault.
- **projectId** (string) - Required - The project ID associated with the vault.
- **projectName** (string) - Required - The name of the project.
- **roleManager** (string) - Required - The address of the role manager.
- **inceptBlock** (string) - Required - The block number at which the vault was initiated.
- **inceptTime** (number) - Required - The timestamp at which the vault was initiated.
- **signature** (string) - Required - EIP-191 signature from the vault's admin.
### Request Example
```json
{
"chainId": 137,
"address": "0x28F53bA70E5c8ce8D03b1FaD41E9dF11Bb646c36",
"asset": "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",
"decimals": 18,
"apiVersion": "3.0.2",
"category": 1,
"projectId": "0x7965726e0000000000000000000000000000000000000000000000000000000",
"projectName": "Yearn Finance",
"roleManager": "0xC4ad0000E223E398DC329235e6C497Db5470B626",
"inceptBlock": "45678900",
"inceptTime": 1672531200,
"signature": "0xabcd1234..."
}
```
### Response
#### Success Response (200)
- **ok** (boolean) - Indicates if the request was processed successfully.
#### Response Example
```json
{
"ok": true
}
```
```
--------------------------------
### Kalani Lib: BigInt Math Operations
Source: https://context7.com/yearn/kalani/llms.txt
Provides utility functions for precise financial calculations using BigInt, preventing floating-point errors. Includes functions for division, multiplication, and calculating USD value from token amounts with specified decimal precision.
```typescript
import { div, mul, mulb, priced } from '@kalani/lib/bmath';
// Divide BigInt with decimal precision
const tokenAmount = 1500000000000000000n; // 1.5 tokens (18 decimals)
const totalSupply = 10000000000000000000n; // 10 tokens
const sharePercentage = div(tokenAmount, totalSupply, 18);
console.log(sharePercentage); // 0.15 (15%)
// Multiply BigInt by number
const currentBalance = 5000000000000000000n; // 5 tokens
const multiplier = 1.1; // 10% increase
const newBalance = mul(currentBalance, multiplier, 18);
console.log(newBalance); // 5.5
// Calculate USD value from token amount
const vaultBalance = 2500000000000000000n; // 2.5 tokens (18 decimals)
const decimals = 18;
const priceUsd = 1850.50; // $1,850.50 per token
const balanceUsd = priced(vaultBalance, decimals, priceUsd);
console.log(balanceUsd); // 4626.25 (2.5 * 1850.50)
```
--------------------------------
### Manage Kong Message Queue Jobs (TypeScript)
Source: https://context7.com/yearn/kalani/llms.txt
Provides internal API functions for managing background jobs in the Kong message queue system. It includes functions to register new entities, extract contract snapshots, and retrieve event logs from the blockchain. Dependencies include utility functions from '@/app/api/kong/lib'.
```typescript
import { postThing, extractSnapshot, extractLogs } from '@/app/api/kong/lib';
// Register new vault/strategy/accountant in database
const thingResult = await postThing(
137, // chainId
'0x28F53bA70E5c8ce8D03b1FaD41E9dF11Bb646c36', // address
'vault', // label
{
erc4626: true,
v3: true,
yearn: false,
asset: '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270',
decimals: 18,
apiVersion: '3.0.2',
category: 1,
projectId: '0x796561726e000000000000000000000000000000000000000000000000000000',
projectName: 'Yearn Finance',
inceptBlock: 45678900n,
inceptTime: 1672531200
}
);
// Returns job result after completion or failure
// Extract current state snapshot from contract
const snapshotResult = await extractSnapshot(
'yearn/3/vault', // abiPath
137, // chainId
'0x28F53bA70E5c8ce8D03b1FaD41E9dF11Bb646c36' // address
);
// Polls job until completion, returns snapshot data
// Extract event logs from blockchain
const logsResult = await extractLogs(
'yearn/3/vault', // abiPath
137, // chainId
'0x28F53bA70E5c8ce8D03b1FaD41E9dF11Bb646c36', // address
45678900n, // from block
45678910n // to block
);
// Returns extracted Deposit, Withdraw, StrategyReported events
```
--------------------------------
### Manage Vault Roles with Bitmasks in TypeScript
Source: https://context7.com/yearn/kalani/llms.txt
Enables type-safe role management for Yearn V3 vault permissions using bitmask operations. It includes functions to check, grant, and manage roles for specific accounts. Requires '@kalani/lib/types', '@kalani/lib/abis', and 'viem'.
```typescript
import { ROLES, containsRole, ALL_ROLES_MASK } from '@kalani/lib/types';
import abis from '@kalani/lib/abis';
import { createPublicClient, http, getContract } from 'viem';
// Check if account has specific role
const vaultAddress = '0x28F53bA70E5c8ce8D03b1FaD41E9dF11Bb646c36';
const accountAddress = '0x70997970C51812dc3A010C7d01b50e0d17dc79C8';
const client = createPublicClient({
chain: chains[137],
transport: http(getRpc(137))
});
const vault = getContract({
address: vaultAddress,
abi: abis.vault,
client
});
const roleMask = await vault.read.roles([accountAddress]);
console.log('Raw role mask:', roleMask); // 4160n
// Check individual roles
const canAddStrategy = containsRole(roleMask, ROLES.ADD_STRATEGY_MANAGER);
const canManageDebt = containsRole(roleMask, ROLES.DEBT_MANAGER);
const isEmergencyManager = containsRole(roleMask, ROLES.EMERGENCY_MANAGER);
console.log('Can add strategy:', canAddStrategy); // true (if bit 0 set)
console.log('Can manage debt:', canManageDebt); // true (if bit 6 set)
console.log('Emergency manager:', isEmergencyManager); // false
// Grant multiple roles
const newRoles = ROLES.ADD_STRATEGY_MANAGER | ROLES.DEBT_MANAGER | ROLES.REPORTING_MANAGER;
// Write transaction: vault.write.set_role([accountAddress, newRoles])
```
--------------------------------
### Kalani API: Index New Yearn V3 Vault
Source: https://context7.com/yearn/kalani/llms.txt
Registers and indexes a new Yearn V3 vault by sending its details and a signature to the platform's API. This POST request triggers backend jobs for data extraction and processing. It requires chain ID, vault address, asset details, and administrative signature.
```typescript
POST /api/kong/index/vault
// Request body with vault details and signature verification
const response = await fetch('https://api.kalani.com/api/kong/index/vault', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chainId: 137,
address: '0x28F53bA70E5c8ce8D03b1FaD41E9dF11Bb646c36',
asset: '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270',
decimals: 18,
apiVersion: '3.0.2',
category: 1,
projectId: '0x7965726e0000000000000000000000000000000000000000000000000000000',
projectName: 'Yearn Finance',
roleManager: '0xC4ad0000E223E398DC329235e6C497Db5470B626',
inceptBlock: '45678900',
inceptTime: 1672531200,
signature: '0xabcd1234...' // EIP-191 signature from vault's chad (admin)
})
});
const result = await response.json();
// Expected output: { ok: true }
// Triggers backend jobs: postThing, extractLogs, extractSnapshot
```
--------------------------------
### Fetch ERC-20 Token Balance and USD Valuation (TypeScript React Hook)
Source: https://context7.com/yearn/kalani/llms.txt
A React hook for fetching an ERC-20 token balance for a specific address and its equivalent USD valuation. It utilizes utility functions for formatting monetary values. The hook expects chain ID, token address, and the user's address as input, returning balance, symbol, USD value, and price.
```typescript
import { useBalance } from '@/hooks/useBalance';
import { fTokens, fUSD } from '@kalani/lib/format';
function WalletBalance() {
const userAddress = '0x70997970C51812dc3A010C7d01b50e0d17dc79C8';
const usdcAddress = '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359';
const balance = useBalance({
chainId: 137,
token: usdcAddress,
address: userAddress
});
if (!balance.data) return
Token: {balance.symbol}
Balance: {fTokens(balance.balance, balance.decimals, { fixed: 2 })}
USD Value: {fUSD(balance.balanceUsd)}
Price: {fUSD(balance.price)}