or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mdethereum-provider.mdindex.mdnetwork-management.mdwallet-operations.mdwidget-management.md

ethereum-provider.mddocs/

0

# Ethereum Provider

1

2

EIP-1193 compliant Ethereum provider for Web3 interactions, RPC requests, and blockchain operations.

3

4

## Capabilities

5

6

### Provider Access

7

8

Access the Ethereum provider instance for Web3 operations.

9

10

```typescript { .api }

11

/** Main Ethereum provider instance (EIP-1193 compliant) */

12

readonly provider: TorusInpageProvider;

13

14

/** Alias for provider (for compatibility) */

15

readonly ethereum: TorusInpageProvider;

16

```

17

18

**Usage Example:**

19

20

```typescript

21

// Access provider

22

const provider = torus.provider;

23

24

// Use with web3 libraries

25

import Web3 from "web3";

26

const web3 = new Web3(provider);

27

28

// Use with ethers.js

29

import { ethers } from "ethers";

30

const ethersProvider = new ethers.providers.Web3Provider(provider);

31

```

32

33

### RPC Request Method

34

35

Primary method for making JSON-RPC requests to the Ethereum network.

36

37

```typescript { .api }

38

/**

39

* Submit RPC request per EIP-1193 specification

40

* @param args - Request arguments containing method and parameters

41

* @returns Promise resolving to the result of the method call

42

*/

43

request<T>(args: RequestArguments): Promise<Maybe<T>>;

44

45

interface RequestArguments {

46

/** The RPC method to request */

47

method: string;

48

/** The parameters for the RPC method */

49

params?: unknown[] | Record<string, unknown>;

50

}

51

52

type Maybe<T> = Partial<T> | null | undefined;

53

```

54

55

**Usage Examples:**

56

57

```typescript

58

// Get account balance

59

const balance = await torus.provider.request({

60

method: "eth_getBalance",

61

params: [address, "latest"]

62

});

63

64

// Send transaction

65

const txHash = await torus.provider.request({

66

method: "eth_sendTransaction",

67

params: [{

68

from: address,

69

to: "0x742d35Cc6765C788200b9aa5FdCFD9A3ebFCF2d7",

70

value: "0xde0b6b3a7640000", // 1 ETH in wei

71

gas: "0x5208" // 21000 gas

72

}]

73

});

74

75

// Sign message

76

const signature = await torus.provider.request({

77

method: "personal_sign",

78

params: ["Hello World", address]

79

});

80

81

// Get network information

82

const chainId = await torus.provider.request({

83

method: "eth_chainId"

84

});

85

86

const networkVersion = await torus.provider.request({

87

method: "net_version"

88

});

89

```

90

91

### Connection Status

92

93

Check provider connection status.

94

95

```typescript { .api }

96

/**

97

* Check if the provider is connected to Torus

98

* @returns Boolean indicating connection status

99

*/

100

isConnected(): boolean;

101

```

102

103

**Usage Example:**

104

105

```typescript

106

if (torus.provider.isConnected()) {

107

console.log("Provider is connected");

108

// Safe to make RPC requests

109

} else {

110

console.log("Provider not connected");

111

// Need to wait for connection or re-initialize

112

}

113

```

114

115

### Legacy Methods (Deprecated)

116

117

For backward compatibility with older dApps.

118

119

```typescript { .api }

120

/**

121

* Legacy callback-based RPC method (deprecated - use request() instead)

122

* @param payload - JSON-RPC request object

123

* @param callback - Error-first callback function

124

*/

125

sendAsync(payload: JRPCRequest<unknown>, callback: (error: Error | null, result?: JRPCResponse<unknown>) => void): void;

126

127

/**

128

* Legacy send methods (deprecated - use request() instead)

129

* Multiple overloads for backward compatibility

130

*/

131

send(method: string, params?: unknown[]): Promise<JRPCResponse<unknown>>;

132

send(payload: JRPCRequest<unknown>, callback: Function): void;

133

send(payload: SendSyncJsonRpcRequest): JRPCResponse<unknown>;

134

```

135

136

**Migration Example:**

137

138

```typescript

139

// Old way (deprecated)

140

torus.provider.sendAsync({

141

method: "eth_getBalance",

142

params: [address, "latest"]

143

}, (error, result) => {

144

if (error) {

145

console.error(error);

146

} else {

147

console.log("Balance:", result.result);

148

}

149

});

150

151

// New way (recommended)

152

try {

153

const balance = await torus.provider.request({

154

method: "eth_getBalance",

155

params: [address, "latest"]

156

});

157

console.log("Balance:", balance);

158

} catch (error) {

159

console.error(error);

160

}

161

```

162

163

### Provider Properties

164

165

Access current provider state information.

166

167

```typescript { .api }

168

/** Current chain ID in hex format (null if not connected) */

169

readonly chainId: string | null;

170

171

/** Currently selected account address (null if not connected/logged in) */

172

readonly selectedAddress: string | null;

173

174

/** Current network version identifier */

175

readonly networkVersion: string | null;

176

177

/** Always true - identifies this as a Torus provider */

178

readonly isTorus: true;

179

180

/** Whether metadata should be sent automatically */

181

readonly shouldSendMetadata: boolean;

182

183

/** Legacy enable function for compatibility */

184

readonly enable: () => Promise<string[]>;

185

186

/** Function for handling preopen requests */

187

readonly tryPreopenHandle: (payload: UnvalidatedJsonRpcRequest | UnvalidatedJsonRpcRequest[], cb: (...args: unknown[]) => void) => void;

188

```

