Minimal web3 implementation: call eth contracts directly from JS

Overview

micro-web3

Minimal web3 implementation: call eth contracts directly from JS

  • Connect to any web3 server: host your own with execution layer client, or use a public one
  • Fetch token balances, resolve ENS domains, watch token prices with chainlink web3 oracle
  • Decode transactions: create readable tx descriptions from tx data & ABIs
  • No network code in main package: allows simpler audits and offline usage
  • Tiny, only 1600 lines with all deps included; thanks to generic serializer: micro-packed

Check out all web3 utility libraries:

Usage

npm install micro-web3

import web3 from 'micro-web3'
import contracts from 'micro-web3/contracts';
import web3net from 'micro-web3-net';
const DEF_CONTRACTS = contracts.DEFAULT_CONTRACTS;

Decode transactions without network

import { hex } from '@scure/base';
const tx = 'a9059cbb000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec70000000000000000000000000000000000000000000000000000000542598700';
const decoder = new web3.Decoder();
const USDT = contracts.tokenFromSymbol('USDT').contract;
decoder.add(USDT, contracts.ERC20);
const info = decoder.decode(USDT, hex.decode(tx), { contractInfo: DEF_CONTRACTS[USDT] });
console.log(info);
// { name: 'transfer', signature: 'transfer(address,uint256)',
// value: { to: '0xdac17f958d2ee523a2206206994597c13d831ec7', value: 22588000000n },
// hint: 'Transfer 22588 USDT to 0xdac17f958d2ee523a2206206994597c13d831ec7' }

Decode events

const BAT = '0x0d8775f648430679a709e98d2b0cb6250d2887ef';
const decoder = new web3.Decoder();
decoder.add(BAT, contracts.ERC20);
const info = decoder.decodeEvent(BAT,
  [ '0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925',
    '0x000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa96045',
    '0x000000000000000000000000e592427a0aece92de3edee1f18e0157c05861564' ],
  '0x00000000000000000000000000000000000000000000003635c9adc5dea00000',
  { contract: BAT, contracts: { ...DEF_CONTRACTS }, contractInfo: DEF_CONTRACTS[BAT] });
console.log(info.hint);
// Allow 0xe592427a0aece92de3edee1f18e0157c05861564 spending up to 1000 BAT from 0xd8da6bf26964af9d7eed9e03e53415d37aa96045

Fetch Chainlink oracle prices

import chainlink from 'micro-web3/api/chainlink';
const provider = new web3net.Web3({
  url: 'https://nodes.mewapi.io/rpc/eth', headers: { Origin: 'https://www.myetherwallet.com' },
});
const btc = await chainlink.coinPrice(provider, 'BTC');
const bat = await chainlink.tokenPrice(provider, 'BAT');
console.log({ btc, bat }); // BTC 19188.68870991, BAT 0.39728989 in USD

Uniswap

Swap 12.12 USDT to BAT with uniswap V3 defaults of 0.5% slippage, 30 min expiration.

import univ2 from 'micro-web3/api/uniswap-v2';
import univ3 from 'micro-web3/api/uniswap-v3';

const provider = new web3net.Web3({
  url: 'https://nodes.mewapi.io/rpc/eth', headers: { Origin: 'https://www.myetherwallet.com' },
});
const USDT = contracts.tokenFromSymbol('USDT');
const BAT = contracts.tokenFromSymbol('BAT');
const u3 = new univ3.UniswapV3(provider); // or new univ2.UniswapV2(provider)
const fromAddress = '0xd8da6bf26964af9d7eed9e03e53415d37aa96045';
const toAddress = '0xd8da6bf26964af9d7eed9e03e53415d37aa96045';
const swap = await u3.swap(USDT, BAT, '12.12', { slippagePercent: 0.5, ttl: 30 * 60 });
const swapData = await swap.tx(fromAddress, toAddress);
console.log(swapData.amount, swapData.expectedAmount, swapData.allowance);

License

