near-kit 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +473 -2
  3. package/dist/contracts/contract.d.ts +63 -0
  4. package/dist/contracts/contract.d.ts.map +1 -0
  5. package/dist/contracts/contract.js +42 -0
  6. package/dist/contracts/contract.js.map +1 -0
  7. package/dist/contracts/index.d.ts +5 -0
  8. package/dist/contracts/index.d.ts.map +1 -0
  9. package/dist/contracts/index.js +5 -0
  10. package/dist/contracts/index.js.map +1 -0
  11. package/dist/core/actions.d.ts +193 -0
  12. package/dist/core/actions.d.ts.map +1 -0
  13. package/dist/core/actions.js +195 -0
  14. package/dist/core/actions.js.map +1 -0
  15. package/dist/core/config-schemas.d.ts +179 -0
  16. package/dist/core/config-schemas.d.ts.map +1 -0
  17. package/dist/core/config-schemas.js +169 -0
  18. package/dist/core/config-schemas.js.map +1 -0
  19. package/dist/core/constants.d.ts +43 -0
  20. package/dist/core/constants.d.ts.map +1 -0
  21. package/dist/core/constants.js +49 -0
  22. package/dist/core/constants.js.map +1 -0
  23. package/dist/core/near.d.ts +301 -0
  24. package/dist/core/near.d.ts.map +1 -0
  25. package/dist/core/near.js +504 -0
  26. package/dist/core/near.js.map +1 -0
  27. package/dist/core/nonce-manager.d.ts +39 -0
  28. package/dist/core/nonce-manager.d.ts.map +1 -0
  29. package/dist/core/nonce-manager.js +73 -0
  30. package/dist/core/nonce-manager.js.map +1 -0
  31. package/dist/core/rpc/rpc-error-handler.d.ts +60 -0
  32. package/dist/core/rpc/rpc-error-handler.d.ts.map +1 -0
  33. package/dist/core/rpc/rpc-error-handler.js +324 -0
  34. package/dist/core/rpc/rpc-error-handler.js.map +1 -0
  35. package/dist/core/rpc/rpc-schemas.d.ts +1812 -0
  36. package/dist/core/rpc/rpc-schemas.d.ts.map +1 -0
  37. package/dist/core/rpc/rpc-schemas.js +424 -0
  38. package/dist/core/rpc/rpc-schemas.js.map +1 -0
  39. package/dist/core/rpc/rpc.d.ts +117 -0
  40. package/dist/core/rpc/rpc.d.ts.map +1 -0
  41. package/dist/core/rpc/rpc.js +325 -0
  42. package/dist/core/rpc/rpc.js.map +1 -0
  43. package/dist/core/schema.d.ts +1188 -0
  44. package/dist/core/schema.d.ts.map +1 -0
  45. package/dist/core/schema.js +396 -0
  46. package/dist/core/schema.js.map +1 -0
  47. package/dist/core/transaction.d.ts +390 -0
  48. package/dist/core/transaction.d.ts.map +1 -0
  49. package/dist/core/transaction.js +653 -0
  50. package/dist/core/transaction.js.map +1 -0
  51. package/dist/core/types.d.ts +271 -0
  52. package/dist/core/types.d.ts.map +1 -0
  53. package/dist/core/types.js +9 -0
  54. package/dist/core/types.js.map +1 -0
  55. package/dist/errors/index.d.ts +226 -0
  56. package/dist/errors/index.d.ts.map +1 -0
  57. package/dist/errors/index.js +366 -0
  58. package/dist/errors/index.js.map +1 -0
  59. package/dist/index.d.ts +16 -0
  60. package/dist/index.d.ts.map +1 -0
  61. package/dist/index.js +23 -0
  62. package/dist/index.js.map +1 -0
  63. package/dist/keys/credential-schemas.d.ts +98 -0
  64. package/dist/keys/credential-schemas.d.ts.map +1 -0
  65. package/dist/keys/credential-schemas.js +128 -0
  66. package/dist/keys/credential-schemas.js.map +1 -0
  67. package/dist/keys/file-keystore.d.ts +130 -0
  68. package/dist/keys/file-keystore.d.ts.map +1 -0
  69. package/dist/keys/file-keystore.js +266 -0
  70. package/dist/keys/file-keystore.js.map +1 -0
  71. package/dist/keys/in-memory-keystore.d.ts +71 -0
  72. package/dist/keys/in-memory-keystore.d.ts.map +1 -0
  73. package/dist/keys/in-memory-keystore.js +85 -0
  74. package/dist/keys/in-memory-keystore.js.map +1 -0
  75. package/dist/keys/index.d.ts +14 -0
  76. package/dist/keys/index.d.ts.map +1 -0
  77. package/dist/keys/index.js +20 -0
  78. package/dist/keys/index.js.map +1 -0
  79. package/dist/keys/native-keystore.d.ts +111 -0
  80. package/dist/keys/native-keystore.d.ts.map +1 -0
  81. package/dist/keys/native-keystore.js +167 -0
  82. package/dist/keys/native-keystore.js.map +1 -0
  83. package/dist/keys/rotating-keystore.d.ts +207 -0
  84. package/dist/keys/rotating-keystore.d.ts.map +1 -0
  85. package/dist/keys/rotating-keystore.js +240 -0
  86. package/dist/keys/rotating-keystore.js.map +1 -0
  87. package/dist/sandbox/index.d.ts +6 -0
  88. package/dist/sandbox/index.d.ts.map +1 -0
  89. package/dist/sandbox/index.js +5 -0
  90. package/dist/sandbox/index.js.map +1 -0
  91. package/dist/sandbox/sandbox.d.ts +55 -0
  92. package/dist/sandbox/sandbox.d.ts.map +1 -0
  93. package/dist/sandbox/sandbox.js +341 -0
  94. package/dist/sandbox/sandbox.js.map +1 -0
  95. package/dist/utils/amount.d.ts +76 -0
  96. package/dist/utils/amount.d.ts.map +1 -0
  97. package/dist/utils/amount.js +137 -0
  98. package/dist/utils/amount.js.map +1 -0
  99. package/dist/utils/gas.d.ts +69 -0
  100. package/dist/utils/gas.d.ts.map +1 -0
  101. package/dist/utils/gas.js +92 -0
  102. package/dist/utils/gas.js.map +1 -0
  103. package/dist/utils/index.d.ts +14 -0
  104. package/dist/utils/index.d.ts.map +1 -0
  105. package/dist/utils/index.js +14 -0
  106. package/dist/utils/index.js.map +1 -0
  107. package/dist/utils/key.d.ts +117 -0
  108. package/dist/utils/key.d.ts.map +1 -0
  109. package/dist/utils/key.js +270 -0
  110. package/dist/utils/key.js.map +1 -0
  111. package/dist/utils/nep413.d.ts +97 -0
  112. package/dist/utils/nep413.d.ts.map +1 -0
  113. package/dist/utils/nep413.js +154 -0
  114. package/dist/utils/nep413.js.map +1 -0
  115. package/dist/utils/validation.d.ts +114 -0
  116. package/dist/utils/validation.d.ts.map +1 -0
  117. package/dist/utils/validation.js +150 -0
  118. package/dist/utils/validation.js.map +1 -0
  119. package/dist/wallets/adapters.d.ts +119 -0
  120. package/dist/wallets/adapters.d.ts.map +1 -0
  121. package/dist/wallets/adapters.js +267 -0
  122. package/dist/wallets/adapters.js.map +1 -0
  123. package/dist/wallets/index.d.ts +11 -0
  124. package/dist/wallets/index.d.ts.map +1 -0
  125. package/dist/wallets/index.js +2 -0
  126. package/dist/wallets/index.js.map +1 -0
  127. package/dist/wallets/types.d.ts +99 -0
  128. package/dist/wallets/types.d.ts.map +1 -0
  129. package/dist/wallets/types.js +10 -0
  130. package/dist/wallets/types.js.map +1 -0
  131. package/package.json +78 -7
  132. package/index.js +0 -1
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 r-near
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,6 +1,477 @@
1
1
  # near-kit
