or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

api-initialization.mdblockchain-queries.mdevents-metadata.mdindex.mdnetwork-providers.mdrpc-operations.mdtransaction-submission.md

api-initialization.mddocs/

0

# API Initialization

1

2

Core API creation and connection management for both Promise and RxJS patterns. The @polkadot/api package provides two main API classes that share the same underlying functionality but differ in their async patterns.

3

4

## Capabilities

5

6

### ApiPromise Class

7

8

Promise-based API implementation for standard async/await patterns.

9

10

```typescript { .api }

11

class ApiPromise {

12

/**

13

* Create API instance and connect to provider

14

* @param options - Configuration options

15

* @returns Promise resolving to connected API instance

16

*/

17

static create(options?: ApiOptions): Promise<ApiPromise>;

18

19

/**

20

* Create API instance (requires manual ready check)

21

* @param options - Configuration options

22

*/

23

constructor(options?: ApiOptions);

24

25

/**

26

* Promise that resolves when API is connected and ready

27

*/

28

get isReady(): Promise<ApiPromise>;

29

30

/**

31

* Promise that resolves or rejects based on connection status

32

*/

33

get isReadyOrError(): Promise<ApiPromise>;

34

35

/**

36

* Create a new API instance with the same configuration

37

*/

38

clone(): ApiPromise;

39

40

/**

41

* Combine multiple subscription functions into a single callback

42

*/

43

combineLatest<T>(

44

fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[],

45

callback: CombinatorCallback<T>

46

): Promise<() => void>;

47

48

/**

49

* Connect to the underlying provider

50

*/

51

connect(): Promise<void>;

52

53

/**

54

* Disconnect from the underlying provider

55

*/

56

disconnect(): Promise<void>;

57

58

/**

59

* Set external signer for transactions

60

*/

61

setSigner(signer?: Signer): void;

62

}

63

```

64

65

### ApiRx Class

66

67

RxJS Observable-based API implementation for reactive programming patterns.

68

69

```typescript { .api }

70

class ApiRx {

71

/**

72

* Create API instance and return Observable of connected instance

73

* @param options - Configuration options

74

* @returns Observable emitting connected API instance

75

*/

76

static create(options?: ApiOptions): Observable<ApiRx>;

77

78

/**

79

* Create API instance (requires manual ready check)

80

* @param options - Configuration options

81

*/

82

constructor(options?: ApiOptions);

83

84

/**

85

* Observable that emits when API is connected and ready

86

*/

87

get isReady(): Observable<ApiRx>;

88

89

/**

90

* Create a new API instance with the same configuration

91

*/

92

clone(): ApiRx;

93

94

/**

95

* Connect to the underlying provider

96

*/

97

connect(): Promise<void>;

98

99

/**

100

* Disconnect from the underlying provider

101

*/

102

disconnect(): Promise<void>;

103

104

/**

105

* Set external signer for transactions

106

*/

107

setSigner(signer?: Signer): void;

108

}

109

```

110

111

### Configuration Options

112

113

Complete configuration interface for API initialization.

114

115

```typescript { .api }

116

interface ApiOptions {

117

/** Provider instance for blockchain connection */

118

provider?: ProviderInterface;

119

120

/** Custom type definitions for runtime types */

121

types?: RegistryTypes;

122

123

/** User-defined RPC methods */

124

rpc?: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>>;

125

126

/** Custom derive functions */

127

derives?: DeriveCustom;

128

129

/** Pre-bundled metadata by genesis hash and spec version */

130

metadata?: Record<string, HexString>;

131

132

/** Disable initialization warnings */

133

noInitWarn?: boolean;

134

135

/** Throw error on connection failure */

136

throwOnConnect?: boolean;

137

138

/** Throw error on unknown types */

139

throwOnUnknown?: boolean;

140

141

/** External transaction signer */

142

signer?: Signer;

143

144

/** Type registry instance */

145

registry?: Registry;

146

147

/** Chain-specific signed extensions */

148

signedExtensions?: ExtDef;

149

150

/** Source API for cloning */

151

source?: ApiBase<any>;

152

153

/** Initialize WASM libraries */

154

initWasm?: boolean;

155

156

/** Enable pedantic storage checking */

157

isPedantic?: boolean;

158

159

/** RPC cache capacity */

160

rpcCacheCapacity?: number;

161

162

/** Runtime call overrides */

163

runtime?: DefinitionsCall;

164

}

165

166

interface RegistryTypes {

167

[typeName: string]: string | object | any;

168

}

169

170

type CombinatorCallback<T> = (...args: T) => void;

171

172

type CombinatorFunction = (callback: (value: any) => void) => UnsubscribePromise;

173

174

type UnsubscribePromise = Promise<() => void>;

175

```

