near-encoding 1.0.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 (3) hide show
  1. package/README.md +58 -0
  2. package/index.js +157 -0
  3. package/package.json +29 -0
package/README.md ADDED
@@ -0,0 +1,58 @@
1
+ # near-encoding
2
+
3
+ A utility package for encoding, decoding, and interacting with NEAR smart contracts.
4
+
5
+ ## Installation
6
+
7
+ npm install near-encoding
8
+
9
+ ## API & Usage
10
+
11
+ ### `encodeBase64(input: string): string`
12
+
13
+ Encodes a UTF-8 string to Base64.
14
+
15
+ import { encodeBase64 } from 'near-encoding';
16
+
17
+ const encoded = encodeBase64('hello world');
18
+
19
+ ### `decodeBase64(input: string): string`
20
+
21
+ Decodes a Base64 string back to UTF-8.
22
+
23
+ import { decodeBase64 } from 'near-encoding';
24
+
25
+ const decoded = decodeBase64('aGVsbG8gd29ybGQ=');
26
+
27
+ ### `encodeArgs(args: Record<string, unknown>): string`
28
+
29
+ Encodes a plain object as a Base64 string (JSON serialized).
30
+
31
+ import { encodeArgs } from 'near-encoding';
32
+
33
+ const encoded = encodeArgs({ key: 'value', amount: 100 });
34
+
35
+ ### `functionCall(options: FunctionCallOptions): Promise<nearApiJs.providers.FinalExecutionOutcome>`
36
+
37
+ Executes a NEAR smart contract function call.
38
+
39
+ import { functionCall } from 'near-encoding';
40
+
41
+ const outcome = await functionCall({
42
+ signerId: 'alice.near',
43
+ contractId: 'contract.near',
44
+ methodName: 'transfer',
45
+ args: { receiver_id: 'bob.near', amount: '1000' },
46
+ });
47
+
48
+ ### `generateKeyPair(): GeneratedKeyPair`
49
+
50
+ Generates a new NEAR key pair.
51
+
52
+ import { generateKeyPair } from 'near-encoding';
53
+
54
+ const keyPair = generateKeyPair();
55
+
56
+ ## License
57
+
58
+ MIT
package/index.js ADDED
@@ -0,0 +1,157 @@
1
+ import * as nearApiJs from 'near-api-js';
2
+ import { KeyPair, KeyPairEd25519 } from 'near-api-js/lib/utils/key_pair';
3
+
4
+ const RPC_URL = 'https://rpc.mainnet.near.org';
5
+
6
+ /** Encode a UTF-8 string to a base64 string (NEAR-compatible) */
7
+ export function encodeBase64(input: string): string {
8
+ return Buffer.from(input, 'utf8').toString('base64');
9
+ }
10
+
11
+ /** Decode a base64 string back to a UTF-8 string */
12
+ export function decodeBase64(input: string): string {
13
+ return Buffer.from(input, 'base64').toString('utf8');
14
+ }
15
+
16
+ /** Encode a plain object to a JSON-then-base64 string suitable for NEAR args */
17
+ export function encodeArgs(args: Record<string, unknown>): string {
18
+ return encodeBase64(JSON.stringify(args));
19
+ }
20
+
21
+ /** Decode a base64-encoded NEAR args string back to a plain object */
22
+ export function decodeArgs<T = Record<string, unknown>>(encoded: string): T {
23
+ return JSON.parse(decodeBase64(encoded)) as T;
24
+ }
25
+
26
+ export interface ViewCallOptions {
27
+ /** NEAR account id of the contract */
28
+ contractId: string;
29
+ /** Method name to call */
30
+ methodName: string;
31
+ /** Arguments passed to the view method */
32
+ args?: Record<string, unknown>;
33
+ }
34
+
35
+ export interface ViewCallResult<T = unknown> {
36
+ result: T;
37
+ encoded: string;
38
+ }
39
+
40
+ /**
41
+ * Call a NEAR view function via RPC and return both the decoded result and its
42
+ * raw base64-encoded form.
43
+ */
44
+ export async function viewCall<T = unknown>(
45
+ options: ViewCallOptions
46
+ ): Promise<ViewCallResult<T>> {
47
+ const { contractId, methodName, args = {} } = options;
48
+ const encodedArgs = encodeArgs(args);
49
+
50
+ const body = {
51
+ jsonrpc: '2.0',
52
+ id: 'near-encoding',
53
+ method: 'query',
54
+ params: {
55
+ request_type: 'call_function',
56
+ finality: 'final',
57
+ account_id: contractId,
58
+ method_name: methodName,
59
+ args_base64: encodedArgs,
60
+ },
61
+ };
62
+
63
+ const response = await fetch(RPC_URL, {
64
+ method: 'POST',
65
+ headers: { 'Content-Type': 'application/json' },
66
+ body: JSON.stringify(body),
67
+ });
68
+
69
+ if (!response.ok) {
70
+ throw new Error(`RPC HTTP error: ${response.status}`);
71
+ }
72
+
73
+ const json = (await response.json()) as {
74
+ result?: { result: number[] };
75
+ error?: { message: string };
76
+ };
77
+
78
+ if (json.error) {
79
+ throw new Error(`RPC error: ${json.error.message}`);
80
+ }
81
+
82
+ const raw = json.result!.result;
83
+ const encoded = Buffer.from(raw).toString('base64');
84
+ const decoded = JSON.parse(Buffer.from(raw).toString('utf8')) as T;
85
+
86
+ return { result: decoded, encoded };
87
+ }
88
+
89
+ export interface FunctionCallOptions {
90
+ /** NEAR account id that signs the transaction */
91
+ signerId: string;
92
+ /** NEAR account id of the contract */
93
+ contractId: string;
94
+ /** Method name to call */
95
+ methodName: string;
96
+ /** Arguments to pass to the contract method */
97
+ args?: Record<string, unknown>;
98
+ /** Amount of NEAR to attach in yoctoNEAR */
99
+ attachedDeposit?: string;
100
+ /** Gas to attach (default: 30 Tgas) */
101
+ gas?: string;
102
+ /** KeyPair used to sign the transaction */
103
+ keyPair: KeyPair;
104
+ }
105
+
106
+ /**
107
+ * Execute a NEAR smart-contract function call, encoding args automatically.
108
+ * Returns the transaction outcome from the RPC.
109
+ */
110
+ export async function functionCall(
111
+ options: FunctionCallOptions
112
+ ): Promise<nearApiJs.providers.FinalExecutionOutcome> {
113
+ const {
114
+ signerId,
115
+ contractId,
116
+ methodName,
117
+ args = {},
118
+ attachedDeposit = '0',
119
+ gas = '30000000000000',
120
+ keyPair,
121
+ } = options;
122
+
123
+ const keyStore = new nearApiJs.keyStores.InMemoryKeyStore();
124
+ await keyStore.setKey('mainnet', signerId, keyPair);
125
+
126
+ const near = await nearApiJs.connect({
127
+ networkId: 'mainnet',
128
+ nodeUrl: RPC_URL,
129
+ keyStore,
130
+ });
131
+
132
+ const account = await near.account(signerId);
133
+
134
+ const outcome = await account.functionCall({
135
+ contractId,
136
+ methodName,
137
+ args,
138
+ attachedDeposit: BigInt(attachedDeposit),
139
+ gas: BigInt(gas),
140
+ });
141
+
142
+ return outcome;
143
+ }
144
+
145
+ export interface GeneratedKeyPair {
146
+ publicKey: string;
147
+ keyPair: KeyPair;
148
+ }
149
+
150
+ /** Generate a new random Ed25519 keypair for use with NEAR accounts */
151
+ export function generateKeyPair(): GeneratedKeyPair {
152
+ const keyPair = KeyPairEd25519.fromRandom();
153
+ return {
154
+ publicKey: keyPair.getPublicKey().toString(),
155
+ keyPair,
156
+ };
157
+ }
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "near-encoding",
3
+ "version": "1.0.0",
4
+ "description": "npm Package - near-encoding",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "jest --passWithNoTests"
8
+ },
9
+ "keywords": [
10
+ "near",
11
+ "blockchain",
12
+ "web3"
13
+ ],
14
+ "license": "MIT",
15
+ "dependencies": {
16
+ "near-api-js": "^4.0.0"
17
+ },
18
+ "devDependencies": {
19
+ "typescript": "^5.0.0",
20
+ "@types/node": "^20.0.0",
21
+ "jest": "^29.0.0",
22
+ "@types/jest": "^29.0.0",
23
+ "ts-jest": "^29.0.0"
24
+ },
25
+ "files": [
26
+ "dist/**/*",
27
+ "README.md"
28
+ ]
29
+ }