npm package: @jasm7314/0g-devtools-sdk
Description: Minimal JS SDK for 0G (EVM): providers, wallet, deploy/read/write, events.
Latest version: 0.1.6

# @jasm7314/sdk

A lightweight JavaScript SDK for interacting with the 0G EVM chain. It simplifies building dApps, indexers, and dev tools by providing helpers for providers, wallets, contracts, and event handling, reducing boilerplate code.

## ✨ Features

- 🌐 Easy provider setup for HTTP and WebSocket connections
- 🔑 Wallet management: Connect with private keys and send native tokens
- 📜 Contract interactions: Deploy, read from, and write to smart contracts
- 📊 Event handling: Fetch historical logs or monitor live events with WebSocket or polling fallback
- 🔁 Built-in retries with exponential backoff for reliable RPC calls

## 📦 Installation

Install the SDK and its peer dependency:
```
npm install @jasm7314/sdk ethers
```

or
```
pnpm add @jasm7314/sdk ethers
```
or
```
yarn add @jasm7314/sdk ethers
```

**Requirements:**

- Node.js 18 or higher
- ESM support (add `"type": "module"` to your `package.json`)

## ⚙️ Setup

Set up environment variables for your 0G endpoints and private key. Use a `.env` file for security:

```
ZEROG_RPC="https://rpc.0g.network"
ZEROG_WS="wss://ws.0g.network"
PRIV_KEY="0xabc...your_private_key"
```

Load them in your code using `process.env` or a library like `dotenv`.

## 🚀 Quickstart

Here's a complete example to get you started. This deploys a simple Counter contract, interacts with it, and monitors events.

```
import {
  createProviders,
  createWallet,
  sendNative,
  deployContract,
  callRead,
  sendWrite,
  getPastEvents,
  watchEvents
} from "@jasm7314/sdk";
import fs from "node:fs";

// Load environment variables
const rpcUrl = process.env.ZEROG_RPC;
const wsUrl = process.env.ZEROG_WS;
const privateKey = process.env.PRIV_KEY;

// 1. Create providers
const { http, ws } = createProviders({ rpcUrl, wsUrl });

// 2. Create a wallet
const { wallet } = createWallet({ privateKey, rpcUrl });

// 3. Send native tokens (example)
await sendNative({ wallet, to: "0xRecipientAddress", valueEth: "0.1" });

// 4. Deploy a contract
const artifact = JSON.parse(fs.readFileSync("./out/Counter.json", "utf8"));
const abi = artifact.abi;
const bytecode = artifact.bytecode;

const { address, transactionHash } = await deployContract({
  rpcUrl,
  privateKey,
  abi,
  bytecode,
  // constructorArgs: [] // if needed
});
console.log(`Deployed at: ${address} (tx: ${transactionHash})`);

// 5. Read from contract
const value = await callRead({ rpcUrl, address, abi, functionName: "value" });
console.log(`Current value: ${value.toString()}`);

// 6. Write to contract
const txReceipt = await sendWrite({
  rpcUrl,
  privateKey,
  address,
  abi,
  functionName: "increment",
  // args: [] // if needed
});
console.log(`Incremented (tx: ${txReceipt.transactionHash})`);

// 7. Fetch past events
const pastLogs = await getPastEvents({
  rpcUrl,
  address,
  abi,
  eventName: "Incremented",
  fromBlock: 0,
  toBlock: "latest"
});
console.log(`Past Incremented events: ${pastLogs.length}`);

// 8. Watch live events
const stopWatching = watchEvents({
  rpcUrl,
  wsUrl,
  address,
  abi,
  eventName: "Incremented",
  onEvent: (event) => console.log("New event:", event.parsed?.args),
  onError: (err) => console.error("Event watcher error:", err)
});

// To stop watching later:
stopWatching();
```

## 📖 API Reference

### Providers

- `createProviders(options: { rpcUrl: string, wsUrl?: string, expectedChainId?: number, staticNetwork?: boolean }) => { http: ethers.Provider, ws?: ethers.Provider }`  
  Creates HTTP and optional WebSocket providers.

### Wallet

- `createWallet(options: { privateKey: string, rpcUrl: string }) => { wallet: ethers.Wallet, provider: ethers.Provider }`  
  Initializes a wallet connected to the provider.
- `sendNative(options: { wallet: ethers.Wallet, to: string, valueEth: string }) => Promise<ethers.TransactionReceipt>`  
  Sends native tokens (e.g., ETH) to an address.

### Contracts

- `deployContract(options: { rpcUrl: string, privateKey: string, abi: any[], bytecode: string, constructorArgs?: any[] }) => Promise<{ address: string, transactionHash: string }>`  
  Deploys a contract and returns its address and tx hash.
- `callRead(options: { rpcUrl: string, address: string, abi: any[], functionName: string, args?: any[] }) => Promise<any>`  
  Calls a read-only function.
- `sendWrite(options: { rpcUrl: string, privateKey: string, address: string, abi: any[], functionName: string, args?: any[] }) => Promise<ethers.TransactionReceipt>`  
  Executes a write transaction.

### Events

- `getPastEvents(options: { rpcUrl: string, address: string, abi: any[], eventName?: string, fromBlock?: number | string, toBlock?: number | string }) => Promise<any[]>`  
  Retrieves and decodes past event logs.
- `watchEvents(options: { rpcUrl: string, wsUrl?: string, address: string, abi: any[], eventName?: string, onEvent: (event: any) => void, onError?: (err: Error) => void }) => () => void`  
  Sets up live event monitoring; returns a stop function.

## 🧪 Example Contract

Use this simple Counter contract for testing:

```
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract Counter {
uint256 public value;
event Incremented(address indexed by, uint256 newValue);


function increment() external {
value += 1;
emit Incremented(msg.sender, value);
}
}

```

Compile with Hardhat or Foundry to get ABI and bytecode.

## 🔒 Security Notes

- Never hardcode or commit private keys—use environment variables or secret managers.
- Specify `expectedChainId` to prevent accidental network switches.
- Be aware of chain reorganizations; query from a safe block depth in production.

## 🗺️ Roadmap

- Add multicall support for batched operations
- Integrate contract verification tools (e.g., Sourcify if supported by 0G)
- Include prebuilt filters for common events (e.g., ERC20 transfers)
- Support for account abstraction (if available on 0G)

## 🤝 Contributing

Contributions are welcome! Please open an issue or pull request on the repository.

## 📝 License

MIT License. See [LICENSE](LICENSE) for details.