176

177

## Usage Examples

178

179

### Basic Promise API Initialization

180

181

```typescript

182

import { ApiPromise, WsProvider } from "@polkadot/api";

183

184

// Simple initialization with default provider

185

const api = await ApiPromise.create();

186

187

// With custom WebSocket provider

188

const provider = new WsProvider("wss://rpc.polkadot.io");

189

const api = await ApiPromise.create({ provider });

190

191

// With error handling

192

try {

193

const api = await ApiPromise.create({

194

provider: new WsProvider("wss://rpc.polkadot.io"),

195

throwOnConnect: true

196

});

197

console.log("Connected successfully");

198

} catch (error) {

199

console.error("Connection failed:", error);

200

}

201

```

202

203

### Basic RxJS API Initialization

204

205

```typescript

206

import { ApiRx, WsProvider } from "@polkadot/api";

207

import { switchMap } from "rxjs";

208

209

// Create and use API in RxJS chain

210

ApiRx.create({ provider: new WsProvider("wss://rpc.polkadot.io") })

211

.pipe(

212

switchMap((api) => api.rpc.chain.subscribeNewHeads())

213

)

214

.subscribe((header) => {

215

console.log(`New block #${header.number}`);

216

});

217

```

218

219

### Advanced Configuration

220

221

```typescript

222

import { ApiPromise, WsProvider } from "@polkadot/api";

223

224

const api = await ApiPromise.create({

225

provider: new WsProvider("wss://rpc.polkadot.io"),

226

types: {

227

// Custom type definitions

228

CustomStruct: {

229

id: "u32",

230

data: "Vec<u8>",

231

owner: "AccountId"

232

}

233

},

234

rpc: {

235

// Custom RPC methods

236

custom: {

237

getCustomData: {

238

description: "Get custom data",

239

params: [

240

{ name: "id", type: "u32" }

241

],

242

type: "CustomStruct"

243

}

244

}

245

},

246

derives: {

247

// Custom derive functions

248

custom: {

249

processedData: (instanceId, api) => (id) =>

250

api.rpc.custom.getCustomData(id).pipe(

251

map(data => ({ ...data, processed: true }))

252

)

253

}

254

}

255

});

256

```

257

258

### Manual Initialization

259

260

```typescript

261

import { ApiPromise, WsProvider } from "@polkadot/api";

262

263

// Create instance without auto-connection

264

const api = new ApiPromise({ provider: new WsProvider("wss://rpc.polkadot.io") });

265

266

// Wait for ready state

267

await api.isReady;

268

console.log("API is ready");

269

270

// Or handle errors

271

try {

272

await api.isReadyOrError;

273

console.log("API connected successfully");

274

} catch (error) {

275

console.error("API connection failed:", error);

276

}

277

```

278

279

### Connection Management

280

281

```typescript

282

import { ApiPromise, WsProvider } from "@polkadot/api";

283

284

const api = await ApiPromise.create({

285

provider: new WsProvider("wss://rpc.polkadot.io")

286

});

287

288

// Check connection status

289

console.log("Connected:", api.isConnected);

290

291

// Manually disconnect

292

await api.disconnect();

293

console.log("Disconnected");

294

295

// Reconnect

296

await api.connect();

297

console.log("Reconnected");

298

```

299

300

### Promise Combinators

301

302

```typescript

303

import { ApiPromise } from "@polkadot/api";

304

305

const api = await ApiPromise.create();

306

307

// Combine multiple subscriptions

308

const unsubscribe = await api.combineLatest([

309

api.rpc.chain.subscribeNewHeads,

310

(callback) => api.query.timestamp.now(callback)

311

], ([header, timestamp]) => {

312

console.log(`Block #${header.number} at ${timestamp}`);

313

});

314

315

// Stop subscriptions

316

unsubscribe();

317

```