Package Exports
- bcfetch
- bcfetch/browser-compatible.js
- bcfetch/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (bcfetch) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
bcfetch
A powerful library to perform multiple fetch operations based on type, including HTTP requests, blockchain data fetching, and AMM LP token price calculations. Supports both Node.js and browser environments.
Features
- π HTTP Operations: GET and POST requests
- π Blockchain Integration: Balance queries for ERC20 tokens and Bitcoin, smart contract calls
- π° Price Data: Binance API integration for cryptocurrency prices
- π¦ AMM Support: Calculate LP token prices for Uniswap and other AMM protocols
- π― XPath Support: Extract content from web pages using XPath selectors (Node.js only)
- β‘ Concurrent Execution: All operations run in parallel for maximum performance
- π§ Type-based: Easy to extend with new operation types
Installation
npm install bcfetchOptional Dependencies
For XPath functionality (Node.js only), you may need to install Puppeteer:
npm install puppeteerEnvironment Support
- Node.js: Full functionality including XPath support
- Browser: All features except XPath (requires Puppeteer)
Quick Start
Node.js Environment
const { fetch } = require('bcfetch');
const operations = [
{
type: 'http-get',
params: { url: 'https://jsonplaceholder.typicode.com/users/1' }
},
{
type: 'balanceOf',
params: {
chainid: 1,
contract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
address: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
}
},
{
type: 'binance',
params: { symbol: 'BTCUSDT' }
},
{
type: 'lpPrice',
params: {
chainid: 1,
contract: '0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc',
reverse: true
}
}
];
async function main() {
try {
const results = await fetch(operations);
console.log('Results:', results);
// results is now an array of strings in the same order as operations
} catch (error) {
console.error('Error:', error.message);
}
}
main();Browser Environment
For browser usage, the library automatically uses the browser-compatible version:
// In browser, use the browser-compatible version
const { fetch } = require('bcfetch/browser-compatible');
const operations = [
{
type: 'binance',
params: { symbol: 'BTCUSDT' }
},
{
type: 'balanceOf',
params: {
chainid: 1,
contract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
address: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
}
}
];
async function fetchData() {
try {
const results = await fetch(operations);
console.log('Results:', results);
// results is now an array of strings in the same order as operations
} catch (error) {
console.error('Error:', error.message);
}
}
fetchData();Note: XPath operations are not available in browser environments as they require Puppeteer.
Supported Operations
HTTP Operations
http-get
Perform HTTP GET requests.
Parameters:
url(string): The URL to fetch
Example:
{
type: 'http-get',
params: { url: 'https://api.example.com/data' }
}http-post
Perform HTTP POST requests.
Parameters:
url(string): The URL to send the request tobody(object): The request body (will be JSON stringified)
Example:
{
type: 'http-post',
params: {
url: 'https://api.example.com/users',
body: { name: 'John Doe', email: 'john@example.com' }
}
}Blockchain Operations
balanceOf
Get ERC20 token balance or Bitcoin balance.
Parameters:
chainid(number|string): Chain ID (1 for Ethereum, 56 for BSC, 137 for Polygon, 'BTC' for Bitcoin)contract(string): ERC20 contract address (not required for Bitcoin)address(string): Wallet address to query
Supported Chains:
- Ethereum Mainnet (1)
- Binance Smart Chain (56)
- Polygon (137)
- Bitcoin ('BTC')
Example:
// ERC20 token balance
{
type: 'balanceOf',
params: {
chainid: 1,
contract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
address: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
}
}
// Bitcoin balance
{
type: 'balanceOf',
params: {
chainid: 'BTC',
address: 'bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq'
}
}call
Execute smart contract calls using raw hex data.
Parameters:
chainid(number): Chain ID (1 for Ethereum, 56 for BSC, 137 for Polygon)contract(string): Smart contract addressdata(string): Raw hex data for the contract call (with or without 0x prefix)
Supported Chains:
- Ethereum Mainnet (1)
- Binance Smart Chain (56)
- Polygon (137)
Example:
// Call ERC20 token name() method
// Function selector for name() is 0x06fdde03
{
type: 'call',
params: {
chainid: 1,
contract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
data: '0x06fdde03'
}
}
// Call ERC20 token symbol() method
// Function selector for symbol() is 0x95d89b41
{
type: 'call',
params: {
chainid: 1,
contract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
data: '0x95d89b41'
}
}
// Call ERC20 token balanceOf(address) method
// Function selector for balanceOf(address) is 0x70a08231
// Parameter: 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045
{
type: 'call',
params: {
chainid: 1,
contract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
data: '0x70a08231000000000000000000000000d8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
}
}Price Operations
binance
Get cryptocurrency prices from Binance API.
Parameters:
symbol(string): Trading pair symbol (e.g., 'BTCUSDT', 'ETHUSDT')
Example:
{
type: 'binance',
params: { symbol: 'BTCUSDT' }
}lpPrice
Calculate AMM LP token prices for Uniswap and other AMM protocols.
Parameters:
chainid(number): Chain ID (1 for Ethereum, 56 for BSC, 137 for Polygon)contract(string): LP contract addressreverse(boolean): Price calculation directionfalse: Calculate token0/token1 pricetrue: Calculate token1/token0 price
Example:
// Calculate USDC/WETH price (token0/token1)
{
type: 'lpPrice',
params: {
chainid: 1,
contract: '0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc',
reverse: false
}
}
// Calculate WETH/USDC price (token1/token0)
{
type: 'lpPrice',
params: {
chainid: 1,
contract: '0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc',
reverse: true
}
}Web Scraping Operations
xpath
Extract content from web pages using XPath selectors.
Parameters:
url(string): The URL of the web page to scrapexpath(string): XPath selector to find elementsattribute(string, optional): Specific attribute to extract (e.g., 'href', 'src', 'class'). If not provided, returns text content.waitFor(number, optional): Wait time in milliseconds for dynamic content to load (default: 3000ms)
Example:
// Extract text content from a specific element
{
type: 'xpath',
params: {
url: 'https://example.com',
xpath: '//h1[@class="title"]'
}
}
// Extract href attribute from links
{
type: 'xpath',
params: {
url: 'https://example.com',
xpath: '//a[@class="main-link"]',
attribute: 'href'
}
}
// Extract multiple elements' text content
{
type: 'xpath',
params: {
url: 'https://example.com',
xpath: '//h2'
}
}
// Extract content from dynamic page (with wait time)
{
type: 'xpath',
params: {
url: 'https://transcription.bihelix.io/zh',
xpath: '/html/body/div[1]/div[2]/div/div[1]/div[1]/div[3]/div[1]/div[1]/div[2]',
waitFor: 5000
}
}API Reference
fetch(operations)
Execute multiple operations concurrently and return results in the same order.
Parameters:
operations(Array): Array of operation objects
Returns:
Promise<Array<string>>: Array of string results in the same order as input operations
Operation Object Structure:
{
type: string, // Operation type (http-get, http-post, balanceOf, call, binance, lpPrice, xpath)
params: object // Operation-specific parameters
}Result Array Structure:
[
"result1", // First operation result
"result2", // Second operation result
// ... more results in order
]Error Handling
The library provides detailed error messages for different failure scenarios:
- Invalid input: "θΎε ₯εΏ ι‘»ζ―δΈδΈͺζδ½ζ°η»γ"
- Missing parameters: Specific error for each operation type
- Network errors: HTTP and RPC call failures
- Unsupported operations: "δΈζ―ζηζδ½η±»ε: [type]"
Examples
Complete Example
const { fetch } = require('bcfetch');
const operations = [
// HTTP GET request
{
type: 'http-get',
params: { url: 'https://jsonplaceholder.typicode.com/users/1' }
},
// HTTP POST request
{
type: 'http-post',
params: {
url: 'https://jsonplaceholder.typicode.com/posts',
body: { title: 'New Post', body: 'Content here', userId: 1 }
}
},
// ERC20 token balance
{
type: 'balanceOf',
params: {
chainid: 1,
contract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
address: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'
}
},
// Smart contract call
{
type: 'call',
params: {
chainid: 1,
contract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
data: '0x06fdde03' // name() function selector
}
},
// Bitcoin balance
{
type: 'balanceOf',
params: {
chainid: 'BTC',
address: 'bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq'
}
},
// Cryptocurrency price
{
type: 'binance',
params: { symbol: 'ETHUSDT' }
},
// AMM LP price
{
type: 'lpPrice',
params: {
chainid: 1,
contract: '0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc',
reverse: true
}
},
// XPath scraping
{
type: 'xpath',
params: {
url: 'https://example.com',
xpath: '//h1'
}
}
];
async function main() {
console.log('Starting operations...');
try {
const results = await fetch(operations);
console.log('All operations completed successfully!');
results.forEach((value, index) => {
console.log(`Result ${index + 1}:`, value);
});
} catch (error) {
console.error('Operation failed:', error.message);
}
}
main();DeFi Portfolio Example
const { fetch } = require('bcfetch');
// Check multiple token balances and prices
const portfolioOperations = [
// Token balances
{
type: 'balanceOf',
params: {
chainid: 1,
contract: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
address: '0xYourWalletAddress'
}
},
{
type: 'balanceOf',
params: {
chainid: 1,
contract: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
address: '0xYourWalletAddress'
}
},
// Current prices
{
type: 'binance',
params: { symbol: 'USDCUSDT' }
},
{
type: 'binance',
params: { symbol: 'ETHUSDT' }
},
// LP token prices
{
type: 'lpPrice',
params: {
chainid: 1,
contract: '0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc',
reverse: false
}
}
];
async function checkPortfolio() {
try {
const results = await fetch(portfolioOperations);
// Calculate portfolio value
const usdcBalance = parseFloat(results[0]);
const wethBalance = parseFloat(results[1]);
const usdcPrice = parseFloat(results[2]);
const ethPrice = parseFloat(results[3]);
const totalValue = (usdcBalance * usdcPrice) + (wethBalance * ethPrice);
console.log('Portfolio Summary:');
console.log(`USDC: ${usdcBalance.toFixed(2)} ($${(usdcBalance * usdcPrice).toFixed(2)})`);
console.log(`WETH: ${wethBalance.toFixed(4)} ($${(wethBalance * ethPrice).toFixed(2)})`);
console.log(`Total Value: $${totalValue.toFixed(2)}`);
console.log(`USDC/WETH LP Price: ${results[4]}`);
} catch (error) {
console.error('Portfolio check failed:', error.message);
}
}
checkPortfolio();Dependencies
- ethers ^6.15.0 - Ethereum library for blockchain interactions
- gemini-code ^0.2.4 - Additional utilities
- cheerio ^1.0.0-rc.12 - Server-side jQuery implementation for HTML parsing
Supported Networks
Ethereum
- Chain ID: 1
- RPC: https://ethereum.publicnode.com
Binance Smart Chain
- Chain ID: 56
- RPC: https://bsc-dataseed.binance.org/
Polygon
- Chain ID: 137
- RPC: https://polygon-rpc.com
Bitcoin
- Chain ID: 'BTC'
- API: https://blockstream.info/api/
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
License
This project is licensed under the ISC License - see the LICENSE file for details.
Changelog
v0.6.0
- NEW: Added
calloperation type for smart contract calls using raw hex data - Added support for direct contract calls with 16-bit hex data strings
- Added automatic 0x prefix handling for hex data
- Enhanced error handling for hex data validation
v0.5.0
- BREAKING CHANGE:
fetch()function now returns an array of strings instead of an array of objects - Removed
namefield requirement from operation objects - Simplified API - results are returned in the same order as input operations
- Updated all examples and documentation to reflect the new API
v0.4.0
- Added
xpathoperation type for web scraping using XPath selectors - Added support for extracting text content and attributes from web pages
- Added cheerio dependency for HTML parsing
v0.3.1
- Fixed parameter naming consistency (chainId β chainid)
v0.3.0
- Added
lpPriceoperation type for AMM LP token price calculations - Added support for Uniswap V2 LP contracts
- Updated keywords and description
v0.2.0
- Added
binanceoperation type for cryptocurrency prices - Added Bitcoin balance support
- Improved error handling
v0.1.0
- Initial release
- HTTP GET/POST operations
- ERC20 token balance queries
- Concurrent execution support
Support
If you encounter any issues or have questions, please open an issue on the GitHub repository.
Made with β€οΈ by Gemini