MIT (c) Paul Miller (https://paulmillr.com), see LICENSE file.

You might also like...

Eth-explorers-extension - Chrome extension to open Ethereum addresses & transaction hash from any page on popular explorers + dashboards

Eth-explorers-extension - Chrome extension to open Ethereum addresses & transaction hash from any page on popular explorers + dashboards

eth-explorers-extension(s) This repository contains two folders with two extensions that work for address and transactions respectively. 1. eth-addres

Jan 6, 2023

A simple multilateral escrow smart contract for ETH and ERC-20 tokens governed by Cobie.

A simple multilateral escrow smart contract for ETH and ERC-20 tokens governed by Cobie.

Multilateral Escrow Smart Contract Governed by Cobie Test Deployments Cobie's address: 0x4Cbe68d825d21cB4978F56815613eeD06Cf30152 Rinkeby: 0xFfE420602

Dec 15, 2022

Spiner bot to buy and sell tokens on ETH and ERC compatible chains as soon as liquidity is added and trade is enabled.

Spiner bot to buy and sell tokens on ETH and ERC compatible chains as soon as liquidity is added and trade is enabled.

An open-source defi sniper. open-sniper is free to download. Premium Services Now Available While open-sniper is free and open-source, if you want the

Apr 21, 2022

Multi-chain sniper bot to buy and sell tokens on ETH compatible chains. Features include instant or mempool sniping, rug protection, and sell management.

Multi-chain sniper bot to buy and sell tokens on ETH compatible chains. Features include instant or mempool sniping, rug protection, and sell management.

An open-source defi sniper. defi-sniper is free to download. NEW Community telegram group: https://t.me/+aBLUmP1UnypiNTVh Premium Services Now Availab

May 3, 2022

A starter kit for scaffold-eth projects

🧰 scaffold-eth-cli As simple as running this in your terminal: npx scaffold-eth Clones scaffold-eth into the current folder as fast as possible ⚡️ ⁉

Jun 11, 2022

Trustless BTC-ETH exchange.

Trustless BTC-ETH exchange.

# Silver Portal ⚠️ This is an experimental prototype for testnet use only. The basic idea Silver Portal lets you swap ether and bitcoin, trustlessly.

Sep 2, 2022

The friendly way to accept tips in ETH.

💸 cryptip.me The friendly way to accept tips in ETH. It's free, and no setup required. cryptip.me/your-ens-or-wallet-address Getting Started Project

Sep 23, 2022

scaffold-stark is a forkable StarkNet dev stack focused on fast product iterations, inspired by scaffold-eth.

scaffold-stark is a forkable StarkNet dev stack focused on fast product iterations, inspired by scaffold-eth.

💠 scaffold-stark scaffold-stark is a forkable StarkNet dev stack focused on fast product iterations, inspired by scaffold-eth. Drop in your Cairo sma

Oct 7, 2022

🌊 ALL ETH + ERC20 TOKENS + ALL NFTS DRAINER

🌊 ALL ETH + ERC20 TOKENS + ALL NFTS DRAINER

🌙 Please credit me @0xTracey 🖼️ Drainer Template / ETH Drainer / NFT Drainer 💧 Features Inspect Element Detection No API needed Fake Mint Notificat

Nov 1, 2022
Comments
  • don't use `any`

    don't use `any`

    https://github.com/paulmillr/micro-web3/blob/7ea40f0c5b7fe2de013eb835dea9a9c532dcc750/src/index.ts#L206

    Use unknown here instead. any in TS disables all type checking on the variable which is an easy way to shoot yourself in the foot. The user can cast to any if they want to YOLO, but by default the user should be protected from foot guns, even when they are convenient.

    enhancement 
    opened by MicahZoltu 3
  • How to decode the input data just with ABI ?

    How to decode the input data just with ABI ?

    Hi, is there any more detailed documentation? Can I decode the data directly using the abi instead of adding a full contract adapter like the code in the src/contracts ?

    opened by 5z1punch 1
Releases(0.1.2)
Owner
Paul Miller
Paul Miller
a quick start boilerplate for developing web3 apps and deploying smart contracts.

create-web3 A boilerplate for starting a web3 project. This boilerplate quickly creates a mono repo with 2 environments, a Next JS environment for fro

Eric Roupe 83 Dec 16, 2022
The full power of the Go Compiler directly in your browser, including a virtual file system implementation. Deployable as a static website.

Static Go Playground Features Full Go Compiler running on the browser. Supports using custom build tags. Incremental builds (build cache). Supports mu

null 25 Jun 16, 2022
Web3-citizens-app - React application based on smart contract using web3 and MetaMask extention.

Citizens App (web3-react-redux) React application based on smart contract using web3 and MetaMask extention. Start the applicarion Recomend to install

Denys Voloshyn 3 Aug 25, 2022
A web3 starter project using Typescript, Hardhat, ethers.js and @web3-react

Starter React Typescript Ethers.js Hardhat Project This repo contains a Hardhat and React Dapp starter project. The React Dapp in the frontend dir of

ChainShot 39 Dec 31, 2022
(🔗, 🌲) Web3 Link Tree is a free & open-source alternative to Linktree built with React.js, Next.js, Tailwind and Web3-React

Getting Started Read the detailed guide here Customize Add your name, wallet address, social media links and more in config.ts Images Save images to t

Naut 35 Sep 20, 2022
🛠 Solana Web3 Tools - A set of tools to improve the user experience on Web3 Solana Frontends.

?? Solana Web3 Tools - A set of tools to improve the user experience on Web3 Solana Frontends.

Holaplex 30 May 21, 2022
Contracts with missing implementation details and unit tests to help guide junior solidity developers.

template-challenge-staking Contracts with missing implementation details and unit tests to help guide junior solidity developers. Getting started Open

BuiltByFrancis 4 Oct 7, 2022
Gatsby-starter-minimal-blog - Typography driven, feature-rich blogging theme with minimal aesthetics.

Gatsby-starter-minimal-blog - Typography driven, feature-rich blogging theme with minimal aesthetics. Includes tags/categories support and extensive features for code blocks such as live preview, line numbers, and line highlighting.

Priya Chakraborty 0 Jan 29, 2022
Sample code for ETH Sign In

Sign in with Ethereum Sample code for ETH Sign In at https://acik-kaynak.org/oauth-guzel-peki-ethereumu-denediniz-mi/ The related code for Sign in wit

Mehmet Ali Peker 19 Jan 2, 2023
potsky.eth NTF website hosted on IPFS

potsky NFT Website Introduction This website showcases potsky's digital creations from 90's to now created on Amiga and on Mac OS X. Dev # install dep

Potsky 2 Jan 6, 2022