2
2
 
3
- Reserved package name for a modern NEAR client toolkit.
3
+ [![npm version](https://img.shields.io/npm/v/near-kit.svg)](https://www.npmjs.com/package/near-kit)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.9-blue.svg)](https://www.typescriptlang.org/)
4
6
 
5
- > ⚠️ This is a placeholder publish. The API is under active design and may change without notice.
7
+ A simple, intuitive TypeScript library for interacting with NEAR Protocol. Designed to feel like a modern fetch library - easy for beginners, powerful for advanced users.
6
8
 
9
+ **[📚 Full Documentation](https://kit.near.tools)**
10
+
11
+ ## Features
12
+
13
+ - **Simple things should be simple** - One-line commands for common operations
14
+ - **Type safety everywhere** - Full TypeScript support with IDE autocomplete
15
+ - **Progressive complexity** - Basic API for simple needs, advanced features when required
16
+ - **Powerful transaction builder** - Fluent, human-readable API for transactions
17
+ - **Wallet-ready** - Full support for [HOT Connector](https://github.com/azbang/hot-connector) and [NEAR Wallet Selector](https://github.com/near/wallet-selector), drop-in integration
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ npm install near-kit
23
+ # or
24
+ bun install near-kit
25
+ ```
26
+
27
+ ## Quick Start
28
+
29
+ ```typescript
30
+ import { Near } from "near-kit"
31
+
32
+ // Initialize for backend/scripts
33
+ const near = new Near({
34
+ network: "testnet",
35
+ privateKey: "ed25519:...",
36
+ defaultSignerId: "alice.testnet",
37
+ })
38
+
39
+ // View methods (read-only, no gas)
40
+ const balance = await near.view("example.testnet", "get_balance", {
41
+ account_id: "alice.testnet",
42
+ })
43
+
44
+ // Call methods (requires signature, costs gas)
45
+ await near.call(
46
+ "example.testnet",
47
+ "increment",
48
+ {},
49
+ {attachedDeposit: "0.1 NEAR"}
50
+ )
51
+
52
+ // Send NEAR tokens
53
+ await near.send("bob.testnet", "5 NEAR")
54
+ ```
55
+
56
+ ## Getting Started
57
+
58
+ near-kit provides a unified API that works across different environments. Configuration varies by environment, but the API for calling contracts, sending transactions, and building transactions remains identical.
59
+
60
+ ### Backend & Scripts
61
+
62
+ For local testing, use the sandbox (no network or key configuration needed):
63
+
64
+ ```typescript
65
+ import { Sandbox } from "near-kit"
66
+
67
+ const sandbox = await Sandbox.start()
68
+ const near = new Near({ network: sandbox })
69
+
70
+ // Test with automatically provisioned accounts
71
+ await near.call("contract.test.near", "method", {})
72
+
73
+ await sandbox.stop()
74
+ ```
75
+
76
+ For testnet/mainnet development, pass a private key directly:
77
+
78
+ ```typescript
79
+ const near = new Near({
80
+ network: "testnet",
81
+ privateKey: "ed25519:...",
82
+ defaultSignerId: "alice.testnet",
83
+ })
84
+ ```
85
+
86
+ For production applications, use a keyStore:
87
+
88
+ ```typescript
89
+ import { FileKeyStore } from "near-kit"
90
+
91
+ const near = new Near({
92
+ network: "testnet",
93
+ keyStore: new FileKeyStore("~/.near-credentials"),
94
+ })
95
+ ```
96
+
97
+ ### Frontend & Wallets
98
+
99
+ In the browser, connect to user wallets. The same `near.call()`, `near.send()`, and `near.transaction()` methods work seamlessly:
100
+
101
+ ```typescript
102
+ import { fromWalletSelector } from "near-kit"
103
+
104
+ const near = new Near({
105
+ network: "testnet",
106
+ wallet: fromWalletSelector(walletInstance),
107
+ })
108
+
109
+ // Same API as backend
110
+ await near.call("contract.near", "method", { arg: "value" })
111
+ ```
112
+
113
+ This works through a signer abstraction - whether you pass `privateKey`, `keyStore`, `wallet`, or `sandbox`, they all implement the same signing interface internally.
114
+
115
+ ## Core API
116
+
117
+ ### Initialization
118
+
119
+ ```typescript
120
+ // Simple - defaults to mainnet
121
+ const near = new Near()
122
+
123
+ // With network selection
124
+ const near = new Near({ network: "testnet" })
125
+
126
+ // With custom configuration
127
+ const near = new Near({
128
+ network: "testnet",
129
+ privateKey: "ed25519:...",
130
+ })
131
+ ```
132
+
133
+ ### Basic Operations
134
+
135
+ ```typescript
136
+ // View methods (free, no signature required)
137
+ const result = await near.view("contract.near", "get_data", { key: "value" })
138
+
139
+ // Check account balance
140
+ const balance = await near.getBalance("alice.near")
141
+
142
+ // Check if account exists
143
+ const exists = await near.accountExists("alice.near")
144
+
145
+ // Get network status
146
+ const status = await near.getStatus()
147
+ ```
148
+
149
+ ### Type-Safe Contracts
150
+
151
+ ```typescript
152
+ import type { Contract } from "near-kit"
153
+
154
+ // Define contract interface using Contract<> helper
155
+ type MyContract = Contract<{
156
+ view: {
157
+ get_balance: (args: { account_id: string }) => Promise<string>
158
+ get_info: () => Promise<{ name: string; version: string }>
159
+ }
160
+ call: {
161
+ // Just define args - options parameter automatically added!
162
+ transfer: (args: { to: string; amount: string }) => Promise<void>
163
+ }
164
+ }>
165
+
166
+ // Create type-safe contract
167
+ const contract = near.contract<MyContract>("example.near")
168
+
169
+ // Fully typed method calls
170
+ const balance = await contract.view.get_balance({ account_id: "alice.near" })
171
+ const info = await contract.view.get_info()
172
+
173
+ // Call methods automatically get options parameter
174
+ await contract.call.transfer(
175
+ { to: "bob.near", amount: "10" },
176
+ { attachedDeposit: "1 NEAR" }
177
+ )
178
+ ```
179
+
180
+ ### Transaction Builder
181
+
182
+ ```typescript
183
+ // Alice builds a transaction with multiple actions
184
+ // 'alice.near' is the signer - the account that signs and pays for this transaction
185
+ const receipt = await near
186
+ .transaction("alice.near") // Alice signs
187
+ .transfer("bob.near", "10 NEAR") // Alice sends Bob 10 NEAR
188
+ .functionCall(
189
+ "market.near",
190
+ "buy",
191
+ { id: "123" },
192
+ { attachedDeposit: "5 NEAR" } // Alice attaches 5 NEAR to the call
193
+ )
194
+ .send()
195
+ ```
196
+
197
+ ### Batch Operations
198
+
199
+ ```typescript
200
+ // Run multiple operations in parallel
201
+ const [balance, status, exists] = await near.batch(
202
+ near.getBalance("alice.near"),
203
+ near.getStatus(),
204
+ near.accountExists("bob.near")
205
+ )
206
+ ```
207
+
208
+ ## Local Testing with Sandbox
209
+
210
+ ```typescript
211
+ import { Sandbox } from "near-kit"
212
+
213
+ const sandbox = await Sandbox.start()
214
+ const near = new Near({ network: sandbox })
215
+ // ... run tests
216
+ await sandbox.stop()
217
+ ```
218
+
219
+ **With test framework:**
220
+
221
+ ```typescript
222
+ let sandbox: Sandbox
223
+ beforeAll(async () => {
224
+ sandbox = await Sandbox.start()
225
+ })
226
+ afterAll(async () => {
227
+ await sandbox.stop()
228
+ })
229
+ ```
230
+
231
+ ## Key Management
232
+
233
+ ```typescript
234
+ import { InMemoryKeyStore, FileKeyStore, RotatingKeyStore } from "near-kit"
235
+
236
+ // In-memory (runtime only)
237
+ const near = new Near({
238
+ keyStore: new InMemoryKeyStore({
239
+ "alice.near": "ed25519:...",
240
+ }),
241
+ })
242
+
243
+ // File-based (persistent)
244
+ const near = new Near({
245
+ keyStore: new FileKeyStore("~/.near-credentials"),
246
+ })
247
+
248
+ // Rotating keys for high-throughput concurrent transactions
249
+ const near = new Near({
250
+ keyStore: new RotatingKeyStore({
251
+ "alice.near": [
252
+ "ed25519:key1...",
253
+ "ed25519:key2...",
254
+ "ed25519:key3...",
255
+ ],
256
+ }),
257
+ })
258
+ ```
259
+
260
+ ## Wallet Integration
261
+
262
+ near-kit integrates with Wallet Selector and HOT Connector through a signer abstraction. Wallet adapters are converted to signers via `fromWalletSelector()` and `fromHotConnect()` shims, allowing the same API to work across backend and frontend without separate client implementations.
263
+
264
+ ### NEAR Wallet Selector
265
+
266
+ ```typescript
267
+ import { Near, fromWalletSelector } from "near-kit"
268
+ import { setupWalletSelector } from "@near-wallet-selector/core"
269
+ import { setupMyNearWallet } from "@near-wallet-selector/my-near-wallet"
270
+ import { setupHereWallet } from "@near-wallet-selector/here-wallet"
271
+
272
+ // Setup wallet selector
273
+ const selector = await setupWalletSelector({
274
+ network: "testnet",
275
+ modules: [setupMyNearWallet(), setupHereWallet()],
276
+ })
277
+
278
+ // Get wallet instance (after user connects)
279
+ const wallet = await selector.wallet()
280
+
281
+ // Use with near-kit
282
+ const near = new Near({
283
+ network: "testnet",
284
+ wallet: fromWalletSelector(wallet),
285
+ })
286
+
287
+ // All operations now use the wallet for signing
288
+ await near.call("contract.near", "method", { arg: "value" })
289
+ await near.send("bob.near", "10 NEAR")
290
+ ```
291
+
292
+ ### HOT Connector
293
+
294
+ ```typescript
295
+ import { Near, fromHotConnect } from "near-kit"
296
+ import { NearConnector } from "@hot-labs/near-connect"
297
+
298
+ // Create connector
299
+ const connector = new NearConnector({ network: "testnet" })
300
+
301
+ // Wait for user to connect
302
+ connector.on("wallet:signIn", async () => {
303
+ const near = new Near({
304
+ network: "testnet",
305
+ wallet: fromHotConnect(connector),
306
+ })
307
+
308
+ // Use near-kit with the connected wallet
309
+ await near.call("contract.near", "method", { arg: "value" })
310
+ })
311
+
312
+ // Trigger wallet connection
313
+ await connector.signIn()
314
+ ```
315
+
316
+ ## Error Handling
317
+
318
+ Errors are organized by category and include detailed context for debugging. Use `instanceof` checks to handle specific error types.
319
+
320
+ #### Network Errors
321
+
322
+ ```typescript
323
+ import { NetworkError, TimeoutError } from "near-kit"
324
+
325
+ try {
326
+ await near.call("contract.near", "method", {})
327
+ } catch (error) {
328
+ if (error instanceof TimeoutError) {
329
+ console.log("Request timed out - already retried automatically")
330
+ } else if (error instanceof NetworkError) {
331
+ // Handle other network issues
332
+ }
333
+ }
334
+ ```
335
+
336
+ #### Transaction Errors
337
+
338
+ ```typescript
339
+ import { InsufficientBalanceError, InvalidNonceError } from "near-kit"
340
+
341
+ try {
342
+ await near.send("bob.near", "1000000 NEAR")
343
+ } catch (error) {
344
+ if (error instanceof InsufficientBalanceError) {
345
+ console.log(`Need ${error.required}, have ${error.available}`)
346
+ } else if (error instanceof InvalidNonceError) {
347
+ // Already retried automatically - only thrown if retries exhausted
348
+ }
349
+ }
350
+ ```
351
+
352
+ #### Contract Errors
353
+
354
+ ```typescript
355
+ import { FunctionCallError } from "near-kit"
356
+
357
+ try {
358
+ await near.call("contract.near", "method", {})
359
+ } catch (error) {
360
+ if (error instanceof FunctionCallError) {
361
+ console.log(`Contract panicked: ${error.panic}`)
362
+ console.log(`Logs:`, error.logs)
363
+ }
364
+ }
365
+ ```
366
+
367
+ ## Advanced Features
368
+
369
+ ### Batch Actions (Multi-Action Transactions)
370
+
371
+ Deploy and initialize a contract in a single transaction:
372
+
373
+ ```typescript
374
+ const contractWasm = await fs.readFile("./contract.wasm")
375
+
376
+ await near
377
+ .transaction("alice.near")
378
+ .createAccount("contract.alice.near")
379
+ .transfer("contract.alice.near", "10 NEAR")
380
+ .deployContract("contract.alice.near", contractWasm)
381
+ .functionCall("contract.alice.near", "init", { owner: "alice.near" })
382
+ .send()
383
+ ```
384
+
385
+ ### NEP-413 Message Signing
386
+
387
+ Authenticate users without gas fees:
388
+
389
+ ```typescript
390
+ const signedMessage = await near.signMessage({
391
+ message: "Login to MyApp",
392
+ recipient: "myapp.near",
393
+ nonce: crypto.getRandomValues(new Uint8Array(32)),
394
+ })
395
+
396
+ // Send to backend for verification
397
+ await fetch("/api/auth", {
398
+ method: "POST",
399
+ body: JSON.stringify(signedMessage),
400
+ })
401
+ ```
402
+
403
+ ### Delegate Actions (NEP-366)
404
+
405
+ Enable meta-transactions and sponsored transactions where a relayer pays the gas:
406
+
407
+ ```typescript
408
+ // User creates and signs a delegate action (no gas cost to user)
409
+ const userNear = new Near({
410
+ network: "testnet",
411
+ privateKey: "ed25519:...", // User's key
412
+ })
413
+
414
+ const signedDelegateAction = await userNear
415
+ .transaction("user.near")
416
+ .transfer("recipient.near", "1 NEAR")
417
+ .delegate({ blockHeightOffset: 100 })
418
+
419
+ // Relayer submits the transaction (pays the gas)
420
+ const relayerNear = new Near({
421
+ network: "testnet",
422
+ privateKey: "ed25519:...", // Relayer's key
423
+ })
424
+
425
+ await relayerNear
426
+ .transaction("relayer.near")
427
+ .signedDelegateAction(signedDelegateAction)
428
+ .send()
429
+ ```
430
+
431
+ ### Automatic Nonce Management
432
+
433
+ No more nonce conflicts - the library handles nonce tracking and retries automatically:
434
+
435
+ ```typescript
436
+ // Safe to run multiple transactions concurrently
437
+ await Promise.all([
438
+ near.send("bob.near", "1 NEAR"),
439
+ near.send("charlie.near", "1 NEAR"),
440
+ near.send("dave.near", "1 NEAR"),
441
+ ])
442
+ // Nonces are automatically managed and conflicts are retried
443
+ ```
444
+
445
+ ### Smart Retry Logic
446
+
447
+ Automatic retries for network errors with exponential backoff:
448
+
449
+ ```typescript
450
+ try {
451
+ await near.call("contract.near", "method", {})
452
+ } catch (error) {
453
+ if (error instanceof TimeoutError && error.retryable) {
454
+ // Already retried automatically
455
+ }
456
+ }
457
+ ```
458
+
459
+ ## Development
460
+
461
+ ```bash
462
+ # Install dependencies
463
+ bun install
464
+
465
+ # Run tests
466
+ bun test
467
+
468
+ # Build
469
+ bun run build
470
+
471
+ # Run examples
472
+ bun run examples/quickstart.ts
473
+ ```
474
+
475
+ ## License
476
+
477
+ MIT
@@ -0,0 +1,63 @@
1
+ import type { Near } from "../core/near.js";
2
+ import type { CallOptions } from "../core/types.js";
3
+ /**
4
+ * Utility type to automatically add options parameter to call methods.
5
+ *
6
+ * Usage:
7
+ * ```typescript
8
+ * type MyContract = Contract<{
9
+ * view: {
10
+ * get_count: () => Promise<number>
11
+ * }
12
+ * call: {
13
+ * increment: (args: { amount: number }) => Promise<void>
14
+ * }
15
+ * }>
16
+ * ```
17
+ *
18
+ * The call method will automatically get an options parameter:
19
+ * increment: (args: { amount: number }, options?: CallOptions) => Promise<void>
20
+ */
21
+ export type Contract<T extends {
22
+ view: Record<string, (...args: any[]) => any>;
23
+ call: Record<string, (...args: any[]) => any>;
24
+ }> = {
25
+ view: T["view"];
26
+ call: {
27
+ [K in keyof T["call"]]: T["call"][K] extends (...args: infer TArgs) => infer TReturn ? TArgs extends [infer TFirstArg, ...infer _Rest] ? (args: TFirstArg, options?: CallOptions) => TReturn : (args?: undefined, options?: CallOptions) => TReturn : never;
28
+ };
29
+ };
30
+ /**
31
+ * Base contract method interface used by {@link Contract}.
32
+ *
33
+ * Methods can be defined as:
34
+ * - View methods: (args?: ArgsType | Uint8Array, options?: BlockReference) => Promise<ReturnType>
35
+ * - Call methods: (args?: ArgsType | Uint8Array, options?: CallOptions) => Promise<ReturnType>
36
+ *
37
+ * This is a base interface without index signatures to allow
38
+ * extending interfaces to define specific method signatures with type safety.
39
+ */
40
+ export interface ContractMethods {
41
+ view: Record<string, (...args: any[]) => Promise<any>>;
42
+ call: Record<string, (...args: any[]) => Promise<any>>;
43
+ }
44
+ /**
45
+ * Create a type-safe contract proxy for a NEAR contract.
46
+ *
47
+ * @param near - The {@link Near} client instance to use for calls.
48
+ * @param contractId - Account ID of the target contract.
49
+ *
50
+ * @returns A proxy implementing the given {@link ContractMethods} interface.
51
+ *
52
+ * @remarks
53
+ * Prefer using {@link Near.contract} instead of calling this function directly.
54
+ */
55
+ export declare function createContract<T extends ContractMethods>(near: Near, contractId: string): T;
56
+ /**
57
+ * Helper to extend {@link Near} prototype with a `contract` method.
58
+ *
59
+ * @internal This is used to keep the core {@link Near} implementation focused;
60
+ * library users should call {@link Near.contract} instead of using this helper.
61
+ */
62
+ export declare function addContractMethod(nearPrototype: typeof Near.prototype): void;
63
+ //# sourceMappingURL=contract.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../../src/contracts/contract.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AAEnD;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,MAAM,QAAQ,CAClB,CAAC,SAAS;IAER,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC,CAAA;IAE7C,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC,CAAA;CAC9C,IACC;IACF,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAA;IACf,IAAI,EAAE;SACH,CAAC,IAAI,MAAM,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAC3C,GAAG,IAAI,EAAE,MAAM,KAAK,KACjB,MAAM,OAAO,GACd,KAAK,SAAS,CAAC,MAAM,SAAS,EAAE,GAAG,MAAM,KAAK,CAAC,GAC7C,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC,EAAE,WAAW,KAAK,OAAO,GACnD,CAAC,IAAI,CAAC,EAAE,SAAS,EAAE,OAAO,CAAC,EAAE,WAAW,KAAK,OAAO,GACtD,KAAK;KACV,CAAA;CACF,CAAA;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,eAAe;IAE9B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC,CAAA;IAEtD,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC,CAAA;CACvD;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,cAAc,CAAC,CAAC,SAAS,eAAe,EACtD,IAAI,EAAE,IAAI,EACV,UAAU,EAAE,MAAM,GACjB,CAAC,CAiCH;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,aAAa,EAAE,OAAO,IAAI,CAAC,SAAS,GAAG,IAAI,CAO5E"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Create a type-safe contract proxy for a NEAR contract.
3
+ *
4
+ * @param near - The {@link Near} client instance to use for calls.
5
+ * @param contractId - Account ID of the target contract.
6
+ *
7
+ * @returns A proxy implementing the given {@link ContractMethods} interface.
8
+ *
9
+ * @remarks
10
+ * Prefer using {@link Near.contract} instead of calling this function directly.
11
+ */
12
+ export function createContract(near, contractId) {
13
+ const proxy = {
14
+ view: new Proxy({}, {
15
+ get: (_target, methodName) => {
16
+ return async (args, options) => {
17
+ return await near.view(contractId, methodName, args || {}, options);
18
+ };
19
+ },
20
+ }),
21
+ call: new Proxy({}, {
22
+ get: (_target, methodName) => {
23
+ return async (args, options) => {
24
+ return await near.call(contractId, methodName, args || {}, options || {});
25
+ };
26
+ },
27
+ }),
28
+ };
29
+ return proxy;
30
+ }
31
+ /**
32
+ * Helper to extend {@link Near} prototype with a `contract` method.
33
+ *
34
+ * @internal This is used to keep the core {@link Near} implementation focused;
35
+ * library users should call {@link Near.contract} instead of using this helper.
36
+ */
37
+ export function addContractMethod(nearPrototype) {
38
+ nearPrototype.contract = function (contractId) {
39
+ return createContract(this, contractId);
40
+ };
41
+ }
42
+ //# sourceMappingURL=contract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract.js","sourceRoot":"","sources":["../../src/contracts/contract.ts"],"names":[],"mappings":"AA2DA;;;;;;;;;;GAUG;AACH,MAAM,UAAU,cAAc,CAC5B,IAAU,EACV,UAAkB;IAElB,MAAM,KAAK,GAAG;QACZ,IAAI,EAAE,IAAI,KAAK,CACb,EAAE,EACF;YACE,GAAG,EAAE,CAAC,OAAO,EAAE,UAAkB,EAAE,EAAE;gBACnC,OAAO,KAAK,EACV,IAA0B,EAC1B,OAAwB,EACxB,EAAE;oBACF,OAAO,MAAM,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,IAAI,EAAE,EAAE,OAAO,CAAC,CAAA;gBACrE,CAAC,CAAA;YACH,CAAC;SACF,CACF;QACD,IAAI,EAAE,IAAI,KAAK,CACb,EAAE,EACF;YACE,GAAG,EAAE,CAAC,OAAO,EAAE,UAAkB,EAAE,EAAE;gBACnC,OAAO,KAAK,EAAE,IAA0B,EAAE,OAAqB,EAAE,EAAE;oBACjE,OAAO,MAAM,IAAI,CAAC,IAAI,CACpB,UAAU,EACV,UAAU,EACV,IAAI,IAAI,EAAE,EACV,OAAO,IAAI,EAAE,CACd,CAAA;gBACH,CAAC,CAAA;YACH,CAAC;SACF,CACF;KACF,CAAA;IAED,OAAO,KAAU,CAAA;AACnB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,aAAoC;IACpE,aAAa,CAAC,QAAQ,GAAG,UAEvB,UAAkB;QAElB,OAAO,cAAc,CAAI,IAAI,EAAE,UAAU,CAAC,CAAA;IAC5C,CAAC,CAAA;AACH,CAAC"}
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Contract interfaces and utilities
3
+ */
4
+ export * from "./contract.js";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/contracts/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,eAAe,CAAA"}
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Contract interfaces and utilities
3
+ */
4
+ export * from "./contract.js";
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/contracts/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,eAAe,CAAA"}