@stableflow/wallet-near 0.0.0-experimental-5a8afd7389-20260703

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 StableFlow AI
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 ADDED
@@ -0,0 +1,28 @@
1
+ # @stableflow/wallet-near
2
+
3
+ NEAR wallet adapter for the StableFlow SDK.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @stableflow/wallet-near @stableflow/core @stableflow/bridges
9
+ ```
10
+
11
+ **Peer dependencies:**
12
+
13
+ - `@near-js/transactions` ^2.5.1
14
+
15
+ ## When to use
16
+
17
+ NEAR Intents and other NEAR-based routes. Pass `wallet.wallet` into `BridgeSFA` quote/send parameters.
18
+
19
+ ## Main exports
20
+
21
+ ```ts
22
+ import NearWallet, { NearWallet as Named } from '@stableflow/wallet-near';
23
+ ```
24
+
25
+ ## See also
26
+
27
+ - [Developer Guide](../../DEVELOPER_GUIDE.md)
28
+ - [@stableflow/bridges](../bridges/README.md)
@@ -0,0 +1,70 @@
1
+ import { Service, SendType } from '@stableflow/core';
2
+
3
+ declare class NearWallet {
4
+ private selector;
5
+ private rpcUrl;
6
+ private csl;
7
+ constructor(_selector: any);
8
+ private query;
9
+ transfer(data: {
10
+ originAsset: string;
11
+ depositAddress: string;
12
+ amount: string;
13
+ }): Promise<any>;
14
+ getBalance(token: any, _account: string, options?: {
15
+ isCatchError?: boolean;
16
+ }): Promise<any>;
17
+ balanceOf(token: any, account: string, options?: {
18
+ isCatchError?: boolean;
19
+ }): Promise<any>;
20
+ /**
21
+ * Get native NEAR balance
22
+ * @param account Account ID
23
+ * @returns NEAR balance in yoctoNEAR (smallest unit)
24
+ */
25
+ getNearBalance(account: string, options?: {
26
+ isCatchError?: boolean;
27
+ }): Promise<string>;
28
+ /**
29
+ * Estimate gas limit for transfer transaction
30
+ * @param data Transfer data
31
+ * @returns Gas limit estimate, gas price, and estimated gas cost
32
+ */
33
+ estimateTransferGas(data: {
34
+ fromToken: any;
35
+ depositAddress: string;
36
+ amount: string;
37
+ }): Promise<{
38
+ gasLimit: bigint;
39
+ gasPrice: bigint;
40
+ estimateGas: bigint;
41
+ }>;
42
+ getEstimateGas(params: any): Promise<{
43
+ gasPrice: any;
44
+ usd: string;
45
+ wei: bigint;
46
+ amount: string;
47
+ }>;
48
+ estimateTransaction(params: any): Promise<{
49
+ estimateSourceGasLimit: bigint;
50
+ estimateSourceGas: bigint;
51
+ estimateSourceGasUsd: string;
52
+ }>;
53
+ checkTransactionStatus(txHash: string): Promise<void>;
54
+ quoteOneClickProxy(params: any): Promise<any>;
55
+ sendTransaction(params: any): Promise<any>;
56
+ /**
57
+ * Unified quote method that routes to specific quote methods based on type
58
+ * @param type Service type from Service
59
+ * @param params Parameters for the quote
60
+ */
61
+ quote(type: Service, params: any): Promise<any>;
62
+ /**
63
+ * Unified send method that routes to specific send methods based on type
64
+ * @param type Send type from SendType enum
65
+ * @param params Parameters for the send transaction
66
+ */
67
+ send(type: SendType, params: any): Promise<any>;
68
+ }
69
+
70
+ export { NearWallet, NearWallet as default };
@@ -0,0 +1,70 @@
1
+ import { Service, SendType } from '@stableflow/core';
2
+
3
+ declare class NearWallet {
4
+ private selector;
5
+ private rpcUrl;
6
+ private csl;
7
+ constructor(_selector: any);
8
+ private query;
9
+ transfer(data: {
10
+ originAsset: string;
11
+ depositAddress: string;
12
+ amount: string;
13
+ }): Promise<any>;
14
+ getBalance(token: any, _account: string, options?: {
15
+ isCatchError?: boolean;
16
+ }): Promise<any>;
17
+ balanceOf(token: any, account: string, options?: {
18
+ isCatchError?: boolean;
19
+ }): Promise<any>;
20
+ /**
21
+ * Get native NEAR balance
22
+ * @param account Account ID
23
+ * @returns NEAR balance in yoctoNEAR (smallest unit)
24
+ */
25
+ getNearBalance(account: string, options?: {
26
+ isCatchError?: boolean;
27
+ }): Promise<string>;
28
+ /**
29
+ * Estimate gas limit for transfer transaction
30
+ * @param data Transfer data
31
+ * @returns Gas limit estimate, gas price, and estimated gas cost
32
+ */
33
+ estimateTransferGas(data: {
34
+ fromToken: any;
35
+ depositAddress: string;
36
+ amount: string;
37
+ }): Promise<{
38
+ gasLimit: bigint;
39
+ gasPrice: bigint;
40
+ estimateGas: bigint;
41
+ }>;
42
+ getEstimateGas(params: any): Promise<{
43
+ gasPrice: any;
44
+ usd: string;
45
+ wei: bigint;
46
+ amount: string;
47
+ }>;
48
+ estimateTransaction(params: any): Promise<{
49
+ estimateSourceGasLimit: bigint;
50
+ estimateSourceGas: bigint;
51
+ estimateSourceGasUsd: string;
52
+ }>;
53
+ checkTransactionStatus(txHash: string): Promise<void>;
54
+ quoteOneClickProxy(params: any): Promise<any>;
55
+ sendTransaction(params: any): Promise<any>;
56
+ /**
57
+ * Unified quote method that routes to specific quote methods based on type
58
+ * @param type Service type from Service
59
+ * @param params Parameters for the quote
60
+ */
61
+ quote(type: Service, params: any): Promise<any>;
62
+ /**
63
+ * Unified send method that routes to specific send methods based on type
64
+ * @param type Send type from SendType enum
65
+ * @param params Parameters for the send transaction
66
+ */
67
+ send(type: SendType, params: any): Promise<any>;
68
+ }
69
+
70
+ export { NearWallet, NearWallet as default };
package/dist/index.js ADDED
@@ -0,0 +1,455 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var buffer = require('buffer');
6
+ var Big = require('big.js');
7
+ var core = require('@stableflow/core');
8
+ var transactions = require('@near-js/transactions');
9
+
10
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
+
12
+ var Big__default = /*#__PURE__*/_interopDefault(Big);
13
+
14
+ // src/near.ts
15
+ var createFunctionCallAction = (methodName, args, gas, deposit) => {
16
+ return transactions.actionCreators.functionCall(
17
+ methodName,
18
+ args,
19
+ BigInt(gas),
20
+ BigInt(deposit)
21
+ );
22
+ };
23
+ var NearWallet = class {
24
+ constructor(_selector) {
25
+ this.selector = _selector;
26
+ this.rpcUrl = core.getChainRpcUrl("near").rpcUrl;
27
+ const cs = new core.Csl(core.OpenAPI.DEBUG);
28
+ this.csl = cs.log;
29
+ }
30
+ async query(contractId, methodName, args = {}) {
31
+ const response = await fetch(this.rpcUrl, {
32
+ method: "POST",
33
+ headers: {
34
+ "Content-Type": "application/json"
35
+ },
36
+ body: JSON.stringify({
37
+ jsonrpc: "2.0",
38
+ id: "dontcare",
39
+ method: "query",
40
+ params: {
41
+ request_type: "call_function",
42
+ finality: "final",
43
+ account_id: contractId,
44
+ method_name: methodName,
45
+ args_base64: buffer.Buffer.from(JSON.stringify(args)).toString("base64")
46
+ }
47
+ })
48
+ });
49
+ const result = await response.json();
50
+ if (result.result && result.result.result) {
51
+ return JSON.parse(buffer.Buffer.from(result.result.result).toString());
52
+ }
53
+ return result;
54
+ }
55
+ async transfer(data) {
56
+ const wallet = await this.selector.wallet();
57
+ const checkStorage = await this.query(
58
+ data.originAsset,
59
+ "storage_balance_of",
60
+ {
61
+ account_id: data.depositAddress
62
+ }
63
+ );
64
+ const transactions = [];
65
+ if (!checkStorage?.available) {
66
+ transactions.push({
67
+ receiverId: data.originAsset,
68
+ actions: [
69
+ createFunctionCallAction(
70
+ "storage_deposit",
71
+ {
72
+ account_id: data.depositAddress,
73
+ registration_only: true
74
+ },
75
+ "15000000000000",
76
+ "1250000000000000000000"
77
+ )
78
+ ]
79
+ });
80
+ }
81
+ transactions.push({
82
+ receiverId: data.originAsset,
83
+ actions: [
84
+ createFunctionCallAction(
85
+ "ft_transfer",
86
+ {
87
+ receiver_id: data.depositAddress,
88
+ amount: data.amount,
89
+ memo: null
90
+ },
91
+ "30000000000000",
92
+ "1"
93
+ )
94
+ ]
95
+ });
96
+ const result = await wallet.signAndSendTransactions({
97
+ transactions,
98
+ callbackUrl: "/"
99
+ });
100
+ if (result.slice(-1).length) {
101
+ return result.slice(-1)[0].transaction.hash;
102
+ }
103
+ return "";
104
+ }
105
+ async getBalance(token, _account, options) {
106
+ const { isCatchError = false } = options || {};
107
+ if (token.symbol === "near" || token.symbol === "NEAR" || token.symbol === "native") {
108
+ return this.getNearBalance(_account, options);
109
+ }
110
+ try {
111
+ const balance = await this.query(token.contractAddress, "ft_balance_of", {
112
+ account_id: _account
113
+ });
114
+ return balance || "0";
115
+ } catch (error) {
116
+ this.csl("Near getTokenBalance", "red-500", "Get token balance failed: %o", error);
117
+ if (isCatchError) {
118
+ throw error;
119
+ }
120
+ return "0";
121
+ }
122
+ }
123
+ async balanceOf(token, account, options) {
124
+ return await this.getBalance(token, account, options);
125
+ }
126
+ /**
127
+ * Get native NEAR balance
128
+ * @param account Account ID
129
+ * @returns NEAR balance in yoctoNEAR (smallest unit)
130
+ */
131
+ async getNearBalance(account, options) {
132
+ const { isCatchError = false } = options || {};
133
+ try {
134
+ const response = await fetch(this.rpcUrl, {
135
+ method: "POST",
136
+ headers: {
137
+ "Content-Type": "application/json"
138
+ },
139
+ body: JSON.stringify({
140
+ jsonrpc: "2.0",
141
+ id: "dontcare",
142
+ method: "query",
143
+ params: {
144
+ request_type: "view_account",
145
+ finality: "final",
146
+ account_id: account
147
+ }
148
+ })
149
+ });
150
+ const result = await response.json();
151
+ return result.result?.amount || "0";
152
+ } catch (error) {
153
+ console.error("Failed to get NEAR balance:", error);
154
+ if (isCatchError) {
155
+ throw error;
156
+ }
157
+ return "0";
158
+ }
159
+ }
160
+ /**
161
+ * Estimate gas limit for transfer transaction
162
+ * @param data Transfer data
163
+ * @returns Gas limit estimate, gas price, and estimated gas cost
164
+ */
165
+ async estimateTransferGas(data) {
166
+ const { fromToken, depositAddress } = data;
167
+ const originAsset = fromToken.contractAddress;
168
+ const checkStorage = await this.query(
169
+ originAsset,
170
+ "storage_balance_of",
171
+ {
172
+ account_id: depositAddress
173
+ }
174
+ );
175
+ let gasLimit;
176
+ if (!checkStorage?.available) {
177
+ gasLimit = BigInt("15000000000000") + BigInt("30000000000000");
178
+ } else {
179
+ gasLimit = BigInt("30000000000000");
180
+ }
181
+ gasLimit = gasLimit * 120n / 100n;
182
+ const gasPrice = BigInt("100000000");
183
+ const estimateGas = gasLimit * gasPrice;
184
+ return {
185
+ gasLimit,
186
+ gasPrice,
187
+ estimateGas
188
+ };
189
+ }
190
+ async getEstimateGas(params) {
191
+ const { gasLimit, price, nativeToken, gasPrice } = params;
192
+ let finalGasPrice = gasPrice;
193
+ if (!finalGasPrice) {
194
+ try {
195
+ const gasPriceResponse = await fetch(this.rpcUrl, {
196
+ method: "POST",
197
+ headers: {
198
+ "Content-Type": "application/json"
199
+ },
200
+ body: JSON.stringify({
201
+ jsonrpc: "2.0",
202
+ id: "dontcare",
203
+ method: "gas_price",
204
+ params: {}
205
+ })
206
+ });
207
+ const gasPriceJson = await gasPriceResponse.json();
208
+ finalGasPrice = BigInt(gasPriceJson.result.gas_price);
209
+ } catch {
210
+ finalGasPrice = BigInt("100000000");
211
+ }
212
+ }
213
+ const estimateGas = BigInt(gasLimit) * BigInt(finalGasPrice);
214
+ const estimateGasAmount = Big__default.default(estimateGas.toString()).div(10 ** nativeToken.decimals);
215
+ const estimateGasUsd = Big__default.default(estimateGasAmount).times(price || 1);
216
+ return {
217
+ gasPrice: finalGasPrice,
218
+ usd: core.numberRemoveEndZero(Big__default.default(estimateGasUsd).toFixed(20)),
219
+ wei: estimateGas,
220
+ amount: core.numberRemoveEndZero(Big__default.default(estimateGasAmount).toFixed(nativeToken.decimals))
221
+ };
222
+ }
223
+ async estimateTransaction(params) {
224
+ const {
225
+ dry,
226
+ transactions,
227
+ fromToken,
228
+ prices
229
+ } = params;
230
+ const nativeTokenPrice = core.getPrice(prices, fromToken.nativeToken.symbol);
231
+ let totalGasLimit = BigInt("50000000000000");
232
+ for (let i = 1; i < transactions.length; i++) {
233
+ totalGasLimit += BigInt("15000000000000");
234
+ }
235
+ totalGasLimit = totalGasLimit * 120n / 100n;
236
+ const result = {
237
+ estimateSourceGasLimit: totalGasLimit,
238
+ estimateSourceGas: 0n,
239
+ estimateSourceGasUsd: "0"
240
+ };
241
+ const setDefaultGasLimit = async () => {
242
+ const { usd, wei } = await this.getEstimateGas({
243
+ gasLimit: totalGasLimit,
244
+ price: nativeTokenPrice,
245
+ nativeToken: fromToken.nativeToken,
246
+ gasPrice: dry ? "100000000" : void 0
247
+ });
248
+ result.estimateSourceGas = wei;
249
+ result.estimateSourceGasUsd = usd;
250
+ };
251
+ await setDefaultGasLimit();
252
+ return result;
253
+ }
254
+ async checkTransactionStatus(txHash) {
255
+ const wallet = await this.selector.wallet();
256
+ const accounts = await wallet.getAccounts();
257
+ const accountId = accounts[0]?.accountId;
258
+ try {
259
+ const response = await fetch(this.rpcUrl, {
260
+ method: "POST",
261
+ headers: {
262
+ "Content-Type": "application/json"
263
+ },
264
+ body: JSON.stringify({
265
+ jsonrpc: "2.0",
266
+ id: "dontcare",
267
+ method: "EXPERIMENTAL_tx_status",
268
+ params: {
269
+ tx_hash: txHash,
270
+ sender_account_id: accountId,
271
+ wait_until: "EXECUTED"
272
+ // wait_until: "NONE" | "EXECUTED_OPTIMISTIC" | "EXECUTED"
273
+ }
274
+ })
275
+ });
276
+ const txStatus = await response.json();
277
+ this.csl("Near checkTransactionStatus", "green-400", "fetch rpc success: %o", txStatus);
278
+ this.csl("Near checkTransactionStatus", "green-400", "fetch rpc status success: %o", typeof txStatus.result?.status?.SuccessValue !== "undefined");
279
+ } catch (error) {
280
+ this.csl("Near checkTransactionStatus", "red-500", "fetch rpc failed: %o", error);
281
+ }
282
+ }
283
+ async quoteOneClickProxy(params) {
284
+ const {
285
+ dry,
286
+ proxyAddress,
287
+ fromToken,
288
+ refundTo,
289
+ depositAddress,
290
+ amountWei,
291
+ prices
292
+ } = params;
293
+ const execTime = new core.ExecTime({ type: "OneClick NEAR", logStyle: "lime-200", isDebug: core.OpenAPI.DEBUG });
294
+ const result = { fees: {} };
295
+ try {
296
+ const wallet = await this.selector.wallet();
297
+ const accounts = await wallet.getAccounts();
298
+ const userAccountId = refundTo || accounts[0]?.accountId;
299
+ if (!userAccountId) {
300
+ throw new Error("No account found");
301
+ }
302
+ const tokenContract = fromToken.contractAddress;
303
+ const STABLEFLOW_CONTRACT = proxyAddress || "stableflowstg.near";
304
+ if (!depositAddress) {
305
+ throw new Error("depositAddress is required");
306
+ }
307
+ const transactions = [];
308
+ execTime.breakpoint();
309
+ const mergedCalls = [
310
+ this.query(
311
+ tokenContract,
312
+ "storage_balance_of",
313
+ {
314
+ account_id: depositAddress
315
+ }
316
+ ),
317
+ this.query(
318
+ tokenContract,
319
+ "storage_balance_of",
320
+ {
321
+ account_id: STABLEFLOW_CONTRACT
322
+ }
323
+ )
324
+ ];
325
+ const [checkStorageDepositAddress, checkStorageStableflow] = await Promise.all(mergedCalls);
326
+ execTime.log("query storage_balance_of (depositAddress and STABLEFLOW_CONTRACT)");
327
+ if (!checkStorageDepositAddress?.available) {
328
+ transactions.push({
329
+ receiverId: tokenContract,
330
+ actions: [
331
+ createFunctionCallAction(
332
+ "storage_deposit",
333
+ {
334
+ account_id: depositAddress,
335
+ registration_only: true
336
+ },
337
+ "15000000000000",
338
+ "1250000000000000000000"
339
+ )
340
+ ]
341
+ });
342
+ }
343
+ if (!checkStorageStableflow?.available) {
344
+ transactions.push({
345
+ receiverId: tokenContract,
346
+ actions: [
347
+ createFunctionCallAction(
348
+ "storage_deposit",
349
+ {
350
+ account_id: STABLEFLOW_CONTRACT,
351
+ registration_only: true
352
+ },
353
+ "15000000000000",
354
+ "1250000000000000000000"
355
+ )
356
+ ]
357
+ });
358
+ }
359
+ transactions.push({
360
+ receiverId: tokenContract,
361
+ actions: [
362
+ createFunctionCallAction(
363
+ "ft_transfer_call",
364
+ {
365
+ receiver_id: STABLEFLOW_CONTRACT,
366
+ amount: amountWei,
367
+ msg: depositAddress
368
+ },
369
+ "50000000000000",
370
+ // ft_transfer_call requires more gas
371
+ "1"
372
+ )
373
+ ]
374
+ });
375
+ execTime.breakpoint();
376
+ const ett = await this.estimateTransaction({
377
+ dry,
378
+ transactions,
379
+ fromToken,
380
+ prices
381
+ });
382
+ execTime.log("estimateTransaction");
383
+ result.fees.estimateGasUsd = ett.estimateSourceGasUsd;
384
+ result.estimateSourceGas = ett.estimateSourceGas;
385
+ result.totalEstimateSourceGas = ett.estimateSourceGas;
386
+ result.estimateSourceGasUsd = ett.estimateSourceGasUsd;
387
+ result.sendParam = {
388
+ transactions,
389
+ callbackUrl: "/"
390
+ };
391
+ } catch (error) {
392
+ this.csl("Near quoteOneClickProxy", "red-500", "oneclick quote proxy failed: %o", error);
393
+ const ett = await this.estimateTransaction({
394
+ dry,
395
+ transactions: [null, null, null],
396
+ fromToken,
397
+ prices
398
+ });
399
+ result.fees.estimateGasUsd = ett.estimateSourceGasUsd;
400
+ result.estimateSourceGas = ett.estimateSourceGas;
401
+ result.totalEstimateSourceGas = ett.estimateSourceGas;
402
+ result.estimateSourceGasUsd = ett.estimateSourceGasUsd;
403
+ }
404
+ execTime.logTotal("quoteOneClickProxy");
405
+ return result;
406
+ }
407
+ async sendTransaction(params) {
408
+ const { transactions, callbackUrl } = params;
409
+ if (!transactions || !Array.isArray(transactions)) {
410
+ throw new Error("Invalid sendParam: transactions array is required");
411
+ }
412
+ const wallet = await this.selector.wallet();
413
+ const result = await wallet.signAndSendTransactions({
414
+ transactions,
415
+ callbackUrl: callbackUrl || "/"
416
+ });
417
+ if (result.slice(-1).length) {
418
+ return result.slice(-1)[0].transaction.hash;
419
+ }
420
+ return "";
421
+ }
422
+ /**
423
+ * Unified quote method that routes to specific quote methods based on type
424
+ * @param type Service type from Service
425
+ * @param params Parameters for the quote
426
+ */
427
+ async quote(type, params) {
428
+ switch (type) {
429
+ case core.Service.OneClick:
430
+ return await this.quoteOneClickProxy(params);
431
+ default:
432
+ throw new Error(`Unsupported quote type: ${type}`);
433
+ }
434
+ }
435
+ /**
436
+ * Unified send method that routes to specific send methods based on type
437
+ * @param type Send type from SendType enum
438
+ * @param params Parameters for the send transaction
439
+ */
440
+ async send(type, params) {
441
+ switch (type) {
442
+ case core.SendType.SEND:
443
+ return await this.sendTransaction(params);
444
+ case core.SendType.TRANSFER:
445
+ return await this.transfer(params);
446
+ default:
447
+ throw new Error(`Unsupported send type: ${type}`);
448
+ }
449
+ }
450
+ };
451
+
452
+ exports.NearWallet = NearWallet;
453
+ exports.default = NearWallet;
454
+ //# sourceMappingURL=index.js.map
455
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/near.ts"],"names":["actionCreators","getChainRpcUrl","Csl","OpenAPI","Buffer","Big","numberRemoveEndZero","getPrice","ExecTime","Service","SendType"],"mappings":";;;;;;;;;;;;;;AAcA,IAAM,wBAAA,GAA2B,CAC/B,UAAA,EACA,IAAA,EACA,KACA,OAAA,KACG;AACH,EAAA,OAAOA,2BAAA,CAAe,YAAA;AAAA,IACpB,UAAA;AAAA,IACA,IAAA;AAAA,IACA,OAAO,GAAG,CAAA;AAAA,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AAA;AACpD,EACF;AACF","file":"index.js","sourcesContent":["import { Buffer } from \"buffer\";\nimport Big from \"big.js\";\nimport {\n getPrice,\n numberRemoveEndZero,\n SendType,\n Service,\n getChainRpcUrl,\n Csl,\n OpenAPI,\n ExecTime,\n} from \"@stableflow/core\";\nimport { actionCreators } from \"@near-js/transactions\";\n\nconst createFunctionCallAction = (\n methodName: string,\n args: Record<string, any>,\n gas: string,\n deposit: string\n) => {\n return actionCreators.functionCall(\n methodName,\n args,\n BigInt(gas),\n BigInt(deposit)\n );\n}\n\nexport default class NearWallet {\n private selector: any;\n private rpcUrl: string;\n private csl;\n\n constructor(_selector: any) {\n this.selector = _selector;\n // https://rpc.mainnet.near.org\n // https://nearinner.deltarpc.com\n this.rpcUrl = getChainRpcUrl(\"near\").rpcUrl;\n\n const cs = new Csl(OpenAPI.DEBUG);\n this.csl = cs.log;\n }\n\n private async query(contractId: string, methodName: string, args: any = {}) {\n const response = await fetch(this.rpcUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: \"dontcare\",\n method: \"query\",\n params: {\n request_type: \"call_function\",\n finality: \"final\",\n account_id: contractId,\n method_name: methodName,\n args_base64: Buffer.from(JSON.stringify(args)).toString(\"base64\")\n }\n })\n });\n const result = await response.json();\n if (result.result && result.result.result) {\n return JSON.parse(Buffer.from(result.result.result).toString());\n }\n return result;\n }\n\n async transfer(data: {\n originAsset: string;\n depositAddress: string;\n amount: string;\n }) {\n const wallet = await this.selector.wallet();\n const checkStorage = await this.query(\n data.originAsset,\n \"storage_balance_of\",\n {\n account_id: data.depositAddress\n }\n );\n const transactions = [];\n if (!checkStorage?.available) {\n transactions.push({\n receiverId: data.originAsset,\n actions: [\n createFunctionCallAction(\n \"storage_deposit\",\n {\n account_id: data.depositAddress,\n registration_only: true\n },\n \"15000000000000\",\n \"1250000000000000000000\"\n )\n ]\n });\n }\n transactions.push({\n receiverId: data.originAsset,\n actions: [\n createFunctionCallAction(\n \"ft_transfer\",\n {\n receiver_id: data.depositAddress,\n amount: data.amount,\n memo: null\n },\n \"30000000000000\",\n \"1\"\n )\n ]\n });\n\n const result = await wallet.signAndSendTransactions({\n transactions,\n callbackUrl: \"/\"\n });\n\n if (result.slice(-1).length) {\n return result.slice(-1)[0].transaction.hash;\n }\n\n return \"\";\n }\n\n async getBalance(token: any, _account: string, options?: { isCatchError?: boolean; }) {\n const { isCatchError = false } = options || {};\n\n if (token.symbol === \"near\" || token.symbol === \"NEAR\" || token.symbol === \"native\") {\n return this.getNearBalance(_account, options);\n }\n try {\n const balance = await this.query(token.contractAddress, \"ft_balance_of\", {\n account_id: _account\n });\n return balance || \"0\";\n } catch (error) {\n this.csl(\"Near getTokenBalance\", \"red-500\", \"Get token balance failed: %o\", error);\n if (isCatchError) {\n throw error;\n }\n return \"0\";\n }\n }\n\n async balanceOf(token: any, account: string, options?: { isCatchError?: boolean; }) {\n return await this.getBalance(token, account, options);\n }\n\n /**\n * Get native NEAR balance\n * @param account Account ID\n * @returns NEAR balance in yoctoNEAR (smallest unit)\n */\n async getNearBalance(account: string, options?: { isCatchError?: boolean; }): Promise<string> {\n const { isCatchError = false } = options || {};\n\n try {\n const response = await fetch(this.rpcUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: \"dontcare\",\n method: \"query\",\n params: {\n request_type: \"view_account\",\n finality: \"final\",\n account_id: account\n }\n })\n });\n const result = await response.json();\n return result.result?.amount || \"0\";\n } catch (error) {\n console.error(\"Failed to get NEAR balance:\", error);\n if (isCatchError) {\n throw error;\n }\n return \"0\";\n }\n }\n\n /**\n * Estimate gas limit for transfer transaction\n * @param data Transfer data\n * @returns Gas limit estimate, gas price, and estimated gas cost\n */\n async estimateTransferGas(data: {\n fromToken: any;\n depositAddress: string;\n amount: string;\n }): Promise<{\n gasLimit: bigint;\n gasPrice: bigint;\n estimateGas: bigint;\n }> {\n const { fromToken, depositAddress } = data;\n const originAsset = fromToken.contractAddress;\n\n // Check if storage deposit is needed\n const checkStorage = await this.query(\n originAsset,\n \"storage_balance_of\",\n {\n account_id: depositAddress\n }\n );\n\n let gasLimit: bigint;\n\n if (!checkStorage?.available) {\n // Storage deposit: 15000000000000 gas\n // ft_transfer: 30000000000000 gas\n gasLimit = BigInt(\"15000000000000\") + BigInt(\"30000000000000\");\n } else {\n // Only ft_transfer needed: 30000000000000 gas\n gasLimit = BigInt(\"30000000000000\");\n }\n\n // Increase by 20% to provide buffer\n gasLimit = (gasLimit * 120n) / 100n;\n\n // NEAR gas price is typically 100000000 yoctoNEAR per gas unit\n const gasPrice = BigInt(\"100000000\");\n\n // Calculate estimated gas cost: gasLimit * gasPrice\n const estimateGas = gasLimit * gasPrice;\n\n return {\n gasLimit,\n gasPrice,\n estimateGas\n };\n }\n\n async getEstimateGas(params: any) {\n const { gasLimit, price, nativeToken, gasPrice } = params;\n\n let finalGasPrice = gasPrice;\n if (!finalGasPrice) {\n try {\n const gasPriceResponse = await fetch(this.rpcUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: \"dontcare\",\n method: \"gas_price\",\n params: {}\n })\n });\n const gasPriceJson = await gasPriceResponse.json();\n finalGasPrice = BigInt(gasPriceJson.result.gas_price);\n } catch {\n finalGasPrice = BigInt(\"100000000\");\n }\n }\n\n const estimateGas = BigInt(gasLimit) * BigInt(finalGasPrice);\n const estimateGasAmount = Big(estimateGas.toString()).div(10 ** nativeToken.decimals);\n const estimateGasUsd = Big(estimateGasAmount).times(price || 1);\n\n return {\n gasPrice: finalGasPrice,\n usd: numberRemoveEndZero(Big(estimateGasUsd).toFixed(20)),\n wei: estimateGas,\n amount: numberRemoveEndZero(Big(estimateGasAmount).toFixed(nativeToken.decimals)),\n };\n }\n\n async estimateTransaction(params: any) {\n const {\n dry,\n transactions,\n fromToken,\n prices,\n } = params;\n\n const nativeTokenPrice = getPrice(prices, fromToken.nativeToken.symbol);\n\n let totalGasLimit = BigInt(\"50000000000000\"); // ft_transfer_call gas\n for (let i = 1; i < transactions.length; i++) {\n totalGasLimit += BigInt(\"15000000000000\");\n }\n // Add 20% buffer\n totalGasLimit = (totalGasLimit * 120n) / 100n;\n\n const result = {\n estimateSourceGasLimit: totalGasLimit,\n estimateSourceGas: 0n,\n estimateSourceGasUsd: \"0\",\n };\n\n const setDefaultGasLimit = async () => {\n const { usd, wei } = await this.getEstimateGas({\n gasLimit: totalGasLimit,\n price: nativeTokenPrice,\n nativeToken: fromToken.nativeToken,\n gasPrice: dry ? \"100000000\" : void 0,\n });\n result.estimateSourceGas = wei;\n result.estimateSourceGasUsd = usd;\n };\n\n await setDefaultGasLimit();\n\n return result;\n }\n\n async checkTransactionStatus(txHash: string) {\n const wallet = await this.selector.wallet();\n const accounts = await wallet.getAccounts();\n const accountId = accounts[0]?.accountId;\n\n try {\n const response = await fetch(this.rpcUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: \"dontcare\",\n method: \"EXPERIMENTAL_tx_status\",\n params: {\n tx_hash: txHash,\n sender_account_id: accountId,\n wait_until: \"EXECUTED\" // wait_until: \"NONE\" | \"EXECUTED_OPTIMISTIC\" | \"EXECUTED\"\n }\n })\n });\n const txStatus = await response.json();\n this.csl(\"Near checkTransactionStatus\", \"green-400\", \"fetch rpc success: %o\", txStatus);\n this.csl(\"Near checkTransactionStatus\", \"green-400\", \"fetch rpc status success: %o\", typeof txStatus.result?.status?.SuccessValue !== \"undefined\");\n } catch (error) {\n this.csl(\"Near checkTransactionStatus\", \"red-500\", \"fetch rpc failed: %o\", error);\n }\n }\n\n async quoteOneClickProxy(params: any) {\n const {\n dry,\n proxyAddress,\n fromToken,\n refundTo,\n depositAddress,\n amountWei,\n prices,\n } = params;\n\n const execTime = new ExecTime({ type: \"OneClick NEAR\", logStyle: \"lime-200\", isDebug: OpenAPI.DEBUG });\n\n const result: any = { fees: {} };\n\n try {\n const wallet = await this.selector.wallet();\n const accounts = await wallet.getAccounts();\n const userAccountId = refundTo || accounts[0]?.accountId;\n\n if (!userAccountId) {\n throw new Error(\"No account found\");\n }\n\n const tokenContract = fromToken.contractAddress;\n // proxyAddress should be stableflowstg.near, use default if not provided\n const STABLEFLOW_CONTRACT = proxyAddress || \"stableflowstg.near\";\n\n if (!depositAddress) {\n throw new Error(\"depositAddress is required\");\n }\n\n // Check and register token: register for intents address (depositAddress) and stableflowstg.near contract\n const transactions: any[] = [];\n\n // Check if depositAddress (intents address) is registered\n // Check if stableflowstg.near is registered\n execTime.breakpoint();\n const mergedCalls = [\n this.query(\n tokenContract,\n \"storage_balance_of\",\n {\n account_id: depositAddress\n }\n ),\n this.query(\n tokenContract,\n \"storage_balance_of\",\n {\n account_id: STABLEFLOW_CONTRACT\n }\n )\n ];\n const [checkStorageDepositAddress, checkStorageStableflow] = await Promise.all(mergedCalls);\n execTime.log(\"query storage_balance_of (depositAddress and STABLEFLOW_CONTRACT)\");\n\n if (!checkStorageDepositAddress?.available) {\n transactions.push({\n receiverId: tokenContract,\n actions: [\n createFunctionCallAction(\n \"storage_deposit\",\n {\n account_id: depositAddress,\n registration_only: true\n },\n \"15000000000000\",\n \"1250000000000000000000\"\n )\n ]\n });\n }\n\n if (!checkStorageStableflow?.available) {\n transactions.push({\n receiverId: tokenContract,\n actions: [\n createFunctionCallAction(\n \"storage_deposit\",\n {\n account_id: STABLEFLOW_CONTRACT,\n registration_only: true\n },\n \"15000000000000\",\n \"1250000000000000000000\"\n )\n ]\n });\n }\n\n // Build ft_transfer_call transaction\n transactions.push({\n receiverId: tokenContract,\n actions: [\n createFunctionCallAction(\n \"ft_transfer_call\",\n {\n receiver_id: STABLEFLOW_CONTRACT,\n amount: amountWei,\n msg: depositAddress\n },\n \"50000000000000\", // ft_transfer_call requires more gas\n \"1\"\n )\n ]\n });\n\n execTime.breakpoint();\n const ett = await this.estimateTransaction({\n dry,\n transactions,\n fromToken,\n prices,\n });\n execTime.log(\"estimateTransaction\");\n\n result.fees.estimateGasUsd = ett.estimateSourceGasUsd;\n result.estimateSourceGas = ett.estimateSourceGas;\n result.totalEstimateSourceGas = ett.estimateSourceGas;\n result.estimateSourceGasUsd = ett.estimateSourceGasUsd;\n\n // Set sendParam for subsequent transaction sending\n result.sendParam = {\n transactions,\n callbackUrl: \"/\"\n };\n\n } catch (error) {\n this.csl(\"Near quoteOneClickProxy\", \"red-500\", \"oneclick quote proxy failed: %o\", error);\n // Use default gas estimation\n const ett = await this.estimateTransaction({\n dry,\n transactions: [null, null, null],\n fromToken,\n prices,\n });\n\n result.fees.estimateGasUsd = ett.estimateSourceGasUsd;\n result.estimateSourceGas = ett.estimateSourceGas;\n result.totalEstimateSourceGas = ett.estimateSourceGas;\n result.estimateSourceGasUsd = ett.estimateSourceGasUsd;\n }\n\n execTime.logTotal(\"quoteOneClickProxy\");\n return result;\n }\n\n async sendTransaction(params: any) {\n const { transactions, callbackUrl } = params;\n\n if (!transactions || !Array.isArray(transactions)) {\n throw new Error(\"Invalid sendParam: transactions array is required\");\n }\n\n const wallet = await this.selector.wallet();\n const result = await wallet.signAndSendTransactions({\n transactions,\n callbackUrl: callbackUrl || \"/\"\n });\n\n if (result.slice(-1).length) {\n return result.slice(-1)[0].transaction.hash;\n }\n\n return \"\";\n }\n\n /**\n * Unified quote method that routes to specific quote methods based on type\n * @param type Service type from Service\n * @param params Parameters for the quote\n */\n async quote(type: Service, params: any) {\n switch (type) {\n case Service.OneClick:\n return await this.quoteOneClickProxy(params);\n default:\n throw new Error(`Unsupported quote type: ${type}`);\n }\n }\n\n /**\n * Unified send method that routes to specific send methods based on type\n * @param type Send type from SendType enum\n * @param params Parameters for the send transaction\n */\n async send(type: SendType, params: any) {\n switch (type) {\n case SendType.SEND:\n return await this.sendTransaction(params);\n case SendType.TRANSFER:\n return await this.transfer(params);\n default:\n throw new Error(`Unsupported send type: ${type}`);\n }\n }\n}\n\nexport { NearWallet };\n"]}
package/dist/index.mjs ADDED
@@ -0,0 +1,446 @@
1
+ import { Buffer } from 'buffer';
2
+ import Big from 'big.js';
3
+ import { getChainRpcUrl, Csl, OpenAPI, numberRemoveEndZero, getPrice, ExecTime, Service, SendType } from '@stableflow/core';
4
+ import { actionCreators } from '@near-js/transactions';
5
+
6
+ // src/near.ts
7
+ var createFunctionCallAction = (methodName, args, gas, deposit) => {
8
+ return actionCreators.functionCall(
9
+ methodName,
10
+ args,
11
+ BigInt(gas),
12
+ BigInt(deposit)
13
+ );
14
+ };
15
+ var NearWallet = class {
16
+ constructor(_selector) {
17
+ this.selector = _selector;
18
+ this.rpcUrl = getChainRpcUrl("near").rpcUrl;
19
+ const cs = new Csl(OpenAPI.DEBUG);
20
+ this.csl = cs.log;
21
+ }
22
+ async query(contractId, methodName, args = {}) {
23
+ const response = await fetch(this.rpcUrl, {
24
+ method: "POST",
25
+ headers: {
26
+ "Content-Type": "application/json"
27
+ },
28
+ body: JSON.stringify({
29
+ jsonrpc: "2.0",
30
+ id: "dontcare",
31
+ method: "query",
32
+ params: {
33
+ request_type: "call_function",
34
+ finality: "final",
35
+ account_id: contractId,
36
+ method_name: methodName,
37
+ args_base64: Buffer.from(JSON.stringify(args)).toString("base64")
38
+ }
39
+ })
40
+ });
41
+ const result = await response.json();
42
+ if (result.result && result.result.result) {
43
+ return JSON.parse(Buffer.from(result.result.result).toString());
44
+ }
45
+ return result;
46
+ }
47
+ async transfer(data) {
48
+ const wallet = await this.selector.wallet();
49
+ const checkStorage = await this.query(
50
+ data.originAsset,
51
+ "storage_balance_of",
52
+ {
53
+ account_id: data.depositAddress
54
+ }
55
+ );
56
+ const transactions = [];
57
+ if (!checkStorage?.available) {
58
+ transactions.push({
59
+ receiverId: data.originAsset,
60
+ actions: [
61
+ createFunctionCallAction(
62
+ "storage_deposit",
63
+ {
64
+ account_id: data.depositAddress,
65
+ registration_only: true
66
+ },
67
+ "15000000000000",
68
+ "1250000000000000000000"
69
+ )
70
+ ]
71
+ });
72
+ }
73
+ transactions.push({
74
+ receiverId: data.originAsset,
75
+ actions: [
76
+ createFunctionCallAction(
77
+ "ft_transfer",
78
+ {
79
+ receiver_id: data.depositAddress,
80
+ amount: data.amount,
81
+ memo: null
82
+ },
83
+ "30000000000000",
84
+ "1"
85
+ )
86
+ ]
87
+ });
88
+ const result = await wallet.signAndSendTransactions({
89
+ transactions,
90
+ callbackUrl: "/"
91
+ });
92
+ if (result.slice(-1).length) {
93
+ return result.slice(-1)[0].transaction.hash;
94
+ }
95
+ return "";
96
+ }
97
+ async getBalance(token, _account, options) {
98
+ const { isCatchError = false } = options || {};
99
+ if (token.symbol === "near" || token.symbol === "NEAR" || token.symbol === "native") {
100
+ return this.getNearBalance(_account, options);
101
+ }
102
+ try {
103
+ const balance = await this.query(token.contractAddress, "ft_balance_of", {
104
+ account_id: _account
105
+ });
106
+ return balance || "0";
107
+ } catch (error) {
108
+ this.csl("Near getTokenBalance", "red-500", "Get token balance failed: %o", error);
109
+ if (isCatchError) {
110
+ throw error;
111
+ }
112
+ return "0";
113
+ }
114
+ }
115
+ async balanceOf(token, account, options) {
116
+ return await this.getBalance(token, account, options);
117
+ }
118
+ /**
119
+ * Get native NEAR balance
120
+ * @param account Account ID
121
+ * @returns NEAR balance in yoctoNEAR (smallest unit)
122
+ */
123
+ async getNearBalance(account, options) {
124
+ const { isCatchError = false } = options || {};
125
+ try {
126
+ const response = await fetch(this.rpcUrl, {
127
+ method: "POST",
128
+ headers: {
129
+ "Content-Type": "application/json"
130
+ },
131
+ body: JSON.stringify({
132
+ jsonrpc: "2.0",
133
+ id: "dontcare",
134
+ method: "query",
135
+ params: {
136
+ request_type: "view_account",
137
+ finality: "final",
138
+ account_id: account
139
+ }
140
+ })
141
+ });
142
+ const result = await response.json();
143
+ return result.result?.amount || "0";
144
+ } catch (error) {
145
+ console.error("Failed to get NEAR balance:", error);
146
+ if (isCatchError) {
147
+ throw error;
148
+ }
149
+ return "0";
150
+ }
151
+ }
152
+ /**
153
+ * Estimate gas limit for transfer transaction
154
+ * @param data Transfer data
155
+ * @returns Gas limit estimate, gas price, and estimated gas cost
156
+ */
157
+ async estimateTransferGas(data) {
158
+ const { fromToken, depositAddress } = data;
159
+ const originAsset = fromToken.contractAddress;
160
+ const checkStorage = await this.query(
161
+ originAsset,
162
+ "storage_balance_of",
163
+ {
164
+ account_id: depositAddress
165
+ }
166
+ );
167
+ let gasLimit;
168
+ if (!checkStorage?.available) {
169
+ gasLimit = BigInt("15000000000000") + BigInt("30000000000000");
170
+ } else {
171
+ gasLimit = BigInt("30000000000000");
172
+ }
173
+ gasLimit = gasLimit * 120n / 100n;
174
+ const gasPrice = BigInt("100000000");
175
+ const estimateGas = gasLimit * gasPrice;
176
+ return {
177
+ gasLimit,
178
+ gasPrice,
179
+ estimateGas
180
+ };
181
+ }
182
+ async getEstimateGas(params) {
183
+ const { gasLimit, price, nativeToken, gasPrice } = params;
184
+ let finalGasPrice = gasPrice;
185
+ if (!finalGasPrice) {
186
+ try {
187
+ const gasPriceResponse = await fetch(this.rpcUrl, {
188
+ method: "POST",
189
+ headers: {
190
+ "Content-Type": "application/json"
191
+ },
192
+ body: JSON.stringify({
193
+ jsonrpc: "2.0",
194
+ id: "dontcare",
195
+ method: "gas_price",
196
+ params: {}
197
+ })
198
+ });
199
+ const gasPriceJson = await gasPriceResponse.json();
200
+ finalGasPrice = BigInt(gasPriceJson.result.gas_price);
201
+ } catch {
202
+ finalGasPrice = BigInt("100000000");
203
+ }
204
+ }
205
+ const estimateGas = BigInt(gasLimit) * BigInt(finalGasPrice);
206
+ const estimateGasAmount = Big(estimateGas.toString()).div(10 ** nativeToken.decimals);
207
+ const estimateGasUsd = Big(estimateGasAmount).times(price || 1);
208
+ return {
209
+ gasPrice: finalGasPrice,
210
+ usd: numberRemoveEndZero(Big(estimateGasUsd).toFixed(20)),
211
+ wei: estimateGas,
212
+ amount: numberRemoveEndZero(Big(estimateGasAmount).toFixed(nativeToken.decimals))
213
+ };
214
+ }
215
+ async estimateTransaction(params) {
216
+ const {
217
+ dry,
218
+ transactions,
219
+ fromToken,
220
+ prices
221
+ } = params;
222
+ const nativeTokenPrice = getPrice(prices, fromToken.nativeToken.symbol);
223
+ let totalGasLimit = BigInt("50000000000000");
224
+ for (let i = 1; i < transactions.length; i++) {
225
+ totalGasLimit += BigInt("15000000000000");
226
+ }
227
+ totalGasLimit = totalGasLimit * 120n / 100n;
228
+ const result = {
229
+ estimateSourceGasLimit: totalGasLimit,
230
+ estimateSourceGas: 0n,
231
+ estimateSourceGasUsd: "0"
232
+ };
233
+ const setDefaultGasLimit = async () => {
234
+ const { usd, wei } = await this.getEstimateGas({
235
+ gasLimit: totalGasLimit,
236
+ price: nativeTokenPrice,
237
+ nativeToken: fromToken.nativeToken,
238
+ gasPrice: dry ? "100000000" : void 0
239
+ });
240
+ result.estimateSourceGas = wei;
241
+ result.estimateSourceGasUsd = usd;
242
+ };
243
+ await setDefaultGasLimit();
244
+ return result;
245
+ }
246
+ async checkTransactionStatus(txHash) {
247
+ const wallet = await this.selector.wallet();
248
+ const accounts = await wallet.getAccounts();
249
+ const accountId = accounts[0]?.accountId;
250
+ try {
251
+ const response = await fetch(this.rpcUrl, {
252
+ method: "POST",
253
+ headers: {
254
+ "Content-Type": "application/json"
255
+ },
256
+ body: JSON.stringify({
257
+ jsonrpc: "2.0",
258
+ id: "dontcare",
259
+ method: "EXPERIMENTAL_tx_status",
260
+ params: {
261
+ tx_hash: txHash,
262
+ sender_account_id: accountId,
263
+ wait_until: "EXECUTED"
264
+ // wait_until: "NONE" | "EXECUTED_OPTIMISTIC" | "EXECUTED"
265
+ }
266
+ })
267
+ });
268
+ const txStatus = await response.json();
269
+ this.csl("Near checkTransactionStatus", "green-400", "fetch rpc success: %o", txStatus);
270
+ this.csl("Near checkTransactionStatus", "green-400", "fetch rpc status success: %o", typeof txStatus.result?.status?.SuccessValue !== "undefined");
271
+ } catch (error) {
272
+ this.csl("Near checkTransactionStatus", "red-500", "fetch rpc failed: %o", error);
273
+ }
274
+ }
275
+ async quoteOneClickProxy(params) {
276
+ const {
277
+ dry,
278
+ proxyAddress,
279
+ fromToken,
280
+ refundTo,
281
+ depositAddress,
282
+ amountWei,
283
+ prices
284
+ } = params;
285
+ const execTime = new ExecTime({ type: "OneClick NEAR", logStyle: "lime-200", isDebug: OpenAPI.DEBUG });
286
+ const result = { fees: {} };
287
+ try {
288
+ const wallet = await this.selector.wallet();
289
+ const accounts = await wallet.getAccounts();
290
+ const userAccountId = refundTo || accounts[0]?.accountId;
291
+ if (!userAccountId) {
292
+ throw new Error("No account found");
293
+ }
294
+ const tokenContract = fromToken.contractAddress;
295
+ const STABLEFLOW_CONTRACT = proxyAddress || "stableflowstg.near";
296
+ if (!depositAddress) {
297
+ throw new Error("depositAddress is required");
298
+ }
299
+ const transactions = [];
300
+ execTime.breakpoint();
301
+ const mergedCalls = [
302
+ this.query(
303
+ tokenContract,
304
+ "storage_balance_of",
305
+ {
306
+ account_id: depositAddress
307
+ }
308
+ ),
309
+ this.query(
310
+ tokenContract,
311
+ "storage_balance_of",
312
+ {
313
+ account_id: STABLEFLOW_CONTRACT
314
+ }
315
+ )
316
+ ];
317
+ const [checkStorageDepositAddress, checkStorageStableflow] = await Promise.all(mergedCalls);
318
+ execTime.log("query storage_balance_of (depositAddress and STABLEFLOW_CONTRACT)");
319
+ if (!checkStorageDepositAddress?.available) {
320
+ transactions.push({
321
+ receiverId: tokenContract,
322
+ actions: [
323
+ createFunctionCallAction(
324
+ "storage_deposit",
325
+ {
326
+ account_id: depositAddress,
327
+ registration_only: true
328
+ },
329
+ "15000000000000",
330
+ "1250000000000000000000"
331
+ )
332
+ ]
333
+ });
334
+ }
335
+ if (!checkStorageStableflow?.available) {
336
+ transactions.push({
337
+ receiverId: tokenContract,
338
+ actions: [
339
+ createFunctionCallAction(
340
+ "storage_deposit",
341
+ {
342
+ account_id: STABLEFLOW_CONTRACT,
343
+ registration_only: true
344
+ },
345
+ "15000000000000",
346
+ "1250000000000000000000"
347
+ )
348
+ ]
349
+ });
350
+ }
351
+ transactions.push({
352
+ receiverId: tokenContract,
353
+ actions: [
354
+ createFunctionCallAction(
355
+ "ft_transfer_call",
356
+ {
357
+ receiver_id: STABLEFLOW_CONTRACT,
358
+ amount: amountWei,
359
+ msg: depositAddress
360
+ },
361
+ "50000000000000",
362
+ // ft_transfer_call requires more gas
363
+ "1"
364
+ )
365
+ ]
366
+ });
367
+ execTime.breakpoint();
368
+ const ett = await this.estimateTransaction({
369
+ dry,
370
+ transactions,
371
+ fromToken,
372
+ prices
373
+ });
374
+ execTime.log("estimateTransaction");
375
+ result.fees.estimateGasUsd = ett.estimateSourceGasUsd;
376
+ result.estimateSourceGas = ett.estimateSourceGas;
377
+ result.totalEstimateSourceGas = ett.estimateSourceGas;
378
+ result.estimateSourceGasUsd = ett.estimateSourceGasUsd;
379
+ result.sendParam = {
380
+ transactions,
381
+ callbackUrl: "/"
382
+ };
383
+ } catch (error) {
384
+ this.csl("Near quoteOneClickProxy", "red-500", "oneclick quote proxy failed: %o", error);
385
+ const ett = await this.estimateTransaction({
386
+ dry,
387
+ transactions: [null, null, null],
388
+ fromToken,
389
+ prices
390
+ });
391
+ result.fees.estimateGasUsd = ett.estimateSourceGasUsd;
392
+ result.estimateSourceGas = ett.estimateSourceGas;
393
+ result.totalEstimateSourceGas = ett.estimateSourceGas;
394
+ result.estimateSourceGasUsd = ett.estimateSourceGasUsd;
395
+ }
396
+ execTime.logTotal("quoteOneClickProxy");
397
+ return result;
398
+ }
399
+ async sendTransaction(params) {
400
+ const { transactions, callbackUrl } = params;
401
+ if (!transactions || !Array.isArray(transactions)) {
402
+ throw new Error("Invalid sendParam: transactions array is required");
403
+ }
404
+ const wallet = await this.selector.wallet();
405
+ const result = await wallet.signAndSendTransactions({
406
+ transactions,
407
+ callbackUrl: callbackUrl || "/"
408
+ });
409
+ if (result.slice(-1).length) {
410
+ return result.slice(-1)[0].transaction.hash;
411
+ }
412
+ return "";
413
+ }
414
+ /**
415
+ * Unified quote method that routes to specific quote methods based on type
416
+ * @param type Service type from Service
417
+ * @param params Parameters for the quote
418
+ */
419
+ async quote(type, params) {
420
+ switch (type) {
421
+ case Service.OneClick:
422
+ return await this.quoteOneClickProxy(params);
423
+ default:
424
+ throw new Error(`Unsupported quote type: ${type}`);
425
+ }
426
+ }
427
+ /**
428
+ * Unified send method that routes to specific send methods based on type
429
+ * @param type Send type from SendType enum
430
+ * @param params Parameters for the send transaction
431
+ */
432
+ async send(type, params) {
433
+ switch (type) {
434
+ case SendType.SEND:
435
+ return await this.sendTransaction(params);
436
+ case SendType.TRANSFER:
437
+ return await this.transfer(params);
438
+ default:
439
+ throw new Error(`Unsupported send type: ${type}`);
440
+ }
441
+ }
442
+ };
443
+
444
+ export { NearWallet, NearWallet as default };
445
+ //# sourceMappingURL=index.mjs.map
446
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/near.ts"],"names":[],"mappings":";;;;;;AAcA,IAAM,wBAAA,GAA2B,CAC/B,UAAA,EACA,IAAA,EACA,KACA,OAAA,KACG;AACH,EAAA,OAAO,cAAA,CAAe,YAAA;AAAA,IACpB,UAAA;AAAA,IACA,IAAA;AAAA,IACA,OAAO,GAAG,CAAA;AAAA,IACV,OAAO,OAAO;AAAA,GAChB;AACF,CAAA;AAEA,IAAqB,aAArB,MAAgC;AAAA,EAK9B,YAAY,SAAA,EAAgB;AAC1B,IAAA,IAAA,CAAK,QAAA,GAAW,SAAA;AAGhB,IAAA,IAAA,CAAK,MAAA,GAAS,cAAA,CAAe,MAAM,CAAA,CAAE,MAAA;AAErC,IAAA,MAAM,EAAA,GAAK,IAAI,GAAA,CAAI,OAAA,CAAQ,KAAK,CAAA;AAChC,IAAA,IAAA,CAAK,MAAM,EAAA,CAAG,GAAA;AAAA,EAChB;AAAA,EAEA,MAAc,KAAA,CAAM,UAAA,EAAoB,UAAA,EAAo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,CAAA,CAAE,CAAC,EAAE,WAAA,CAAY,IAAA;AAAA,IACzC;AAEA,IAAA,OAAO,EAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,KAAA,CAAM,IAAA,EAAe,MAAA,EAAa;AACtC,IAAA,QAAQ,IAAA;AAAM,MACZ,KAAK,OAAA,CAAQ,QAAA;AACX,QAAA,OAAO,MAAM,IAAA,CAAK,kBAAA,CAAmB,MAAM,CAAA;AAAA,MAC7C;AACE,QAAA,MAAM,IAAI,KAAA,CAAM,CAAA,wBAAA,EAA2B,IAAI,CAAA,CAAE,CAAA;AAAA;AACrD,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,IAAA,CAAK,IAAA,EAAgB,MAAA,EAAa;AACtC,IAAA,QAAQ,IAAA;AAAM,MACZ,KAAK,QAAA,CAAS,IAAA;AACZ,QAAA,OAAO,MAAM,IAAA,CAAK,eAAA,CAAgB,MAAM,CAAA;AAAA,MAC1C,KAAK,QAAA,CAAS,QAAA;AACZ,QAAA,OAAO,MAAM,IAAA,CAAK,QAAA,CAAS,MAAM,CAAA;AAAA,MACnC;AACE,QAAA,MAAM,IAAI,KAAA,CAAM,CAAA,uBAAA,EAA0B,IAAI,CAAA,CAAE,CAAA;AAAA;AACpD,EACF;AACF","file":"index.mjs","sourcesContent":["import { Buffer } from \"buffer\";\nimport Big from \"big.js\";\nimport {\n getPrice,\n numberRemoveEndZero,\n SendType,\n Service,\n getChainRpcUrl,\n Csl,\n OpenAPI,\n ExecTime,\n} from \"@stableflow/core\";\nimport { actionCreators } from \"@near-js/transactions\";\n\nconst createFunctionCallAction = (\n methodName: string,\n args: Record<string, any>,\n gas: string,\n deposit: string\n) => {\n return actionCreators.functionCall(\n methodName,\n args,\n BigInt(gas),\n BigInt(deposit)\n );\n}\n\nexport default class NearWallet {\n private selector: any;\n private rpcUrl: string;\n private csl;\n\n constructor(_selector: any) {\n this.selector = _selector;\n // https://rpc.mainnet.near.org\n // https://nearinner.deltarpc.com\n this.rpcUrl = getChainRpcUrl(\"near\").rpcUrl;\n\n const cs = new Csl(OpenAPI.DEBUG);\n this.csl = cs.log;\n }\n\n private async query(contractId: string, methodName: string, args: any = {}) {\n const response = await fetch(this.rpcUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: \"dontcare\",\n method: \"query\",\n params: {\n request_type: \"call_function\",\n finality: \"final\",\n account_id: contractId,\n method_name: methodName,\n args_base64: Buffer.from(JSON.stringify(args)).toString(\"base64\")\n }\n })\n });\n const result = await response.json();\n if (result.result && result.result.result) {\n return JSON.parse(Buffer.from(result.result.result).toString());\n }\n return result;\n }\n\n async transfer(data: {\n originAsset: string;\n depositAddress: string;\n amount: string;\n }) {\n const wallet = await this.selector.wallet();\n const checkStorage = await this.query(\n data.originAsset,\n \"storage_balance_of\",\n {\n account_id: data.depositAddress\n }\n );\n const transactions = [];\n if (!checkStorage?.available) {\n transactions.push({\n receiverId: data.originAsset,\n actions: [\n createFunctionCallAction(\n \"storage_deposit\",\n {\n account_id: data.depositAddress,\n registration_only: true\n },\n \"15000000000000\",\n \"1250000000000000000000\"\n )\n ]\n });\n }\n transactions.push({\n receiverId: data.originAsset,\n actions: [\n createFunctionCallAction(\n \"ft_transfer\",\n {\n receiver_id: data.depositAddress,\n amount: data.amount,\n memo: null\n },\n \"30000000000000\",\n \"1\"\n )\n ]\n });\n\n const result = await wallet.signAndSendTransactions({\n transactions,\n callbackUrl: \"/\"\n });\n\n if (result.slice(-1).length) {\n return result.slice(-1)[0].transaction.hash;\n }\n\n return \"\";\n }\n\n async getBalance(token: any, _account: string, options?: { isCatchError?: boolean; }) {\n const { isCatchError = false } = options || {};\n\n if (token.symbol === \"near\" || token.symbol === \"NEAR\" || token.symbol === \"native\") {\n return this.getNearBalance(_account, options);\n }\n try {\n const balance = await this.query(token.contractAddress, \"ft_balance_of\", {\n account_id: _account\n });\n return balance || \"0\";\n } catch (error) {\n this.csl(\"Near getTokenBalance\", \"red-500\", \"Get token balance failed: %o\", error);\n if (isCatchError) {\n throw error;\n }\n return \"0\";\n }\n }\n\n async balanceOf(token: any, account: string, options?: { isCatchError?: boolean; }) {\n return await this.getBalance(token, account, options);\n }\n\n /**\n * Get native NEAR balance\n * @param account Account ID\n * @returns NEAR balance in yoctoNEAR (smallest unit)\n */\n async getNearBalance(account: string, options?: { isCatchError?: boolean; }): Promise<string> {\n const { isCatchError = false } = options || {};\n\n try {\n const response = await fetch(this.rpcUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: \"dontcare\",\n method: \"query\",\n params: {\n request_type: \"view_account\",\n finality: \"final\",\n account_id: account\n }\n })\n });\n const result = await response.json();\n return result.result?.amount || \"0\";\n } catch (error) {\n console.error(\"Failed to get NEAR balance:\", error);\n if (isCatchError) {\n throw error;\n }\n return \"0\";\n }\n }\n\n /**\n * Estimate gas limit for transfer transaction\n * @param data Transfer data\n * @returns Gas limit estimate, gas price, and estimated gas cost\n */\n async estimateTransferGas(data: {\n fromToken: any;\n depositAddress: string;\n amount: string;\n }): Promise<{\n gasLimit: bigint;\n gasPrice: bigint;\n estimateGas: bigint;\n }> {\n const { fromToken, depositAddress } = data;\n const originAsset = fromToken.contractAddress;\n\n // Check if storage deposit is needed\n const checkStorage = await this.query(\n originAsset,\n \"storage_balance_of\",\n {\n account_id: depositAddress\n }\n );\n\n let gasLimit: bigint;\n\n if (!checkStorage?.available) {\n // Storage deposit: 15000000000000 gas\n // ft_transfer: 30000000000000 gas\n gasLimit = BigInt(\"15000000000000\") + BigInt(\"30000000000000\");\n } else {\n // Only ft_transfer needed: 30000000000000 gas\n gasLimit = BigInt(\"30000000000000\");\n }\n\n // Increase by 20% to provide buffer\n gasLimit = (gasLimit * 120n) / 100n;\n\n // NEAR gas price is typically 100000000 yoctoNEAR per gas unit\n const gasPrice = BigInt(\"100000000\");\n\n // Calculate estimated gas cost: gasLimit * gasPrice\n const estimateGas = gasLimit * gasPrice;\n\n return {\n gasLimit,\n gasPrice,\n estimateGas\n };\n }\n\n async getEstimateGas(params: any) {\n const { gasLimit, price, nativeToken, gasPrice } = params;\n\n let finalGasPrice = gasPrice;\n if (!finalGasPrice) {\n try {\n const gasPriceResponse = await fetch(this.rpcUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: \"dontcare\",\n method: \"gas_price\",\n params: {}\n })\n });\n const gasPriceJson = await gasPriceResponse.json();\n finalGasPrice = BigInt(gasPriceJson.result.gas_price);\n } catch {\n finalGasPrice = BigInt(\"100000000\");\n }\n }\n\n const estimateGas = BigInt(gasLimit) * BigInt(finalGasPrice);\n const estimateGasAmount = Big(estimateGas.toString()).div(10 ** nativeToken.decimals);\n const estimateGasUsd = Big(estimateGasAmount).times(price || 1);\n\n return {\n gasPrice: finalGasPrice,\n usd: numberRemoveEndZero(Big(estimateGasUsd).toFixed(20)),\n wei: estimateGas,\n amount: numberRemoveEndZero(Big(estimateGasAmount).toFixed(nativeToken.decimals)),\n };\n }\n\n async estimateTransaction(params: any) {\n const {\n dry,\n transactions,\n fromToken,\n prices,\n } = params;\n\n const nativeTokenPrice = getPrice(prices, fromToken.nativeToken.symbol);\n\n let totalGasLimit = BigInt(\"50000000000000\"); // ft_transfer_call gas\n for (let i = 1; i < transactions.length; i++) {\n totalGasLimit += BigInt(\"15000000000000\");\n }\n // Add 20% buffer\n totalGasLimit = (totalGasLimit * 120n) / 100n;\n\n const result = {\n estimateSourceGasLimit: totalGasLimit,\n estimateSourceGas: 0n,\n estimateSourceGasUsd: \"0\",\n };\n\n const setDefaultGasLimit = async () => {\n const { usd, wei } = await this.getEstimateGas({\n gasLimit: totalGasLimit,\n price: nativeTokenPrice,\n nativeToken: fromToken.nativeToken,\n gasPrice: dry ? \"100000000\" : void 0,\n });\n result.estimateSourceGas = wei;\n result.estimateSourceGasUsd = usd;\n };\n\n await setDefaultGasLimit();\n\n return result;\n }\n\n async checkTransactionStatus(txHash: string) {\n const wallet = await this.selector.wallet();\n const accounts = await wallet.getAccounts();\n const accountId = accounts[0]?.accountId;\n\n try {\n const response = await fetch(this.rpcUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: \"dontcare\",\n method: \"EXPERIMENTAL_tx_status\",\n params: {\n tx_hash: txHash,\n sender_account_id: accountId,\n wait_until: \"EXECUTED\" // wait_until: \"NONE\" | \"EXECUTED_OPTIMISTIC\" | \"EXECUTED\"\n }\n })\n });\n const txStatus = await response.json();\n this.csl(\"Near checkTransactionStatus\", \"green-400\", \"fetch rpc success: %o\", txStatus);\n this.csl(\"Near checkTransactionStatus\", \"green-400\", \"fetch rpc status success: %o\", typeof txStatus.result?.status?.SuccessValue !== \"undefined\");\n } catch (error) {\n this.csl(\"Near checkTransactionStatus\", \"red-500\", \"fetch rpc failed: %o\", error);\n }\n }\n\n async quoteOneClickProxy(params: any) {\n const {\n dry,\n proxyAddress,\n fromToken,\n refundTo,\n depositAddress,\n amountWei,\n prices,\n } = params;\n\n const execTime = new ExecTime({ type: \"OneClick NEAR\", logStyle: \"lime-200\", isDebug: OpenAPI.DEBUG });\n\n const result: any = { fees: {} };\n\n try {\n const wallet = await this.selector.wallet();\n const accounts = await wallet.getAccounts();\n const userAccountId = refundTo || accounts[0]?.accountId;\n\n if (!userAccountId) {\n throw new Error(\"No account found\");\n }\n\n const tokenContract = fromToken.contractAddress;\n // proxyAddress should be stableflowstg.near, use default if not provided\n const STABLEFLOW_CONTRACT = proxyAddress || \"stableflowstg.near\";\n\n if (!depositAddress) {\n throw new Error(\"depositAddress is required\");\n }\n\n // Check and register token: register for intents address (depositAddress) and stableflowstg.near contract\n const transactions: any[] = [];\n\n // Check if depositAddress (intents address) is registered\n // Check if stableflowstg.near is registered\n execTime.breakpoint();\n const mergedCalls = [\n this.query(\n tokenContract,\n \"storage_balance_of\",\n {\n account_id: depositAddress\n }\n ),\n this.query(\n tokenContract,\n \"storage_balance_of\",\n {\n account_id: STABLEFLOW_CONTRACT\n }\n )\n ];\n const [checkStorageDepositAddress, checkStorageStableflow] = await Promise.all(mergedCalls);\n execTime.log(\"query storage_balance_of (depositAddress and STABLEFLOW_CONTRACT)\");\n\n if (!checkStorageDepositAddress?.available) {\n transactions.push({\n receiverId: tokenContract,\n actions: [\n createFunctionCallAction(\n \"storage_deposit\",\n {\n account_id: depositAddress,\n registration_only: true\n },\n \"15000000000000\",\n \"1250000000000000000000\"\n )\n ]\n });\n }\n\n if (!checkStorageStableflow?.available) {\n transactions.push({\n receiverId: tokenContract,\n actions: [\n createFunctionCallAction(\n \"storage_deposit\",\n {\n account_id: STABLEFLOW_CONTRACT,\n registration_only: true\n },\n \"15000000000000\",\n \"1250000000000000000000\"\n )\n ]\n });\n }\n\n // Build ft_transfer_call transaction\n transactions.push({\n receiverId: tokenContract,\n actions: [\n createFunctionCallAction(\n \"ft_transfer_call\",\n {\n receiver_id: STABLEFLOW_CONTRACT,\n amount: amountWei,\n msg: depositAddress\n },\n \"50000000000000\", // ft_transfer_call requires more gas\n \"1\"\n )\n ]\n });\n\n execTime.breakpoint();\n const ett = await this.estimateTransaction({\n dry,\n transactions,\n fromToken,\n prices,\n });\n execTime.log(\"estimateTransaction\");\n\n result.fees.estimateGasUsd = ett.estimateSourceGasUsd;\n result.estimateSourceGas = ett.estimateSourceGas;\n result.totalEstimateSourceGas = ett.estimateSourceGas;\n result.estimateSourceGasUsd = ett.estimateSourceGasUsd;\n\n // Set sendParam for subsequent transaction sending\n result.sendParam = {\n transactions,\n callbackUrl: \"/\"\n };\n\n } catch (error) {\n this.csl(\"Near quoteOneClickProxy\", \"red-500\", \"oneclick quote proxy failed: %o\", error);\n // Use default gas estimation\n const ett = await this.estimateTransaction({\n dry,\n transactions: [null, null, null],\n fromToken,\n prices,\n });\n\n result.fees.estimateGasUsd = ett.estimateSourceGasUsd;\n result.estimateSourceGas = ett.estimateSourceGas;\n result.totalEstimateSourceGas = ett.estimateSourceGas;\n result.estimateSourceGasUsd = ett.estimateSourceGasUsd;\n }\n\n execTime.logTotal(\"quoteOneClickProxy\");\n return result;\n }\n\n async sendTransaction(params: any) {\n const { transactions, callbackUrl } = params;\n\n if (!transactions || !Array.isArray(transactions)) {\n throw new Error(\"Invalid sendParam: transactions array is required\");\n }\n\n const wallet = await this.selector.wallet();\n const result = await wallet.signAndSendTransactions({\n transactions,\n callbackUrl: callbackUrl || \"/\"\n });\n\n if (result.slice(-1).length) {\n return result.slice(-1)[0].transaction.hash;\n }\n\n return \"\";\n }\n\n /**\n * Unified quote method that routes to specific quote methods based on type\n * @param type Service type from Service\n * @param params Parameters for the quote\n */\n async quote(type: Service, params: any) {\n switch (type) {\n case Service.OneClick:\n return await this.quoteOneClickProxy(params);\n default:\n throw new Error(`Unsupported quote type: ${type}`);\n }\n }\n\n /**\n * Unified send method that routes to specific send methods based on type\n * @param type Send type from SendType enum\n * @param params Parameters for the send transaction\n */\n async send(type: SendType, params: any) {\n switch (type) {\n case SendType.SEND:\n return await this.sendTransaction(params);\n case SendType.TRANSFER:\n return await this.transfer(params);\n default:\n throw new Error(`Unsupported send type: ${type}`);\n }\n }\n}\n\nexport { NearWallet };\n"]}
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@stableflow/wallet-near",
3
+ "version": "0.0.0-experimental-5a8afd7389-20260703",
4
+ "description": "NEAR wallet adapter for StableFlow SDK",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/stableflow-ai/stableflow-sdk.git",
9
+ "directory": "packages/wallet-near"
10
+ },
11
+ "main": "./dist/index.js",
12
+ "module": "./dist/index.mjs",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.mjs",
18
+ "require": "./dist/index.js"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "dependencies": {
25
+ "big.js": "^7.0.1",
26
+ "buffer": "^6.0.3",
27
+ "@stableflow/core": "0.0.0-experimental-5a8afd7389-20260703"
28
+ },
29
+ "peerDependencies": {
30
+ "@near-js/transactions": "^2.5.1"
31
+ },
32
+ "devDependencies": {
33
+ "@types/big.js": "^6.2.2",
34
+ "tsup": "^8.5.1",
35
+ "typescript": "^5.9.3"
36
+ },
37
+ "scripts": {
38
+ "build": "tsup",
39
+ "clean": "rm -rf dist"
40
+ }
41
+ }