varaeth
v0.0.1
Published
Typescript library for interacting with Gear.exe
Readme
Gear.exe TypeScript API
A comprehensive TypeScript library for interacting with Gear.exe, a revolutionary decentralized compute network that enhances Ethereum's computational capabilities without requiring bridges or fragmented liquidity.
What is Gear.exe?
Gear.exe is a groundbreaking decentralized compute network designed to significantly enhance the computational capabilities of Ethereum. Unlike conventional Layer-2 solutions, Gear.exe provides:
- Real-time, high-performance, parallel execution environment
- Near-zero gas fees for intensive computations
- Instant finalization and seamless Ethereum integration
- Up to 2GB memory per program for resource-heavy computations
- Multi-threaded execution supporting parallel processing
- Rust-based programming for performance and safety
- No asset bridging required - full Ethereum integration
Each program in Gear.exe operates as its own individual rollup, collectively forming a "swarm of rollups" that delivers unparalleled flexibility and scalability.
Installation
Install the package using npm or yarn:
npm install gearexeyarn add gearexePeer Dependencies
The library requires ethers v6.14+ as a peer dependency:
npm install ethers@^6.14Key Features
- 🔗 Ethereum Integration: Seamless interaction with Ethereum smart contracts
- ⚡ High Performance: Multi-threaded execution with near-zero gas fees
- 🔒 Type Safety: Full TypeScript support with strict typing
- 🛠️ Developer Tools: Comprehensive APIs for program management
- 💰 Cost Efficient: Reverse gas model and reduced computation costs
- 🚀 Real-time: Instant pre-confirmations with blockchain security
Core Concepts
Programs
WebAssembly (WASM) programs running on Gear.exe that handle computationally intensive logic extracted from Solidity contracts.
Router Contract
The main entry point for creating programs and managing code validation on the Ethereum side.
Ref: Router Contract
Mirror Contract
Represents a deployed program on Ethereum, enabling message sending and state management.
Ref: Mirror Contract
Wrapped VARA (wVARA)
ERC20 representation of VARA tokens used for gas payments and program interactions.
Ref: Wrapped VARA
Quick Start
import {
GearExeApi,
HttpGearexeProvider,
getRouterContract,
getMirrorContract,
getWrappedVaraContract
} from 'gearexe';
import { ethers } from 'ethers';
// Initialize API and wallet
const api = new GearExeApi(new HttpGearexeProvider('http://localhost:9944'));
const wallet = new ethers.Wallet(privateKey, provider);
// Get contract instances
const router = getRouterContract(routerAddress, wallet);
const wvara = getWrappedVaraContract(wvaraAddress, wallet);Main Functionality
1. Code Upload and Validation
Upload and validate WebAssembly code before creating programs:
import * as fs from 'fs';
// Upload code for validation
const code = fs.readFileSync('path/to/program.wasm');
const txManager = await router.requestCodeValidation(code);
await txManager.sendAndWaitForReceipt();
// Wait for validation
const isValidated = await tx.waitForCodeGotValidated();
console.log('Code validated:', isValidated);2. Program Creation
Create programs from validated code:
// Create a new program
const createTx = await router.createProgram(codeId);
await createTx.send();
// Get the program ID
const programId = await createTx.getProgramId();
// Get mirror contract for program interaction
const mirror = getMirrorContract(programId, wallet);3. Program State Management
Query and manage program state:
// Check if program is active
const stateHash = await mirror.stateHash();
const state = await api.query.program.readState(stateHash);
console.log('Program active:', 'Active' in state.program);
// Get program code ID
const codeId = await api.query.program.codeId(programId);
// List all program IDs
const programIds = await api.query.program.getIds();4. Message Sending
Send messages to programs with payload encoding.
Most likely program is written with Sails framework so sails-js library can be used to encode payloads.
const payload = `<payload encoded by sails-js library>`;
const tx = await mirror.sendMessage(payload, 0n);
await tx.send();
// Handle reply
const { waitForReply: waitIncrement } = await tx.setupReplyListener();
const { payload: replyPayload, replyCode, value } = await waitIncrement;
const result = sails.services.Counter.functions.Increment.decodeResult(replyPayload);5. Balance Management
Manage wrapped VARA tokens for program operations:
// Check balance
const balance = await wvara.balanceOf(wallet.address);
console.log('wVARA balance:', balance.toString());
// Approve spending
const approveTx = await wvara.approve(programId, BigInt(10 * 1e12));
await approveTx.send();
// Check allowance
const allowance = await wvara.allowance(wallet.address, programId);
console.log('Allowance:', allowance.toString());
// Top up executable balance
const topUpTx = await mirror.executableBalanceTopUp(BigInt(10 * 1e12));
const { status } = await topUpTx.sendAndWaitForReceipt();6. State Queries
Perform read-only operations on program state:
// Calculate reply for handle call
const queryPayload = sails.services.Counter.queries.GetValue.encodePayload();
const reply = await api.call.program.calculateReplyForHandle(
sourceAddress,
programId,
queryPayload
);
// Decode result
const value = sails.services.Counter.queries.GetValue.decodeResult(reply.payload);
console.log('Current counter value:', value);7. Transaction Management
Advanced transaction handling with the TxManager (see section 8 for detailed TxManager functionality):
// Create transaction with custom options
const tx = await router.createProgram(codeId);
// Send and get receipt
const receipt = await tx.sendAndWaitForReceipt();
console.log('Transaction status:', receipt.status);
// Get transaction response
const response = await tx.send();
console.log('Transaction hash:', response.hash);
// Access transaction events using TxManager
const event = await tx.findEvent('ProgramCreated');
console.log('Program created:', event.args);
// Use contract-specific helper functions
const programId = await tx.getProgramId(); // Custom helper function8. Transaction Manager (TxManager)
The TxManager is a core component that handles all Ethereum transactions in the gearexe library. It provides a unified interface for transaction lifecycle management with TypeScript generics support for extensibility.
Key Features
- Generic Type Support: Allows custom helper functions for transaction-specific operations
- Transaction Lifecycle Management: From gas estimation to receipt handling
- Event Processing: Automatic event parsing and retrieval from transaction receipts
- Type Safety: Full TypeScript support with interface definitions
Core Methods
class TxManager<T = object, U = object> {
// Send transaction to network
async send(): Promise<TransactionResponse>;
// Send and wait for confirmation
async sendAndWaitForReceipt(): Promise<TransactionReceipt>;
// Get transaction receipt
async getReceipt(): Promise<TransactionReceipt>;
// Estimate gas for transaction
async estimateGas(): Promise<bigint>;
// Find specific events in receipt
async findEvent(eventName: string): Promise<EventLog>;
// Get transaction request details
getTx(): TransactionRequest;
}Usage Examples
// Basic transaction handling
const tx = await router.createProgram(codeId);
await tx.send();
const receipt = await tx.getReceipt();
// With gas estimation
await tx.estimateGas();
const gasLimit = tx.getTx().gasLimit;
// Event handling
const transferEvent = await tx.findEvent('Transfer');
console.log('Transfer event:', transferEvent.args);
// Custom helper functions (transaction-dependent)
const txWithHelpers = new TxManager(
wallet,
transactionRequest,
contractInterface,
{
// Helper function that depends on this transaction
getProgramId: (manager) => async () => {
const event = await manager.findEvent('ProgramCreated');
return event.args.programId;
}
}
);
// Use the helper function
const programId = await txWithHelpers.getProgramId();Helper Functions
The TxManager supports two types of helper functions:
- Transaction-Dependent Helpers: Functions that need access to the transaction manager instance
- Transaction-Independent Helpers: Static utility functions
// Example from router contract
const createTx = new TxManager(
wallet,
request,
interface,
{
// Transaction-dependent: needs access to transaction events
getProgramId: (manager) => async () => {
const event = await manager.findEvent('ProgramCreated');
return event.args.programId;
},
waitForCodeGotValidated: (manager) => async () => {
// Custom logic for waiting for validation
return new Promise(resolve => {
// Implementation details...
});
}
},
{
// Transaction-independent: utility functions
processDevBlob: async () => {
// Development-specific processing
}
}
);This design pattern ensures type safety while providing flexibility for contract-specific operations.
API Reference
GearExeApi
Main API class for interacting with Gear.exe:
class GearExeApi {
constructor(provider: IGearExeProvider);
// Query methods (read-only)
query: {
program: {
getIds(): Promise<string[]>;
readState(hash: string): Promise<ProgramState>;
codeId(programId: string): Promise<string>;
};
};
// Call methods (transactions)
call: {
program: {
calculateReplyForHandle(
source: string,
program: string,
payload: string
): Promise<ReplyInfo>;
};
};
}Contract Utilities
Helper functions for contract interaction:
// Get contract instances
function getRouterContract(address: string, signer: Signer): RouterContract;
function getMirrorContract(address: string, signer: Signer): MirrorContract;
function getWrappedVaraContract(address: string, signer: Signer): WrappedVaraContract;Providers
Network communication providers:
// HTTP provider for standard requests
class HttpGearexeProvider implements IGearExeProvider {
constructor(url?: string); // defaults to 'http://127.0.0.1:9944'
}
// WebSocket provider for real-time subscriptions
class WsGearexeProvider implements IGearExeProvider {
constructor(url?: string); // defaults to 'ws://127.0.0.1:9944'
}Development
Building
yarn buildTesting
yarn testTypeScript Support
The library is built with strict TypeScript support, providing:
- Full type safety for all API interactions
- Interface definitions for contracts and responses
- Generic type support for transaction management
- JSDoc documentation for all public APIs
Error Handling
The library provides comprehensive error handling:
try {
const result = await api.call.program.calculateReplyForHandle(
sourceId,
invalidProgramId,
payload
);
} catch (error) {
console.error('Program call failed:', error.message);
}Contributing
Contributions are welcome! Please check the contributing guidelines for details.
License
This project is licensed under the GPL 3.0 License - see the LICENSE file for details.
Resources
- Gear.exe Whitepaper - Comprehensive technical documentation
- Gear Wiki - Developer documentation and guides
- Gear IDEA - Online IDE for Gear program development
- Vara Network - The Gear Protocol mainnet
Questions or Issues?
If you have questions about the gearexe library functionality, need clarification on any features, or encounter issues:
- Check the Gear Wiki for comprehensive documentation
- Review the test examples in this repository for practical usage patterns
- Open an issue in this repository for bug reports or feature requests
- Join the Gear Discord for community support
Is anything unclear in this documentation? Please let us know what needs better explanation!
