@fastnear/intents 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,802 @@
1
+ /* ⋈ 🏃🏻💨 FastNear intents - IIFE/UMD (@fastnear/intents version 1.6.0) */
2
+ /* https://www.npmjs.com/package/@fastnear/intents/v/1.6.0 */
3
+ "use strict";
4
+ var nearIntents = (() => {
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (let key of __getOwnPropNames(from))
17
+ if (!__hasOwnProp.call(to, key) && key !== except)
18
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
+ }
20
+ return to;
21
+ };
22
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
23
+
24
+ // src/index.ts
25
+ var src_exports2 = {};
26
+ __export(src_exports2, {
27
+ FT_TRANSFER_CALL_GAS: () => FT_TRANSFER_CALL_GAS,
28
+ INTENTS_CONTRACT_ID: () => INTENTS_CONTRACT_ID,
29
+ IntentsHttpError: () => IntentsHttpError,
30
+ ONE_CLICK_BASE_URL: () => ONE_CLICK_BASE_URL,
31
+ ONE_YOCTO: () => ONE_YOCTO,
32
+ SOLVER_RELAY_URL: () => SOLVER_RELAY_URL,
33
+ SolverRelayError: () => SolverRelayError,
34
+ WITHDRAW_GAS: () => WITHDRAW_GAS,
35
+ WRAP_NEAR_CONTRACT_ID: () => WRAP_NEAR_CONTRACT_ID,
36
+ WRAP_NEAR_GAS: () => WRAP_NEAR_GAS,
37
+ buildIntentMessage: () => buildIntentMessage,
38
+ createOneClickClient: () => createOneClickClient,
39
+ createSolverRelayClient: () => createSolverRelayClient,
40
+ createWalletIntentSigner: () => createWalletIntentSigner,
41
+ defaultDeadline: () => defaultDeadline,
42
+ encodeIntentSignature: () => encodeIntentSignature,
43
+ ftDepositAction: () => ftDepositAction,
44
+ ftWithdrawAction: () => ftWithdrawAction,
45
+ mtBalance: () => mtBalance,
46
+ mtBatchBalances: () => mtBatchBalances,
47
+ normalizeIntentPublicKey: () => normalizeIntentPublicKey,
48
+ randomNonce: () => randomNonce,
49
+ toSignedIntent: () => toSignedIntent,
50
+ unsignedPayloadParts: () => unsignedPayloadParts,
51
+ wrapNearAction: () => wrapNearAction
52
+ });
53
+
54
+ // src/types.ts
55
+ var INTENTS_CONTRACT_ID = "intents.near";
56
+ var ONE_CLICK_BASE_URL = "https://1click.chaindefuser.com";
57
+ var SOLVER_RELAY_URL = "https://solver-relay-v2.chaindefuser.com/rpc";
58
+
59
+ // src/one-click.ts
60
+ var IntentsHttpError = class extends Error {
61
+ static {
62
+ __name(this, "IntentsHttpError");
63
+ }
64
+ status;
65
+ body;
66
+ constructor(message, status, body) {
67
+ super(message);
68
+ this.name = "IntentsHttpError";
69
+ this.status = status;
70
+ this.body = body;
71
+ }
72
+ };
73
+ async function parseBody(response) {
74
+ const text = await response.text();
75
+ try {
76
+ return text ? JSON.parse(text) : null;
77
+ } catch {
78
+ return text;
79
+ }
80
+ }
81
+ __name(parseBody, "parseBody");
82
+ function createOneClickClient(options = {}) {
83
+ const baseUrl = (options.baseUrl ?? ONE_CLICK_BASE_URL).replace(/\/$/, "");
84
+ const fetchImplementation = options.fetch ?? globalThis.fetch;
85
+ if (typeof fetchImplementation !== "function") {
86
+ throw new Error("A fetch implementation is required");
87
+ }
88
+ const authHeaders = {};
89
+ if (options.apiKey) authHeaders["X-API-Key"] = options.apiKey;
90
+ if (options.jwt) authHeaders.Authorization = `Bearer ${options.jwt}`;
91
+ async function request(method, path, body) {
92
+ const headers = body === void 0 ? authHeaders : { ...authHeaders, "Content-Type": "application/json" };
93
+ const response = await fetchImplementation(`${baseUrl}${path}`, {
94
+ method,
95
+ headers,
96
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
97
+ });
98
+ const parsed = await parseBody(response);
99
+ if (!response.ok) {
100
+ const detail = parsed && typeof parsed === "object" && "message" in parsed ? ` \u2014 ${JSON.stringify(parsed.message)}` : "";
101
+ throw new IntentsHttpError(
102
+ `1Click ${method} ${path} failed with ${response.status}${detail}`,
103
+ response.status,
104
+ parsed
105
+ );
106
+ }
107
+ return parsed;
108
+ }
109
+ __name(request, "request");
110
+ return {
111
+ tokens: /* @__PURE__ */ __name(() => request("GET", "/v0/tokens"), "tokens"),
112
+ quote: /* @__PURE__ */ __name((quoteRequest) => request("POST", "/v0/quote", quoteRequest), "quote"),
113
+ status: /* @__PURE__ */ __name(({ depositAddress, depositMemo }) => {
114
+ const query = new URLSearchParams({ depositAddress });
115
+ if (depositMemo) query.set("depositMemo", depositMemo);
116
+ return request("GET", `/v0/status?${query}`);
117
+ }, "status"),
118
+ submitDeposit: /* @__PURE__ */ __name((submitRequest) => request("POST", "/v0/deposit/submit", submitRequest), "submitDeposit"),
119
+ generateIntent: /* @__PURE__ */ __name(({ standard = "nep413", signerId, depositAddress }) => request("POST", "/v0/generate-intent", {
120
+ type: "swap_transfer",
121
+ standard,
122
+ signerId,
123
+ depositAddress
124
+ }), "generateIntent"),
125
+ submitIntent: /* @__PURE__ */ __name(({ signedData }) => request("POST", "/v0/submit-intent", {
126
+ type: "swap_transfer",
127
+ signedData
128
+ }), "submitIntent")
129
+ };
130
+ }
131
+ __name(createOneClickClient, "createOneClickClient");
132
+
133
+ // ../utils/node_modules/base58-js/base58_chars.js
134
+ var base58_chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
135
+ var base58_chars_default = base58_chars;
136
+
137
+ // ../utils/node_modules/base58-js/create_base58_map.js
138
+ var create_base58_map = /* @__PURE__ */ __name(() => {
139
+ const base58M = Array(256).fill(-1);
140
+ for (let i = 0; i < base58_chars_default.length; ++i)
141
+ base58M[base58_chars_default.charCodeAt(i)] = i;
142
+ return base58M;
143
+ }, "create_base58_map");
144
+ var create_base58_map_default = create_base58_map;
145
+
146
+ // ../utils/node_modules/base58-js/binary_to_base58.js
147
+ var base58Map = create_base58_map_default();
148
+ function binary_to_base58(uint8array) {
149
+ const result = [];
150
+ for (const byte of uint8array) {
151
+ let carry = byte;
152
+ for (let j = 0; j < result.length; ++j) {
153
+ const x = (base58Map[result[j]] << 8) + carry;
154
+ result[j] = base58_chars_default.charCodeAt(x % 58);
155
+ carry = x / 58 | 0;
156
+ }
157
+ while (carry) {
158
+ result.push(base58_chars_default.charCodeAt(carry % 58));
159
+ carry = carry / 58 | 0;
160
+ }
161
+ }
162
+ for (const byte of uint8array)
163
+ if (byte) break;
164
+ else result.push("1".charCodeAt(0));
165
+ result.reverse();
166
+ return String.fromCharCode(...result);
167
+ }
168
+ __name(binary_to_base58, "binary_to_base58");
169
+ var binary_to_base58_default = binary_to_base58;
170
+
171
+ // ../../node_modules/js-base64/base64.mjs
172
+ var _hasBuffer = typeof Buffer === "function";
173
+ var _TD = typeof TextDecoder === "function" ? new TextDecoder() : void 0;
174
+ var _TE = typeof TextEncoder === "function" ? new TextEncoder() : void 0;
175
+ var b64ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
176
+ var b64chs = Array.prototype.slice.call(b64ch);
177
+ var b64tab = ((a) => {
178
+ let tab = {};
179
+ a.forEach((c, i) => tab[c] = i);
180
+ return tab;
181
+ })(b64chs);
182
+ var b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
183
+ var _fromCC = String.fromCharCode.bind(String);
184
+ var _U8Afrom = typeof Uint8Array.from === "function" ? Uint8Array.from.bind(Uint8Array) : (it) => new Uint8Array(Array.prototype.slice.call(it, 0));
185
+ var _mkUriSafe = /* @__PURE__ */ __name((src) => src.replace(/=/g, "").replace(/[+\/]/g, (m0) => m0 == "+" ? "-" : "_"), "_mkUriSafe");
186
+ var _tidyB64 = /* @__PURE__ */ __name((s) => s.replace(/[^A-Za-z0-9\+\/]/g, ""), "_tidyB64");
187
+ var btoaPolyfill = /* @__PURE__ */ __name((bin) => {
188
+ let u32, c0, c1, c2, asc = "";
189
+ const pad = bin.length % 3;
190
+ for (let i = 0; i < bin.length; ) {
191
+ if ((c0 = bin.charCodeAt(i++)) > 255 || (c1 = bin.charCodeAt(i++)) > 255 || (c2 = bin.charCodeAt(i++)) > 255)
192
+ throw new TypeError("invalid character found");
193
+ u32 = c0 << 16 | c1 << 8 | c2;
194
+ asc += b64chs[u32 >> 18 & 63] + b64chs[u32 >> 12 & 63] + b64chs[u32 >> 6 & 63] + b64chs[u32 & 63];
195
+ }
196
+ return pad ? asc.slice(0, pad - 3) + "===".substring(pad) : asc;
197
+ }, "btoaPolyfill");
198
+ var _btoa = typeof btoa === "function" ? (bin) => btoa(bin) : _hasBuffer ? (bin) => Buffer.from(bin, "binary").toString("base64") : btoaPolyfill;
199
+ var _fromUint8Array = _hasBuffer ? (u8a) => Buffer.from(u8a).toString("base64") : (u8a) => {
200
+ const maxargs = 4096;
201
+ let strs = [];
202
+ for (let i = 0, l = u8a.length; i < l; i += maxargs) {
203
+ strs.push(_fromCC.apply(null, u8a.subarray(i, i + maxargs)));
204
+ }
205
+ return _btoa(strs.join(""));
206
+ };
207
+ var fromUint8Array = /* @__PURE__ */ __name((u8a, urlsafe = false) => urlsafe ? _mkUriSafe(_fromUint8Array(u8a)) : _fromUint8Array(u8a), "fromUint8Array");
208
+ var atobPolyfill = /* @__PURE__ */ __name((asc) => {
209
+ asc = asc.replace(/\s+/g, "");
210
+ if (!b64re.test(asc))
211
+ throw new TypeError("malformed base64.");
212
+ asc += "==".slice(2 - (asc.length & 3));
213
+ let u24, bin = "", r1, r2;
214
+ for (let i = 0; i < asc.length; ) {
215
+ u24 = b64tab[asc.charAt(i++)] << 18 | b64tab[asc.charAt(i++)] << 12 | (r1 = b64tab[asc.charAt(i++)]) << 6 | (r2 = b64tab[asc.charAt(i++)]);
216
+ bin += r1 === 64 ? _fromCC(u24 >> 16 & 255) : r2 === 64 ? _fromCC(u24 >> 16 & 255, u24 >> 8 & 255) : _fromCC(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255);
217
+ }
218
+ return bin;
219
+ }, "atobPolyfill");
220
+ var _atob = typeof atob === "function" ? (asc) => atob(_tidyB64(asc)) : _hasBuffer ? (asc) => Buffer.from(asc, "base64").toString("binary") : atobPolyfill;
221
+ var _toUint8Array = _hasBuffer ? (a) => _U8Afrom(Buffer.from(a, "base64")) : (a) => _U8Afrom(_atob(a).split("").map((c) => c.charCodeAt(0)));
222
+ var toUint8Array = /* @__PURE__ */ __name((a) => _toUint8Array(_unURI(a)), "toUint8Array");
223
+ var _unURI = /* @__PURE__ */ __name((a) => _tidyB64(a.replace(/[-_]/g, (m0) => m0 == "-" ? "+" : "/")), "_unURI");
224
+
225
+ // ../utils/src/storage.ts
226
+ var memoryStore = /* @__PURE__ */ new Map();
227
+ var memoryStorageBackend = {
228
+ getItem: /* @__PURE__ */ __name((key) => memoryStore.get(key) || null, "getItem"),
229
+ setItem: /* @__PURE__ */ __name((key, value) => memoryStore.set(key, value), "setItem"),
230
+ removeItem: /* @__PURE__ */ __name((key) => memoryStore.delete(key), "removeItem"),
231
+ clear: /* @__PURE__ */ __name(() => memoryStore.clear(), "clear")
232
+ };
233
+ var createDefaultStorage = /* @__PURE__ */ __name(() => {
234
+ try {
235
+ if (typeof globalThis !== "undefined" && "localStorage" in globalThis && globalThis.localStorage) {
236
+ return globalThis.localStorage;
237
+ }
238
+ } catch {
239
+ }
240
+ return memoryStorageBackend;
241
+ }, "createDefaultStorage");
242
+ var storageBackend = createDefaultStorage();
243
+
244
+ // ../utils/src/misc.ts
245
+ function base64ToBytes(b64Val) {
246
+ return toUint8Array(b64Val);
247
+ }
248
+ __name(base64ToBytes, "base64ToBytes");
249
+ function bytesToBase64(bytesArr) {
250
+ return fromUint8Array(bytesArr);
251
+ }
252
+ __name(bytesToBase64, "bytesToBase64");
253
+
254
+ // ../borsh-schema/src/index.ts
255
+ var nearChainSchema = new class BorshSchema {
256
+ static {
257
+ __name(this, "BorshSchema");
258
+ }
259
+ Ed25519Signature = {
260
+ struct: {
261
+ data: { array: { type: "u8", len: 64 } }
262
+ }
263
+ };
264
+ Secp256k1Signature = {
265
+ struct: {
266
+ data: { array: { type: "u8", len: 65 } }
267
+ }
268
+ };
269
+ MlDsa65Signature = {
270
+ struct: {
271
+ data: { array: { type: "u8", len: 3309 } }
272
+ }
273
+ };
274
+ Signature = {
275
+ enum: [
276
+ { struct: { ed25519Signature: this.Ed25519Signature } },
277
+ { struct: { secp256k1Signature: this.Secp256k1Signature } },
278
+ { struct: { mlDsa65Signature: this.MlDsa65Signature } }
279
+ ]
280
+ };
281
+ Ed25519Data = {
282
+ struct: {
283
+ data: { array: { type: "u8", len: 32 } }
284
+ }
285
+ };
286
+ Secp256k1Data = {
287
+ struct: {
288
+ data: { array: { type: "u8", len: 64 } }
289
+ }
290
+ };
291
+ MlDsa65Data = {
292
+ struct: {
293
+ data: { array: { type: "u8", len: 1952 } }
294
+ }
295
+ };
296
+ PublicKey = {
297
+ enum: [
298
+ { struct: { ed25519Key: this.Ed25519Data } },
299
+ { struct: { secp256k1Key: this.Secp256k1Data } },
300
+ { struct: { mlDsa65Key: this.MlDsa65Data } }
301
+ ]
302
+ };
303
+ FunctionCallPermission = {
304
+ struct: {
305
+ allowance: { option: "u128" },
306
+ receiverId: "string",
307
+ methodNames: { array: { type: "string" } }
308
+ }
309
+ };
310
+ FullAccessPermission = {
311
+ struct: {}
312
+ };
313
+ AccessKeyPermission = {
314
+ enum: [
315
+ { struct: { functionCall: this.FunctionCallPermission } },
316
+ { struct: { fullAccess: this.FullAccessPermission } }
317
+ ]
318
+ };
319
+ AccessKey = {
320
+ struct: {
321
+ nonce: "u64",
322
+ permission: this.AccessKeyPermission
323
+ }
324
+ };
325
+ CreateAccount = {
326
+ struct: {}
327
+ };
328
+ DeployContract = {
329
+ struct: {
330
+ code: { array: { type: "u8" } }
331
+ }
332
+ };
333
+ FunctionCall = {
334
+ struct: {
335
+ methodName: "string",
336
+ args: { array: { type: "u8" } },
337
+ gas: "u64",
338
+ deposit: "u128"
339
+ }
340
+ };
341
+ Transfer = {
342
+ struct: {
343
+ deposit: "u128"
344
+ }
345
+ };
346
+ Stake = {
347
+ struct: {
348
+ stake: "u128",
349
+ publicKey: this.PublicKey
350
+ }
351
+ };
352
+ AddKey = {
353
+ struct: {
354
+ publicKey: this.PublicKey,
355
+ accessKey: this.AccessKey
356
+ }
357
+ };
358
+ DeleteKey = {
359
+ struct: {
360
+ publicKey: this.PublicKey
361
+ }
362
+ };
363
+ DeleteAccount = {
364
+ struct: {
365
+ beneficiaryId: "string"
366
+ }
367
+ };
368
+ ClassicAction = {
369
+ enum: [
370
+ { struct: { createAccount: this.CreateAccount } },
371
+ { struct: { deployContract: this.DeployContract } },
372
+ { struct: { functionCall: this.FunctionCall } },
373
+ { struct: { transfer: this.Transfer } },
374
+ { struct: { stake: this.Stake } },
375
+ { struct: { addKey: this.AddKey } },
376
+ { struct: { deleteKey: this.DeleteKey } },
377
+ { struct: { deleteAccount: this.DeleteAccount } }
378
+ ]
379
+ };
380
+ DelegateAction = {
381
+ struct: {
382
+ senderId: "string",
383
+ receiverId: "string",
384
+ actions: { array: { type: this.ClassicAction } },
385
+ nonce: "u64",
386
+ maxBlockHeight: "u64",
387
+ publicKey: this.PublicKey
388
+ }
389
+ };
390
+ SignedDelegate = {
391
+ struct: {
392
+ delegateAction: this.DelegateAction,
393
+ signature: this.Signature
394
+ }
395
+ };
396
+ Action = {
397
+ enum: [
398
+ { struct: { createAccount: this.CreateAccount } },
399
+ { struct: { deployContract: this.DeployContract } },
400
+ { struct: { functionCall: this.FunctionCall } },
401
+ { struct: { transfer: this.Transfer } },
402
+ { struct: { stake: this.Stake } },
403
+ { struct: { addKey: this.AddKey } },
404
+ { struct: { deleteKey: this.DeleteKey } },
405
+ { struct: { deleteAccount: this.DeleteAccount } },
406
+ { struct: { signedDelegate: this.SignedDelegate } }
407
+ ]
408
+ };
409
+ Transaction = {
410
+ struct: {
411
+ signerId: "string",
412
+ publicKey: this.PublicKey,
413
+ nonce: "u64",
414
+ receiverId: "string",
415
+ blockHash: { array: { type: "u8", len: 32 } },
416
+ actions: { array: { type: this.Action } }
417
+ }
418
+ };
419
+ SignedTransaction = {
420
+ struct: {
421
+ transaction: this.Transaction,
422
+ signature: this.Signature
423
+ }
424
+ };
425
+ }();
426
+ var getBorshSchema = /* @__PURE__ */ __name(() => nearChainSchema, "getBorshSchema");
427
+
428
+ // ../utils/src/transaction.ts
429
+ var SCHEMA = getBorshSchema();
430
+
431
+ // src/signing.ts
432
+ function randomNonce() {
433
+ return crypto.getRandomValues(new Uint8Array(32));
434
+ }
435
+ __name(randomNonce, "randomNonce");
436
+ var DEFAULT_DEADLINE_MS = 5 * 60 * 1e3;
437
+ function defaultDeadline(ms = DEFAULT_DEADLINE_MS) {
438
+ return new Date(Date.now() + ms).toISOString();
439
+ }
440
+ __name(defaultDeadline, "defaultDeadline");
441
+ function buildIntentMessage({
442
+ signerId,
443
+ intents,
444
+ deadline
445
+ }) {
446
+ if (!signerId) throw new Error("signerId is required");
447
+ if (!Array.isArray(intents) || intents.length === 0) {
448
+ throw new Error("At least one intent is required");
449
+ }
450
+ return {
451
+ signer_id: signerId,
452
+ deadline: deadline ?? defaultDeadline(),
453
+ intents
454
+ };
455
+ }
456
+ __name(buildIntentMessage, "buildIntentMessage");
457
+ function encodeIntentSignature(signature) {
458
+ if (typeof signature === "string") {
459
+ if (signature.startsWith("ed25519:") || signature.startsWith("secp256k1:")) {
460
+ return signature;
461
+ }
462
+ return encodeIntentSignature(base64ToBytes(signature));
463
+ }
464
+ if (signature.length === 64) return `ed25519:${binary_to_base58_default(signature)}`;
465
+ if (signature.length === 65) return `secp256k1:${binary_to_base58_default(signature)}`;
466
+ throw new Error(
467
+ `Unsupported NEP-413 signature length: ${signature.length} (expected 64 or 65 bytes)`
468
+ );
469
+ }
470
+ __name(encodeIntentSignature, "encodeIntentSignature");
471
+ function normalizeIntentPublicKey(publicKey) {
472
+ if (!publicKey) throw new Error("A public key is required");
473
+ return publicKey.includes(":") ? publicKey : `ed25519:${publicKey}`;
474
+ }
475
+ __name(normalizeIntentPublicKey, "normalizeIntentPublicKey");
476
+ function toSignedIntent({
477
+ message,
478
+ nonce,
479
+ recipient = INTENTS_CONTRACT_ID,
480
+ publicKey,
481
+ signature,
482
+ callbackUrl
483
+ }) {
484
+ if (nonce.length !== 32) {
485
+ throw new Error(`NEP-413 nonce must be exactly 32 bytes, got ${nonce.length}`);
486
+ }
487
+ return {
488
+ standard: "nep413",
489
+ payload: {
490
+ message: typeof message === "string" ? message : JSON.stringify(message),
491
+ nonce: bytesToBase64(nonce),
492
+ recipient,
493
+ ...callbackUrl ? { callbackUrl } : {}
494
+ },
495
+ public_key: normalizeIntentPublicKey(publicKey),
496
+ signature: encodeIntentSignature(signature)
497
+ };
498
+ }
499
+ __name(toSignedIntent, "toSignedIntent");
500
+ function unsignedPayloadParts(input) {
501
+ const payload = "payload" in input && typeof input.payload === "object" ? input.payload : input;
502
+ if ("standard" in input && typeof input.standard === "string" && input.standard !== "nep413") {
503
+ throw new Error(
504
+ `This signer only signs nep413 payloads; got standard "${input.standard}"`
505
+ );
506
+ }
507
+ if (typeof payload?.message !== "string" || typeof payload?.recipient !== "string") {
508
+ throw new Error("Unsigned payload must carry message and recipient strings");
509
+ }
510
+ const nonce = typeof payload.nonce === "string" ? base64ToBytes(payload.nonce) : payload.nonce;
511
+ if (!(nonce instanceof Uint8Array) || nonce.length !== 32) {
512
+ throw new Error("Unsigned payload nonce must decode to exactly 32 bytes");
513
+ }
514
+ return {
515
+ message: payload.message,
516
+ nonce,
517
+ recipient: payload.recipient,
518
+ ...payload.callbackUrl ? { callbackUrl: payload.callbackUrl } : {}
519
+ };
520
+ }
521
+ __name(unsignedPayloadParts, "unsignedPayloadParts");
522
+ function assertExpectedRecipient(recipient, options) {
523
+ const expected = options?.expectedRecipient ?? INTENTS_CONTRACT_ID;
524
+ if (recipient !== expected) {
525
+ throw new Error(
526
+ `Refusing to sign a payload for recipient "${recipient}" \u2014 expected "${expected}". Pass { expectedRecipient } only when intentionally targeting a different verifier.`
527
+ );
528
+ }
529
+ }
530
+ __name(assertExpectedRecipient, "assertExpectedRecipient");
531
+ function signerIdFromMessage(message) {
532
+ try {
533
+ const parsed = JSON.parse(message);
534
+ return typeof parsed?.signer_id === "string" ? parsed.signer_id : void 0;
535
+ } catch {
536
+ return void 0;
537
+ }
538
+ }
539
+ __name(signerIdFromMessage, "signerIdFromMessage");
540
+ function createWalletIntentSigner({
541
+ wallet,
542
+ network = "mainnet"
543
+ }) {
544
+ if (!wallet || typeof wallet.signMessage !== "function") {
545
+ throw new Error(
546
+ "A FastNEAR wallet module with signMessage is required (connect @fastnear/wallet first)"
547
+ );
548
+ }
549
+ async function signParts({
550
+ message,
551
+ nonce,
552
+ recipient,
553
+ callbackUrl,
554
+ expectedSigner
555
+ }) {
556
+ if (callbackUrl) {
557
+ throw new Error(
558
+ "Wallet intent signing cannot bind callbackUrl payloads; use the local signer or drop callbackUrl"
559
+ );
560
+ }
561
+ const signed = await wallet.signMessage({
562
+ message,
563
+ recipient,
564
+ nonce,
565
+ network
566
+ });
567
+ if (expectedSigner && signed.accountId && signed.accountId !== expectedSigner) {
568
+ throw new Error(
569
+ `Wallet signed as ${signed.accountId} but the intent names ${expectedSigner}; reconnect the intended account`
570
+ );
571
+ }
572
+ return toSignedIntent({
573
+ message,
574
+ nonce,
575
+ recipient,
576
+ publicKey: signed.publicKey,
577
+ signature: signed.signature,
578
+ callbackUrl
579
+ });
580
+ }
581
+ __name(signParts, "signParts");
582
+ return {
583
+ async signIntents(params) {
584
+ const signerId = params.signerId ?? (typeof wallet.accountId === "function" ? wallet.accountId({ network }) : null);
585
+ if (!signerId) {
586
+ throw new Error(`No wallet account connected on ${network}`);
587
+ }
588
+ const message = buildIntentMessage({
589
+ signerId,
590
+ intents: params.intents,
591
+ deadline: params.deadline
592
+ });
593
+ return signParts({
594
+ message: JSON.stringify(message),
595
+ nonce: params.nonce ?? randomNonce(),
596
+ recipient: params.verifyingContract ?? INTENTS_CONTRACT_ID,
597
+ expectedSigner: signerId
598
+ });
599
+ },
600
+ async signPayload(payload, options) {
601
+ const parts = unsignedPayloadParts(payload);
602
+ assertExpectedRecipient(parts.recipient, options);
603
+ return signParts({
604
+ ...parts,
605
+ expectedSigner: signerIdFromMessage(parts.message)
606
+ });
607
+ }
608
+ };
609
+ }
610
+ __name(createWalletIntentSigner, "createWalletIntentSigner");
611
+
612
+ // src/verifier.ts
613
+ var FT_TRANSFER_CALL_GAS = "100000000000000";
614
+ var WITHDRAW_GAS = "100000000000000";
615
+ var WRAP_NEAR_GAS = "30000000000000";
616
+ var ONE_YOCTO = "1";
617
+ var WRAP_NEAR_CONTRACT_ID = "wrap.near";
618
+ function ftDepositAction({
619
+ amount,
620
+ creditTo,
621
+ msg,
622
+ verifierId = INTENTS_CONTRACT_ID,
623
+ gas = FT_TRANSFER_CALL_GAS
624
+ }) {
625
+ if (creditTo !== void 0 && msg !== void 0) {
626
+ throw new Error("Pass either creditTo or msg, not both");
627
+ }
628
+ return {
629
+ type: "FunctionCall",
630
+ methodName: "ft_transfer_call",
631
+ args: {
632
+ receiver_id: verifierId,
633
+ amount,
634
+ msg: msg ?? creditTo ?? ""
635
+ },
636
+ gas,
637
+ deposit: ONE_YOCTO
638
+ };
639
+ }
640
+ __name(ftDepositAction, "ftDepositAction");
641
+ function wrapNearAction({
642
+ amountYocto,
643
+ gas = WRAP_NEAR_GAS
644
+ }) {
645
+ return {
646
+ type: "FunctionCall",
647
+ methodName: "near_deposit",
648
+ args: {},
649
+ gas,
650
+ deposit: amountYocto
651
+ };
652
+ }
653
+ __name(wrapNearAction, "wrapNearAction");
654
+ function ftWithdrawAction({
655
+ token,
656
+ receiverId,
657
+ amount,
658
+ memo,
659
+ msg,
660
+ storageDeposit,
661
+ gas = WITHDRAW_GAS
662
+ }) {
663
+ if (token.includes(":")) {
664
+ throw new Error(
665
+ `ft_withdraw takes the plain token contract id, not a prefixed multi-token id: ${token}`
666
+ );
667
+ }
668
+ return {
669
+ type: "FunctionCall",
670
+ methodName: "ft_withdraw",
671
+ args: {
672
+ token,
673
+ receiver_id: receiverId,
674
+ amount,
675
+ ...memo !== void 0 ? { memo } : {},
676
+ ...msg !== void 0 ? { msg } : {},
677
+ ...storageDeposit !== void 0 ? { storage_deposit: storageDeposit } : {}
678
+ },
679
+ gas,
680
+ deposit: ONE_YOCTO
681
+ };
682
+ }
683
+ __name(ftWithdrawAction, "ftWithdrawAction");
684
+ async function mtBalance({
685
+ accountId,
686
+ tokenId,
687
+ view,
688
+ verifierId = INTENTS_CONTRACT_ID
689
+ }) {
690
+ const result = await view({
691
+ contractId: verifierId,
692
+ methodName: "mt_balance_of",
693
+ args: { account_id: accountId, token_id: tokenId }
694
+ });
695
+ return String(result ?? "0");
696
+ }
697
+ __name(mtBalance, "mtBalance");
698
+ async function mtBatchBalances({
699
+ accountId,
700
+ tokenIds,
701
+ view,
702
+ verifierId = INTENTS_CONTRACT_ID
703
+ }) {
704
+ const result = await view({
705
+ contractId: verifierId,
706
+ methodName: "mt_batch_balance_of",
707
+ args: { account_id: accountId, token_ids: tokenIds }
708
+ });
709
+ if (!Array.isArray(result) || result.length !== tokenIds.length) {
710
+ throw new Error(
711
+ `mt_batch_balance_of returned ${Array.isArray(result) ? result.length : typeof result} results for ${tokenIds.length} token ids`
712
+ );
713
+ }
714
+ return Object.fromEntries(
715
+ tokenIds.map((tokenId, index) => [tokenId, String(result[index] ?? "0")])
716
+ );
717
+ }
718
+ __name(mtBatchBalances, "mtBatchBalances");
719
+
720
+ // src/relay.ts
721
+ var SolverRelayError = class extends Error {
722
+ static {
723
+ __name(this, "SolverRelayError");
724
+ }
725
+ rpcError;
726
+ constructor(message, rpcError) {
727
+ super(message);
728
+ this.name = "SolverRelayError";
729
+ this.rpcError = rpcError;
730
+ }
731
+ };
732
+ function createSolverRelayClient(options = {}) {
733
+ const url = options.url ?? SOLVER_RELAY_URL;
734
+ const fetchImplementation = options.fetch ?? globalThis.fetch;
735
+ if (typeof fetchImplementation !== "function") {
736
+ throw new Error("A fetch implementation is required");
737
+ }
738
+ const headers = { "Content-Type": "application/json" };
739
+ if (options.apiKey) headers["X-API-Key"] = options.apiKey;
740
+ let nextId = 0;
741
+ async function call(method, params) {
742
+ const id = ++nextId;
743
+ const response = await fetchImplementation(url, {
744
+ method: "POST",
745
+ headers,
746
+ body: JSON.stringify({ id, jsonrpc: "2.0", method, params: [params] })
747
+ });
748
+ const text = await response.text();
749
+ let parsed = null;
750
+ try {
751
+ parsed = text ? JSON.parse(text) : null;
752
+ } catch {
753
+ parsed = text;
754
+ }
755
+ if (!response.ok) {
756
+ throw new IntentsHttpError(
757
+ `Solver relay ${method} failed with ${response.status}`,
758
+ response.status,
759
+ parsed
760
+ );
761
+ }
762
+ const body = parsed;
763
+ if (body && typeof body === "object" && body.error != null) {
764
+ throw new SolverRelayError(
765
+ `Solver relay ${method} returned an error: ${JSON.stringify(body.error)}`,
766
+ body.error
767
+ );
768
+ }
769
+ if (!body || typeof body !== "object" || !("result" in body)) {
770
+ throw new SolverRelayError(
771
+ `Solver relay ${method} returned a malformed JSON-RPC envelope`,
772
+ parsed
773
+ );
774
+ }
775
+ return body.result;
776
+ }
777
+ __name(call, "call");
778
+ return {
779
+ quote: /* @__PURE__ */ __name((params) => call("quote", params), "quote"),
780
+ publishIntent: /* @__PURE__ */ __name(({ signedData, quoteHashes }) => call("publish_intent", {
781
+ signed_data: signedData,
782
+ quote_hashes: quoteHashes
783
+ }), "publishIntent"),
784
+ publishIntents: /* @__PURE__ */ __name(({ signedDatas, quoteHashes, requote }) => call("publish_intents", {
785
+ signed_datas: signedDatas,
786
+ quote_hashes: quoteHashes,
787
+ ...requote === void 0 ? {} : { requote }
788
+ }), "publishIntents"),
789
+ getStatus: /* @__PURE__ */ __name(({ intentHash }) => call("get_status", { intent_hash: intentHash }), "getStatus")
790
+ };
791
+ }
792
+ __name(createSolverRelayClient, "createSolverRelayClient");
793
+ return __toCommonJS(src_exports2);
794
+ })();
795
+
796
+ Object.defineProperty(globalThis, 'nearIntents', {
797
+ value: nearIntents,
798
+ enumerable: true,
799
+ configurable: false,
800
+ });
801
+
802
+ //# sourceMappingURL=browser.global.js.map