189

190

**Usage Example:**

191

192

```typescript

193

// Check current state

194

console.log("Provider state:", {

195

chainId: torus.provider.chainId,

196

selectedAddress: torus.provider.selectedAddress,

197

networkVersion: torus.provider.networkVersion,

198

connected: torus.provider.isConnected()

199

});

200

201

// Legacy enable (for older dApps)

202

const accounts = await torus.provider.enable();

203

console.log("Enabled accounts:", accounts);

204

```

205

206

### Event Handling

207

208

The provider emits events for state changes (extends SafeEventEmitter).

209

210

```typescript { .api }

211

// Event types (standard EIP-1193 events)

212

provider.on("connect", (connectInfo) => {

213

console.log("Provider connected:", connectInfo);

214

});

215

216

provider.on("disconnect", (error) => {

217

console.log("Provider disconnected:", error);

218

});

219

220

provider.on("accountsChanged", (accounts) => {

221

console.log("Accounts changed:", accounts);

222

});

223

224

provider.on("chainChanged", (chainId) => {

225

console.log("Chain changed:", chainId);

226

});

227

228

provider.on("message", (message) => {

229

console.log("Provider message:", message);

230

});

231

```

232

233

**Complete Event Handling Example:**

234

235

```typescript

236

// Set up all provider event handlers

237

function setupProviderEvents() {

238

const provider = torus.provider;

239

240

provider.on("connect", (connectInfo) => {

241

console.log("Connected to chain:", connectInfo.chainId);

242

updateUI({ connected: true });

243

});

244

245

provider.on("disconnect", (error) => {

246

console.error("Provider disconnected:", error);

247

updateUI({ connected: false });

248

});

249

250

provider.on("accountsChanged", (accounts) => {

251

if (accounts.length === 0) {

252

console.log("User disconnected all accounts");

253

updateUI({ account: null });

254

} else {

255

console.log("Active account:", accounts[0]);

256

updateUI({ account: accounts[0] });

257

}

258

});

259

260

provider.on("chainChanged", (chainId) => {

261

console.log("Network changed to:", chainId);

262

updateUI({ chainId });

263

// Reload the page to avoid issues with stale state

264

window.location.reload();

265

});

266

}

267

```

268

269

### Common RPC Methods

270

271

Frequently used Ethereum JSON-RPC methods.

272

273

```typescript { .api }

274

// Account and balance information

275

eth_accounts // Get available accounts

276

eth_getBalance // Get account balance

277

eth_getTransactionCount // Get account nonce

278

279

// Transaction methods

280

eth_sendTransaction // Send transaction

281

eth_signTransaction // Sign transaction

282

eth_getTransactionReceipt // Get transaction receipt

283

284

// Message signing

285

personal_sign // Sign message

286

eth_signTypedData_v4 // Sign typed data (EIP-712)

287

288

// Network information

289

eth_chainId // Get chain ID

290

net_version // Get network version

291

eth_blockNumber // Get latest block number

292

293

// Smart contract interaction

294

eth_call // Call contract method

295

eth_estimateGas // Estimate gas for transaction

296

eth_getLogs // Get contract event logs

297

298

// Wallet management

299

wallet_addEthereumChain // Add custom network

300

wallet_switchEthereumChain // Switch networks

301

wallet_requestPermissions // Request permissions

302

```

303

304

### Error Handling

305

306

Proper error handling for provider requests.

307

308

```typescript

309

try {

310

const result = await torus.provider.request({

311

method: "eth_sendTransaction",

312

params: [transactionObject]

313

});

314

console.log("Transaction sent:", result);

315

} catch (error) {

316

// Handle different error types

317

if (error.code === 4001) {

318

console.log("User rejected the request");

319

} else if (error.code === -32602) {

320

console.error("Invalid request parameters");

321

} else if (error.code === -32603) {

322

console.error("Internal JSON-RPC error");

323

} else {

324

console.error("Unexpected error:", error.message);

325

}

326

}

327

```

328

329

### TypeScript Integration

330

331

Full TypeScript support with proper typing.

332

333

```typescript { .api }

334

interface JRPCRequest<T> {

335

id?: string | number;

336

jsonrpc: "2.0";

337

method: string;

338

params?: T;

339

}

340

341

interface JRPCResponse<T> {

342

id: string | number;

343

jsonrpc: "2.0";

344

result?: T;

345

error?: {

346

code: number;

347

message: string;

348

data?: unknown;

349

};

350

}

351

352

interface UnvalidatedJsonRpcRequest {

353

id?: string | number;

354

jsonrpc?: string;

355

method: string;

356

params?: unknown;

357

preopenInstanceId?: string;

358

}

359

360

interface SendSyncJsonRpcRequest extends JRPCRequest<unknown> {

361

method: "eth_accounts" | "eth_coinbase" | "eth_uninstallFilter" | "net_version";

362

}

363

```