-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLLM.txt
More file actions
4246 lines (3176 loc) · 118 KB
/
LLM.txt
File metadata and controls
4246 lines (3176 loc) · 118 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Frontend Integration
Source: https://kit.near.tools/dapp-workflow/frontend-integration
`near-kit` is designed to work seamlessly in browser environments. The logic for building transactions is identical to the server-side; the only difference is that signing is delegated to the user's wallet via an **Adapter**.
<Info>
**New to React?** Check out [`@near-kit/react`](/react/overview) for ready-to-use hooks that handle loading states, error handling, and integrate with React Query or SWR.
</Info>
## 🚀 Live Demo
See `near-kit` running in a real React application using both Wallet Selector and HOT Connector.
* **Live App:** [guestbook.near.tools](https://guestbook.near.tools/)
* **Source Code:** [github.com/r-near/near-kit-guestbook-demo](https://github.com/r-near/near-kit-guestbook-demo)
***
## The Adapter Pattern
You initialize the `Near` instance with a `wallet` object instead of a private key.
```typescript theme={null}
const near = new Near({
network: "testnet",
wallet: fromWalletSelector(wallet), // <--- The Adapter
})
```
Once initialized, you use `near` exactly as you would in a backend script. When you call `.send()`, the library automatically triggers the wallet's popup for the user to approve the transaction.
## 1. NEAR Wallet Selector
[`@near-wallet-selector`](https://github.com/near/wallet-selector) is a popular library for connecting to the NEAR ecosystem. It supports MyNearWallet, Meteor, Sender, Here, and many others.
### Setup
```typescript theme={null}
import { setupWalletSelector } from "@near-wallet-selector/core"
import { setupModal } from "@near-wallet-selector/modal-ui"
import { Near, fromWalletSelector } from "near-kit"
// 1. Initialize Wallet Selector (Standard Setup)
const selector = await setupWalletSelector({
network: "testnet",
modules: [
/* ... wallet modules ... */
],
})
const modal = setupModal(selector, { contractId: "guestbook.near" })
// 2. Connect
if (!selector.isSignedIn()) {
modal.show()
}
// 3. Create the Near Instance
const wallet = await selector.wallet()
const near = new Near({
network: "testnet",
wallet: fromWalletSelector(wallet),
})
// 4. Transact
await near.send("bob.near", "1 NEAR")
```
## 2. HOT Connector
[HOT Connector](https://github.com/azbang/hot-connector) is the new standard, and intended to replace NEAR Wallet Selector.
### Setup
```typescript theme={null}
import { NearConnector } from "@hot-labs/near-connect"
import { Near, fromHotConnect } from "near-kit"
// 1. Initialize Connector
const connector = new NearConnector({ network: "testnet" })
// 2. Listen for Sign In
connector.on("wallet:signIn", async (data) => {
// 3. Create Near Instance
const near = new Near({
network: "testnet",
wallet: fromHotConnect(connector),
})
console.log("Connected via HOT!")
})
// Trigger connection
connector.connect()
```
## Best Practice: React Context
<Tip>
For a more streamlined React experience with built-in hooks, see the [`@near-kit/react`](/react/overview) package which provides `NearProvider`, `useView`, `useCall`, and more.
</Tip>
In a React application, you should create a `WalletContext` to store the `Near` instance so it can be accessed by any component.
Here is a simplified pattern from the [Guestbook Demo](https://github.com/r-near/near-kit-guestbook-demo/blob/main/src/WalletProvider.tsx):
```jsx theme={null}
// WalletProvider.tsx
import { createContext, useContext, useEffect, useState } from "react"
import { Near, fromWalletSelector } from "near-kit"
const WalletContext = createContext<{ near: Near | null }>(null)
export const WalletProvider = ({ children }) => {
const [near, setNear] = useState<Near | null>(null)
useEffect(() => {
// ... setup selector ...
const wallet = await selector.wallet()
if (wallet) {
setNear(
new Near({
network: "testnet",
wallet: fromWalletSelector(wallet),
})
)
}
}, [])
return (
<WalletContext.Provider value={{ near }}>{children}</WalletContext.Provider>
)
}
// Use it in any component!
export const useWallet = () => useContext(WalletContext)
```
# Testing with Sandbox
Source: https://kit.near.tools/dapp-workflow/testing
Don't rely on Testnet for integration tests. It's slow, you need a faucet, and other people can mess up your state. `near-kit` includes a built-in **Sandbox** manager that runs a local NEAR node for you.
## Setup
We recommend using a test runner like `bun:test`, `jest`, or `vitest`.
```typescript theme={null}
import { Near } from "near-kit"
import { Sandbox } from "near-kit/sandbox"
import { beforeAll, afterAll, test, expect } from "bun:test"
let sandbox: Sandbox
let near: Near
// 1. Start Sandbox
beforeAll(async () => {
// This downloads a NEAR binary and starts a node locally
sandbox = await Sandbox.start()
// near-kit automatically configures the RPC and
// loads the root account key for you.
near = new Near({ network: sandbox })
})
// 2. Stop Sandbox
afterAll(async () => {
if (sandbox) await sandbox.stop()
})
// 3. Write Tests
test("can create account", async () => {
const newAccount = `test.${sandbox.rootAccount.id}`
await near
.transaction(sandbox.rootAccount.id)
.createAccount(newAccount)
.send()
const exists = await near.accountExists(newAccount)
expect(exists).toBe(true)
})
```
## Pre-Funded Accounts
The sandbox comes with one "Root Account" (`test.near`) that has a massive balance. Use this account to create sub-accounts for your tests.
```typescript theme={null}
const root = sandbox.rootAccount
console.log(root.id) // "test.near"
console.log(root.secretKey) // "ed25519:..."
```
## Custom Binary
By default, `Sandbox.start()` downloads the near-sandbox binary from NEAR's servers. You can use a local binary instead:
```typescript theme={null}
// Option 1: Pass the path directly
const sandbox = await Sandbox.start({
binaryPath: "/path/to/near-sandbox"
})
// Option 2: Set environment variable
// NEAR_SANDBOX_BIN_PATH=/path/to/near-sandbox
const sandbox = await Sandbox.start()
```
Priority order:
1. `binaryPath` option (if provided)
2. `NEAR_SANDBOX_BIN_PATH` environment variable
3. Download from NEAR's S3 bucket
This is useful for:
* CI environments with pre-cached binaries
* Testing against a custom-built sandbox
* Offline development
# The "Universal Code" Pattern
Source: https://kit.near.tools/dapp-workflow/universal-pattern
Write once, run anywhere - backend, frontend, or tests
One of `near-kit`'s superpowers is that it abstracts the "Signer."
Whether a transaction is signed by a generic private key, a secure server-side keystore, or a user's browser wallet, **the code to build and send that transaction is identical.**
This allows you to write "Universal Business Logic"—functions that define *what* to do, without caring *where* they are running.
## 1. The Business Logic
First, write your logic as a standalone function. It should accept a `Near` instance and a `signerId`.
```typescript theme={null}
// src/features/buy-item.ts
import { Near } from "near-kit"
/**
* Buys an item from the market.
* This function works on the Server, Client, and in Tests!
*/
export async function buyItem(near: Near, signerId: string, itemId: string) {
console.log(`Attempting to buy ${itemId} as ${signerId}...`)
return await near
.transaction(signerId)
.functionCall(
"market.near",
"buy",
{ item_id: itemId },
{ attachedDeposit: "1 NEAR", gas: "50 Tgas" }
)
.send()
}
```
## 2. Injecting the `Near` Instance
Now, let's see how to initialize the `Near` object for different environments.
<Tabs>
<Tab title="Script">
For simple scripts, passing a raw private key is the easiest method.
```typescript theme={null}
import { Near } from "near-kit"
import { buyItem } from "./features/buy-item"
const near = new Near({
network: "testnet",
privateKey: process.env.ADMIN_KEY, // "ed25519:..."
defaultSignerId: "admin.testnet",
})
await buyItem(near, "admin.testnet", "sword-1")
```
</Tab>
<Tab title="Backend">
In production server environments, you rarely handle raw private key strings manually. You use a `KeyStore`.
A `KeyStore` manages keys for multiple accounts. When you call `.transaction("alice.near")`, the `Near` instance automatically looks up Alice's key in the store.
```typescript theme={null}
import { Near } from "near-kit"
import { FileKeyStore } from "near-kit/keys/file" // Node.js only
import { buyItem } from "./features/buy-item"
// Load keys from the standard ~/.near-credentials directory
const keyStore = new FileKeyStore("~/.near-credentials", "testnet")
const near = new Near({
network: "testnet",
keyStore: keyStore, // Pass the store instead of a single key
})
// The Near instance will look inside ~/.near-credentials/testnet/worker.json
// to find the key for 'worker.testnet'
await buyItem(near, "worker.testnet", "sword-1")
```
<Tip>
**Why use a KeyStore?** It allows your app to manage multiple accounts (e.g., `worker-1`, `worker-2`, `admin`) seamlessly. You just switch the `signerId` argument, and `near-kit` finds the right key.
</Tip>
</Tab>
<Tab title="Frontend">
In the browser, you don't have private keys. You have a Wallet Adapter.
```typescript theme={null}
import { Near, fromWalletSelector } from "near-kit"
import { buyItem } from "./features/buy-item"
// ... setup wallet selector ...
const wallet = await selector.wallet()
const near = new Near({
network: "testnet",
wallet: fromWalletSelector(wallet), // Adapter handles signing
})
const userAccount = (await wallet.getAccounts())[0].accountId
// The wallet popup will appear for the user!
await buyItem(near, userAccount, "sword-1")
```
</Tab>
<Tab title="Testing">
In tests, `near-kit` auto-configures everything when you pass the sandbox object.
```typescript theme={null}
import { Near } from "near-kit"
import { Sandbox } from "near-kit/sandbox"
import { buyItem } from "./features/buy-item"
const sandbox = await Sandbox.start()
const near = new Near({
network: sandbox, // Auto-configures RPC and Root Key
})
await buyItem(near, sandbox.rootAccount.id, "sword-1")
```
</Tab>
</Tabs>
## Summary
| Environment | Config Option | Who Signs? |
| :----------- | :------------------ | :---------------------------------------------- |
| **Script** | `privateKey: "..."` | The provided key string. |
| **Backend** | `keyStore: store` | The key matching `signerId` found in the store. |
| **Frontend** | `wallet: adapter` | The user (via wallet popup). |
| **Sandbox** | `network: sandbox` | The root account key (in-memory). |
Your business logic (`buyItem`) never needs to know which one is happening.
# Reading Data
Source: https://kit.near.tools/essentials/reading-data
Reading data from the blockchain is free, fast, and does not require a private key (unless you are connecting to a private node).
## 1. Calling View Methods
Use `near.view()` to query smart contracts. This connects to the RPC and fetches the state directly.
### Basic Usage
Arguments are automatically JSON-serialized for you.
```typescript theme={null}
const messages = await near.view(
"guestbook.near", // Contract ID
"get_messages", // Method Name
{ limit: 10 } // Arguments object
)
```
### Typed Return Values
By default, `near.view` returns `any`. You can pass a generic type to get a strongly-typed response.
```typescript theme={null}
// Define what the contract returns
type Message = {
sender: string
text: string
}
// Pass the type to .view<T>()
const messages = await near.view<Message[]>("guestbook.near", "get_messages", {
limit: 10,
})
// Now 'messages' is typed as Message[]
console.log(messages[0].sender)
```
> **Pro Tip:** For even better type safety (including arguments), check out [Type-Safe Contracts](./type-safe-contracts).
## 2. Reading Historical Data (Time Travel)
By default, you read from the "Optimistic" head of the chain (the absolute latest state). Sometimes you need to read from a specific point in the past, or ensure you are reading fully finalized data.
Most read methods accept an options object as the last argument.
```typescript theme={null}
// Read from a specific Block Height
await near.view(
"token.near",
"ft_balance_of",
{ account_id: "alice.near" },
{
blockId: 120494923,
}
)
// Read from a specific Block Hash
await near.getBalance("alice.near", {
blockId: "GZ8vK...",
})
// Read only "Final" data (slower, but immutable)
await near.view(
"game.near",
"get_winner",
{},
{
finality: "final",
}
)
```
## 3. Checking Balances
### Available Balance
Use `near.getBalance()` to get the **available** (spendable) balance. This accounts for storage costs and staked tokens.
```typescript theme={null}
const available = await near.getBalance("alice.near")
console.log(`Can spend: ${available} NEAR`) // "98.50"
```
### Full Account State
Use `near.getAccount()` when you need all balance details:
```typescript theme={null}
const account = await near.getAccount("alice.near")
console.log(`Liquid balance: ${account.balance} NEAR`) // Total liquid tokens
console.log(`Available to spend: ${account.available} NEAR`) // What you can actually transfer
console.log(`Staked: ${account.staked} NEAR`) // Locked for staking (validators)
console.log(`Storage cost: ${account.storageUsage} NEAR`) // Reserved for on-chain storage
console.log(`Storage bytes: ${account.storageBytes}`) // Raw storage in bytes
console.log(`Has contract: ${account.hasContract}`) // Whether contract is deployed
```
<Note>
**Why is available different from balance?**
NEAR accounts must reserve tokens to pay for on-chain storage. However, staked tokens count towards this requirement. So:
* If staked ≥ storage cost → all liquid balance is available
* If staked \< storage cost → some liquid balance is reserved
This is why `getBalance()` returns `available`, not `balance` — it's what you can actually spend.
</Note>
## 4. Listing Access Keys
Use `near.getAccessKeys()` to list all access keys for an account.
```typescript theme={null}
const keys = await near.getAccessKeys("alice.near")
for (const key of keys.keys) {
console.log(key.public_key) // "ed25519:..."
if (key.access_key.permission === "FullAccess") {
console.log("Full access key")
} else {
// Function call key - has receiver_id, method_names, allowance
console.log("Function call key for:", key.access_key.permission.FunctionCall.receiver_id)
}
}
```
To get a single access key by public key, use `near.getAccessKey()`:
```typescript theme={null}
const accessKey = await near.getAccessKey("alice.near", "ed25519:...")
if (accessKey) {
console.log("Nonce:", accessKey.nonce)
}
```
## 5. Batching Requests
If you need to make multiple read calls at once, use `near.batch()`. This runs them in parallel (like `Promise.all`) but preserves the types of the results in the returned tuple.
```typescript theme={null}
const [balance, messages, exists] = await near.batch(
near.getBalance("alice.near"),
near.view<Message[]>("guestbook.near", "get_messages", {}),
near.accountExists("bob.near")
)
```
## 6. Network Status
Use `near.getStatus()` to check the health of the node and the latest block height.
```typescript theme={null}
const status = await near.getStatus()
console.log(`Latest Block: ${status.latestBlockHeight}`)
console.log(`Syncing: ${status.syncing}`)
```
# Type-Safe Contracts
Source: https://kit.near.tools/essentials/type-safe-contracts
Using `near.view` and `near.call` works well for quick scripts, but they are "stringly typed." If you misspell a method name or pass the wrong arguments, you won't know until your code crashes at runtime.
`near-kit` allows you to define a TypeScript interface for your contract. This gives you:
1. **Autocomplete** for method names.
2. **Type Checking** for arguments and return values.
3. **Inline Documentation** (if you add JSDoc comments).
## 1. Define the Interface
You define a type that passes a generic object to `Contract`. This object must have `view` and `call` properties describing your methods.
```typescript theme={null}
import type { Contract } from "near-kit"
// Define your data shapes
type Message = { sender: string; text: string }
// Define the contract type using the Generic syntax
type Guestbook = Contract<{
view: {
// MethodName: (args: Arguments) => Promise<ReturnValue>
get_messages: (args: { limit: number }) => Promise<Message[]>
total_messages: () => Promise<number>
}
call: {
// Call methods usually return void, but can return values too
add_message: (args: { text: string }) => Promise<void>
}
}>
```
## 2. Create the Proxy
Use the `near.contract<T>()` method to create a typed proxy for a specific contract ID.
```typescript theme={null}
// This object now has all the methods defined in your type
const guestbook = near.contract<Guestbook>("guestbook.near")
```
## 3. Use it!
You can now access methods directly under `.view` and `.call`.
### Calling Views
Arguments are passed as the first parameter.
```typescript theme={null}
// ✅ Autocomplete works here!
const messages = await guestbook.view.get_messages({ limit: 5 })
// ❌ TypeScript Error: Argument 'limit' is missing
// const messages = await guestbook.view.get_messages({});
```
### Calling Change Methods
Change methods take two arguments:
1. **Args:** The arguments for the contract function.
2. **Options:** (Optional) Gas and Attached Deposit.
```typescript theme={null}
await guestbook.call.add_message(
{ text: "Hello Types!" }, // 1. Contract Args
{ gas: "30 Tgas", attachedDeposit: "0.1 NEAR" } // 2. Transaction Options
)
```
# Writing Data (Transactions)
Source: https://kit.near.tools/essentials/writing-data
To change state on the blockchain (send money, write to a contract), you must send a transaction. Transactions cost **Gas** and must be signed by an account with a private key.
## 1. The Transaction Builder
The primary way to write data is the fluent **Transaction Builder**. It allows you to chain multiple actions into a single, atomic package.
```typescript theme={null}
const result = await near
.transaction("alice.near") // 1. Who is paying? (Signer)
.functionCall(
// 2. Action
"guestbook.near",
"add_message",
{ text: "Hello World" }
)
.send() // 3. Sign & Broadcast
```
## 2. Atomicity (Batching Actions)
You can chain multiple actions in one transaction. **This is atomic**: either every action succeeds, or the entire transaction is rolled back.
This is perfect for scenarios like "Create an account AND fund it AND deploy a contract."
```typescript theme={null}
await near
.transaction("alice.near")
.createAccount("bob.alice.near") // 1. Create
.transfer("bob.alice.near", "1 NEAR") // 2. Fund
.deployContract("bob.alice.near", code) // 3. Deploy Code
.functionCall("bob.alice.near", "init", {}) // 4. Initialize
.send()
```
If the `init` call fails, the account `bob.alice.near` will not be created, and the 1 NEAR will stay with Alice.
## 3. Attaching Gas & Deposits
When calling a function, you often need to attach Gas (computation limit) or a Deposit (real NEAR tokens).
These are passed as the 4th argument (the `options` object) to `.functionCall`.
```typescript theme={null}
await near
.transaction("alice.near")
.functionCall(
"nft.near",
"mint_token",
{ token_id: "1" },
{
gas: "100 Tgas", // Limit for complex operations
attachedDeposit: "0.1 NEAR", // Payment (e.g. for storage)
}
)
.send()
```
* **Gas:** Defaults to 30 Tgas. Increase this for complex calculations.
* **Deposit:** Defaults to 0. Required if the contract needs to pay for storage or if you are transferring value to a contract.
## 4. Working with Amounts (Dynamic Values)
For dynamic calculations, use the `Amount` helper instead of manually constructing strings:
```typescript theme={null}
import { Amount } from "near-kit"
// Dynamic NEAR amounts
const basePrice = 5
const quantity = 2
await near.send("bob.near", Amount.NEAR(basePrice * quantity)) // "10 NEAR"
// Fractional amounts
await near.send("bob.near", Amount.NEAR(10.5)) // "10.5 NEAR"
// YoctoNEAR (10^-24 NEAR) for precise calculations
await near.send("bob.near", Amount.yocto(1000000n)) // "1000000 yocto"
// Or pass bigint directly (treated as yoctoNEAR)
await near.send("bob.near", 1000000n)
```
**Constants:**
* `Amount.ZERO` → `"0 yocto"`
* `Amount.ONE_NEAR` → `"1 NEAR"`
* `Amount.ONE_YOCTO` → `"1 yocto"`
## 5. Shortcuts
For simple, single-action transactions, `near-kit` provides shortcuts. These are just syntax sugar around the builder.
```typescript theme={null}
// Shortcut for .transaction().transfer().send()
await near.send("bob.near", "5 NEAR")
// Shortcut for .transaction().functionCall().send()
await near.call("counter.near", "increment", {})
```
## 6. Inspecting the Result
The `.send()` method returns a `FinalExecutionOutcome` object. This contains everything that happened on-chain.
```typescript theme={null}
const result = await near.call(...);
// ✅ Check the Transaction Hash
console.log("Tx Hash:", result.transaction.hash);
// 📜 Check Logs
// Logs from ALL receipts in the transaction are collected here
const logs = result.receipts_outcome.flatMap(r => r.outcome.logs);
console.log("Contract Logs:", logs);
// 📦 Get the Return Value
// If the contract returned data (e.g. a JSON object), it's base64 encoded here.
if (result.status.SuccessValue) {
const raw = Buffer.from(result.status.SuccessValue, 'base64').toString();
const value = JSON.parse(raw);
console.log("Returned:", value);
}
```
## 7. Execution Speed (WaitUntil)
By default, `.send()` waits until the transaction is "Optimistically Executed" (usually 1-2 seconds). You can change this behavior.
```typescript theme={null}
// Fast: Returns as soon as the network accepts it. No return value available.
.send({ waitUntil: "INCLUDED" })
// Slow: Waits for full BFT Finality (extra 2-3 seconds). 100% irreversible.
.send({ waitUntil: "FINAL" })
```
# Advanced Transactions
Source: https://kit.near.tools/in-depth/advanced-transactions
The `TransactionBuilder` allows you to orchestrate complex account management and state changes. Understanding how these actions execute is critical for writing safe smart contracts and scripts.
## 1. Atomicity & Execution
All actions added to a single transaction are executed **sequentially as one atomic unit on-chain**:
* If **all actions succeed**, the state changes produced by those actions are committed and any promises (cross-contract calls) they created are emitted.
* If **any action fails** (e.g. a function call panics, a transfer hits insufficient balance, etc.), the entire transaction is reverted.
In other words: **within one transaction / receipt, it’s all-or-nothing.**
<Warning title="The atomicity boundary stops at the transaction itself">
Cross-contract calls created *by* your transaction run later as separate receipts. Once those child receipts have been emitted and executed on other contracts, their effects are **not** automatically rolled back if something else fails later—you must implement any "compensating logic" yourself.
</Warning>
## 2. The "Factory" Pattern (Batching)
Because of the atomicity rules above, we can safely use the "Factory" pattern: creating a new sub-account, funding it, deploying a contract to it, and initializing that contract—all in one transaction.
<Tip title="Why do it this way?">
If you deploy a contract but forget to initialize it, anyone could call `init` and take ownership. By bundling `deploy` and `init` in one atomic transaction, you guarantee that **only you** can initialize it, and if initialization fails, the account creation is rolled back entirely.
</Tip>
```typescript theme={null}
import { generateKey } from "near-kit"
import { readFileSync } from "fs"
const wasm = readFileSync("./token.wasm")
const newKey = generateKey() // Generate a fresh KeyPair
const newAccountId = "token.alice.near"
await near
.transaction("alice.near")
// 1. Create the account on-chain
.createAccount(newAccountId)
// 2. Fund it (needs storage for the contract)
.transfer(newAccountId, "6 NEAR")
// 3. Add a Full Access Key so we can control it later
.addKey(newKey.publicKey.toString(), { type: "fullAccess" })
// 4. Deploy the compiled Wasm
.deployContract(newAccountId, wasm)
// 5. Initialize the contract state
.functionCall(newAccountId, "init", {
owner_id: "alice.near",
total_supply: "1000000",
})
.send()
console.log("🚀 Deployed!")
```
## 3. Managing Access Keys
NEAR has a unique permission system based on Access Keys. You can add multiple keys to a single account with different permission levels.
### Adding a Restricted Key (FunctionCall)
This is how "Sign in with NEAR" works. You create a key that can **only** call specific methods on a specific contract. It cannot transfer NEAR.
```typescript theme={null}
const appKey = generateKey()
await near
.transaction("alice.near")
.addKey(appKey.publicKey.toString(), {
type: "functionCall",
// The ONLY contract this key can interact with
receiverId: "game.near",
// The ONLY methods this key can call
// (Empty array = Any method on this contract)
methodNames: ["move", "attack", "heal"],
// The max amount of gas fees this key can spend
allowance: "0.25 NEAR",
})
.send()
```
<Info title="Understanding Allowance">
The `allowance` is a specific amount of NEAR set aside **strictly for gas fees**. It cannot be transferred or withdrawn. If the key uses up this allowance, it will be deleted automatically.
</Info>
### Rotating Keys (Security)
To rotate keys (e.g., for security hygiene), you add a new key and delete the old one in the same transaction. This prevents you from locking yourself out.
```typescript theme={null}
const newMasterKey = generateKey()
await near
.transaction("alice.near")
.addKey(newMasterKey.publicKey.toString(), { type: "fullAccess" })
.deleteKey("alice.near", "ed25519:OLD_KEY...")
.send()
```
## 4. Staking
You can stake NEAR natively with a validator to earn rewards.
```typescript theme={null}
// Stake 100 NEAR with your validator's public key
await near
.transaction("alice.near")
.stake("ed25519:VALIDATOR_PUBLIC_KEY...", "100 NEAR")
.send()
```
<Note title="Unstaking">
To unstake, you typically need to call function methods (`unstake`, `withdraw`) on the staking pool contract rather than using a native action.
</Note>
## 5. Deleting Accounts
You can delete an account to recover its storage rent (the NEAR locked to pay for its data). The account passed to `.transaction()` is the account being deleted, and the `beneficiary` receives the remaining NEAR balance.
```typescript theme={null}
// Delete 'old-account.alice.near' and send all funds to 'alice.near'
await near
.transaction("old-account.alice.near")
.deleteAccount({ beneficiary: "alice.near" })
.send()
```
## 6. Transaction Lifecycle & Finality
When you call `.send()`, you can control exactly when `near-kit` returns using the `waitUntil` option.
### The Lifecycle
1. **Validation:** RPC checks structure.
2. **Inclusion:** The transaction hits a validator node. Signature is checked, gas is pre-paid, nonce is updated.
3. **Execution:** The receipt is processed. If it's a function call, the VM runs.
4. **Finalization:** The block containing the transaction is finalized by consensus.
### `waitUntil` Options
You can pass these options to `.send({ waitUntil: "..." })`.
#### `EXECUTED_OPTIMISTIC` (Default)
* **Returns:** When the entire chain of receipts finishes execution.
* **Data:** Full logs and return values are available.
<Tip title="Best for most cases">
This is the default for a reason. It provides the return value you need for your UI, and happens relatively quickly (\~2s).
</Tip>
#### `INCLUDED`
* **Returns:** When the transaction is in a block.
* **Data:** **No return values or logs are available yet.**
<Warning title="Missing Data">
Use `INCLUDED` only for "fire-and-forget" UI feedback. You cannot check if the smart contract call actually succeeded or failed logic checks yet.
</Warning>
#### `FINAL`
* **Returns:** When the block containing the *last* receipt is finalized.
* **State:** 100% irreversible.
<Tip title="High Value Transfer">
Use `FINAL` when moving large amounts of money to ensure 100% certainty.
```typescript theme={null}
await near.transaction("alice.near")
.transfer("bob.near", "10000 NEAR")
.send({ waitUntil: "FINAL" });
```
</Tip>
# Error Handling
Source: https://kit.near.tools/in-depth/error-handling
Typed errors for clean exception handling
`near-kit` converts cryptic RPC JSON errors into typed JavaScript Error classes. You can `catch` these errors and handle them logically.
## The Error Hierarchy
All errors extend `NearError`. You can check for specific types using `instanceof`.
```typescript theme={null}
import {
FunctionCallError,
AccountDoesNotExistError,
NetworkError,
} from "near-kit"
try {
await near.call("contract.near", "method", {})
} catch (e) {
if (e instanceof FunctionCallError) {
// The contract logic failed
console.log("Panic:", e.panic)
console.log("Logs:", e.logs)
} else if (e instanceof AccountDoesNotExistError) {
// The account isn't real
console.log(`Account ${e.accountId} not found`)
} else if (e instanceof NetworkError) {
// RPC is down
if (e.retryable) {
// You might want to try again
}
}
}
```
## Error Types
<AccordionGroup>
<Accordion title="FunctionCallError" icon="code">
Thrown when a smart contract call fails (panics or runs out of gas).
**Properties:**
* `panic`: The panic message from the contract
* `logs`: Any logs emitted before the failure
```typescript theme={null}
if (e instanceof FunctionCallError) {
console.log("Contract panicked:", e.panic)
}
```
</Accordion>
<Accordion title="AccountDoesNotExistError" icon="user-slash">
Thrown when trying to interact with an account that doesn't exist.
**Properties:**