@vleap/warps-adapter-near 0.1.0-beta.2

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/dist/index.mjs ADDED
@@ -0,0 +1,1145 @@
1
+ // src/WarpNearDataLoader.ts
2
+ import {
3
+ CacheTtl,
4
+ getProviderConfig,
5
+ WarpCache,
6
+ WarpCacheKey
7
+ } from "@vleap/warps";
8
+ import { connect, keyStores } from "near-api-js";
9
+
10
+ // src/constants.ts
11
+ var WarpNearConstants = {
12
+ NativeToken: {
13
+ Identifier: "NEAR",
14
+ Decimals: 24
15
+ },
16
+ Gas: {
17
+ Default: "300000000000000",
18
+ Transfer: "100000000000000",
19
+ FunctionCall: "300000000000000"
20
+ }
21
+ };
22
+ var NearExplorers = /* @__PURE__ */ ((NearExplorers2) => {
23
+ NearExplorers2["NearExplorer"] = "near_explorer";
24
+ NearExplorers2["NearBlocks"] = "near_blocks";
25
+ NearExplorers2["NearScan"] = "nearscan";
26
+ return NearExplorers2;
27
+ })(NearExplorers || {});
28
+ var NearExplorerMap = {
29
+ near: {
30
+ mainnet: ["near_explorer" /* NearExplorer */, "near_blocks" /* NearBlocks */, "nearscan" /* NearScan */],
31
+ testnet: ["near_explorer" /* NearExplorer */, "near_blocks" /* NearBlocks */, "nearscan" /* NearScan */],
32
+ devnet: ["near_explorer" /* NearExplorer */, "near_blocks" /* NearBlocks */, "nearscan" /* NearScan */]
33
+ }
34
+ };
35
+ var ExplorerUrls = {
36
+ ["near_explorer" /* NearExplorer */]: "https://explorer.near.org",
37
+ ["near_blocks" /* NearBlocks */]: "https://nearblocks.io",
38
+ ["nearscan" /* NearScan */]: "https://nearscan.io"
39
+ };
40
+ var NearExplorerNames = {
41
+ mainnet: ["near_explorer" /* NearExplorer */, "near_blocks" /* NearBlocks */, "nearscan" /* NearScan */],
42
+ testnet: ["near_explorer" /* NearExplorer */, "near_blocks" /* NearBlocks */, "nearscan" /* NearScan */],
43
+ devnet: ["near_explorer" /* NearExplorer */, "near_blocks" /* NearBlocks */, "nearscan" /* NearScan */]
44
+ };
45
+ var NearExplorerUrls = ExplorerUrls;
46
+
47
+ // src/tokens.ts
48
+ var NearTokens = [];
49
+ var KnownTokens = {
50
+ near: {
51
+ mainnet: NearTokens,
52
+ testnet: NearTokens,
53
+ devnet: NearTokens
54
+ }
55
+ };
56
+ var findKnownTokenById = (chain, env, id) => {
57
+ const chainTokens = KnownTokens[chain]?.[env] || [];
58
+ return chainTokens.find((token) => token.identifier === id) || null;
59
+ };
60
+ var getKnownTokensForChain = (chainName, env = "mainnet") => {
61
+ return KnownTokens[chainName]?.[env] || [];
62
+ };
63
+
64
+ // src/WarpNearDataLoader.ts
65
+ var WarpNearDataLoader = class {
66
+ constructor(config, chain) {
67
+ this.config = config;
68
+ this.chain = chain;
69
+ this.cache = new WarpCache(config.cache?.type);
70
+ const providerConfig = getProviderConfig(this.config, this.chain.name, this.config.env, this.chain.defaultApiUrl);
71
+ this.nearConfig = {
72
+ networkId: this.config.env === "mainnet" ? "mainnet" : this.config.env === "testnet" ? "testnet" : "testnet",
73
+ nodeUrl: providerConfig.url,
74
+ keyStore: new keyStores.InMemoryKeyStore()
75
+ };
76
+ }
77
+ async getAccount(address) {
78
+ try {
79
+ const near = await connect(this.nearConfig);
80
+ const account = await near.account(address);
81
+ const balance = await account.getAccountBalance();
82
+ const balanceBigInt = BigInt(balance.total);
83
+ return {
84
+ chain: this.chain.name,
85
+ address,
86
+ balance: balanceBigInt
87
+ };
88
+ } catch (error) {
89
+ throw new Error(`Failed to get account: ${error}`);
90
+ }
91
+ }
92
+ async getAccountAssets(address) {
93
+ try {
94
+ const account = await this.getAccount(address);
95
+ const assets = account.balance > 0n ? [{ ...this.chain.nativeToken, amount: account.balance }] : [];
96
+ const env = this.config.env === "mainnet" ? "mainnet" : this.config.env === "devnet" ? "devnet" : "testnet";
97
+ const knownTokens = getKnownTokensForChain(this.chain.name, env);
98
+ for (const token of knownTokens) {
99
+ try {
100
+ const near = await connect(this.nearConfig);
101
+ const accountObj = await near.account(address);
102
+ const balance = await accountObj.viewFunction({
103
+ contractId: token.identifier,
104
+ methodName: "ft_balance_of",
105
+ args: { account_id: address }
106
+ });
107
+ if (balance && BigInt(balance) > 0n) {
108
+ assets.push({
109
+ ...token,
110
+ amount: BigInt(balance)
111
+ });
112
+ }
113
+ } catch {
114
+ }
115
+ }
116
+ return assets;
117
+ } catch (error) {
118
+ return [];
119
+ }
120
+ }
121
+ async getAsset(identifier) {
122
+ try {
123
+ if (identifier === this.chain.nativeToken.identifier || identifier === WarpNearConstants.NativeToken.Identifier) {
124
+ return this.chain.nativeToken;
125
+ }
126
+ const cacheKey = WarpCacheKey.Asset(this.config.env, this.chain.name, identifier);
127
+ const cachedAsset = this.cache.get(cacheKey);
128
+ if (cachedAsset) {
129
+ return cachedAsset;
130
+ }
131
+ const env = this.config.env === "mainnet" ? "mainnet" : this.config.env === "devnet" ? "devnet" : "testnet";
132
+ const knownToken = findKnownTokenById(this.chain.name, env, identifier);
133
+ if (knownToken) {
134
+ return {
135
+ chain: this.chain.name,
136
+ identifier,
137
+ name: knownToken.name,
138
+ symbol: knownToken.symbol,
139
+ amount: 0n,
140
+ decimals: knownToken.decimals,
141
+ logoUrl: knownToken.logoUrl
142
+ };
143
+ }
144
+ try {
145
+ const near = await connect(this.nearConfig);
146
+ const account = await near.account(identifier);
147
+ const metadata = await account.viewFunction({
148
+ contractId: identifier,
149
+ methodName: "ft_metadata",
150
+ args: {}
151
+ });
152
+ const asset = {
153
+ chain: this.chain.name,
154
+ identifier,
155
+ name: metadata.name || "Unknown Token",
156
+ symbol: metadata.symbol || "UNKNOWN",
157
+ amount: 0n,
158
+ decimals: metadata.decimals || WarpNearConstants.NativeToken.Decimals,
159
+ logoUrl: metadata.icon || ""
160
+ };
161
+ this.cache.set(cacheKey, asset, CacheTtl.OneHour);
162
+ return asset;
163
+ } catch {
164
+ const asset = {
165
+ chain: this.chain.name,
166
+ identifier,
167
+ name: "Unknown Token",
168
+ symbol: "UNKNOWN",
169
+ amount: 0n,
170
+ decimals: WarpNearConstants.NativeToken.Decimals,
171
+ logoUrl: ""
172
+ };
173
+ return asset;
174
+ }
175
+ } catch (error) {
176
+ return null;
177
+ }
178
+ }
179
+ async getAction(identifier, awaitCompleted = false) {
180
+ try {
181
+ const near = await connect(this.nearConfig);
182
+ const txStatus = await near.connection.provider.txStatus(identifier, this.nearConfig.networkId);
183
+ if (!txStatus) return null;
184
+ const statusObj = txStatus.status;
185
+ const isSuccess = statusObj && ("SuccessValue" in statusObj || "SuccessReceiptId" in statusObj);
186
+ const status = isSuccess ? "success" : "failed";
187
+ const transaction = txStatus.transaction;
188
+ const receipt = txStatus.receipts?.[0];
189
+ const sender = transaction.signer_id;
190
+ const receiver = transaction.receiver_id;
191
+ const value = transaction.actions?.[0]?.Transfer?.deposit ? BigInt(transaction.actions[0].Transfer.deposit) : 0n;
192
+ return {
193
+ chain: this.chain.name,
194
+ id: identifier,
195
+ receiver,
196
+ sender,
197
+ value,
198
+ function: transaction.actions?.[0]?.FunctionCall?.method_name || "transfer",
199
+ status,
200
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
201
+ error: status === "failed" ? JSON.stringify(txStatus.status) : null,
202
+ tx: txStatus
203
+ };
204
+ } catch (error) {
205
+ return null;
206
+ }
207
+ }
208
+ async getAccountActions(address, options) {
209
+ return [];
210
+ }
211
+ };
212
+
213
+ // src/WarpNearExecutor.ts
214
+ import {
215
+ applyOutputToMessages,
216
+ extractResolvedInputValues as extractResolvedInputValues2,
217
+ getNextInfo,
218
+ getProviderConfig as getProviderConfig3,
219
+ getWarpActionByIndex,
220
+ getWarpWalletAddressFromConfig as getWarpWalletAddressFromConfig2
221
+ } from "@vleap/warps";
222
+ import { connect as connect3, keyStores as keyStores3 } from "near-api-js";
223
+
224
+ // src/WarpNearOutput.ts
225
+ import {
226
+ evaluateOutputCommon,
227
+ extractResolvedInputValues,
228
+ getProviderConfig as getProviderConfig2,
229
+ getWarpWalletAddressFromConfig,
230
+ parseOutputOutIndex,
231
+ WarpCache as WarpCache2,
232
+ WarpCacheKey as WarpCacheKey2,
233
+ WarpConstants as WarpConstants2
234
+ } from "@vleap/warps";
235
+ import { connect as connect2, keyStores as keyStores2 } from "near-api-js";
236
+
237
+ // src/WarpNearSerializer.ts
238
+ import {
239
+ WarpConstants,
240
+ WarpSerializer
241
+ } from "@vleap/warps";
242
+ var WarpNearSerializer = class {
243
+ constructor() {
244
+ this.coreSerializer = new WarpSerializer();
245
+ }
246
+ typedToString(value) {
247
+ if (typeof value === "string") {
248
+ if (value.endsWith(".near") || value.length > 2 && value.length < 65 && /^[a-z0-9._-]+$/.test(value) && !value.includes(" ")) {
249
+ return `address:${value}`;
250
+ }
251
+ if (value.startsWith("0x") || /^[0-9a-fA-F]+$/.test(value)) {
252
+ return `hex:${value}`;
253
+ }
254
+ return `string:${value}`;
255
+ }
256
+ if (typeof value === "number") {
257
+ if (Number.isInteger(value)) {
258
+ if (value >= 0 && value <= 255) return `uint8:${value}`;
259
+ if (value >= 0 && value <= 65535) return `uint16:${value}`;
260
+ if (value >= 0 && value <= 4294967295) return `uint32:${value}`;
261
+ return `uint64:${value}`;
262
+ }
263
+ return `string:${value}`;
264
+ }
265
+ if (typeof value === "bigint") {
266
+ return `biguint:${value.toString()}`;
267
+ }
268
+ if (typeof value === "boolean") {
269
+ return `boolean:${value}`;
270
+ }
271
+ if (value instanceof Uint8Array) {
272
+ return `hex:${Buffer.from(value).toString("hex")}`;
273
+ }
274
+ if (typeof value === "object" && value !== null && "identifier" in value && "amount" in value) {
275
+ const asset = value;
276
+ if (asset.decimals !== void 0) {
277
+ return `asset:${asset.identifier}${WarpConstants.ArgCompositeSeparator}${asset.amount.toString()}${WarpConstants.ArgCompositeSeparator}${asset.decimals}`;
278
+ }
279
+ return `asset:${asset.identifier}${WarpConstants.ArgCompositeSeparator}${asset.amount.toString()}`;
280
+ }
281
+ if (Array.isArray(value)) {
282
+ if (value.length === 0) return `list:string:`;
283
+ const types = value.map((item) => this.typedToString(item).split(WarpConstants.ArgParamsSeparator)[0]);
284
+ const type = types[0];
285
+ const values = value.map((item) => this.typedToString(item).split(WarpConstants.ArgParamsSeparator)[1]);
286
+ return `list:${type}:${values.join(",")}`;
287
+ }
288
+ if (value === null || value === void 0) {
289
+ return `string:null`;
290
+ }
291
+ return `string:${String(value)}`;
292
+ }
293
+ typedToNative(value) {
294
+ const stringValue = this.typedToString(value);
295
+ const [type, ...valueParts] = stringValue.split(WarpConstants.ArgParamsSeparator);
296
+ const nativeValue = valueParts.join(WarpConstants.ArgParamsSeparator);
297
+ return [type, this.parseNativeValue(type, nativeValue)];
298
+ }
299
+ nativeToTyped(type, value) {
300
+ switch (type) {
301
+ case "string":
302
+ return String(value);
303
+ case "uint8":
304
+ case "uint16":
305
+ case "uint32":
306
+ case "uint64":
307
+ return BigInt(value);
308
+ case "biguint":
309
+ return BigInt(value);
310
+ case "boolean":
311
+ return Boolean(value);
312
+ case "address":
313
+ return String(value);
314
+ case "hex":
315
+ return String(value);
316
+ case "asset":
317
+ if (typeof value === "object" && value !== null && "identifier" in value && "amount" in value) {
318
+ return value;
319
+ }
320
+ return value;
321
+ default:
322
+ if (type.startsWith("list:")) {
323
+ const [, itemType, itemsStr] = type.split(":");
324
+ if (!itemsStr) return [];
325
+ const items = itemsStr.split(",");
326
+ return items.map((item) => this.nativeToTyped(itemType, item));
327
+ }
328
+ return String(value);
329
+ }
330
+ }
331
+ nativeToType(type) {
332
+ switch (type) {
333
+ case "string":
334
+ return "string";
335
+ case "uint8":
336
+ case "uint16":
337
+ case "uint32":
338
+ case "uint64":
339
+ case "biguint":
340
+ return "bigint";
341
+ case "boolean":
342
+ return "boolean";
343
+ case "address":
344
+ return "string";
345
+ case "hex":
346
+ return "string";
347
+ default:
348
+ return "string";
349
+ }
350
+ }
351
+ stringToTyped(value) {
352
+ const parts = value.split(WarpConstants.ArgParamsSeparator, 2);
353
+ if (parts.length < 2) {
354
+ return value;
355
+ }
356
+ const [type, stringValue] = parts;
357
+ switch (type) {
358
+ case "string":
359
+ return stringValue;
360
+ case "uint8":
361
+ case "uint16":
362
+ case "uint32":
363
+ case "uint64":
364
+ return BigInt(stringValue);
365
+ case "biguint":
366
+ return BigInt(stringValue);
367
+ case "boolean":
368
+ return stringValue === "true";
369
+ case "address":
370
+ return stringValue;
371
+ case "hex":
372
+ return stringValue;
373
+ case "asset":
374
+ const assetParts = stringValue.split(WarpConstants.ArgCompositeSeparator);
375
+ const identifier = assetParts[0] || "";
376
+ const amount = assetParts[1] ? BigInt(assetParts[1]) : 0n;
377
+ const decimals = assetParts[2] ? parseInt(assetParts[2], 10) : void 0;
378
+ return { identifier, amount, decimals };
379
+ default:
380
+ if (type.startsWith("list:")) {
381
+ const [, itemType, itemsStr] = type.split(":");
382
+ if (!itemsStr) return [];
383
+ const items = itemsStr.split(",");
384
+ return items.map((item) => this.stringToTyped(`${itemType}:${item}`));
385
+ }
386
+ return stringValue;
387
+ }
388
+ }
389
+ parseNativeValue(type, value) {
390
+ switch (type) {
391
+ case "string":
392
+ return value;
393
+ case "uint8":
394
+ case "uint16":
395
+ case "uint32":
396
+ case "uint64":
397
+ case "biguint":
398
+ return BigInt(value);
399
+ case "boolean":
400
+ return value === "true";
401
+ case "address":
402
+ return value;
403
+ case "hex":
404
+ return value;
405
+ default:
406
+ return value;
407
+ }
408
+ }
409
+ };
410
+
411
+ // src/WarpNearOutput.ts
412
+ var WarpNearOutput = class {
413
+ constructor(config, chain) {
414
+ this.config = config;
415
+ this.chain = chain;
416
+ this.serializer = new WarpNearSerializer();
417
+ const providerConfig = getProviderConfig2(this.config, this.chain.name, this.config.env, this.chain.defaultApiUrl);
418
+ this.nearConfig = {
419
+ networkId: this.config.env === "mainnet" ? "mainnet" : this.config.env === "testnet" ? "testnet" : "testnet",
420
+ nodeUrl: providerConfig.url,
421
+ keyStore: new keyStores2.InMemoryKeyStore()
422
+ };
423
+ this.cache = new WarpCache2(config.cache?.type);
424
+ }
425
+ async getActionExecution(warp, actionIndex, tx) {
426
+ const inputs = this.cache.get(WarpCacheKey2.WarpExecutable(this.config.env, warp.meta?.hash || "", actionIndex)) ?? [];
427
+ const resolvedInputs = extractResolvedInputValues(inputs);
428
+ if (!tx) {
429
+ return this.createFailedExecution(warp, actionIndex, resolvedInputs);
430
+ }
431
+ if ("status" in tx && typeof tx.status === "string") {
432
+ return this.handleWarpChainAction(warp, actionIndex, tx, resolvedInputs);
433
+ }
434
+ if (typeof tx === "string") {
435
+ return this.handleTransactionHash(warp, actionIndex, tx, resolvedInputs);
436
+ }
437
+ return this.createFailedExecution(warp, actionIndex, resolvedInputs);
438
+ }
439
+ createFailedExecution(warp, actionIndex, resolvedInputs = []) {
440
+ return {
441
+ status: "error",
442
+ warp,
443
+ action: actionIndex,
444
+ user: getWarpWalletAddressFromConfig(this.config, this.chain.name),
445
+ txHash: "",
446
+ tx: null,
447
+ next: null,
448
+ values: { string: [], native: [], mapped: {} },
449
+ output: {},
450
+ messages: {},
451
+ destination: null,
452
+ resolvedInputs
453
+ };
454
+ }
455
+ handleWarpChainAction(warp, actionIndex, tx, resolvedInputs = []) {
456
+ const success = tx.status === "success";
457
+ const transactionHash = tx.id || tx.tx?.hash || "";
458
+ const rawValues = [transactionHash];
459
+ const stringValues = rawValues.map(String);
460
+ return {
461
+ status: success ? "success" : "error",
462
+ warp,
463
+ action: actionIndex,
464
+ user: getWarpWalletAddressFromConfig(this.config, this.chain.name),
465
+ txHash: transactionHash,
466
+ tx,
467
+ next: null,
468
+ values: { string: stringValues, native: rawValues, mapped: {} },
469
+ output: {},
470
+ messages: {},
471
+ destination: null,
472
+ resolvedInputs
473
+ };
474
+ }
475
+ async handleTransactionHash(warp, actionIndex, hash, resolvedInputs = []) {
476
+ try {
477
+ const near = await connect2(this.nearConfig);
478
+ const txStatus = await near.connection.provider.txStatus(hash, this.nearConfig.networkId);
479
+ if (!txStatus) {
480
+ return this.createFailedExecution(warp, actionIndex, resolvedInputs);
481
+ }
482
+ const statusObj = txStatus.status;
483
+ const success = statusObj && ("SuccessValue" in statusObj || "SuccessReceiptId" in statusObj);
484
+ const transaction = txStatus.transaction;
485
+ const rawValues = [hash];
486
+ const stringValues = rawValues.map(String);
487
+ return {
488
+ status: success ? "success" : "error",
489
+ warp,
490
+ action: actionIndex,
491
+ user: getWarpWalletAddressFromConfig(this.config, this.chain.name),
492
+ txHash: hash,
493
+ tx: {
494
+ hash,
495
+ transaction,
496
+ status: txStatus.status
497
+ },
498
+ next: null,
499
+ values: { string: stringValues, native: rawValues, mapped: {} },
500
+ output: {},
501
+ messages: {},
502
+ destination: null,
503
+ resolvedInputs
504
+ };
505
+ } catch (error) {
506
+ return this.createFailedExecution(warp, actionIndex, resolvedInputs);
507
+ }
508
+ }
509
+ async extractQueryOutput(warp, typedValues, actionIndex, inputs) {
510
+ const stringValues = typedValues.map((t) => this.serializer.typedToString(t));
511
+ const nativeValues = typedValues.map((t) => this.serializer.typedToNative(t)[1]);
512
+ const values = { string: stringValues, native: nativeValues, mapped: {} };
513
+ let output = {};
514
+ if (!warp.output) return { values, output };
515
+ const getNestedValue = (path) => {
516
+ const indices = path.split(".").slice(1).map((i) => parseInt(i) - 1);
517
+ if (indices.length === 0) return void 0;
518
+ let value = nativeValues[indices[0]];
519
+ for (let i = 1; i < indices.length; i++) {
520
+ if (value === void 0 || value === null) return void 0;
521
+ value = value[indices[i]];
522
+ }
523
+ return value;
524
+ };
525
+ for (const [key, path] of Object.entries(warp.output)) {
526
+ if (path.startsWith(WarpConstants2.Transform.Prefix)) continue;
527
+ const currentActionIndex = parseOutputOutIndex(path);
528
+ if (currentActionIndex !== null && currentActionIndex !== actionIndex) {
529
+ output[key] = null;
530
+ continue;
531
+ }
532
+ if (path.startsWith("out.") || path === "out" || path.startsWith("out[")) {
533
+ output[key] = getNestedValue(path) || null;
534
+ } else {
535
+ output[key] = path;
536
+ }
537
+ }
538
+ return { values, output: await evaluateOutputCommon(warp, output, actionIndex, inputs, this.serializer.coreSerializer, this.config) };
539
+ }
540
+ async getTransactionStatus(txHash) {
541
+ try {
542
+ const near = await connect2(this.nearConfig);
543
+ const txStatus = await near.connection.provider.txStatus(txHash, this.nearConfig.networkId);
544
+ if (!txStatus) {
545
+ return { status: "pending" };
546
+ }
547
+ const statusObj = txStatus.status;
548
+ const isSuccess = statusObj && ("SuccessValue" in statusObj || "SuccessReceiptId" in statusObj);
549
+ return {
550
+ status: isSuccess ? "confirmed" : "failed",
551
+ blockNumber: txStatus.transaction_outcome?.block_hash ? 0 : void 0,
552
+ gasUsed: BigInt(0)
553
+ };
554
+ } catch (error) {
555
+ throw new Error(`Failed to get transaction status: ${error}`);
556
+ }
557
+ }
558
+ async getTransactionReceipt(txHash) {
559
+ try {
560
+ const near = await connect2(this.nearConfig);
561
+ const txStatus = await near.connection.provider.txStatus(txHash, this.nearConfig.networkId);
562
+ if (!txStatus) {
563
+ return null;
564
+ }
565
+ return {
566
+ hash: txHash,
567
+ transaction: txStatus.transaction,
568
+ status: txStatus.status
569
+ };
570
+ } catch (error) {
571
+ return null;
572
+ }
573
+ }
574
+ };
575
+
576
+ // src/WarpNearExecutor.ts
577
+ var WarpNearExecutor = class {
578
+ constructor(config, chain) {
579
+ this.config = config;
580
+ this.chain = chain;
581
+ this.serializer = new WarpNearSerializer();
582
+ const providerConfig = getProviderConfig3(this.config, chain.name, this.config.env, this.chain.defaultApiUrl);
583
+ this.nearConfig = {
584
+ networkId: this.config.env === "mainnet" ? "mainnet" : this.config.env === "testnet" ? "testnet" : "testnet",
585
+ nodeUrl: providerConfig.url,
586
+ keyStore: new keyStores3.InMemoryKeyStore()
587
+ };
588
+ this.output = new WarpNearOutput(config, this.chain);
589
+ }
590
+ async createTransaction(executable) {
591
+ const action = getWarpActionByIndex(executable.warp, executable.action);
592
+ let tx = null;
593
+ if (action.type === "transfer") {
594
+ tx = await this.createTransferTransaction(executable);
595
+ } else if (action.type === "contract") {
596
+ tx = await this.createContractCallTransaction(executable);
597
+ } else if (action.type === "query") {
598
+ throw new Error("WarpNearExecutor: Invalid action type for createTransaction; Use executeQuery instead");
599
+ } else if (action.type === "collect") {
600
+ throw new Error("WarpNearExecutor: Invalid action type for createTransaction; Use executeCollect instead");
601
+ }
602
+ if (!tx) throw new Error(`WarpNearExecutor: Invalid action type (${action.type})`);
603
+ return tx;
604
+ }
605
+ async createTransferTransaction(executable) {
606
+ const userWallet = getWarpWalletAddressFromConfig2(this.config, executable.chain.name);
607
+ if (!userWallet) throw new Error("WarpNearExecutor: createTransfer - user address not set");
608
+ if (!executable.destination) throw new Error("WarpNearExecutor: Destination address is required");
609
+ if (executable.transfers && executable.transfers.length > 0) {
610
+ return this.createTokenTransferTransaction(executable, userWallet);
611
+ }
612
+ const amount = executable.value > 0n ? executable.value : 0n;
613
+ const amountInYoctoNear = amount.toString();
614
+ return {
615
+ receiverId: executable.destination,
616
+ actions: [
617
+ {
618
+ type: "Transfer",
619
+ params: {
620
+ deposit: amountInYoctoNear
621
+ }
622
+ }
623
+ ]
624
+ };
625
+ }
626
+ async createContractCallTransaction(executable) {
627
+ const userWallet = getWarpWalletAddressFromConfig2(this.config, executable.chain.name);
628
+ if (!userWallet) throw new Error("WarpNearExecutor: createContractCall - user address not set");
629
+ const action = getWarpActionByIndex(executable.warp, executable.action);
630
+ if (!action || !("func" in action) || !action.func) throw new Error("WarpNearExecutor: Contract action must have a function name");
631
+ if (!executable.destination) throw new Error("WarpNearExecutor: Contract address is required");
632
+ try {
633
+ const nativeArgs = executable.args.map((arg) => this.serializer.coreSerializer.stringToNative(arg)[1]);
634
+ const args = nativeArgs.length > 0 ? nativeArgs : {};
635
+ const gas = WarpNearConstants.Gas.FunctionCall;
636
+ const deposit = executable.value > 0n ? executable.value.toString() : "0";
637
+ return {
638
+ receiverId: executable.destination,
639
+ actions: [
640
+ {
641
+ type: "FunctionCall",
642
+ params: {
643
+ methodName: action.func,
644
+ args,
645
+ gas,
646
+ deposit
647
+ }
648
+ }
649
+ ]
650
+ };
651
+ } catch (error) {
652
+ const errorMessage = error instanceof Error ? error.message : String(error);
653
+ throw new Error(`WarpNearExecutor: Failed to create contract call: ${errorMessage}`);
654
+ }
655
+ }
656
+ async createTokenTransferTransaction(executable, userWallet) {
657
+ if (executable.transfers.length === 0) throw new Error("WarpNearExecutor: No transfers provided");
658
+ if (!this.chain.nativeToken?.identifier) throw new Error("WarpNearExecutor: No native token defined for this chain");
659
+ const nativeTokenTransfers = executable.transfers.filter(
660
+ (transfer) => transfer.identifier === this.chain.nativeToken.identifier || transfer.identifier === WarpNearConstants.NativeToken.Identifier
661
+ );
662
+ const ftTokenTransfers = executable.transfers.filter(
663
+ (transfer) => transfer.identifier !== this.chain.nativeToken.identifier && transfer.identifier !== WarpNearConstants.NativeToken.Identifier
664
+ );
665
+ if (nativeTokenTransfers.length === 1 && ftTokenTransfers.length === 0) {
666
+ const transfer = nativeTokenTransfers[0];
667
+ if (transfer.amount <= 0n) throw new Error("WarpNearExecutor: Native token transfer amount must be positive");
668
+ return {
669
+ receiverId: executable.destination,
670
+ actions: [
671
+ {
672
+ type: "Transfer",
673
+ params: {
674
+ deposit: transfer.amount.toString()
675
+ }
676
+ }
677
+ ]
678
+ };
679
+ }
680
+ if (nativeTokenTransfers.length === 0 && ftTokenTransfers.length === 1) {
681
+ return this.createSingleTokenTransfer(executable, ftTokenTransfers[0]);
682
+ }
683
+ if (executable.transfers.length > 1) throw new Error("WarpNearExecutor: Multiple token transfers not yet supported");
684
+ throw new Error("WarpNearExecutor: Invalid transfer configuration");
685
+ }
686
+ async createSingleTokenTransfer(executable, transfer) {
687
+ if (!executable.destination) throw new Error("WarpNearExecutor: Destination address is required");
688
+ const userWallet = getWarpWalletAddressFromConfig2(this.config, executable.chain.name);
689
+ if (!userWallet) throw new Error("WarpNearExecutor: User wallet not set");
690
+ const args = {
691
+ receiver_id: executable.destination,
692
+ amount: transfer.amount.toString()
693
+ };
694
+ return {
695
+ receiverId: transfer.identifier,
696
+ actions: [
697
+ {
698
+ type: "FunctionCall",
699
+ params: {
700
+ methodName: "ft_transfer",
701
+ args,
702
+ gas: WarpNearConstants.Gas.FunctionCall,
703
+ deposit: "1"
704
+ }
705
+ }
706
+ ]
707
+ };
708
+ }
709
+ async executeQuery(executable) {
710
+ const action = getWarpActionByIndex(executable.warp, executable.action);
711
+ if (action.type !== "query") throw new Error(`WarpNearExecutor: Invalid action type for executeQuery: ${action.type}`);
712
+ if (!action.func) throw new Error("WarpNearExecutor: Query action must have a function name");
713
+ let queryAddress;
714
+ try {
715
+ if (!executable.destination) throw new Error("WarpNearExecutor: Query address is required");
716
+ queryAddress = executable.destination;
717
+ } catch {
718
+ throw new Error(`WarpNearExecutor: Invalid address for query: ${executable.destination}`);
719
+ }
720
+ try {
721
+ const nativeArgs = executable.args.map((arg) => this.serializer.coreSerializer.stringToNative(arg)[1]);
722
+ const args = nativeArgs.length > 0 ? nativeArgs : {};
723
+ const near = await connect3(this.nearConfig);
724
+ const account = await near.account(queryAddress);
725
+ const result = await account.viewFunction({
726
+ contractId: queryAddress,
727
+ methodName: action.func,
728
+ args
729
+ });
730
+ const { values, output } = await this.output.extractQueryOutput(
731
+ executable.warp,
732
+ Array.isArray(result) ? result : [result],
733
+ executable.action,
734
+ executable.resolvedInputs
735
+ );
736
+ const next = getNextInfo(this.config, [], executable.warp, executable.action, output);
737
+ const destinationInput = executable.resolvedInputs.find((i) => i.input.position === "receiver" || i.input.position === "destination");
738
+ const destination = destinationInput?.value || executable.destination;
739
+ const resolvedInputs = extractResolvedInputValues2(executable.resolvedInputs);
740
+ return {
741
+ status: "success",
742
+ warp: executable.warp,
743
+ action: executable.action,
744
+ user: getWarpWalletAddressFromConfig2(this.config, executable.chain.name),
745
+ txHash: null,
746
+ tx: null,
747
+ next,
748
+ values,
749
+ output: { ...output, _DATA: result },
750
+ messages: applyOutputToMessages(executable.warp, output, this.config),
751
+ destination,
752
+ resolvedInputs
753
+ };
754
+ } catch (error) {
755
+ const errorMessage = error instanceof Error ? error.message : String(error);
756
+ const destinationInput = executable.resolvedInputs.find((i) => i.input.position === "receiver" || i.input.position === "destination");
757
+ const destination = destinationInput?.value || executable.destination;
758
+ const resolvedInputs = extractResolvedInputValues2(executable.resolvedInputs);
759
+ return {
760
+ status: "error",
761
+ warp: executable.warp,
762
+ action: executable.action,
763
+ user: getWarpWalletAddressFromConfig2(this.config, executable.chain.name),
764
+ txHash: null,
765
+ tx: null,
766
+ next: null,
767
+ values: { string: [], native: [], mapped: {} },
768
+ output: { _DATA: errorMessage, _ERROR: errorMessage },
769
+ messages: {},
770
+ destination,
771
+ resolvedInputs
772
+ };
773
+ }
774
+ }
775
+ };
776
+
777
+ // src/WarpNearExplorer.ts
778
+ var WarpNearExplorer = class {
779
+ constructor(chain, config) {
780
+ this.chain = chain;
781
+ this.config = config;
782
+ }
783
+ getExplorers() {
784
+ const explorers = NearExplorerNames[this.config.env];
785
+ if (!explorers) {
786
+ return ["near_explorer" /* NearExplorer */];
787
+ }
788
+ return explorers;
789
+ }
790
+ getPrimaryExplorer() {
791
+ const explorers = this.getExplorers();
792
+ return explorers[0];
793
+ }
794
+ getExplorerUrlByName(explorer) {
795
+ const userPreference = this.config.preferences?.explorers?.[this.chain.name];
796
+ if (userPreference && !explorer) {
797
+ const url2 = NearExplorerUrls[userPreference];
798
+ if (url2) return url2;
799
+ }
800
+ if (explorer) {
801
+ const url2 = NearExplorerUrls[explorer];
802
+ if (url2) return url2;
803
+ }
804
+ const primaryExplorer = this.getPrimaryExplorer();
805
+ const url = NearExplorerUrls[primaryExplorer];
806
+ return url || NearExplorerUrls[primaryExplorer];
807
+ }
808
+ getAccountUrl(address, explorer) {
809
+ const baseUrl = this.getExplorerUrlByName(explorer);
810
+ const network = this.config.env === "mainnet" ? "" : `/${this.config.env}`;
811
+ return `${baseUrl}${network}/accounts/${address}`;
812
+ }
813
+ getTransactionUrl(hash, explorer) {
814
+ const baseUrl = this.getExplorerUrlByName(explorer);
815
+ const network = this.config.env === "mainnet" ? "" : `/${this.config.env}`;
816
+ return `${baseUrl}${network}/transactions/${hash}`;
817
+ }
818
+ getBlockUrl(blockNumber, explorer) {
819
+ const baseUrl = this.getExplorerUrlByName(explorer);
820
+ const network = this.config.env === "mainnet" ? "" : `/${this.config.env}`;
821
+ return `${baseUrl}${network}/blocks/${blockNumber}`;
822
+ }
823
+ getAssetUrl(identifier, explorer) {
824
+ const baseUrl = this.getExplorerUrlByName(explorer);
825
+ const network = this.config.env === "mainnet" ? "" : `/${this.config.env}`;
826
+ return `${baseUrl}${network}/tokens/${identifier}`;
827
+ }
828
+ getContractUrl(address, explorer) {
829
+ const baseUrl = this.getExplorerUrlByName(explorer);
830
+ const network = this.config.env === "mainnet" ? "" : `/${this.config.env}`;
831
+ return `${baseUrl}${network}/accounts/${address}`;
832
+ }
833
+ getAllExplorers() {
834
+ return this.getExplorers();
835
+ }
836
+ getExplorerByName(name) {
837
+ const explorers = this.getExplorers();
838
+ return explorers.find((explorer) => explorer.toLowerCase() === name.toLowerCase());
839
+ }
840
+ getAccountUrls(address) {
841
+ const explorers = this.getAllExplorers();
842
+ const urls = {};
843
+ const network = this.config.env === "mainnet" ? "" : `/${this.config.env}`;
844
+ explorers.forEach((explorer) => {
845
+ const url = NearExplorerUrls[explorer];
846
+ if (url) {
847
+ urls[explorer] = `${url}${network}/accounts/${address}`;
848
+ }
849
+ });
850
+ return urls;
851
+ }
852
+ getTransactionUrls(hash) {
853
+ const explorers = this.getAllExplorers();
854
+ const urls = {};
855
+ const network = this.config.env === "mainnet" ? "" : `/${this.config.env}`;
856
+ explorers.forEach((explorer) => {
857
+ const url = NearExplorerUrls[explorer];
858
+ if (url) {
859
+ urls[explorer] = `${url}${network}/transactions/${hash}`;
860
+ }
861
+ });
862
+ return urls;
863
+ }
864
+ getAssetUrls(identifier) {
865
+ const explorers = this.getAllExplorers();
866
+ const urls = {};
867
+ const network = this.config.env === "mainnet" ? "" : `/${this.config.env}`;
868
+ explorers.forEach((explorer) => {
869
+ const url = NearExplorerUrls[explorer];
870
+ if (url) {
871
+ urls[explorer] = `${url}${network}/tokens/${identifier}`;
872
+ }
873
+ });
874
+ return urls;
875
+ }
876
+ getContractUrls(address) {
877
+ const explorers = this.getAllExplorers();
878
+ const urls = {};
879
+ const network = this.config.env === "mainnet" ? "" : `/${this.config.env}`;
880
+ explorers.forEach((explorer) => {
881
+ const url = NearExplorerUrls[explorer];
882
+ if (url) {
883
+ urls[explorer] = `${url}${network}/accounts/${address}`;
884
+ }
885
+ });
886
+ return urls;
887
+ }
888
+ getBlockUrls(blockNumber) {
889
+ const explorers = this.getAllExplorers();
890
+ const urls = {};
891
+ const network = this.config.env === "mainnet" ? "" : `/${this.config.env}`;
892
+ explorers.forEach((explorer) => {
893
+ const url = NearExplorerUrls[explorer];
894
+ if (url) {
895
+ urls[explorer] = `${url}${network}/blocks/${blockNumber}`;
896
+ }
897
+ });
898
+ return urls;
899
+ }
900
+ };
901
+
902
+ // src/WarpNearWallet.ts
903
+ import * as bip39 from "@scure/bip39";
904
+ import { wordlist } from "@scure/bip39/wordlists/english.js";
905
+ import {
906
+ getProviderConfig as getProviderConfig4,
907
+ getWarpWalletMnemonicFromConfig,
908
+ getWarpWalletPrivateKeyFromConfig
909
+ } from "@vleap/warps";
910
+ import bs58 from "bs58";
911
+ import { connect as connect4, KeyPair, keyStores as keyStores4 } from "near-api-js";
912
+ var WarpNearWallet = class {
913
+ constructor(config, chain) {
914
+ this.config = config;
915
+ this.chain = chain;
916
+ const providerConfig = getProviderConfig4(config, chain.name, config.env, chain.defaultApiUrl);
917
+ this.nearConfig = {
918
+ networkId: this.config.env === "mainnet" ? "mainnet" : this.config.env === "testnet" ? "testnet" : "testnet",
919
+ nodeUrl: providerConfig.url,
920
+ keyStore: new keyStores4.InMemoryKeyStore()
921
+ };
922
+ }
923
+ async signTransaction(tx) {
924
+ if (!tx || typeof tx !== "object") throw new Error("Invalid transaction object");
925
+ const keyPair = this.getKeyPair();
926
+ const accountId = this.getAddress();
927
+ if (!accountId) throw new Error("No account ID available");
928
+ await this.nearConfig.keyStore.setKey(this.nearConfig.networkId, accountId, keyPair);
929
+ const near = await connect4(this.nearConfig);
930
+ const account = await near.account(accountId);
931
+ if (tx.signature) {
932
+ return tx;
933
+ }
934
+ const signedTx = await account.signAndSendTransaction({
935
+ receiverId: tx.receiverId,
936
+ actions: tx.actions
937
+ });
938
+ return {
939
+ ...tx,
940
+ signature: signedTx.transaction.hash,
941
+ transactionHash: signedTx.transaction.hash
942
+ };
943
+ }
944
+ async signTransactions(txs) {
945
+ if (txs.length === 0) return [];
946
+ return Promise.all(txs.map(async (tx) => this.signTransaction(tx)));
947
+ }
948
+ async signMessage(message) {
949
+ const keyPair = this.getKeyPair();
950
+ const messageBytes = new TextEncoder().encode(message);
951
+ const signature = keyPair.sign(messageBytes);
952
+ return bs58.encode(signature.signature);
953
+ }
954
+ async sendTransaction(tx) {
955
+ if (!tx || typeof tx !== "object") throw new Error("Invalid transaction object");
956
+ const keyPair = this.getKeyPair();
957
+ const accountId = this.getAddress();
958
+ if (!accountId) throw new Error("No account ID available");
959
+ await this.nearConfig.keyStore.setKey(this.nearConfig.networkId, accountId, keyPair);
960
+ const near = await connect4(this.nearConfig);
961
+ const account = await near.account(accountId);
962
+ if (tx.transactionHash) {
963
+ return tx.transactionHash;
964
+ }
965
+ const result = await account.signAndSendTransaction({
966
+ receiverId: tx.receiverId,
967
+ actions: tx.actions
968
+ });
969
+ return result.transaction.hash;
970
+ }
971
+ async sendTransactions(txs) {
972
+ return Promise.all(txs.map(async (tx) => this.sendTransaction(tx)));
973
+ }
974
+ create(mnemonic) {
975
+ const seed = bip39.mnemonicToSeedSync(mnemonic);
976
+ const keyPair = KeyPair.fromRandom("ed25519");
977
+ const publicKey = keyPair.getPublicKey();
978
+ const accountId = publicKey.toString().split(":")[1] || publicKey.toString();
979
+ return {
980
+ address: accountId,
981
+ privateKey: keyPair.toString(),
982
+ mnemonic
983
+ };
984
+ }
985
+ generate() {
986
+ const mnemonic = bip39.generateMnemonic(wordlist);
987
+ const seed = bip39.mnemonicToSeedSync(mnemonic);
988
+ const keyPair = KeyPair.fromRandom("ed25519");
989
+ const publicKey = keyPair.getPublicKey();
990
+ const accountId = publicKey.toString().split(":")[1] || publicKey.toString();
991
+ return {
992
+ address: accountId,
993
+ privateKey: keyPair.toString(),
994
+ mnemonic
995
+ };
996
+ }
997
+ getAddress() {
998
+ try {
999
+ const privateKey = getWarpWalletPrivateKeyFromConfig(this.config, this.chain.name);
1000
+ if (privateKey) {
1001
+ try {
1002
+ const keyPair = KeyPair.fromString(privateKey);
1003
+ const publicKey = keyPair.getPublicKey();
1004
+ return publicKey.toString().split(":")[1] || publicKey.toString();
1005
+ } catch {
1006
+ return null;
1007
+ }
1008
+ }
1009
+ const mnemonic = getWarpWalletMnemonicFromConfig(this.config, this.chain.name);
1010
+ if (mnemonic) {
1011
+ const seed = bip39.mnemonicToSeedSync(mnemonic);
1012
+ const keyPair = KeyPair.fromRandom("ed25519");
1013
+ const publicKey = keyPair.getPublicKey();
1014
+ return publicKey.toString().split(":")[1] || publicKey.toString();
1015
+ }
1016
+ const wallet = this.config.user?.wallets?.[this.chain.name];
1017
+ if (wallet && typeof wallet === "object" && "address" in wallet) {
1018
+ return wallet.address;
1019
+ }
1020
+ if (wallet && typeof wallet === "string") {
1021
+ return wallet;
1022
+ }
1023
+ return null;
1024
+ } catch {
1025
+ return null;
1026
+ }
1027
+ }
1028
+ getPublicKey() {
1029
+ try {
1030
+ const keyPair = this.getKeyPair();
1031
+ const publicKey = keyPair.getPublicKey();
1032
+ return publicKey.toString();
1033
+ } catch {
1034
+ return null;
1035
+ }
1036
+ }
1037
+ getKeyPair() {
1038
+ const privateKey = getWarpWalletPrivateKeyFromConfig(this.config, this.chain.name);
1039
+ if (privateKey) {
1040
+ try {
1041
+ try {
1042
+ return KeyPair.fromString(privateKey);
1043
+ } catch {
1044
+ }
1045
+ const keyPair = KeyPair.fromRandom("ed25519");
1046
+ return keyPair;
1047
+ } catch (error) {
1048
+ if (error instanceof Error) {
1049
+ throw new Error(`Invalid private key format: ${error.message}`);
1050
+ }
1051
+ throw new Error("Invalid private key format");
1052
+ }
1053
+ }
1054
+ const mnemonic = getWarpWalletMnemonicFromConfig(this.config, this.chain.name);
1055
+ if (mnemonic) {
1056
+ const seed = bip39.mnemonicToSeedSync(mnemonic);
1057
+ const keyPair = KeyPair.fromRandom("ed25519");
1058
+ return keyPair;
1059
+ }
1060
+ throw new Error("No private key or mnemonic provided");
1061
+ }
1062
+ };
1063
+
1064
+ // src/chains/common.ts
1065
+ var createNearAdapter = (chainName, chainInfos) => {
1066
+ return (config, fallback) => {
1067
+ if (!fallback) throw new Error(`${chainName} adapter requires a fallback adapter`);
1068
+ return {
1069
+ chainInfo: chainInfos[config.env],
1070
+ builder: () => fallback.builder(),
1071
+ executor: new WarpNearExecutor(config, chainInfos[config.env]),
1072
+ output: new WarpNearOutput(config, chainInfos[config.env]),
1073
+ serializer: new WarpNearSerializer(),
1074
+ registry: fallback.registry,
1075
+ explorer: new WarpNearExplorer(chainInfos[config.env], config),
1076
+ abiBuilder: () => fallback.abiBuilder(),
1077
+ brandBuilder: () => fallback.brandBuilder(),
1078
+ dataLoader: new WarpNearDataLoader(config, chainInfos[config.env]),
1079
+ wallet: new WarpNearWallet(config, chainInfos[config.env])
1080
+ };
1081
+ };
1082
+ };
1083
+
1084
+ // src/chains/near.ts
1085
+ var NativeTokenNear = {
1086
+ chain: "near",
1087
+ identifier: "NEAR",
1088
+ symbol: "NEAR",
1089
+ name: "NEAR",
1090
+ decimals: 24,
1091
+ logoUrl: "https://vleap.ai/images/tokens/near.svg"
1092
+ };
1093
+ var getNearAdapter = createNearAdapter("near", {
1094
+ mainnet: {
1095
+ name: "near",
1096
+ displayName: "NEAR Mainnet",
1097
+ chainId: "mainnet",
1098
+ blockTime: 1200,
1099
+ addressHrp: "",
1100
+ defaultApiUrl: "https://rpc.mainnet.near.org",
1101
+ logoUrl: "https://vleap.ai/images/chains/near.svg",
1102
+ nativeToken: NativeTokenNear
1103
+ },
1104
+ testnet: {
1105
+ name: "near",
1106
+ displayName: "NEAR Testnet",
1107
+ chainId: "testnet",
1108
+ blockTime: 1200,
1109
+ addressHrp: "",
1110
+ defaultApiUrl: "https://rpc.testnet.near.org",
1111
+ logoUrl: "https://vleap.ai/images/chains/near.svg",
1112
+ nativeToken: NativeTokenNear
1113
+ },
1114
+ devnet: {
1115
+ name: "near",
1116
+ displayName: "NEAR Devnet",
1117
+ chainId: "testnet",
1118
+ blockTime: 1200,
1119
+ addressHrp: "",
1120
+ defaultApiUrl: "https://rpc.testnet.near.org",
1121
+ logoUrl: "https://vleap.ai/images/chains/near.svg",
1122
+ nativeToken: NativeTokenNear
1123
+ }
1124
+ });
1125
+ export {
1126
+ ExplorerUrls,
1127
+ KnownTokens,
1128
+ NativeTokenNear,
1129
+ NearExplorerMap,
1130
+ NearExplorerNames,
1131
+ NearExplorerUrls,
1132
+ NearExplorers,
1133
+ NearTokens,
1134
+ WarpNearConstants,
1135
+ WarpNearDataLoader,
1136
+ WarpNearExecutor,
1137
+ WarpNearExplorer,
1138
+ WarpNearOutput,
1139
+ WarpNearSerializer,
1140
+ WarpNearWallet,
1141
+ findKnownTokenById,
1142
+ getKnownTokensForChain,
1143
+ getNearAdapter
1144
+ };
1145
+ //# sourceMappingURL=index.mjs.map