near-api-ts 0.5.0 → 0.5.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.cjs CHANGED
@@ -30,28 +30,60 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
- addFullAccessKey: () => addFullAccessKey,
34
- addFunctionCallKey: () => addFunctionCallKey,
33
+ addFullAccessKey: () => throwableAddFullAccessKey,
34
+ addFunctionCallKey: () => throwableAddFunctionCallKey,
35
35
  createAccount: () => createAccount,
36
- createClient: () => createClient,
36
+ createClient: () => throwableCreateClient,
37
37
  createMainnetClient: () => createMainnetClient,
38
- createMemoryKeyService: () => createMemoryKeyService,
39
- createMemorySigner: () => createMemorySigner,
38
+ createMemoryKeyService: () => throwableCreateMemoryKeyService,
39
+ createMemorySigner: () => throwableCreateMemorySigner,
40
+ createMemorySignerFactory: () => createThrowableMemorySignerFactory,
41
+ createSafeMemorySignerFactory: () => createSafeMemorySignerFactory,
40
42
  createTestnetClient: () => createTestnetClient,
41
- deleteAccount: () => deleteAccount,
42
- deleteKey: () => deleteKey,
43
- deployContract: () => deployContract,
44
- functionCall: () => functionCall,
45
- gas: () => gas,
46
- near: () => near,
47
- teraGas: () => teraGas,
48
- transfer: () => transfer,
49
- yoctoNear: () => yoctoNear
43
+ deleteAccount: () => throwableDeleteAccount,
44
+ deleteKey: () => throwableDeleteKey,
45
+ deployContract: () => throwableDeployContract,
46
+ functionCall: () => throwableFunctionCall,
47
+ gas: () => throwableGas,
48
+ isNatError: () => isNatError,
49
+ isNearGas: () => isNearGas,
50
+ isNearToken: () => isNearToken,
51
+ keyPair: () => throwableKeyPair,
52
+ near: () => throwableNear,
53
+ nearGas: () => throwableNearGas,
54
+ nearToken: () => throwableNearToken,
55
+ randomEd25519KeyPair: () => throwableRandomEd25519KeyPair,
56
+ randomSecp256k1KeyPair: () => throwableRandomSecp256k1KeyPair,
57
+ safeAddFullAccessKey: () => safeAddFullAccessKey,
58
+ safeAddFunctionCallKey: () => safeAddFunctionCallKey,
59
+ safeCreateClient: () => safeCreateClient,
60
+ safeCreateMemoryKeyService: () => safeCreateMemoryKeyService,
61
+ safeCreateMemorySigner: () => safeCreateMemorySigner,
62
+ safeDeleteAccount: () => safeDeleteAccount,
63
+ safeDeleteKey: () => safeDeleteKey,
64
+ safeDeployContract: () => safeDeployContract,
65
+ safeFunctionCall: () => safeFunctionCall,
66
+ safeGas: () => safeGas,
67
+ safeKeyPair: () => safeKeyPair,
68
+ safeNear: () => safeNear,
69
+ safeNearGas: () => safeNearGas,
70
+ safeNearToken: () => safeNearToken,
71
+ safeRandomEd25519KeyPair: () => safeRandomEd25519KeyPair,
72
+ safeRandomSecp256k1KeyPair: () => safeRandomSecp256k1KeyPair,
73
+ safeTeraGas: () => safeTeraGas,
74
+ safeTransfer: () => safeTransfer,
75
+ safeYoctoNear: () => safeYoctoNear,
76
+ teraGas: () => throwableTeraGas,
77
+ transfer: () => throwableTransfer,
78
+ yoctoNear: () => throwableYoctoNear
50
79
  });
51
80
  module.exports = __toCommonJS(index_exports);
52
81
 
53
- // src/client/methods/account/getAccountState.ts
54
- var z = __toESM(require("zod/mini"), 1);
82
+ // src/client/createClient.ts
83
+ var z33 = __toESM(require("zod/mini"), 1);
84
+
85
+ // src/client/methods/account/getAccountInfo/getAccountInfo.ts
86
+ var z8 = __toESM(require("zod/mini"), 1);
55
87
 
56
88
  // src/_common/transformers/toNative/blockReference.ts
57
89
  var toNativeBlockReference = (blockReference, defaultBlockReference) => {
@@ -72,10 +104,59 @@ var toNativeBlockReference = (blockReference, defaultBlockReference) => {
72
104
  return { finality: "near-final" };
73
105
  };
74
106
 
75
- // src/client/methods/account/getAccountState.ts
107
+ // src/_common/utils/result.ts
108
+ var result = {
109
+ ok: (value) => ({ ok: true, value }),
110
+ err: (error) => ({ ok: false, error })
111
+ };
112
+
113
+ // src/_common/natError.ts
114
+ var NatErrorBrand = Symbol("NatError");
115
+ var NatError = class extends Error {
116
+ [NatErrorBrand] = true;
117
+ kind;
118
+ context;
119
+ constructor(args) {
120
+ super(`<${args.kind}>`);
121
+ this.name = "NatError";
122
+ this.kind = args.kind;
123
+ this.context = args.context;
124
+ }
125
+ };
126
+ var createNatError = (args) => new NatError(args);
127
+ var isNatError = (error, kind) => {
128
+ const isNatErr = typeof error === "object" && error !== null && NatErrorBrand in error;
129
+ if (kind === void 0) return isNatErr;
130
+ return isNatErr && error?.kind === kind;
131
+ };
132
+ var isNatErrorOf = (error, kinds) => {
133
+ const isNatErr = typeof error === "object" && error !== null && NatErrorBrand in error;
134
+ if (!isNatErr) return false;
135
+ return kinds.includes(error.kind);
136
+ };
137
+
138
+ // src/_common/utils/wrapInternalError.ts
139
+ var returnError = (e, kind) => result.err(
140
+ createNatError({
141
+ kind,
142
+ context: { cause: e }
143
+ })
144
+ );
145
+ var wrapInternalError = (kind, fn) => (...args) => {
146
+ try {
147
+ const res = fn(...args);
148
+ if (res instanceof Promise) return res.catch((e) => returnError(e, kind));
149
+ return res;
150
+ } catch (e) {
151
+ return returnError(e, kind);
152
+ }
153
+ };
154
+
155
+ // src/client/methods/account/getAccountInfo/handleResult.ts
156
+ var z2 = __toESM(require("zod/mini"), 1);
76
157
  var import_jsonrpc_types = require("@near-js/jsonrpc-types");
77
158
 
78
- // src/_common/utils/tokenConverter/helpers.ts
159
+ // src/helpers/tokens/tokenConverter/helpers.ts
79
160
  var POW10_CACHE = {};
80
161
  var pow10 = (decimals) => {
81
162
  const cached = POW10_CACHE[decimals];
@@ -84,24 +165,9 @@ var pow10 = (decimals) => {
84
165
  POW10_CACHE[decimals] = value;
85
166
  return value;
86
167
  };
87
- var assertValidDecimals = (decimals) => {
88
- if (!Number.isInteger(decimals) || decimals < 1 || decimals > 100) {
89
- throw new Error("Decimals must be an integer in the range 1..100");
90
- }
91
- };
92
168
 
93
- // src/_common/utils/tokenConverter/convertTokensToUnits.ts
94
- var assertValidTokens = (tokens, decimals) => {
95
- const decimalPattern = new RegExp(`^\\d+(?:\\.\\d{1,${decimals}})?$`);
96
- if (!decimalPattern.test(tokens)) {
97
- throw new Error(
98
- `Tokens must be a positive decimal with up to ${decimals} fractional digits`
99
- );
100
- }
101
- };
169
+ // src/helpers/tokens/tokenConverter/convertTokensToUnits.ts
102
170
  var convertTokensToUnits = (tokens, decimals) => {
103
- assertValidDecimals(decimals);
104
- assertValidTokens(tokens, decimals);
105
171
  const [integerPartRaw, fractionalPartRaw = ""] = tokens.split(".");
106
172
  const scale = pow10(decimals);
107
173
  const integerUnits = BigInt(integerPartRaw) * scale;
@@ -109,19 +175,11 @@ var convertTokensToUnits = (tokens, decimals) => {
109
175
  return integerUnits + fractionalUnits;
110
176
  };
111
177
 
112
- // src/_common/utils/tokenConverter/convertUnitsToTokens.ts
113
- var assertValidUnits = (units) => {
114
- if (typeof units === "string" && !/^\d+$/.test(units)) {
115
- throw new Error("Units must be a positive integer string (digits only)");
116
- }
117
- };
178
+ // src/helpers/tokens/tokenConverter/convertUnitsToTokens.ts
118
179
  var convertUnitsToTokens = (units, decimals) => {
119
- assertValidDecimals(decimals);
120
- assertValidUnits(units);
121
- const unitsBigInt = BigInt(units);
122
180
  const scale = pow10(decimals);
123
- const wholePart = unitsBigInt / scale;
124
- const fractionalRemainder = unitsBigInt % scale;
181
+ const wholePart = units / scale;
182
+ const fractionalRemainder = units % scale;
125
183
  if (fractionalRemainder === 0n) return wholePart.toString();
126
184
  const fractionalDigits = fractionalRemainder.toString().padStart(decimals, "0").replace(/0+$/, "");
127
185
  if (fractionalDigits.length === 0) return wholePart.toString();
@@ -129,23 +187,23 @@ var convertUnitsToTokens = (units, decimals) => {
129
187
  };
130
188
 
131
189
  // src/_common/configs/constants.ts
132
- var BinaryCryptoKeyLengths = {
190
+ var BinaryLengths = {
133
191
  Ed25519: {
134
- // SecretKey + PublicKey
135
192
  PrivateKey: 64,
193
+ // SecretKey + PublicKey
136
194
  SecretKey: 32,
137
- PublicKey: 32
195
+ PublicKey: 32,
196
+ Signature: 64
138
197
  },
139
198
  Secp256k1: {
140
- // SecretKey + PublicKey
141
199
  PrivateKey: 96,
200
+ // SecretKey + PublicKey
142
201
  SecretKey: 32,
143
- PublicKey: 64
202
+ PublicKey: 64,
203
+ Signature: 65
144
204
  }
145
205
  };
146
206
  var NearDecimals = 24;
147
- var RefetchBlockHashInterval = 6e5;
148
- var SignerTaskTtlMs = 6e4;
149
207
 
150
208
  // src/_common/utils/common.ts
151
209
  var oneLine = (msg) => msg.replace(/\s+/g, " ").trim();
@@ -159,12 +217,63 @@ var fromJsonBytes = (bytes) => {
159
217
  var combineAbortSignals = (signals) => AbortSignal.any(signals.filter((signal) => typeof signal !== "undefined"));
160
218
  var randomBetween = (min, max) => Math.random() * (max - min) + min;
161
219
 
162
- // src/helpers/near.ts
220
+ // src/_common/schemas/zod/common/nearToken.ts
221
+ var z = __toESM(require("zod/mini"), 1);
222
+ var createTokensInputSchema = (decimals) => z.string().check(
223
+ z.refine(
224
+ (val) => {
225
+ const decimalPattern = new RegExp(`^\\d+(?:\\.\\d{1,${decimals}})?$`);
226
+ return decimalPattern.test(val);
227
+ },
228
+ {
229
+ message: `Must be a valid number with up to ${decimals} decimal places`
230
+ }
231
+ )
232
+ );
233
+ var NearInputSchema = createTokensInputSchema(24);
234
+ var BigintStringSchema = z.pipe(
235
+ z.string().check(z.regex(/^\d+$/, "Must contain only digits")),
236
+ z.transform((v) => BigInt(v))
237
+ );
238
+ var YoctoNearInputSchema = z.union([z.bigint(), BigintStringSchema]);
239
+ var NearTokenArgsSchema = z.union([
240
+ z.object({
241
+ near: NearInputSchema
242
+ }),
243
+ z.object({
244
+ yoctoNear: YoctoNearInputSchema
245
+ })
246
+ ]);
247
+
248
+ // src/_common/utils/asThrowable.ts
249
+ var asThrowable = (safeFn) => {
250
+ return (...args) => {
251
+ const result2 = safeFn(...args);
252
+ if (result2 instanceof Promise) {
253
+ return result2.then((res) => {
254
+ if (res.ok) return res.value;
255
+ throw res.error;
256
+ });
257
+ }
258
+ if (result2.ok) return result2.value;
259
+ throw result2.error;
260
+ };
261
+ };
262
+
263
+ // src/helpers/tokens/nearToken.ts
264
+ var NearTokenBrand = Symbol("NearToken");
163
265
  var cache = {
164
- near: /* @__PURE__ */ new WeakMap(),
165
- yoctoNear: /* @__PURE__ */ new WeakMap()
266
+ yoctoNear: /* @__PURE__ */ new WeakMap(),
267
+ near: /* @__PURE__ */ new WeakMap()
268
+ };
269
+ var isNearToken = (value) => typeof value === "object" && value !== null && NearTokenBrand in value;
270
+ var toYoctoNear = (x) => {
271
+ if (isNearToken(x)) return result.ok(x.yoctoNear);
272
+ const nearToken = safeNearToken(x);
273
+ return nearToken.ok ? result.ok(nearToken.value.yoctoNear) : nearToken;
166
274
  };
167
275
  var nearTokenProto = {
276
+ [NearTokenBrand]: true,
168
277
  // Lazy getter - calculate the 'near' value only after the first direct access;
169
278
  // save the result in the cache
170
279
  get near() {
@@ -181,21 +290,43 @@ var nearTokenProto = {
181
290
  cache.yoctoNear.set(this, value);
182
291
  return value;
183
292
  },
184
- // TODO add support for NearToken and avoid creating a new instance if x is NearToken
185
- add(x) {
186
- return yoctoNear(this.yoctoNear + fromNearOption(x).yoctoNear);
293
+ // TODO Need to reuse method code and reduce boilerplate code, and reduce useless
294
+ // transformations
295
+ safeAdd(value) {
296
+ return wrapInternalError("CreateNearToken.Internal", () => {
297
+ const yoctoNear = toYoctoNear(value);
298
+ return yoctoNear.ok ? safeNearToken({ yoctoNear: this.yoctoNear + yoctoNear.value }) : yoctoNear;
299
+ })();
300
+ },
301
+ add(value) {
302
+ return asThrowable(this.safeAdd.bind(this))(value);
303
+ },
304
+ safeSub(value) {
305
+ return wrapInternalError("CreateNearToken.Internal", () => {
306
+ const yoctoNear = toYoctoNear(value);
307
+ return yoctoNear.ok ? safeNearToken({ yoctoNear: this.yoctoNear - yoctoNear.value }) : yoctoNear;
308
+ })();
187
309
  },
188
- sub(x) {
189
- return yoctoNear(this.yoctoNear - fromNearOption(x).yoctoNear);
310
+ sub(value) {
311
+ return asThrowable(this.safeSub.bind(this))(value);
190
312
  },
191
- mul(x) {
192
- return yoctoNear(this.yoctoNear * fromNearOption(x).yoctoNear);
313
+ safeGt(value) {
314
+ return wrapInternalError("CreateNearToken.Internal", () => {
315
+ const yoctoNear = toYoctoNear(value);
316
+ return yoctoNear.ok ? result.ok(this.yoctoNear > yoctoNear.value) : yoctoNear;
317
+ })();
193
318
  },
194
- gt(x) {
195
- return this.yoctoNear > fromNearOption(x).yoctoNear;
319
+ gt(value) {
320
+ return asThrowable(this.safeGt.bind(this))(value);
196
321
  },
197
- lt(x) {
198
- return this.yoctoNear < fromNearOption(x).yoctoNear;
322
+ safeLt(value) {
323
+ return wrapInternalError("CreateNearToken.Internal", () => {
324
+ const yoctoNear = toYoctoNear(value);
325
+ return yoctoNear.ok ? result.ok(this.yoctoNear < yoctoNear.value) : yoctoNear;
326
+ })();
327
+ },
328
+ lt(value) {
329
+ return asThrowable(this.safeLt.bind(this))(value);
199
330
  },
200
331
  toString() {
201
332
  return JSON.stringify({
@@ -213,99 +344,446 @@ var nearTokenProto = {
213
344
  }
214
345
  }
215
346
  };
216
- var yoctoNear = (units) => {
217
- const yoctoNear2 = BigInt(units);
218
- const obj = Object.create(nearTokenProto);
219
- Object.defineProperty(obj, "yoctoNear", {
220
- value: yoctoNear2,
221
- enumerable: true
222
- });
223
- return Object.freeze(obj);
224
- };
225
- var near = (tokens) => {
226
- const obj = Object.create(nearTokenProto);
227
- Object.defineProperty(obj, "near", {
228
- value: tokens,
229
- enumerable: true
230
- });
231
- return Object.freeze(obj);
232
- };
233
- var fromNearOption = (nearOption) => {
234
- if ("yoctoNear" in nearOption) return yoctoNear(nearOption.yoctoNear);
235
- if ("near" in nearOption) return near(nearOption.near);
236
- throw new Error("Invalid nearOption format");
237
- };
238
-
239
- // src/_common/utils/addTo.ts
240
- var addTo = (target) => ({
241
- field: (key, value, predicate = (v4) => v4 !== void 0) => {
242
- if (predicate(value)) {
243
- target[key] = value;
244
- }
245
- return addTo(target);
246
- },
247
- done: () => target
248
- });
347
+ var safeYoctoNear = wrapInternalError(
348
+ "CreateNearTokenFromYoctoNear.Internal",
349
+ (yoctoNear) => {
350
+ const validYoctoNear = YoctoNearInputSchema.safeParse(yoctoNear);
351
+ if (!validYoctoNear.success)
352
+ return result.err(
353
+ createNatError({
354
+ kind: "CreateNearTokenFromYoctoNear.Args.InvalidSchema",
355
+ context: { zodError: validYoctoNear.error }
356
+ })
357
+ );
358
+ const nearToken = Object.create(nearTokenProto);
359
+ Object.defineProperty(nearToken, "yoctoNear", {
360
+ value: validYoctoNear.data,
361
+ enumerable: true
362
+ });
363
+ return result.ok(Object.freeze(nearToken));
364
+ }
365
+ );
366
+ var throwableYoctoNear = asThrowable(safeYoctoNear);
367
+ var safeNear = wrapInternalError(
368
+ "CreateNearTokenFromNear.Internal",
369
+ (near) => {
370
+ const validNear = NearInputSchema.safeParse(near);
371
+ if (!validNear.success)
372
+ return result.err(
373
+ createNatError({
374
+ kind: "CreateNearTokenFromNear.Args.InvalidSchema",
375
+ context: { zodError: validNear.error }
376
+ })
377
+ );
378
+ const nearToken = Object.create(nearTokenProto);
379
+ Object.defineProperty(nearToken, "near", {
380
+ value: validNear.data,
381
+ enumerable: true
382
+ });
383
+ return result.ok(Object.freeze(nearToken));
384
+ }
385
+ );
386
+ var throwableNear = asThrowable(safeNear);
387
+ var safeNearToken = wrapInternalError(
388
+ "CreateNearToken.Internal",
389
+ (args) => {
390
+ const validArgs = NearTokenArgsSchema.safeParse(args);
391
+ if (!validArgs.success)
392
+ return result.err(
393
+ createNatError({
394
+ kind: "CreateNearToken.Args.InvalidSchema",
395
+ context: { zodError: validArgs.error }
396
+ })
397
+ );
398
+ return "yoctoNear" in args ? result.ok(throwableYoctoNear(args.yoctoNear)) : result.ok(throwableNear(args.near));
399
+ }
400
+ );
401
+ var throwableNearToken = asThrowable(safeNearToken);
249
402
 
250
- // src/client/methods/account/getAccountState.ts
251
- var RpcQueryAccountViewResponseSchema = z.object({
403
+ // src/client/methods/account/getAccountInfo/handleResult.ts
404
+ var RpcQueryViewAccountResultSchema = z2.object({
252
405
  ...(0, import_jsonrpc_types.AccountViewSchema)().shape,
253
- blockHash: (0, import_jsonrpc_types.CryptoHashSchema)(),
254
- blockHeight: z.number()
255
- });
256
- var transformResult = (result, args) => {
257
- const valid = RpcQueryAccountViewResponseSchema.parse(result);
258
- const lockedBalance = yoctoNear(valid.locked);
259
- const totalBalance = yoctoNear(valid.amount).add(lockedBalance);
260
- const final = {
261
- blockHash: valid.blockHash,
262
- blockHeight: valid.blockHeight,
406
+ blockHash: z2.string(),
407
+ blockHeight: z2.number()
408
+ });
409
+ var handleResult = (rpcResponse, args) => {
410
+ const rpcResult = RpcQueryViewAccountResultSchema.safeParse(
411
+ rpcResponse.result
412
+ );
413
+ if (!rpcResult.success)
414
+ return result.err(
415
+ createNatError({
416
+ kind: "Client.GetAccountInfo.SendRequest.Failed",
417
+ context: {
418
+ cause: createNatError({
419
+ kind: "Client.Transport.SendRequest.Response.Result.InvalidSchema",
420
+ context: { zodError: rpcResult.error }
421
+ })
422
+ }
423
+ })
424
+ );
425
+ const accountInfo = rpcResult.data;
426
+ const lockedBalance = throwableYoctoNear(accountInfo.locked);
427
+ const totalBalance = throwableYoctoNear(accountInfo.amount).add(
428
+ lockedBalance
429
+ );
430
+ const output = {
431
+ blockHash: accountInfo.blockHash,
432
+ blockHeight: accountInfo.blockHeight,
263
433
  accountId: args.accountId,
264
- accountState: {
434
+ accountInfo: {
265
435
  balance: {
266
436
  total: totalBalance,
267
437
  locked: lockedBalance
268
438
  },
269
- usedStorageBytes: valid.storageUsage
270
- }
439
+ usedStorageBytes: accountInfo.storageUsage
440
+ },
441
+ rawRpcResult: accountInfo
271
442
  };
272
- addTo(final.accountState).field(
273
- "contractHash",
274
- valid.codeHash,
275
- // When near account doesn't have a deployed contract on it,
276
- // it returns the placeholder instead of WASM hash
277
- (v4) => v4 !== "11111111111111111111111111111111"
278
- ).field(
279
- "globalContractHash",
280
- valid.globalContractHash,
281
- (v4) => typeof v4 === "string"
282
- ).field(
283
- "globalContractAccountId",
284
- valid.globalContractAccountId,
285
- (v4) => typeof v4 === "string"
443
+ if (accountInfo.codeHash !== "11111111111111111111111111111111") {
444
+ output.accountInfo.contractHash = accountInfo.codeHash;
445
+ }
446
+ if (typeof accountInfo.globalContractHash === "string") {
447
+ output.accountInfo.globalContractHash = accountInfo.globalContractHash;
448
+ }
449
+ if (typeof accountInfo.globalContractAccountId === "string") {
450
+ output.accountInfo.globalContractAccountId = accountInfo.globalContractAccountId;
451
+ }
452
+ return result.ok(output);
453
+ };
454
+
455
+ // src/_common/schemas/zod/client.ts
456
+ var z6 = __toESM(require("zod/mini"), 1);
457
+
458
+ // src/client/transport/transportPolicy.ts
459
+ var z3 = __toESM(require("zod/mini"), 1);
460
+ var import_lodash_es = require("lodash-es");
461
+ var Regular = z3.literal("Regular");
462
+ var Archival = z3.literal("Archival");
463
+ var RpcTypePreferencesSchema = z3.union([
464
+ z3.tuple([Regular]),
465
+ z3.tuple([Archival]),
466
+ z3.tuple([Regular, Archival]),
467
+ z3.tuple([Archival, Regular])
468
+ ]);
469
+ var TransportPolicySchema = z3.object({
470
+ rpcTypePreferences: RpcTypePreferencesSchema,
471
+ timeouts: z3.object({
472
+ // Unlikely that a request could finish less in than 100ms -
473
+ // doesn't make sense to have such small timeout
474
+ requestMs: z3.number().check(z3.int(), z3.minimum(100)),
475
+ attemptMs: z3.number().check(z3.int(), z3.minimum(100))
476
+ }),
477
+ rpc: z3.object({
478
+ maxAttempts: z3.number().check(z3.int(), z3.minimum(1)),
479
+ retryBackoff: z3.object({
480
+ minDelayMs: z3.number().check(z3.int(), z3.nonnegative()),
481
+ maxDelayMs: z3.number().check(z3.int(), z3.nonnegative()),
482
+ multiplier: z3.number().check(z3.int(), z3.minimum(1))
483
+ })
484
+ }),
485
+ failover: z3.object({
486
+ maxRounds: z3.number().check(z3.int(), z3.minimum(1)),
487
+ nextRpcDelayMs: z3.number().check(z3.int(), z3.nonnegative()),
488
+ nextRoundDelayMs: z3.number().check(z3.int(), z3.nonnegative())
489
+ })
490
+ });
491
+ var PartialTransportPolicySchema = z3.optional(
492
+ z3.partial(TransportPolicySchema)
493
+ );
494
+ var defaultTransportPolicy = {
495
+ rpcTypePreferences: ["Regular", "Archival"],
496
+ timeouts: {
497
+ requestMs: 3e4,
498
+ attemptMs: 5e3
499
+ },
500
+ rpc: {
501
+ maxAttempts: 2,
502
+ retryBackoff: {
503
+ minDelayMs: 100,
504
+ maxDelayMs: 500,
505
+ multiplier: 3
506
+ }
507
+ },
508
+ failover: {
509
+ maxRounds: 2,
510
+ nextRpcDelayMs: 200,
511
+ nextRoundDelayMs: 200
512
+ }
513
+ };
514
+ var mergeTransportPolicy = (base, next = {}) => (0, import_lodash_es.mergeWith)(
515
+ {},
516
+ (0, import_lodash_es.cloneDeep)(base),
517
+ (0, import_lodash_es.cloneDeep)(next),
518
+ (_objValue, srcValue, key) => {
519
+ if (key === "rpcTypePreferences" && Array.isArray(srcValue)) {
520
+ return srcValue;
521
+ }
522
+ }
523
+ );
524
+
525
+ // src/_common/schemas/zod/common/common.ts
526
+ var z5 = __toESM(require("zod/mini"), 1);
527
+
528
+ // src/_common/schemas/zod/common/cryptoHash.ts
529
+ var z4 = __toESM(require("zod/mini"), 1);
530
+ var import_base = require("@scure/base");
531
+ var Base58StringSchema = z4.string().check(
532
+ z4.regex(
533
+ /^[1-9A-HJ-NP-Za-km-z]+$/,
534
+ oneLine(`Base58 string contains invalid characters. Allowed characters:
535
+ 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`)
536
+ )
537
+ );
538
+ var CryptoHashSchema = z4.pipe(
539
+ Base58StringSchema,
540
+ z4.transform((cryptoHash) => {
541
+ const u8CryptoHash = import_base.base58.decode(cryptoHash);
542
+ return { cryptoHash, u8CryptoHash };
543
+ })
544
+ ).check(
545
+ z4.refine(({ u8CryptoHash }) => u8CryptoHash.length === 32, {
546
+ error: "Crypto hash length should be 32 bytes"
547
+ })
548
+ );
549
+
550
+ // src/_common/schemas/zod/common/common.ts
551
+ var BlockHashSchema = CryptoHashSchema;
552
+ var BlockHeightSchema = z5.number().check(z5.nonnegative());
553
+ var BlockIdSchema = z5.union([BlockHeightSchema, BlockHashSchema]);
554
+ var NonceSchema = z5.number().check(z5.int(), z5.nonnegative());
555
+ var ContractFunctionNameSchema = z5.string().check(z5.minLength(1), z5.maxLength(256));
556
+ var JsonSchema = z5.json();
557
+
558
+ // src/_common/schemas/zod/client.ts
559
+ var PoliciesSchema = z6.optional(
560
+ z6.object({
561
+ transport: PartialTransportPolicySchema
562
+ })
563
+ );
564
+ var BaseOptionsSchema = z6.optional(
565
+ z6.object({
566
+ signal: z6.optional(z6.instanceof(AbortSignal))
567
+ })
568
+ );
569
+ var BlockReferenceSchema = z6.union([
570
+ z6.literal("LatestOptimisticBlock"),
571
+ z6.literal("LatestNearFinalBlock"),
572
+ z6.literal("LatestFinalBlock"),
573
+ z6.literal("EarliestAvailableBlock"),
574
+ z6.literal("GenesisBlock"),
575
+ z6.object({
576
+ blockHash: BlockHashSchema,
577
+ blockHeight: z6.optional(z6.never())
578
+ }),
579
+ z6.object({
580
+ blockHash: z6.optional(z6.never()),
581
+ blockHeight: BlockHeightSchema
582
+ })
583
+ ]);
584
+
585
+ // src/_common/schemas/zod/common/accountId.ts
586
+ var z7 = __toESM(require("zod/mini"), 1);
587
+ var AccountIdSchema = z7.string().check(
588
+ z7.minLength(2),
589
+ z7.maxLength(64),
590
+ z7.regex(/^(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+$/, {
591
+ error: oneLine(`Account ID may contain only lowercase letters (a\u2013z),
592
+ digits (0\u20139), and separators (., -, _).`)
593
+ })
594
+ );
595
+
596
+ // src/client/methods/account/getAccountInfo/handleError.ts
597
+ var import_jsonrpc_types2 = require("@near-js/jsonrpc-types");
598
+ var handleError = (rpcResponse) => {
599
+ const rpcError = (0, import_jsonrpc_types2.ErrorWrapperFor_RpcQueryErrorSchema)().safeParse(
600
+ rpcResponse.error
601
+ );
602
+ if (!rpcError.success)
603
+ return result.err(
604
+ createNatError({
605
+ kind: "Client.GetAccountInfo.SendRequest.Failed",
606
+ context: {
607
+ cause: createNatError({
608
+ kind: "Client.Transport.SendRequest.Response.Error.InvalidSchema",
609
+ context: { zodError: rpcError.error }
610
+ })
611
+ }
612
+ })
613
+ );
614
+ const { name, cause } = rpcError.data;
615
+ if (name === "HANDLER_ERROR") {
616
+ if (cause.name === "NO_SYNCED_BLOCKS")
617
+ return result.err(
618
+ createNatError({
619
+ kind: `Client.GetAccountInfo.Rpc.NotSynced`,
620
+ context: null
621
+ })
622
+ );
623
+ if (cause.name === "UNAVAILABLE_SHARD")
624
+ return result.err(
625
+ createNatError({
626
+ kind: `Client.GetAccountInfo.Rpc.Shard.NotTracked`,
627
+ context: { shardId: cause.info.requestedShardId }
628
+ })
629
+ );
630
+ if (cause.name === "GARBAGE_COLLECTED_BLOCK")
631
+ return result.err(
632
+ createNatError({
633
+ kind: `Client.GetAccountInfo.Rpc.Block.GarbageCollected`,
634
+ context: {
635
+ blockHash: cause.info.blockHash,
636
+ blockHeight: cause.info.blockHeight
637
+ }
638
+ })
639
+ );
640
+ if (cause.name === "UNKNOWN_BLOCK" && "blockId" in cause.info.blockReference)
641
+ return result.err(
642
+ createNatError({
643
+ kind: `Client.GetAccountInfo.Rpc.Block.NotFound`,
644
+ context: {
645
+ blockId: cause.info.blockReference.blockId
646
+ }
647
+ })
648
+ );
649
+ }
650
+ if (cause.name === "UNKNOWN_ACCOUNT")
651
+ return result.err(
652
+ createNatError({
653
+ kind: `Client.GetAccountInfo.Rpc.Account.NotFound`,
654
+ context: {
655
+ accountId: cause.info.requestedAccountId,
656
+ blockHash: cause.info.blockHash,
657
+ blockHeight: cause.info.blockHeight
658
+ }
659
+ })
660
+ );
661
+ return result.err(
662
+ createNatError({
663
+ kind: "Client.GetAccountInfo.Internal",
664
+ context: {
665
+ cause: createNatError({
666
+ kind: "Client.GetAccountInfo.Rpc.Unclassified",
667
+ context: { rpcResponse }
668
+ })
669
+ }
670
+ })
286
671
  );
287
- return final;
288
672
  };
289
- var createGetAccountState = ({ sendRequest }) => async (args) => {
290
- const result = await sendRequest({
673
+
674
+ // src/client/methods/account/getAccountInfo/getAccountInfo.ts
675
+ var GetAccountInfoArgsSchema = z8.object({
676
+ accountId: AccountIdSchema,
677
+ atMomentOf: z8.optional(BlockReferenceSchema),
678
+ policies: PoliciesSchema,
679
+ options: BaseOptionsSchema
680
+ });
681
+ var createSafeGetAccountInfo = (context) => wrapInternalError("Client.GetAccountInfo.Internal", async (args) => {
682
+ const validArgs = GetAccountInfoArgsSchema.safeParse(args);
683
+ if (!validArgs.success)
684
+ return result.err(
685
+ createNatError({
686
+ kind: "Client.GetAccountInfo.Args.InvalidSchema",
687
+ context: { zodError: validArgs.error }
688
+ })
689
+ );
690
+ const { accountId, policies, options } = validArgs.data;
691
+ const rpcResponse = await context.sendRequest({
291
692
  method: "query",
292
693
  params: {
293
694
  request_type: "view_account",
294
- account_id: args.accountId,
695
+ account_id: accountId,
295
696
  ...toNativeBlockReference(args.atMomentOf)
296
697
  },
297
- transportPolicy: args.policies?.transport,
298
- signal: args.options?.signal
698
+ transportPolicy: policies?.transport,
699
+ signal: options?.signal
299
700
  });
300
- return transformResult(result, args);
701
+ if (!rpcResponse.ok)
702
+ return result.err(
703
+ createNatError({
704
+ kind: "Client.GetAccountInfo.SendRequest.Failed",
705
+ context: { cause: rpcResponse.error }
706
+ })
707
+ );
708
+ return rpcResponse.value.error ? handleError(rpcResponse.value) : handleResult(rpcResponse.value, args);
709
+ });
710
+
711
+ // src/client/methods/account/getAccountAccessKey/getAccountAccessKey.ts
712
+ var z12 = __toESM(require("zod/mini"), 1);
713
+
714
+ // src/client/methods/account/getAccountAccessKey/handleError.ts
715
+ var import_jsonrpc_types3 = require("@near-js/jsonrpc-types");
716
+ var handleError2 = (rpcResponse) => {
717
+ const rpcError = (0, import_jsonrpc_types3.ErrorWrapperFor_RpcQueryErrorSchema)().safeParse(
718
+ rpcResponse.error
719
+ );
720
+ if (!rpcError.success)
721
+ return result.err(
722
+ createNatError({
723
+ kind: "Client.GetAccountAccessKey.SendRequest.Failed",
724
+ context: {
725
+ cause: createNatError({
726
+ kind: "Client.Transport.SendRequest.Response.Error.InvalidSchema",
727
+ context: { zodError: rpcError.error }
728
+ })
729
+ }
730
+ })
731
+ );
732
+ const { name, cause } = rpcError.data;
733
+ if (name === "HANDLER_ERROR") {
734
+ if (cause.name === "NO_SYNCED_BLOCKS")
735
+ return result.err(
736
+ createNatError({
737
+ kind: `Client.GetAccountAccessKey.Rpc.NotSynced`,
738
+ context: null
739
+ })
740
+ );
741
+ if (cause.name === "UNAVAILABLE_SHARD")
742
+ return result.err(
743
+ createNatError({
744
+ kind: `Client.GetAccountAccessKey.Rpc.Shard.NotTracked`,
745
+ context: { shardId: cause.info.requestedShardId }
746
+ })
747
+ );
748
+ if (cause.name === "GARBAGE_COLLECTED_BLOCK")
749
+ return result.err(
750
+ createNatError({
751
+ kind: `Client.GetAccountAccessKey.Rpc.Block.GarbageCollected`,
752
+ context: {
753
+ blockHash: cause.info.blockHash,
754
+ blockHeight: cause.info.blockHeight
755
+ }
756
+ })
757
+ );
758
+ if (cause.name === "UNKNOWN_BLOCK" && "blockId" in cause.info.blockReference)
759
+ return result.err(
760
+ createNatError({
761
+ kind: `Client.GetAccountAccessKey.Rpc.Block.NotFound`,
762
+ context: {
763
+ blockId: cause.info.blockReference.blockId
764
+ }
765
+ })
766
+ );
767
+ }
768
+ return result.err(
769
+ createNatError({
770
+ kind: "Client.GetAccountAccessKey.Internal",
771
+ context: {
772
+ cause: createNatError({
773
+ kind: "Client.GetAccountAccessKey.Rpc.Unclassified",
774
+ context: { rpcResponse }
775
+ })
776
+ }
777
+ })
778
+ );
301
779
  };
302
780
 
303
- // src/client/methods/account/getAccountKey.ts
304
- var z2 = __toESM(require("zod/mini"), 1);
305
- var import_jsonrpc_types2 = require("@near-js/jsonrpc-types");
781
+ // src/client/methods/account/getAccountAccessKey/handleResult.ts
782
+ var z9 = __toESM(require("zod/mini"), 1);
783
+ var import_jsonrpc_types4 = require("@near-js/jsonrpc-types");
306
784
 
307
- // src/client/methods/account/helpers/transformKey.ts
308
- var transformKey = (key) => {
785
+ // src/client/methods/account/_common/transformAccessKey.ts
786
+ var transformAccessKey = (key) => {
309
787
  const publicKey = key.publicKey;
310
788
  const nonce = key.accessKey.nonce;
311
789
  if (key.accessKey.permission === "FullAccess")
@@ -322,7 +800,7 @@ var transformKey = (key) => {
322
800
  contractAccountId: receiverId
323
801
  };
324
802
  if (typeof allowance === "string") {
325
- functionCallKey.gasBudget = yoctoNear(allowance);
803
+ functionCallKey.gasBudget = throwableYoctoNear(allowance);
326
804
  }
327
805
  if (methodNames.length > 0) {
328
806
  functionCallKey.allowedFunctions = methodNames;
@@ -330,397 +808,289 @@ var transformKey = (key) => {
330
808
  return functionCallKey;
331
809
  };
332
810
 
333
- // src/client/rpcError.ts
334
- var Brand = Symbol.for("near-api-ts.RpcError");
335
- var parseRequestValidationError = (name) => {
336
- if (name === "PARSE_ERROR")
337
- return {
338
- code: "ParseRequest",
339
- message: `Invalid request format. Please check it and try again.`
340
- };
341
- if (name === "METHOD_NOT_FOUND")
342
- return {
343
- code: "MethodNotFound",
344
- message: `Unsupported method. Please check it and try again.`
345
- };
346
- return {
347
- code: "UnknownValidationError",
348
- message: "Unknown request validation error."
349
- };
350
- };
351
- var parseHandlerError = (cause) => {
352
- const { name } = cause;
353
- if (name === "TIMEOUT_ERROR")
354
- return {
355
- code: "RpcTransactionTimeout",
356
- message: oneLine(`RPC does not know the result of this transaction,
357
- probably it is not executed yet. Please try again later.`)
358
- };
359
- if (name === "UNKNOWN_BLOCK")
360
- return {
361
- code: "UnknownBlock",
362
- message: oneLine(`Block either has never been observed on
363
- the node or has been garbage collected. Please try again later or use
364
- another RPC node.`)
365
- };
366
- if (name === "GARBAGE_COLLECTED_BLOCK")
367
- return {
368
- code: "GarbageCollectedBlock",
369
- message: oneLine(`Block is no longer available on this RPC node.
370
- Please use an archival node to fetch historical data.`)
371
- };
372
- if (name === "NO_SYNCED_BLOCKS")
373
- return {
374
- code: "NoSyncedBlocks",
375
- message: oneLine(`There are no fully synchronized blocks
376
- on the node yet. Please try again later.`)
377
- };
378
- return {
379
- code: "HandlerError",
380
- message: `Request execution error. Please check it and try again.`
381
- };
382
- };
383
- var getErrorInfo = (__rawRpcError) => {
384
- const { name: type, cause } = __rawRpcError;
385
- if (type === "REQUEST_VALIDATION_ERROR")
386
- return parseRequestValidationError(cause.name);
387
- if (type === "HANDLER_ERROR") return parseHandlerError(cause);
388
- if (type === "INTERNAL_ERROR")
389
- return {
390
- code: "InternalServerError",
391
- message: `Internal server error. Please try again later or use another RPC node.`
392
- };
393
- return {
394
- code: "UnknownRequestError",
395
- message: "Unknown request error."
396
- };
397
- };
398
- var RpcError = class extends Error {
399
- [Brand] = true;
400
- code;
401
- request;
402
- __rawRpcError;
403
- errors;
404
- timestamp;
405
- constructor(args) {
406
- const { code, message } = getErrorInfo(args.__rawRpcError);
407
- super(
408
- `[${code}]: ${message}
409
- Type: ${args.__rawRpcError.name}
410
- Cause: ${JSON.stringify(args.__rawRpcError.cause, null, 2)}`
411
- );
412
- this.name = "RpcError";
413
- this.code = code;
414
- this.request = args.request;
415
- this.__rawRpcError = args.__rawRpcError;
416
- this.timestamp = Date.now();
417
- }
418
- static is(e) {
419
- return typeof e === "object" && e[Brand] === true;
420
- }
421
- };
422
- var hasRpcErrorCode = (error, list) => RpcError.is(error) && list.includes(error.code);
423
-
424
- // src/client/transport/transportError.ts
425
- var NatError = class extends Error {
426
- code;
427
- name;
428
- errors;
429
- timestamp;
430
- request;
431
- constructor(args, name = "NatError") {
432
- super(`[${args.code}] ${args.message}`, { cause: args.cause });
433
- this.name = name;
434
- this.code = args.code;
435
- this.timestamp = Date.now();
436
- this.request = args.request;
437
- }
438
- static is(e) {
439
- return typeof e === "object" && e[Symbol.for(`near-api-ts.${this.name}`)] === true;
440
- }
441
- };
442
- var TransportErrorBrand = Symbol.for("near-api-ts.TransportError");
443
- var TransportError = class extends NatError {
444
- [TransportErrorBrand] = true;
445
- constructor(args) {
446
- super(args, "TransportError");
447
- }
448
- };
449
- var hasTransportErrorCode = (error, list) => TransportError.is(error) && list.includes(error.code);
450
-
451
- // src/client/methods/account/getAccountKey.ts
452
- var BaseSchema = z2.object({
453
- blockHash: (0, import_jsonrpc_types2.CryptoHashSchema)(),
454
- blockHeight: z2.number()
811
+ // src/client/methods/account/getAccountAccessKey/handleResult.ts
812
+ var UnknownKeySchema = z9.object({
813
+ blockHash: z9.string(),
814
+ blockHeight: z9.number(),
815
+ error: z9.string(),
816
+ logs: z9.array(z9.string())
817
+ // will always an empty array
455
818
  });
456
- var RpcQueryAccessKeyViewResponseSchema = z2.union([
457
- z2.object({
458
- ...BaseSchema.shape,
459
- ...(0, import_jsonrpc_types2.AccessKeyViewSchema)().shape
460
- }),
461
- z2.object({
462
- ...BaseSchema.shape,
463
- error: z2.string(),
464
- logs: z2.array(z2.string())
465
- })
819
+ var RpcQueryViewAccessKeyOkResultSchema = z9.object({
820
+ blockHash: z9.string(),
821
+ blockHeight: z9.number(),
822
+ ...(0, import_jsonrpc_types4.AccessKeyViewSchema)().shape
823
+ });
824
+ var RpcQueryViewAccessKeyResultSchema = z9.union([
825
+ RpcQueryViewAccessKeyOkResultSchema,
826
+ UnknownKeySchema
466
827
  ]);
467
- var transformResult2 = (result, args) => {
468
- const valid = RpcQueryAccessKeyViewResponseSchema.parse(result);
469
- if ("error" in valid)
470
- throw new NatError({
471
- code: "AccountKeyNotFound",
472
- message: `This account does not have such key.`,
473
- cause: valid
474
- });
475
- return {
476
- blockHash: valid.blockHash,
477
- blockHeight: valid.blockHeight,
828
+ var handleResult2 = (rpcResponse, args) => {
829
+ const rpcResult = RpcQueryViewAccessKeyResultSchema.safeParse(
830
+ rpcResponse.result
831
+ );
832
+ if (!rpcResult.success)
833
+ return result.err(
834
+ createNatError({
835
+ kind: "Client.GetAccountAccessKey.SendRequest.Failed",
836
+ context: {
837
+ cause: createNatError({
838
+ kind: "Client.Transport.SendRequest.Response.Result.InvalidSchema",
839
+ context: { zodError: rpcResult.error }
840
+ })
841
+ }
842
+ })
843
+ );
844
+ const { blockHash, blockHeight } = rpcResult.data;
845
+ if ("error" in rpcResult.data)
846
+ return result.err(
847
+ createNatError({
848
+ kind: "Client.GetAccountAccessKey.Rpc.AccountAccessKey.NotFound",
849
+ context: {
850
+ accountId: args.accountId,
851
+ publicKey: args.publicKey,
852
+ blockHash,
853
+ blockHeight
854
+ }
855
+ })
856
+ );
857
+ const output = {
858
+ blockHash,
859
+ blockHeight,
478
860
  accountId: args.accountId,
479
- accountKey: transformKey({
480
- accessKey: valid,
861
+ accountAccessKey: transformAccessKey({
862
+ accessKey: rpcResult.data,
481
863
  publicKey: args.publicKey
482
- })
864
+ }),
865
+ rawRpcResult: rpcResult.data
483
866
  };
484
- };
485
- var createGetAccountKey = ({ sendRequest }) => async (args) => {
486
- const result = await sendRequest({
487
- method: "query",
488
- params: {
489
- request_type: "view_access_key",
490
- account_id: args.accountId,
491
- public_key: args.publicKey,
492
- ...toNativeBlockReference(args.atMomentOf)
493
- },
494
- transportPolicy: args.policies?.transport,
495
- signal: args.options?.signal
496
- });
497
- return transformResult2(result, args);
867
+ return result.ok(output);
498
868
  };
499
869
 
500
- // src/client/methods/account/getAccountKeys.ts
501
- var z3 = __toESM(require("zod/mini"), 1);
502
- var import_jsonrpc_types3 = require("@near-js/jsonrpc-types");
503
- var RpcQueryAccessKeyListResponseSchema = z3.object({
504
- ...(0, import_jsonrpc_types3.AccessKeyListSchema)().shape,
505
- blockHash: (0, import_jsonrpc_types3.CryptoHashSchema)(),
506
- blockHeight: z3.number()
507
- });
508
- var transformResult3 = (result, args) => {
509
- const valid = RpcQueryAccessKeyListResponseSchema.parse(result);
510
- return {
511
- blockHash: valid.blockHash,
512
- blockHeight: valid.blockHeight,
513
- accountId: args.accountId,
514
- accountKeys: valid.keys.map(transformKey)
515
- };
516
- };
517
- var createGetAccountKeys = ({ sendRequest }) => async (args) => {
518
- const result = await sendRequest({
519
- method: "query",
520
- params: {
521
- request_type: "view_access_key_list",
522
- account_id: args.accountId,
523
- ...toNativeBlockReference(args.atMomentOf)
524
- },
525
- transportPolicy: args.policies?.transport,
526
- signal: args.options?.signal
527
- });
528
- return transformResult3(result, args);
529
- };
870
+ // src/_common/schemas/zod/common/publicKey.ts
871
+ var z11 = __toESM(require("zod/mini"), 1);
530
872
 
531
- // src/client/methods/contract/getContractState.ts
532
- var z4 = __toESM(require("zod/mini"), 1);
533
- var import_base = require("@scure/base");
534
- var import_jsonrpc_types4 = require("@near-js/jsonrpc-types");
535
- var RpcQueryViewStateResponseSchema = z4.object({
536
- ...(0, import_jsonrpc_types4.ViewStateResultSchema)().shape,
537
- blockHash: (0, import_jsonrpc_types4.CryptoHashSchema)(),
538
- blockHeight: z4.number()
539
- });
540
- var transformResult4 = (result, args) => {
541
- const valid = RpcQueryViewStateResponseSchema.parse(result);
542
- const final = {
543
- blockHash: valid.blockHash,
544
- blockHeight: valid.blockHeight,
545
- contractAccountId: args.contractAccountId,
546
- contractState: valid.values
547
- };
548
- if (valid.proof) final.proof = valid.proof;
549
- return final;
550
- };
551
- var createGetContractState = ({ sendRequest }) => async (args) => {
552
- const base64KeyPrefix = args.keyPrefix ? import_base.base64.encode(Uint8Array.from(args.keyPrefix)) : "";
553
- const result = await sendRequest({
873
+ // src/_common/schemas/zod/common/curveString.ts
874
+ var z10 = __toESM(require("zod/mini"), 1);
875
+ var import_base2 = require("@scure/base");
876
+ var CurveStringSchema = z10.pipe(
877
+ z10.string().check(
878
+ z10.regex(
879
+ /^(ed25519|secp256k1):[1-9A-HJ-NP-Za-km-z]+$/,
880
+ oneLine(`Curve strings should use the
881
+ ed25519:<base58String> or secp256k1:<base58String> format.`)
882
+ )
883
+ ),
884
+ z10.transform((curveString) => {
885
+ const [curve, base58String] = curveString.split(":");
886
+ return {
887
+ curveString,
888
+ curve,
889
+ u8Data: import_base2.base58.decode(base58String)
890
+ };
891
+ })
892
+ );
893
+
894
+ // src/_common/schemas/zod/common/publicKey.ts
895
+ var { Ed25519, Secp256k1 } = BinaryLengths;
896
+ var PublicKeySchema = z11.pipe(
897
+ CurveStringSchema,
898
+ z11.transform((val) => ({
899
+ publicKey: val.curveString,
900
+ u8PublicKey: val.u8Data,
901
+ curve: val.curve
902
+ }))
903
+ ).check(
904
+ z11.refine(
905
+ ({ curve, u8PublicKey }) => curve === "ed25519" ? u8PublicKey.length === Ed25519.PublicKey : u8PublicKey.length === Secp256k1.PublicKey,
906
+ { error: "Invalid public key length" }
907
+ )
908
+ );
909
+
910
+ // src/client/methods/account/getAccountAccessKey/getAccountAccessKey.ts
911
+ var GetAccountAccessKeyArgsSchema = z12.object({
912
+ accountId: AccountIdSchema,
913
+ publicKey: PublicKeySchema,
914
+ atMomentOf: z12.optional(BlockReferenceSchema),
915
+ policies: PoliciesSchema,
916
+ options: BaseOptionsSchema
917
+ });
918
+ var createSafeGetAccountAccessKey = (context) => wrapInternalError("Client.GetAccountAccessKey.Internal", async (args) => {
919
+ const validArgs = GetAccountAccessKeyArgsSchema.safeParse(args);
920
+ if (!validArgs.success)
921
+ return result.err(
922
+ createNatError({
923
+ kind: "Client.GetAccountAccessKey.Args.InvalidSchema",
924
+ context: { zodError: validArgs.error }
925
+ })
926
+ );
927
+ const rpcResponse = await context.sendRequest({
554
928
  method: "query",
555
929
  params: {
556
- request_type: "view_state",
557
- account_id: args.contractAccountId,
558
- prefix_base64: base64KeyPrefix,
559
- include_proof: args.includeProof,
930
+ request_type: "view_access_key",
931
+ account_id: args.accountId,
932
+ public_key: args.publicKey,
560
933
  ...toNativeBlockReference(args.atMomentOf)
561
934
  },
562
935
  transportPolicy: args.policies?.transport,
563
936
  signal: args.options?.signal
564
937
  });
565
- return transformResult4(result, args);
566
- };
938
+ if (!rpcResponse.ok)
939
+ return result.err(
940
+ createNatError({
941
+ kind: "Client.GetAccountAccessKey.SendRequest.Failed",
942
+ context: { cause: rpcResponse.error }
943
+ })
944
+ );
945
+ return rpcResponse.value.error ? handleError2(rpcResponse.value) : handleResult2(rpcResponse.value, args);
946
+ });
567
947
 
568
- // src/client/methods/contract/callContractReadFunction.ts
569
- var import_base2 = require("@scure/base");
570
- var z5 = __toESM(require("zod/mini"), 1);
948
+ // src/client/methods/account/getAccountAccessKeys/getAccountAccessKeys.ts
949
+ var z14 = __toESM(require("zod/mini"), 1);
950
+
951
+ // src/client/methods/account/getAccountAccessKeys/handleError.ts
571
952
  var import_jsonrpc_types5 = require("@near-js/jsonrpc-types");
572
- var baseDeserializeResul = ({ rawResult }) => fromJsonBytes(rawResult);
573
- var BaseSchema2 = z5.object({
574
- logs: z5.array(z5.string()),
575
- blockHash: (0, import_jsonrpc_types5.CryptoHashSchema)(),
576
- blockHeight: z5.number()
577
- });
578
- var RpcCallFunctionResponseSchema = z5.union([
579
- z5.object({ ...BaseSchema2.shape, result: z5.array(z5.number()) }),
580
- z5.object({ ...BaseSchema2.shape, error: z5.string() })
581
- ]);
582
- var transformResult5 = (result, args) => {
583
- const valid = RpcCallFunctionResponseSchema.parse(result);
584
- if ("error" in valid)
585
- throw new NatError({
586
- code: "ContractExecutionError",
587
- message: `Contract read function call failed: ${valid.error}`,
588
- cause: valid
589
- });
590
- const transformer = args?.options?.deserializeResult ? args.options.deserializeResult : baseDeserializeResul;
591
- return {
592
- blockHash: valid.blockHash,
593
- blockHeight: valid.blockHeight,
594
- result: transformer({ rawResult: valid.result }),
595
- logs: valid.logs
596
- };
597
- };
598
- var serializeFunctionArgs = (args) => {
599
- if (args?.options?.serializeArgs)
600
- return args.options.serializeArgs({ functionArgs: args.functionArgs });
601
- if (args?.functionArgs) return toJsonBytes(args?.functionArgs);
602
- return new Uint8Array();
603
- };
604
- var createCallContractReadFunction = ({ sendRequest }) => async (args) => {
605
- const result = await sendRequest({
606
- method: "query",
607
- params: {
608
- request_type: "call_function",
609
- account_id: args.contractAccountId,
610
- method_name: args.functionName,
611
- args_base64: import_base2.base64.encode(serializeFunctionArgs(args)),
612
- ...toNativeBlockReference(args.withStateAt)
613
- },
614
- transportPolicy: args.policies?.transport,
615
- signal: args.options?.signal
616
- });
617
- return transformResult5(result, args);
953
+ var handleError3 = (rpcResponse) => {
954
+ const rpcError = (0, import_jsonrpc_types5.ErrorWrapperFor_RpcQueryErrorSchema)().safeParse(
955
+ rpcResponse.error
956
+ );
957
+ if (!rpcError.success)
958
+ return result.err(
959
+ createNatError({
960
+ kind: "Client.GetAccountAccessKeys.SendRequest.Failed",
961
+ context: {
962
+ cause: createNatError({
963
+ kind: "Client.Transport.SendRequest.Response.Error.InvalidSchema",
964
+ context: { zodError: rpcError.error }
965
+ })
966
+ }
967
+ })
968
+ );
969
+ const { name, cause } = rpcError.data;
970
+ if (name === "HANDLER_ERROR") {
971
+ if (cause.name === "NO_SYNCED_BLOCKS")
972
+ return result.err(
973
+ createNatError({
974
+ kind: `Client.GetAccountAccessKeys.Rpc.NotSynced`,
975
+ context: null
976
+ })
977
+ );
978
+ if (cause.name === "UNAVAILABLE_SHARD")
979
+ return result.err(
980
+ createNatError({
981
+ kind: `Client.GetAccountAccessKeys.Rpc.Shard.NotTracked`,
982
+ context: { shardId: cause.info.requestedShardId }
983
+ })
984
+ );
985
+ if (cause.name === "GARBAGE_COLLECTED_BLOCK")
986
+ return result.err(
987
+ createNatError({
988
+ kind: `Client.GetAccountAccessKeys.Rpc.Block.GarbageCollected`,
989
+ context: {
990
+ blockHash: cause.info.blockHash,
991
+ blockHeight: cause.info.blockHeight
992
+ }
993
+ })
994
+ );
995
+ if (cause.name === "UNKNOWN_BLOCK" && "blockId" in cause.info.blockReference)
996
+ return result.err(
997
+ createNatError({
998
+ kind: `Client.GetAccountAccessKeys.Rpc.Block.NotFound`,
999
+ context: {
1000
+ blockId: cause.info.blockReference.blockId
1001
+ }
1002
+ })
1003
+ );
1004
+ }
1005
+ return result.err(
1006
+ createNatError({
1007
+ kind: "Client.GetAccountAccessKeys.Internal",
1008
+ context: {
1009
+ cause: createNatError({
1010
+ kind: "Client.GetAccountAccessKeys.Rpc.Unclassified",
1011
+ context: { rpcResponse }
1012
+ })
1013
+ }
1014
+ })
1015
+ );
618
1016
  };
619
1017
 
620
- // src/client/methods/block/getBlock.ts
1018
+ // src/client/methods/account/getAccountAccessKeys/handleResult.ts
1019
+ var z13 = __toESM(require("zod/mini"), 1);
621
1020
  var import_jsonrpc_types6 = require("@near-js/jsonrpc-types");
622
- var transformResult6 = (result) => {
623
- return (0, import_jsonrpc_types6.RpcBlockResponseSchema)().parse(result);
624
- };
625
- var createGetBlock = ({ sendRequest }) => async (args) => {
626
- const result = await sendRequest({
627
- method: "block",
628
- params: toNativeBlockReference(args?.blockReference),
629
- transportPolicy: args?.policies?.transport,
630
- signal: args?.options?.signal
631
- });
632
- return transformResult6(result);
633
- };
634
-
635
- // src/client/methods/protocol/getGasPrice.ts
636
- var z7 = __toESM(require("zod/mini"), 1);
637
- var import_jsonrpc_types7 = require("@near-js/jsonrpc-types");
638
-
639
- // src/_common/schemas/zod/common.ts
640
- var z6 = __toESM(require("zod/mini"), 1);
641
- var import_base3 = require("@scure/base");
642
- var Base58StringSchema = z6.string().check(
643
- z6.regex(
644
- /^[1-9A-HJ-NP-Za-km-z]+$/,
645
- oneLine(`Base58 string contains invalid characters. Allowed characters:
646
- 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`)
647
- )
648
- );
649
- var CryptoHashSchema6 = Base58StringSchema.check(
650
- z6.refine(
651
- (val) => {
652
- try {
653
- const bytes = import_base3.base58.decode(val);
654
- return bytes.length === 32;
655
- } catch {
656
- return false;
657
- }
658
- },
659
- { error: "CryptoHash string must decode to 32 bytes" }
660
- )
661
- );
662
- var BlockHashSchema = CryptoHashSchema6;
663
- var BlockHeightSchema = z6.uint64();
664
- var BlockIdSchema = z6.union([BlockHeightSchema, BlockHashSchema]);
665
-
666
- // src/client/methods/protocol/getGasPrice.ts
667
- var transformResult7 = (result) => {
668
- const valid = (0, import_jsonrpc_types7.RpcGasPriceResponseSchema)().parse(result);
669
- return {
670
- gasPrice: yoctoNear(valid.gasPrice)
1021
+ var RpcQueryAccessKeyListResultSchema = z13.object({
1022
+ ...(0, import_jsonrpc_types6.AccessKeyListSchema)().shape,
1023
+ blockHash: z13.string(),
1024
+ blockHeight: z13.number()
1025
+ });
1026
+ var handleResult3 = (rpcResponse, args) => {
1027
+ const rpcResult = RpcQueryAccessKeyListResultSchema.safeParse(
1028
+ rpcResponse.result
1029
+ );
1030
+ if (!rpcResult.success)
1031
+ return result.err(
1032
+ createNatError({
1033
+ kind: "Client.GetAccountAccessKeys.SendRequest.Failed",
1034
+ context: {
1035
+ cause: createNatError({
1036
+ kind: "Client.Transport.SendRequest.Response.Result.InvalidSchema",
1037
+ context: { zodError: rpcResult.error }
1038
+ })
1039
+ }
1040
+ })
1041
+ );
1042
+ const { blockHash, blockHeight } = rpcResult.data;
1043
+ const output = {
1044
+ blockHash,
1045
+ blockHeight,
1046
+ accountId: args.accountId,
1047
+ accountAccessKeys: rpcResult.data.keys.map(transformAccessKey),
1048
+ rawRpcResult: rpcResult.data
671
1049
  };
1050
+ return result.ok(output);
672
1051
  };
673
- var GetGasPriceArgsSchema = z7.optional(
674
- z7.object({
675
- blockId: z7.optional(BlockIdSchema)
676
- })
677
- );
678
- var getBlockId = (atMomentOf) => {
679
- if (atMomentOf === "LatestOptimisticBlock") return null;
680
- if (atMomentOf && "blockHash" in atMomentOf) return atMomentOf.blockHash;
681
- if (atMomentOf && "blockHeight" in atMomentOf) return atMomentOf.blockHeight;
682
- return null;
683
- };
684
- var createGetGasPrice = ({ sendRequest }) => async (args) => {
685
- GetGasPriceArgsSchema.parse(args);
686
- const result = await sendRequest({
687
- method: "gas_price",
1052
+
1053
+ // src/client/methods/account/getAccountAccessKeys/getAccountAccessKeys.ts
1054
+ var GetAccountAccessKeysArgsSchema = z14.object({
1055
+ accountId: AccountIdSchema,
1056
+ atMomentOf: z14.optional(BlockReferenceSchema),
1057
+ policies: PoliciesSchema,
1058
+ options: BaseOptionsSchema
1059
+ });
1060
+ var createSafeGetAccountAccessKeys = (context) => wrapInternalError("Client.GetAccountAccessKeys.Internal", async (args) => {
1061
+ const validArgs = GetAccountAccessKeysArgsSchema.safeParse(args);
1062
+ if (!validArgs.success)
1063
+ return result.err(
1064
+ createNatError({
1065
+ kind: "Client.GetAccountAccessKeys.Args.InvalidSchema",
1066
+ context: { zodError: validArgs.error }
1067
+ })
1068
+ );
1069
+ const rpcResponse = await context.sendRequest({
1070
+ method: "query",
688
1071
  params: {
689
- block_id: getBlockId(args?.atMomentOf)
1072
+ request_type: "view_access_key_list",
1073
+ account_id: args.accountId,
1074
+ ...toNativeBlockReference(args.atMomentOf)
690
1075
  },
691
- transportPolicy: args?.policies?.transport,
692
- signal: args?.options?.signal
1076
+ transportPolicy: args.policies?.transport,
1077
+ signal: args.options?.signal
693
1078
  });
694
- return transformResult7(result);
695
- };
696
-
697
- // src/client/methods/protocol/getProtocolConfig.ts
698
- var z8 = __toESM(require("zod/mini"), 1);
699
- var import_jsonrpc_types8 = require("@near-js/jsonrpc-types");
700
- var TemporaryProtocolConfigShema = z8.object({
701
- ...(0, import_jsonrpc_types8.RpcProtocolConfigResponseSchema)().shape,
702
- runtimeConfig: z8.object({
703
- ...(0, import_jsonrpc_types8.RuntimeConfigViewSchema)().shape,
704
- wasmConfig: z8.omit((0, import_jsonrpc_types8.VMConfigViewSchema)(), { reftypesBulkMemory: true })
705
- })
1079
+ if (!rpcResponse.ok)
1080
+ return result.err(
1081
+ createNatError({
1082
+ kind: "Client.GetAccountAccessKeys.SendRequest.Failed",
1083
+ context: { cause: rpcResponse.error }
1084
+ })
1085
+ );
1086
+ return rpcResponse.value.error ? handleError3(rpcResponse.value) : handleResult3(rpcResponse.value, args);
706
1087
  });
707
- var transformResult8 = (result) => {
708
- return TemporaryProtocolConfigShema.parse(result);
709
- };
710
- var createGetProtocolConfig = ({ sendRequest }) => async (args) => {
711
- const result = await sendRequest({
712
- method: "EXPERIMENTAL_protocol_config",
713
- params: toNativeBlockReference(args?.atMomentOf),
714
- transportPolicy: args?.policies?.transport,
715
- signal: args?.options?.signal
716
- });
717
- return transformResult8(result);
718
- };
719
1088
 
720
- // src/client/methods/transaction/sendSignedTransaction.ts
721
- var import_base7 = require("@scure/base");
1089
+ // src/client/methods/transaction/sendSignedTransaction/sendSignedTransaction.ts
1090
+ var z26 = __toESM(require("zod/mini"), 1);
1091
+ var import_base3 = require("@scure/base");
722
1092
 
723
- // src/_common/transformers/toBorshBytes/signedTransaction.ts
1093
+ // src/_common/transformers/toBorshBytes/transaction.ts
724
1094
  var import_borsh = require("borsh");
725
1095
 
726
1096
  // src/_common/schemas/borsh/publicKey.ts
@@ -1002,8 +1372,6 @@ var transactionBorshSchema = {
1002
1372
  actions: { array: { type: actionBorshSchema } }
1003
1373
  }
1004
1374
  };
1005
-
1006
- // src/_common/schemas/borsh/signedTransaction.ts
1007
1375
  var signedTransactionBorshSchema = {
1008
1376
  struct: {
1009
1377
  transaction: transactionBorshSchema,
@@ -1011,39 +1379,16 @@ var signedTransactionBorshSchema = {
1011
1379
  }
1012
1380
  };
1013
1381
 
1014
- // src/_common/transformers/curveString.ts
1015
- var import_base4 = require("@scure/base");
1016
- var toEd25519CurveString = (u8Data) => `ed25519:${import_base4.base58.encode(u8Data)}`;
1017
- var toSecp256k1CurveString = (u8Data) => `secp256k1:${import_base4.base58.encode(u8Data)}`;
1018
- var fromCurveString = (value) => {
1019
- const [curve, base58String] = value.split(":");
1020
- return {
1021
- curve,
1022
- u8Data: import_base4.base58.decode(base58String)
1023
- };
1024
- };
1025
-
1026
- // src/_common/transformers/toNative/signature.ts
1027
- var toNativeSignature = (signature) => {
1028
- const { curve, u8Data } = fromCurveString(signature);
1029
- if (curve === "ed25519") return { ed25519Signature: { data: u8Data } };
1030
- return { secp256k1Signature: { data: u8Data } };
1031
- };
1032
-
1033
- // src/_common/transformers/toNative/transaction.ts
1034
- var import_base6 = require("@scure/base");
1035
-
1036
1382
  // src/_common/transformers/toNative/publicKey.ts
1037
- var toNativePublicKey = (publicKey) => {
1038
- const { curve, u8Data } = fromCurveString(publicKey);
1039
- if (curve === "ed25519") return { ed25519Key: { data: u8Data } };
1040
- return { secp256k1Key: { data: u8Data } };
1041
- };
1383
+ var toNativePublicKey = ({
1384
+ u8PublicKey,
1385
+ curve
1386
+ }) => curve === "ed25519" ? { ed25519Key: { data: u8PublicKey } } : { secp256k1Key: { data: u8PublicKey } };
1042
1387
 
1043
1388
  // src/_common/transformers/toNative/actions/transfer.ts
1044
1389
  var toNativeTransferAction = (action) => ({
1045
1390
  transfer: {
1046
- deposit: fromNearOption(action.params.amount).yoctoNear
1391
+ deposit: throwableNearToken(action.amount).yoctoNear
1047
1392
  }
1048
1393
  });
1049
1394
 
@@ -1053,74 +1398,210 @@ var toNativeCreateAccountAction = () => ({
1053
1398
  });
1054
1399
 
1055
1400
  // src/_common/transformers/toNative/actions/addKey.ts
1056
- var getPermission = (params) => {
1057
- if (params.accessType === "FullAccess") return { fullAccess: {} };
1058
- const { contractAccountId, gasBudget, allowedFunctions } = params;
1401
+ var getPermission = (action) => {
1402
+ if (action.accessType === "FullAccess") return { fullAccess: {} };
1403
+ const { contractAccountId, gasBudget, allowedFunctions } = action;
1059
1404
  return {
1060
1405
  functionCall: {
1061
1406
  receiverId: contractAccountId,
1062
- allowance: gasBudget && fromNearOption(gasBudget).yoctoNear,
1407
+ allowance: gasBudget && throwableNearToken(gasBudget).yoctoNear,
1063
1408
  methodNames: allowedFunctions ?? []
1064
1409
  }
1065
1410
  };
1066
1411
  };
1067
1412
  var toNativeAddKeyAction = (action) => ({
1068
1413
  addKey: {
1069
- publicKey: toNativePublicKey(action.params.publicKey),
1414
+ publicKey: toNativePublicKey(action.publicKey),
1070
1415
  accessKey: {
1071
1416
  nonce: 0n,
1072
1417
  // Placeholder; It's not usable anymore: https://gov.near.org/t/issue-with-access-key-nonce/749
1073
- permission: getPermission(action.params)
1418
+ permission: getPermission(action)
1074
1419
  }
1075
1420
  }
1076
1421
  });
1077
1422
 
1078
1423
  // src/_common/transformers/toNative/actions/deployContract.ts
1079
- var import_base5 = require("@scure/base");
1080
- var toNativeDeployContractAction = (action) => {
1081
- const code = action.params.wasmBytes ? action.params.wasmBytes : import_base5.base64.decode(action.params.wasmBase64);
1082
- return {
1083
- deployContract: { code }
1084
- };
1085
- };
1424
+ var toNativeDeployContractAction = (action) => ({
1425
+ deployContract: { code: action.wasmBytes }
1426
+ });
1086
1427
 
1087
- // src/helpers/gas.ts
1088
- var TeraCoefficient = 10n ** 12n;
1089
- var gas = (gas2) => {
1090
- return {
1091
- gas: BigInt(gas2),
1092
- teraGas: String(BigInt(gas2) / TeraCoefficient)
1093
- // We don't keep decimals here
1094
- };
1095
- };
1096
- var teraGas = (teraGas2) => {
1097
- return {
1098
- gas: BigInt(teraGas2) * TeraCoefficient,
1099
- teraGas: teraGas2
1100
- };
1101
- };
1102
- var fromGasOption = (gasOption) => {
1103
- if ("teraGas" in gasOption) return teraGas(gasOption.teraGas);
1104
- if ("gas" in gasOption) return gas(gasOption.gas);
1105
- throw new Error("Invalid gas option");
1106
- };
1428
+ // src/_common/schemas/zod/common/nearGas.ts
1429
+ var z15 = __toESM(require("zod/mini"), 1);
1430
+ var GasInputSchema = z15.union([
1431
+ z15.bigint(),
1432
+ z15.pipe(
1433
+ z15.number().check(z15.int()),
1434
+ z15.transform((v) => BigInt(v))
1435
+ )
1436
+ ]);
1437
+ var createTeraGasInputSchema = (decimals) => z15.string().check(
1438
+ z15.refine(
1439
+ (val) => {
1440
+ const decimalPattern = new RegExp(`^\\d+(?:\\.\\d{1,${decimals}})?$`);
1441
+ return decimalPattern.test(val);
1442
+ },
1443
+ {
1444
+ message: `Must be a valid number with up to ${decimals} decimal places`
1445
+ }
1446
+ )
1447
+ );
1448
+ var TeraGasInputSchema = createTeraGasInputSchema(12);
1449
+ var NearGasArgsSchema = z15.union([
1450
+ z15.object({
1451
+ gas: GasInputSchema
1452
+ }),
1453
+ z15.object({
1454
+ teraGas: TeraGasInputSchema
1455
+ })
1456
+ ]);
1107
1457
 
1108
- // src/_common/transformers/contract.ts
1109
- var toContractFnArgsBytes = (args) => {
1110
- if (args.fnArgsBytes) return args.fnArgsBytes;
1111
- if (args.fnArgsJson) return toJsonBytes(args.fnArgsJson);
1112
- return new Uint8Array();
1458
+ // src/helpers/nearGas.ts
1459
+ var NearGasBrand = Symbol("NearGas");
1460
+ var cache2 = {
1461
+ gas: /* @__PURE__ */ new WeakMap(),
1462
+ teraGas: /* @__PURE__ */ new WeakMap()
1463
+ };
1464
+ var isNearGas = (value) => typeof value === "object" && value !== null && NearGasBrand in value;
1465
+ var toGas = (x) => {
1466
+ if (isNearGas(x)) return result.ok(x.gas);
1467
+ const nearGas = safeNearGas(x);
1468
+ return nearGas.ok ? result.ok(nearGas.value.gas) : nearGas;
1469
+ };
1470
+ var nearGasProto = {
1471
+ [NearGasBrand]: true,
1472
+ get teraGas() {
1473
+ const maybeValue = cache2.teraGas.get(this);
1474
+ if (maybeValue) return maybeValue;
1475
+ const value = convertUnitsToTokens(this.gas, 12);
1476
+ cache2.teraGas.set(this, value);
1477
+ return value;
1478
+ },
1479
+ get gas() {
1480
+ const maybeValue = cache2.gas.get(this);
1481
+ if (maybeValue) return maybeValue;
1482
+ const value = convertTokensToUnits(this.teraGas, 12);
1483
+ cache2.gas.set(this, value);
1484
+ return value;
1485
+ },
1486
+ // TODO Need to reuse method code and reduce boilerplate code, and reduce useless
1487
+ // transformations
1488
+ safeAdd(value) {
1489
+ return wrapInternalError("CreateNearGas.Internal", () => {
1490
+ const gas = toGas(value);
1491
+ return gas.ok ? safeNearGas({ gas: this.gas + gas.value }) : gas;
1492
+ })();
1493
+ },
1494
+ add(value) {
1495
+ return asThrowable(this.safeAdd.bind(this))(value);
1496
+ },
1497
+ safeSub(value) {
1498
+ return wrapInternalError("CreateNearGas.Internal", () => {
1499
+ const gas = toGas(value);
1500
+ return gas.ok ? safeNearGas({ gas: this.gas - gas.value }) : gas;
1501
+ })();
1502
+ },
1503
+ sub(value) {
1504
+ return asThrowable(this.safeSub.bind(this))(value);
1505
+ },
1506
+ safeGt(value) {
1507
+ return wrapInternalError("CreateNearGas.Internal", () => {
1508
+ const gas = toGas(value);
1509
+ return gas.ok ? result.ok(this.gas > gas.value) : gas;
1510
+ })();
1511
+ },
1512
+ gt(value) {
1513
+ return asThrowable(this.safeGt.bind(this))(value);
1514
+ },
1515
+ safeLt(value) {
1516
+ return wrapInternalError("CreateNearGas.Internal", () => {
1517
+ const gas = toGas(value);
1518
+ return gas.ok ? result.ok(this.gas < gas.value) : gas;
1519
+ })();
1520
+ },
1521
+ lt(value) {
1522
+ return asThrowable(this.safeLt.bind(this))(value);
1523
+ },
1524
+ toString() {
1525
+ return JSON.stringify({
1526
+ teraGas: this.teraGas,
1527
+ gas: this.gas.toString()
1528
+ });
1529
+ },
1530
+ // In Node.js, this allows you to see the teraGas/gas getter values,
1531
+ // which are not normally visible unless you access them directly.
1532
+ // This does not work in the browser — there you can only see a getter’s value
1533
+ // by explicitly expanding/clicking on it.
1534
+ ...nodeInspectSymbol && {
1535
+ [nodeInspectSymbol](_depth, _opts) {
1536
+ return { teraGas: this.teraGas, gas: this.gas };
1537
+ }
1538
+ }
1113
1539
  };
1540
+ var safeGas = wrapInternalError(
1541
+ "CreateNearGasFromGas.Internal",
1542
+ (gas) => {
1543
+ const validGas = GasInputSchema.safeParse(gas);
1544
+ if (!validGas.success)
1545
+ return result.err(
1546
+ createNatError({
1547
+ kind: "CreateNearGasFromGas.Args.InvalidSchema",
1548
+ context: { zodError: validGas.error }
1549
+ })
1550
+ );
1551
+ const nearGas = Object.create(nearGasProto);
1552
+ Object.defineProperty(nearGas, "gas", {
1553
+ value: validGas.data,
1554
+ enumerable: true
1555
+ });
1556
+ return result.ok(Object.freeze(nearGas));
1557
+ }
1558
+ );
1559
+ var throwableGas = asThrowable(safeGas);
1560
+ var safeTeraGas = wrapInternalError(
1561
+ "CreateNearGasFromTeraGas.Internal",
1562
+ (teraGas) => {
1563
+ const validTeraGas = TeraGasInputSchema.safeParse(teraGas);
1564
+ if (!validTeraGas.success)
1565
+ return result.err(
1566
+ createNatError({
1567
+ kind: "CreateNearGasFromTeraGas.Args.InvalidSchema",
1568
+ context: { zodError: validTeraGas.error }
1569
+ })
1570
+ );
1571
+ const nearGas = Object.create(nearGasProto);
1572
+ Object.defineProperty(nearGas, "teraGas", {
1573
+ value: validTeraGas.data,
1574
+ enumerable: true
1575
+ });
1576
+ return result.ok(Object.freeze(nearGas));
1577
+ }
1578
+ );
1579
+ var throwableTeraGas = asThrowable(safeTeraGas);
1580
+ var safeNearGas = wrapInternalError(
1581
+ "CreateNearGas.Internal",
1582
+ (args) => {
1583
+ const validArgs = NearGasArgsSchema.safeParse(args);
1584
+ if (!validArgs.success)
1585
+ return result.err(
1586
+ createNatError({
1587
+ kind: "CreateNearGas.Args.InvalidSchema",
1588
+ context: { zodError: validArgs.error }
1589
+ })
1590
+ );
1591
+ return "gas" in args ? result.ok(throwableGas(args.gas)) : result.ok(throwableTeraGas(args.teraGas));
1592
+ }
1593
+ );
1594
+ var throwableNearGas = asThrowable(safeNearGas);
1114
1595
 
1115
1596
  // src/_common/transformers/toNative/actions/functionCall.ts
1116
1597
  var toNativeFunctionCallAction = (action) => {
1117
- const { functionName, attachedDeposit, gasLimit } = action.params;
1598
+ const { functionName, attachedDeposit, gasLimit, functionArgs } = action;
1118
1599
  return {
1119
1600
  functionCall: {
1120
1601
  methodName: functionName,
1121
- args: toContractFnArgsBytes(action.params),
1122
- gas: fromGasOption(gasLimit).gas,
1123
- deposit: attachedDeposit ? fromNearOption(attachedDeposit).yoctoNear : 0n
1602
+ args: functionArgs,
1603
+ gas: throwableNearGas(gasLimit).gas,
1604
+ deposit: attachedDeposit ? throwableNearToken(attachedDeposit).yoctoNear : 0n
1124
1605
  }
1125
1606
  };
1126
1607
  };
@@ -1128,31 +1609,32 @@ var toNativeFunctionCallAction = (action) => {
1128
1609
  // src/_common/transformers/toNative/actions/deleteKey.ts
1129
1610
  var toNativeDeleteKeyAction = (action) => ({
1130
1611
  deleteKey: {
1131
- publicKey: toNativePublicKey(action.params.publicKey)
1612
+ publicKey: toNativePublicKey(action.publicKey)
1132
1613
  }
1133
1614
  });
1134
1615
 
1135
1616
  // src/_common/transformers/toNative/actions/deleteAccount.ts
1136
1617
  var toNativeDeleteAccountAction = (action) => ({
1137
1618
  deleteAccount: {
1138
- beneficiaryId: action.params.beneficiaryAccountId
1619
+ beneficiaryId: action.beneficiaryAccountId
1139
1620
  }
1140
1621
  });
1141
1622
 
1623
+ // src/_common/transformers/toNative/signature.ts
1624
+ var toNativeSignature = ({
1625
+ u8Signature,
1626
+ curve
1627
+ }) => curve === "ed25519" ? { ed25519Signature: { data: u8Signature } } : { secp256k1Signature: { data: u8Signature } };
1628
+
1142
1629
  // src/_common/transformers/toNative/transaction.ts
1143
1630
  var toNativeAction = (action) => {
1144
1631
  if (action.actionType === "Transfer") return toNativeTransferAction(action);
1145
- if (action.actionType === "CreateAccount")
1146
- return toNativeCreateAccountAction();
1632
+ if (action.actionType === "CreateAccount") return toNativeCreateAccountAction();
1147
1633
  if (action.actionType === "AddKey") return toNativeAddKeyAction(action);
1148
- if (action.actionType === "DeployContract")
1149
- return toNativeDeployContractAction(action);
1150
- if (action.actionType === "FunctionCall")
1151
- return toNativeFunctionCallAction(action);
1634
+ if (action.actionType === "DeployContract") return toNativeDeployContractAction(action);
1635
+ if (action.actionType === "FunctionCall") return toNativeFunctionCallAction(action);
1152
1636
  if (action.actionType === "DeleteKey") return toNativeDeleteKeyAction(action);
1153
- if (action.actionType === "DeleteAccount")
1154
- return toNativeDeleteAccountAction(action);
1155
- throw new Error("Invalid transaction action type");
1637
+ return toNativeDeleteAccountAction(action);
1156
1638
  };
1157
1639
  var toNativeActions = (transaction) => {
1158
1640
  if (transaction.action) return [toNativeAction(transaction.action)];
@@ -1166,86 +1648,527 @@ var toNativeTransaction = (transaction) => ({
1166
1648
  actions: toNativeActions(transaction),
1167
1649
  receiverId: transaction.receiverAccountId,
1168
1650
  nonce: BigInt(transaction.nonce),
1169
- blockHash: import_base6.base58.decode(transaction.blockHash)
1651
+ blockHash: transaction.blockHash.u8CryptoHash
1652
+ });
1653
+ var toNativeSignedTransaction = (signedTransaction) => ({
1654
+ transaction: toNativeTransaction(signedTransaction.transaction),
1655
+ signature: toNativeSignature(signedTransaction.signature)
1656
+ });
1657
+
1658
+ // src/_common/transformers/toBorshBytes/transaction.ts
1659
+ var toBorshTransaction = (transaction) => {
1660
+ const nativeTransaction = toNativeTransaction(transaction);
1661
+ return (0, import_borsh.serialize)(transactionBorshSchema, nativeTransaction);
1662
+ };
1663
+ var toBorshSignedTransaction = (signedTransaction) => {
1664
+ const nativeSignedTransaction = toNativeSignedTransaction(signedTransaction);
1665
+ return (0, import_borsh.serialize)(signedTransactionBorshSchema, nativeSignedTransaction);
1666
+ };
1667
+
1668
+ // src/_common/schemas/zod/transaction/transaction.ts
1669
+ var z24 = __toESM(require("zod/mini"), 1);
1670
+
1671
+ // src/_common/schemas/zod/transaction/actions/createAccount.ts
1672
+ var z16 = __toESM(require("zod/mini"), 1);
1673
+ var CreateAccountActionSchema = z16.object({
1674
+ actionType: z16.literal("CreateAccount")
1675
+ });
1676
+
1677
+ // src/_common/schemas/zod/transaction/actions/addKey.ts
1678
+ var z17 = __toESM(require("zod/mini"), 1);
1679
+ var AddFullAccessKeyActionSchema = z17.object({
1680
+ actionType: z17.literal("AddKey"),
1681
+ accessType: z17.literal("FullAccess"),
1682
+ publicKey: PublicKeySchema
1170
1683
  });
1171
- var TransactionExecutionStatusMap = {
1172
- None: "NONE",
1173
- Included: "INCLUDED",
1174
- ExecutedOptimistic: "EXECUTED_OPTIMISTIC",
1175
- IncludedFinal: "INCLUDED_FINAL",
1176
- Executed: "EXECUTED",
1177
- Final: "FINAL"
1684
+ var AddFunctionCallKeyActionSchema = z17.object({
1685
+ actionType: z17.literal("AddKey"),
1686
+ accessType: z17.literal("FunctionCall"),
1687
+ publicKey: PublicKeySchema,
1688
+ contractAccountId: AccountIdSchema,
1689
+ gasBudget: z17.optional(NearTokenArgsSchema),
1690
+ allowedFunctions: z17.optional(
1691
+ z17.array(ContractFunctionNameSchema).check(z17.minLength(1))
1692
+ )
1693
+ });
1694
+ var AddKeyActionSchema = z17.union([
1695
+ AddFullAccessKeyActionSchema,
1696
+ AddFunctionCallKeyActionSchema
1697
+ ]);
1698
+
1699
+ // src/_common/schemas/zod/transaction/actions/transfer.ts
1700
+ var z18 = __toESM(require("zod/mini"), 1);
1701
+ var TransferActionSchema = z18.object({
1702
+ actionType: z18.literal("Transfer"),
1703
+ amount: NearTokenArgsSchema
1704
+ });
1705
+
1706
+ // src/_common/schemas/zod/transaction/actions/deployContract.ts
1707
+ var z19 = __toESM(require("zod/mini"), 1);
1708
+ var DeployContractActionSchema = z19.object({
1709
+ actionType: z19.literal("DeployContract"),
1710
+ wasmBytes: z19.instanceof(Uint8Array)
1711
+ });
1712
+
1713
+ // src/_common/schemas/zod/transaction/actions/deleteKey.ts
1714
+ var z20 = __toESM(require("zod/mini"), 1);
1715
+ var DeleteKeyActionSchema = z20.object({
1716
+ actionType: z20.literal("DeleteKey"),
1717
+ publicKey: PublicKeySchema
1718
+ });
1719
+
1720
+ // src/_common/schemas/zod/transaction/actions/deleteAccount.ts
1721
+ var z21 = __toESM(require("zod/mini"), 1);
1722
+ var DeleteAccountActionSchema = z21.object({
1723
+ actionType: z21.literal("DeleteAccount"),
1724
+ beneficiaryAccountId: AccountIdSchema
1725
+ });
1726
+
1727
+ // src/_common/schemas/zod/transaction/actions/functionCall.ts
1728
+ var z22 = __toESM(require("zod/mini"), 1);
1729
+ var FunctionCallActionSchema = z22.object({
1730
+ actionType: z22.literal("FunctionCall"),
1731
+ functionName: ContractFunctionNameSchema,
1732
+ functionArgs: z22.instanceof(Uint8Array),
1733
+ gasLimit: NearGasArgsSchema,
1734
+ attachedDeposit: z22.optional(NearTokenArgsSchema)
1735
+ });
1736
+
1737
+ // src/_common/schemas/zod/common/signature.ts
1738
+ var z23 = __toESM(require("zod/mini"), 1);
1739
+ var { Ed25519: Ed255192, Secp256k1: Secp256k12 } = BinaryLengths;
1740
+ var SignatureSchema = z23.pipe(
1741
+ CurveStringSchema,
1742
+ z23.transform((val) => ({
1743
+ signature: val.curveString,
1744
+ u8Signature: val.u8Data,
1745
+ curve: val.curve
1746
+ }))
1747
+ ).check(
1748
+ z23.refine(
1749
+ ({ curve, u8Signature }) => curve === "ed25519" ? u8Signature.length === Ed255192.Signature : u8Signature.length === Secp256k12.Signature,
1750
+ { error: "Invalid signature length" }
1751
+ )
1752
+ );
1753
+
1754
+ // src/_common/schemas/zod/transaction/transaction.ts
1755
+ var ActionSchema = z24.union([
1756
+ CreateAccountActionSchema,
1757
+ TransferActionSchema,
1758
+ AddKeyActionSchema,
1759
+ DeployContractActionSchema,
1760
+ FunctionCallActionSchema,
1761
+ DeleteKeyActionSchema,
1762
+ DeleteAccountActionSchema
1763
+ ]);
1764
+ var TransactionBaseSchema = z24.object({
1765
+ signerAccountId: AccountIdSchema,
1766
+ signerPublicKey: PublicKeySchema,
1767
+ receiverAccountId: AccountIdSchema,
1768
+ nonce: NonceSchema,
1769
+ blockHash: BlockHashSchema
1770
+ });
1771
+ var SingleActionTransactionSchema = z24.object({
1772
+ ...TransactionBaseSchema.shape,
1773
+ action: ActionSchema,
1774
+ actions: z24.optional(z24.never())
1775
+ });
1776
+ var MultiActionsTransactionSchema = z24.object({
1777
+ ...TransactionBaseSchema.shape,
1778
+ action: z24.optional(z24.never()),
1779
+ actions: z24.array(ActionSchema).check(z24.minLength(1))
1780
+ });
1781
+ var TransactionSchema = z24.union([
1782
+ SingleActionTransactionSchema,
1783
+ MultiActionsTransactionSchema
1784
+ ]);
1785
+ var SingleActionTransactionIntentSchema = z24.object({
1786
+ action: ActionSchema,
1787
+ actions: z24.optional(z24.never()),
1788
+ receiverAccountId: AccountIdSchema
1789
+ });
1790
+ var MultiActionsTransactionIntentSchema = z24.object({
1791
+ action: z24.optional(z24.never()),
1792
+ actions: z24.array(ActionSchema).check(z24.minLength(1)),
1793
+ receiverAccountId: AccountIdSchema
1794
+ });
1795
+ var TransactionIntentSchema = z24.union([
1796
+ SingleActionTransactionIntentSchema,
1797
+ MultiActionsTransactionIntentSchema
1798
+ ]);
1799
+ var SignedTransactionSchema = z24.object({
1800
+ transaction: TransactionSchema,
1801
+ transactionHash: CryptoHashSchema,
1802
+ signature: SignatureSchema
1803
+ });
1804
+
1805
+ // src/client/methods/transaction/sendSignedTransaction/handleError/handleError.ts
1806
+ var import_jsonrpc_types8 = require("@near-js/jsonrpc-types");
1807
+
1808
+ // src/client/methods/transaction/sendSignedTransaction/handleError/handleInvalidTransaction.ts
1809
+ var z25 = __toESM(require("zod/mini"), 1);
1810
+ var import_jsonrpc_types7 = require("@near-js/jsonrpc-types");
1811
+ var InvalidTransactionErrorSchema = z25.object({
1812
+ TxExecutionError: z25.object({
1813
+ InvalidTxError: (0, import_jsonrpc_types7.InvalidTxErrorSchema)()
1814
+ })
1815
+ });
1816
+ var handleInvalidTransaction = (rpcResponse) => {
1817
+ const invalidTransactionError = InvalidTransactionErrorSchema.safeParse(
1818
+ rpcResponse.error?.data
1819
+ );
1820
+ if (!invalidTransactionError.success)
1821
+ return result.err(
1822
+ createNatError({
1823
+ kind: "Client.SendSignedTransaction.SendRequest.Failed",
1824
+ context: {
1825
+ cause: createNatError({
1826
+ kind: "Client.Transport.SendRequest.Response.Error.InvalidSchema",
1827
+ context: { zodError: invalidTransactionError.error }
1828
+ })
1829
+ }
1830
+ })
1831
+ );
1832
+ const { InvalidTxError } = invalidTransactionError.data.TxExecutionError;
1833
+ if (typeof InvalidTxError === "string") {
1834
+ if (InvalidTxError === "Expired") {
1835
+ return result.err(
1836
+ createNatError({
1837
+ kind: "Client.SendSignedTransaction.Rpc.Transaction.Expired",
1838
+ context: null
1839
+ })
1840
+ );
1841
+ }
1842
+ if (InvalidTxError === "InvalidSignature") {
1843
+ return result.err(
1844
+ createNatError({
1845
+ kind: "Client.SendSignedTransaction.Rpc.Transaction.Signature.Invalid",
1846
+ context: null
1847
+ })
1848
+ );
1849
+ }
1850
+ }
1851
+ if (typeof InvalidTxError === "object") {
1852
+ if ("InvalidNonce" in InvalidTxError) {
1853
+ const { akNonce, txNonce } = InvalidTxError.InvalidNonce;
1854
+ return result.err(
1855
+ createNatError({
1856
+ kind: "Client.SendSignedTransaction.Rpc.Transaction.Nonce.Invalid",
1857
+ context: {
1858
+ accessKeyNonce: akNonce,
1859
+ transactionNonce: txNonce
1860
+ }
1861
+ })
1862
+ );
1863
+ }
1864
+ if ("SignerDoesNotExist" in InvalidTxError) {
1865
+ return result.err(
1866
+ createNatError({
1867
+ kind: "Client.SendSignedTransaction.Rpc.Transaction.Signer.NotFound",
1868
+ context: {
1869
+ signerAccountId: InvalidTxError.SignerDoesNotExist.signerId
1870
+ }
1871
+ })
1872
+ );
1873
+ }
1874
+ if ("NotEnoughBalance" in InvalidTxError) {
1875
+ const { signerId, balance, cost } = InvalidTxError.NotEnoughBalance;
1876
+ return result.err(
1877
+ createNatError({
1878
+ kind: "Client.SendSignedTransaction.Rpc.Transaction.Signer.Balance.TooLow",
1879
+ context: {
1880
+ balance: throwableYoctoNear(balance),
1881
+ transactionCost: throwableYoctoNear(cost),
1882
+ signerAccountId: signerId
1883
+ }
1884
+ })
1885
+ );
1886
+ }
1887
+ }
1888
+ return result.err(
1889
+ createNatError({
1890
+ kind: "Client.SendSignedTransaction.Internal",
1891
+ context: {
1892
+ cause: createNatError({
1893
+ kind: "Client.SendSignedTransaction.Rpc.Unclassified",
1894
+ context: { rpcResponse }
1895
+ })
1896
+ }
1897
+ })
1898
+ );
1899
+ };
1900
+
1901
+ // src/client/methods/transaction/sendSignedTransaction/handleError/handleError.ts
1902
+ var handleError4 = (rpcResponse) => {
1903
+ const rpcError = (0, import_jsonrpc_types8.ErrorWrapperFor_RpcTransactionErrorSchema)().safeParse(
1904
+ rpcResponse.error
1905
+ );
1906
+ if (!rpcError.success)
1907
+ return result.err(
1908
+ createNatError({
1909
+ kind: "Client.SendSignedTransaction.SendRequest.Failed",
1910
+ context: {
1911
+ cause: createNatError({
1912
+ kind: "Client.Transport.SendRequest.Response.Error.InvalidSchema",
1913
+ context: { zodError: rpcError.error }
1914
+ })
1915
+ }
1916
+ })
1917
+ );
1918
+ const { name, cause } = rpcError.data;
1919
+ if (name === "HANDLER_ERROR") {
1920
+ if (cause.name === "TIMEOUT_ERROR")
1921
+ return result.err(
1922
+ createNatError({
1923
+ kind: `Client.SendSignedTransaction.Rpc.Transaction.Timeout`,
1924
+ context: null
1925
+ })
1926
+ );
1927
+ if (cause.name === "INVALID_TRANSACTION")
1928
+ return handleInvalidTransaction(rpcResponse);
1929
+ }
1930
+ return result.err(
1931
+ createNatError({
1932
+ kind: "Client.SendSignedTransaction.Internal",
1933
+ context: {
1934
+ cause: createNatError({
1935
+ kind: "Client.SendSignedTransaction.Rpc.Unclassified",
1936
+ context: { rpcResponse }
1937
+ })
1938
+ }
1939
+ })
1940
+ );
1178
1941
  };
1179
- var toNativeTransactionExecutionStatus = (status) => TransactionExecutionStatusMap[status];
1180
1942
 
1181
- // src/_common/transformers/toNative/signedTransaction.ts
1182
- var toNativeSignedTransaction = (signedTransaction) => ({
1183
- transaction: toNativeTransaction(signedTransaction.transaction),
1184
- signature: toNativeSignature(signedTransaction.signature)
1185
- });
1943
+ // src/client/methods/transaction/sendSignedTransaction/handleResult/handleResult.ts
1944
+ var import_jsonrpc_types9 = require("@near-js/jsonrpc-types");
1186
1945
 
1187
- // src/_common/transformers/toBorshBytes/signedTransaction.ts
1188
- var serializeNativeSignedTransaction = (nativeSignedTransaction) => (0, import_borsh.serialize)(signedTransactionBorshSchema, nativeSignedTransaction);
1189
- var serializeSignedTransaction = (signedTransaction) => serializeNativeSignedTransaction(
1190
- toNativeSignedTransaction(signedTransaction)
1191
- );
1946
+ // src/client/methods/transaction/sendSignedTransaction/handleResult/handleActionError.ts
1947
+ var handleActionError = (actionError, rpcResponse, inputArgs) => {
1948
+ const { transactionHash } = inputArgs.signedTransaction;
1949
+ const { kind, index: actionIndex } = actionError;
1950
+ if (typeof actionIndex !== "number")
1951
+ return result.err(
1952
+ createNatError({
1953
+ kind: "Client.SendSignedTransaction.Internal",
1954
+ context: {
1955
+ cause: createNatError({
1956
+ kind: "Client.SendSignedTransaction.Rpc.Transaction.Action.InvalidIndex",
1957
+ context: { rpcResponse }
1958
+ })
1959
+ }
1960
+ })
1961
+ );
1962
+ if (typeof kind === "object") {
1963
+ if ("AccountAlreadyExists" in kind) {
1964
+ return result.err(
1965
+ createNatError({
1966
+ kind: "Client.SendSignedTransaction.Rpc.Transaction.Action.CreateAccount.AlreadyExist",
1967
+ context: {
1968
+ accountId: kind.AccountAlreadyExists.accountId,
1969
+ actionIndex,
1970
+ transactionHash
1971
+ }
1972
+ })
1973
+ );
1974
+ }
1975
+ if ("AccountDoesNotExist" in kind) {
1976
+ return result.err(
1977
+ createNatError({
1978
+ kind: "Client.SendSignedTransaction.Rpc.Transaction.Receiver.NotFound",
1979
+ context: {
1980
+ receiverAccountId: kind.AccountDoesNotExist.accountId,
1981
+ actionIndex,
1982
+ transactionHash
1983
+ }
1984
+ })
1985
+ );
1986
+ }
1987
+ }
1988
+ return result.err(
1989
+ createNatError({
1990
+ kind: "Client.SendSignedTransaction.Internal",
1991
+ context: {
1992
+ cause: createNatError({
1993
+ kind: "Client.SendSignedTransaction.Rpc.Unclassified",
1994
+ context: { rpcResponse }
1995
+ })
1996
+ }
1997
+ })
1998
+ );
1999
+ };
1192
2000
 
1193
- // src/client/methods/transaction/sendSignedTransaction.ts
1194
- var import_jsonrpc_types9 = require("@near-js/jsonrpc-types");
1195
- var transformResult9 = (result) => {
1196
- return (0, import_jsonrpc_types9.RpcTransactionResponseSchema)().parse(result);
2001
+ // src/client/methods/transaction/sendSignedTransaction/handleResult/handleResult.ts
2002
+ var handleResult4 = (rpcResponse, inputArgs) => {
2003
+ const rpcResult = (0, import_jsonrpc_types9.RpcTransactionResponseSchema)().safeParse(
2004
+ rpcResponse.result
2005
+ );
2006
+ if (!rpcResult.success)
2007
+ return result.err(
2008
+ createNatError({
2009
+ kind: "Client.SendSignedTransaction.SendRequest.Failed",
2010
+ context: {
2011
+ cause: createNatError({
2012
+ kind: "Client.Transport.SendRequest.Response.Result.InvalidSchema",
2013
+ context: { zodError: rpcResult.error }
2014
+ })
2015
+ }
2016
+ })
2017
+ );
2018
+ if (typeof rpcResult.data.status === "object" && "Failure" in rpcResult.data.status && "ActionError" in rpcResult.data.status.Failure)
2019
+ return handleActionError(
2020
+ rpcResult.data.status.Failure.ActionError,
2021
+ rpcResponse,
2022
+ inputArgs
2023
+ );
2024
+ const output = {
2025
+ rawRpcResult: rpcResult.data
2026
+ // TODO Return result without errors
2027
+ };
2028
+ return result.ok(output);
1197
2029
  };
1198
- var createSendSignedTransaction = ({ sendRequest }) => async (args) => {
1199
- const waitUntil = args?.policies?.waitUntil ?? "ExecutedOptimistic";
1200
- const result = await sendRequest({
2030
+
2031
+ // src/client/methods/transaction/sendSignedTransaction/sendSignedTransaction.ts
2032
+ var SendSignedTransactionArgsShema = z26.object({
2033
+ signedTransaction: SignedTransactionSchema,
2034
+ policies: PoliciesSchema,
2035
+ options: BaseOptionsSchema
2036
+ });
2037
+ var createSafeSendSignedTransaction = (context) => wrapInternalError("Client.SendSignedTransaction.Internal", async (args) => {
2038
+ const validArgs = SendSignedTransactionArgsShema.safeParse(args);
2039
+ if (!validArgs.success)
2040
+ return result.err(
2041
+ createNatError({
2042
+ kind: "Client.SendSignedTransaction.Args.InvalidSchema",
2043
+ context: { zodError: validArgs.error }
2044
+ })
2045
+ );
2046
+ const rpcResponse = await context.sendRequest({
1201
2047
  method: "send_tx",
1202
2048
  params: {
1203
- signed_tx_base64: import_base7.base64.encode(
1204
- serializeSignedTransaction(args.signedTransaction)
2049
+ signed_tx_base64: import_base3.base64.encode(
2050
+ toBorshSignedTransaction(validArgs.data.signedTransaction)
1205
2051
  ),
1206
- wait_until: toNativeTransactionExecutionStatus(waitUntil)
2052
+ wait_until: "FINAL"
1207
2053
  },
1208
2054
  transportPolicy: args.policies?.transport,
1209
2055
  signal: args.options?.signal
1210
2056
  });
1211
- return transformResult9(result);
1212
- };
2057
+ if (!rpcResponse.ok)
2058
+ return result.err(
2059
+ createNatError({
2060
+ kind: "Client.SendSignedTransaction.SendRequest.Failed",
2061
+ context: { cause: rpcResponse.error }
2062
+ })
2063
+ );
2064
+ return rpcResponse.value.error ? handleError4(rpcResponse.value) : handleResult4(rpcResponse.value, args);
2065
+ });
1213
2066
 
1214
- // src/client/transport/transportPolicy.ts
1215
- var import_lodash_es = require("lodash-es");
1216
- var defaultTransportPolicy = {
1217
- rpcTypePreferences: ["Regular", "Archival"],
1218
- timeouts: {
1219
- requestMs: 3e4,
1220
- attemptMs: 1e4
1221
- },
1222
- retry: {
1223
- maxAttempts: 2,
1224
- backoff: {
1225
- minDelayMs: 100,
1226
- maxDelayMs: 200,
1227
- multiplier: 3
1228
- }
1229
- },
1230
- failover: {
1231
- maxRounds: 2,
1232
- nextRpcDelayMs: 100,
1233
- nextRoundDelayMs: 100
2067
+ // src/client/methods/block/getBlock/getBlock.ts
2068
+ var z27 = __toESM(require("zod/mini"), 1);
2069
+
2070
+ // src/client/methods/block/getBlock/handleError.ts
2071
+ var import_jsonrpc_types10 = require("@near-js/jsonrpc-types");
2072
+ var handleError5 = (rpcResponse) => {
2073
+ const rpcError = (0, import_jsonrpc_types10.ErrorWrapperFor_RpcBlockErrorSchema)().safeParse(
2074
+ rpcResponse.error
2075
+ );
2076
+ if (!rpcError.success)
2077
+ return result.err(
2078
+ createNatError({
2079
+ kind: "Client.GetBlock.SendRequest.Failed",
2080
+ context: {
2081
+ cause: createNatError({
2082
+ kind: "Client.Transport.SendRequest.Response.Error.InvalidSchema",
2083
+ context: { zodError: rpcError.error }
2084
+ })
2085
+ }
2086
+ })
2087
+ );
2088
+ const { name, cause } = rpcError.data;
2089
+ if (name === "HANDLER_ERROR") {
2090
+ if (cause.name === "NOT_SYNCED_YET")
2091
+ return result.err(
2092
+ createNatError({
2093
+ kind: `Client.GetBlock.Rpc.NotSynced`,
2094
+ context: null
2095
+ })
2096
+ );
2097
+ if (cause.name === "UNKNOWN_BLOCK")
2098
+ return result.err(
2099
+ createNatError({
2100
+ kind: `Client.GetBlock.Rpc.Block.NotFound`,
2101
+ context: null
2102
+ })
2103
+ );
1234
2104
  }
2105
+ return result.err(
2106
+ createNatError({
2107
+ kind: "Client.GetBlock.Internal",
2108
+ context: {
2109
+ cause: createNatError({
2110
+ kind: "Client.GetBlock.Rpc.Unclassified",
2111
+ context: { rpcResponse }
2112
+ })
2113
+ }
2114
+ })
2115
+ );
1235
2116
  };
1236
- var mergeTransportPolicy = (base, next = {}) => (0, import_lodash_es.mergeWith)(
1237
- {},
1238
- (0, import_lodash_es.cloneDeep)(base),
1239
- (0, import_lodash_es.cloneDeep)(next),
1240
- (_objValue, srcValue, key) => {
1241
- if (key === "rpcTypePreferences" && Array.isArray(srcValue)) {
1242
- return srcValue;
1243
- }
1244
- }
1245
- );
1246
2117
 
1247
- // src/client/transport/sendRequest/5-sendOnce/sendOnce.ts
1248
- var z10 = __toESM(require("zod/mini"), 1);
2118
+ // src/client/methods/block/getBlock/handleResult.ts
2119
+ var import_jsonrpc_types11 = require("@near-js/jsonrpc-types");
2120
+ var handleResult5 = (rpcResponse) => {
2121
+ const rpcResult = (0, import_jsonrpc_types11.RpcBlockResponseSchema)().safeParse(rpcResponse.result);
2122
+ if (!rpcResult.success)
2123
+ return result.err(
2124
+ createNatError({
2125
+ kind: "Client.GetBlock.SendRequest.Failed",
2126
+ context: {
2127
+ cause: createNatError({
2128
+ kind: "Client.Transport.SendRequest.Response.Result.InvalidSchema",
2129
+ context: { zodError: rpcResult.error }
2130
+ })
2131
+ }
2132
+ })
2133
+ );
2134
+ const output = {
2135
+ rawRpcResult: rpcResult.data
2136
+ };
2137
+ return result.ok(output);
2138
+ };
2139
+
2140
+ // src/client/methods/block/getBlock/getBlock.ts
2141
+ var GetBlockArgsSchema = z27.optional(
2142
+ z27.object({
2143
+ blockReference: z27.optional(BlockReferenceSchema),
2144
+ policies: PoliciesSchema,
2145
+ options: BaseOptionsSchema
2146
+ })
2147
+ );
2148
+ var createSafeGetBlock = (context) => wrapInternalError("Client.GetBlock.Internal", async (args) => {
2149
+ const validArgs = GetBlockArgsSchema.safeParse(args);
2150
+ if (!validArgs.success)
2151
+ return result.err(
2152
+ createNatError({
2153
+ kind: "Client.GetBlock.Args.InvalidSchema",
2154
+ context: { zodError: validArgs.error }
2155
+ })
2156
+ );
2157
+ const rpcResponse = await context.sendRequest({
2158
+ method: "block",
2159
+ params: toNativeBlockReference(args?.blockReference),
2160
+ transportPolicy: args?.policies?.transport,
2161
+ signal: args?.options?.signal
2162
+ });
2163
+ if (!rpcResponse.ok)
2164
+ return result.err(
2165
+ createNatError({
2166
+ kind: "Client.GetBlock.SendRequest.Failed",
2167
+ context: { cause: rpcResponse.error }
2168
+ })
2169
+ );
2170
+ return rpcResponse.value.error ? handleError5(rpcResponse.value) : handleResult5(rpcResponse.value);
2171
+ });
1249
2172
 
1250
2173
  // src/_common/utils/snakeToCamelCase.ts
1251
2174
  var snakeToCamelCase = (obj) => {
@@ -1271,24 +2194,69 @@ var snakeToCamelCase = (obj) => {
1271
2194
  };
1272
2195
 
1273
2196
  // src/_common/schemas/zod/rpc.ts
1274
- var z9 = __toESM(require("zod/mini"), 1);
1275
- var import_jsonrpc_types10 = require("@near-js/jsonrpc-types");
1276
- var RpcResponseSchema = z9.object({
1277
- jsonrpc: z9.literal("2.0"),
1278
- id: z9.unknown(),
1279
- result: z9.optional(z9.unknown()),
1280
- error: z9.optional((0, import_jsonrpc_types10.RpcErrorSchema)())
2197
+ var z28 = __toESM(require("zod/mini"), 1);
2198
+ var BaseRpcResponseSchema = z28.object({
2199
+ jsonrpc: z28.literal("2.0"),
2200
+ id: z28.number()
1281
2201
  });
2202
+ var BaseRpcErrorSchema = z28.object({
2203
+ code: z28.number(),
2204
+ message: z28.string(),
2205
+ data: z28.optional(z28.unknown())
2206
+ });
2207
+ var RpcErrorSchema = z28.discriminatedUnion("name", [
2208
+ z28.object({
2209
+ ...BaseRpcErrorSchema.shape,
2210
+ name: z28.literal("REQUEST_VALIDATION_ERROR"),
2211
+ cause: z28.discriminatedUnion("name", [
2212
+ z28.object({
2213
+ name: z28.literal("METHOD_NOT_FOUND"),
2214
+ info: z28.object({ methodName: z28.string() })
2215
+ }),
2216
+ z28.object({
2217
+ name: z28.literal("PARSE_ERROR"),
2218
+ info: z28.object({ errorMessage: z28.string() })
2219
+ })
2220
+ ])
2221
+ }),
2222
+ z28.object({
2223
+ ...BaseRpcErrorSchema.shape,
2224
+ name: z28.literal("HANDLER_ERROR"),
2225
+ cause: z28.object({
2226
+ info: z28.unknown(),
2227
+ name: z28.string()
2228
+ })
2229
+ }),
2230
+ z28.object({
2231
+ ...BaseRpcErrorSchema.shape,
2232
+ name: z28.literal("INTERNAL_ERROR"),
2233
+ cause: z28.object({
2234
+ name: z28.literal("INTERNAL_ERROR"),
2235
+ info: z28.object({ errorMessage: z28.string() })
2236
+ })
2237
+ })
2238
+ ]);
2239
+ var RpcResponseSchema = z28.union([
2240
+ z28.object({
2241
+ ...BaseRpcResponseSchema.shape,
2242
+ result: z28.unknown(),
2243
+ error: z28.optional(z28.never())
2244
+ }),
2245
+ z28.object({
2246
+ ...BaseRpcResponseSchema.shape,
2247
+ result: z28.optional(z28.never()),
2248
+ error: RpcErrorSchema
2249
+ })
2250
+ ]);
1282
2251
 
1283
2252
  // src/client/transport/sendRequest/5-sendOnce/fetchData/createAttemptTimeout.ts
1284
2253
  var createAttemptTimeout = (attemptTimeoutMs) => {
1285
2254
  const controller = new AbortController();
1286
2255
  const timeoutId = setTimeout(
1287
2256
  () => controller.abort(
1288
- new TransportError({
1289
- code: "AttemptTimeout",
1290
- message: oneLine(`The request attempt exceeded the configured timeout
1291
- and was aborted.`)
2257
+ createNatError({
2258
+ kind: "Client.Transport.SendRequest.Request.Attempt.Timeout",
2259
+ context: { allowedMs: attemptTimeoutMs }
1292
2260
  })
1293
2261
  ),
1294
2262
  attemptTimeoutMs
@@ -1315,21 +2283,24 @@ var fetchData = async (context, rpc, body) => {
1315
2283
  attemptTimeout.signal
1316
2284
  ])
1317
2285
  });
1318
- return { result: response };
2286
+ return result.ok(response);
1319
2287
  } catch (e) {
1320
- if (hasTransportErrorCode(e, [
1321
- "ExternalAbort",
1322
- "RequestTimeout",
1323
- "AttemptTimeout"
2288
+ if (isNatErrorOf(e, [
2289
+ "Client.Transport.SendRequest.Request.Attempt.Timeout",
2290
+ "Client.Transport.SendRequest.Request.Timeout",
2291
+ "Client.Transport.SendRequest.Request.Aborted"
1324
2292
  ]))
1325
- return { error: e };
1326
- return {
1327
- error: new TransportError({
1328
- code: "Fetch",
1329
- message: `Fetch failed: unable to send the request to '${rpc.url}' (connection refused, DNS error or network issues).`,
1330
- cause: e
2293
+ return result.err(e);
2294
+ return result.err(
2295
+ createNatError({
2296
+ kind: "Client.Transport.SendRequest.Request.FetchFailed",
2297
+ context: {
2298
+ cause: e,
2299
+ rpc,
2300
+ requestBody: body
2301
+ }
1331
2302
  })
1332
- };
2303
+ );
1333
2304
  } finally {
1334
2305
  clearTimeout(attemptTimeout.timeoutId);
1335
2306
  }
@@ -1338,81 +2309,86 @@ var fetchData = async (context, rpc, body) => {
1338
2309
  // src/client/transport/sendRequest/5-sendOnce/parseJsonResponse.ts
1339
2310
  var parseJsonResponse = async (response, rpc) => {
1340
2311
  try {
1341
- return { result: await response.json() };
2312
+ return result.ok(await response.json());
1342
2313
  } catch (e) {
1343
- return {
1344
- error: new TransportError({
1345
- code: "ParseResponseToJson",
1346
- message: `Failed to parse response as JSON from the RPC node: ${rpc.url}`,
1347
- cause: e
2314
+ return result.err(
2315
+ createNatError({
2316
+ kind: "Client.Transport.SendRequest.Response.JsonParseFailed",
2317
+ context: {
2318
+ cause: e,
2319
+ rpc,
2320
+ response
2321
+ }
1348
2322
  })
1349
- };
2323
+ );
2324
+ }
2325
+ };
2326
+
2327
+ // src/client/transport/sendRequest/5-sendOnce/extractRpcErrors.ts
2328
+ var prefix = "Client.Transport.SendRequest.Rpc";
2329
+ var getErrorKind = ({
2330
+ name,
2331
+ cause
2332
+ }) => {
2333
+ if (name === "REQUEST_VALIDATION_ERROR") {
2334
+ if (cause.name === "METHOD_NOT_FOUND") return `${prefix}.MethodNotFound`;
2335
+ if (cause.name === "PARSE_ERROR") return `${prefix}.ParseFailed`;
2336
+ }
2337
+ if (name === "HANDLER_ERROR") {
2338
+ if (cause.name === "NO_SYNCED_BLOCKS") return `${prefix}.NotSynced`;
2339
+ if (cause.name === "NOT_SYNCED_YET") return `${prefix}.NotSynced`;
2340
+ if (cause.name === "TIMEOUT_ERROR") return `${prefix}.Transaction.Timeout`;
2341
+ if (cause.name === "GARBAGE_COLLECTED_BLOCK") return `${prefix}.Block.GarbageCollected`;
2342
+ if (cause.name === "UNKNOWN_BLOCK") return `${prefix}.Block.NotFound`;
2343
+ if (cause.name === "INTERNAL_ERROR") return `${prefix}.Internal`;
1350
2344
  }
2345
+ if (name === "INTERNAL_ERROR") return `${prefix}.Internal`;
2346
+ };
2347
+ var extractRpcErrors = (generalRpcResponse, rpc) => {
2348
+ if ("result" in generalRpcResponse) return result.ok(generalRpcResponse);
2349
+ const kind = getErrorKind(generalRpcResponse.error);
2350
+ if (!kind) return result.ok(generalRpcResponse);
2351
+ return result.err(
2352
+ createNatError({
2353
+ kind,
2354
+ context: {
2355
+ rawRpcResponse: generalRpcResponse,
2356
+ rpc
2357
+ }
2358
+ })
2359
+ );
1351
2360
  };
1352
2361
 
1353
2362
  // src/client/transport/sendRequest/5-sendOnce/sendOnce.ts
1354
- var sendOnce = async (context, rpc, roundIndex, attemptIndex) => {
2363
+ var sendOnce = async (context, rpc) => {
1355
2364
  const body = {
1356
2365
  jsonrpc: "2.0",
1357
2366
  id: 0,
1358
2367
  method: context.method,
1359
2368
  params: context.params
1360
2369
  };
1361
- const request = {
1362
- url: rpc.url,
1363
- rpcType: rpc.type,
1364
- method: "POST",
1365
- headers: rpc.headers,
1366
- body,
1367
- roundIndex,
1368
- attemptIndex
1369
- };
1370
2370
  const response = await fetchData(context, rpc, body);
1371
- if (response.error) {
1372
- response.error.request = request;
1373
- context.errors.push(response.error);
1374
- return response;
1375
- }
1376
- const json = await parseJsonResponse(response.result, rpc);
1377
- if (json.error) {
1378
- json.error.request = request;
1379
- context.errors.push(json.error);
1380
- return json;
1381
- }
1382
- const camelCased = snakeToCamelCase(json.result);
1383
- const validated = RpcResponseSchema.safeParse(camelCased);
1384
- if (validated.error) {
1385
- const validationError = new TransportError({
1386
- code: "InvalidResponseSchema",
1387
- message: `Invalid RPC response format:
1388
- ${z10.prettifyError(validated.error)}
1389
-
1390
- Response: ${JSON.stringify(camelCased, null, 2)}
1391
-
1392
- Please try again or use another RPC node.`,
1393
- request,
1394
- cause: validated.error
1395
- });
1396
- context.errors.push(validationError);
1397
- return { error: validationError };
1398
- }
1399
- const { result, error } = validated.data;
1400
- if (error) {
1401
- const rpcError = new RpcError({
1402
- request,
1403
- __rawRpcError: error
1404
- });
1405
- context.errors.push(rpcError);
1406
- return { error: rpcError };
2371
+ if (!response.ok) return response;
2372
+ const json2 = await parseJsonResponse(response.value, rpc);
2373
+ if (!json2.ok) return json2;
2374
+ const camelCased = snakeToCamelCase(json2.value);
2375
+ const generalRpcResponse = RpcResponseSchema.safeParse(camelCased);
2376
+ if (!generalRpcResponse.success) {
2377
+ return result.err(
2378
+ createNatError({
2379
+ kind: "Client.Transport.SendRequest.Response.InvalidSchema",
2380
+ context: { zodError: generalRpcResponse.error }
2381
+ })
2382
+ );
1407
2383
  }
1408
- return { result };
2384
+ return extractRpcErrors(generalRpcResponse.data, rpc);
1409
2385
  };
1410
2386
 
1411
2387
  // src/_common/utils/sleep.ts
1412
2388
  var safeSleep = (ms, signal) => new Promise((resolve) => {
1413
- const abort = () => resolve(signal?.reason);
2389
+ const abort = () => resolve(result.err(signal?.reason));
1414
2390
  if (signal?.aborted) abort();
1415
- const timeoutId = setTimeout(() => resolve(), ms);
2391
+ const timeoutId = setTimeout(() => resolve(result.ok(true)), ms);
1416
2392
  if (signal)
1417
2393
  signal.addEventListener(
1418
2394
  "abort",
@@ -1426,106 +2402,97 @@ var safeSleep = (ms, signal) => new Promise((resolve) => {
1426
2402
 
1427
2403
  // src/client/transport/sendRequest/4-sendWithRetry/sendWithRetry.ts
1428
2404
  var getBackoffDelay = (cap, base, sleep, multiplier) => Math.min(cap, Math.round(randomBetween(base, sleep * multiplier)));
1429
- var shouldRetry = (result) => hasTransportErrorCode(result.error, ["Fetch", "AttemptTimeout"]) || hasRpcErrorCode(result.error, [
1430
- "RpcTransactionTimeout",
1431
- "NoSyncedBlocks",
1432
- "UnknownRequestError",
1433
- "InternalServerError"
2405
+ var shouldRetry = (sendOnceResult) => !sendOnceResult.ok && isNatErrorOf(sendOnceResult.error, [
2406
+ "Client.Transport.SendRequest.Request.FetchFailed",
2407
+ "Client.Transport.SendRequest.Request.Attempt.Timeout",
2408
+ "Client.Transport.SendRequest.Rpc.Transaction.Timeout",
2409
+ "Client.Transport.SendRequest.Rpc.NotSynced",
2410
+ "Client.Transport.SendRequest.Rpc.Internal"
1434
2411
  ]);
1435
- var sendWithRetry = async (context, rpc, roundIndex) => {
1436
- const { maxAttempts, backoff } = context.transportPolicy.retry;
1437
- let backoffDelay = backoff.minDelayMs;
2412
+ var sendWithRetry = async (context, rpc) => {
2413
+ const { maxAttempts, retryBackoff } = context.transportPolicy.rpc;
2414
+ let backoffDelay = retryBackoff.minDelayMs;
1438
2415
  const attempt = async (attemptIndex) => {
1439
- const result = await sendOnce(context, rpc, roundIndex, attemptIndex);
2416
+ const sendOnceResult = await sendOnce(context, rpc);
1440
2417
  const isLastAttempt = attemptIndex >= maxAttempts - 1;
1441
- if (isLastAttempt || !shouldRetry(result)) return result;
2418
+ if (isLastAttempt || !shouldRetry(sendOnceResult)) return sendOnceResult;
1442
2419
  backoffDelay = getBackoffDelay(
1443
- backoff.maxDelayMs,
1444
- backoff.minDelayMs,
2420
+ retryBackoff.maxDelayMs,
2421
+ retryBackoff.minDelayMs,
1445
2422
  backoffDelay,
1446
- backoff.multiplier
2423
+ retryBackoff.multiplier
1447
2424
  );
1448
- const abortError = await safeSleep(
2425
+ const sleepResult = await safeSleep(
1449
2426
  backoffDelay,
1450
2427
  combineAbortSignals([
1451
2428
  context.externalAbortSignal,
1452
2429
  context.requestTimeoutSignal
1453
2430
  ])
1454
2431
  );
1455
- if (abortError) {
1456
- context.errors.push(abortError);
1457
- return { error: abortError };
1458
- }
1459
- return attempt(attemptIndex + 1);
2432
+ return sleepResult.ok ? attempt(attemptIndex + 1) : sleepResult;
1460
2433
  };
1461
2434
  return attempt(0);
1462
2435
  };
1463
2436
 
1464
2437
  // src/client/transport/sendRequest/3-tryOneRound/tryOneRound.ts
1465
- var shouldTryAnotherRpc = (result) => hasTransportErrorCode(result.error, [
1466
- "Fetch",
1467
- "AttemptTimeout",
1468
- "ParseResponseToJson",
1469
- "InvalidResponseSchema"
1470
- ]) || hasRpcErrorCode(result.error, [
1471
- "ParseRequest",
1472
- "MethodNotFound",
1473
- "UnknownValidationError",
1474
- "RpcTransactionTimeout"
2438
+ var shouldTryAnotherRpc = (sendOnceResult) => !sendOnceResult.ok && isNatErrorOf(sendOnceResult.error, [
2439
+ "Client.Transport.SendRequest.Request.FetchFailed",
2440
+ "Client.Transport.SendRequest.Request.Attempt.Timeout",
2441
+ "Client.Transport.SendRequest.Response.JsonParseFailed",
2442
+ "Client.Transport.SendRequest.Response.InvalidSchema",
2443
+ "Client.Transport.SendRequest.Rpc.MethodNotFound",
2444
+ "Client.Transport.SendRequest.Rpc.ParseFailed",
2445
+ "Client.Transport.SendRequest.Rpc.Transaction.Timeout",
2446
+ "Client.Transport.SendRequest.Rpc.NotSynced",
2447
+ "Client.Transport.SendRequest.Rpc.Internal"
1475
2448
  ]);
1476
- var tryOneRound = async (context, rpcs, roundIndex) => {
2449
+ var tryOneRound = async (context, rpcs) => {
1477
2450
  const { nextRpcDelayMs } = context.transportPolicy.failover;
1478
2451
  const roundOnRpc = async (rpcIndex) => {
1479
2452
  const rpc = rpcs[rpcIndex];
1480
- const result = await sendWithRetry(context, rpc, roundIndex);
2453
+ const sendWithRetryResult = await sendWithRetry(context, rpc);
1481
2454
  const isLastRpc = rpcIndex >= rpcs.length - 1;
1482
- if (isLastRpc || !shouldTryAnotherRpc(result)) return result;
1483
- const abortError = await safeSleep(
2455
+ if (isLastRpc || !shouldTryAnotherRpc(sendWithRetryResult))
2456
+ return sendWithRetryResult;
2457
+ const sleepResult = await safeSleep(
1484
2458
  nextRpcDelayMs,
1485
2459
  combineAbortSignals([
1486
2460
  context.externalAbortSignal,
1487
2461
  context.requestTimeoutSignal
1488
2462
  ])
1489
2463
  );
1490
- if (abortError) {
1491
- context.errors.push(abortError);
1492
- return { error: abortError };
1493
- }
1494
- return roundOnRpc(rpcIndex + 1);
2464
+ return sleepResult.ok ? roundOnRpc(rpcIndex + 1) : sleepResult;
1495
2465
  };
1496
2466
  return roundOnRpc(0);
1497
2467
  };
1498
2468
 
1499
2469
  // src/client/transport/sendRequest/2-tryMultipleRounds/tryMultipleRounds.ts
1500
- var shouldTryAnotherRound = (result) => hasTransportErrorCode(result.error, [
1501
- "Fetch",
1502
- "AttemptTimeout",
1503
- "ParseResponseToJson",
1504
- "InvalidResponseSchema"
1505
- ]) || hasRpcErrorCode(result.error, [
1506
- "ParseRequest",
1507
- "MethodNotFound",
1508
- "UnknownValidationError",
1509
- "RpcTransactionTimeout"
2470
+ var shouldTryAnotherRound = (sendOnceResult) => !sendOnceResult.ok && isNatErrorOf(sendOnceResult.error, [
2471
+ "Client.Transport.SendRequest.Request.FetchFailed",
2472
+ "Client.Transport.SendRequest.Request.Attempt.Timeout",
2473
+ "Client.Transport.SendRequest.Response.JsonParseFailed",
2474
+ "Client.Transport.SendRequest.Response.InvalidSchema",
2475
+ "Client.Transport.SendRequest.Rpc.MethodNotFound",
2476
+ "Client.Transport.SendRequest.Rpc.ParseFailed",
2477
+ "Client.Transport.SendRequest.Rpc.Transaction.Timeout",
2478
+ "Client.Transport.SendRequest.Rpc.NotSynced",
2479
+ "Client.Transport.SendRequest.Rpc.Internal"
1510
2480
  ]);
1511
2481
  var tryMultipleRounds = async (context, rpcs) => {
1512
2482
  const { maxRounds, nextRoundDelayMs } = context.transportPolicy.failover;
1513
2483
  const round = async (roundIndex) => {
1514
- const result = await tryOneRound(context, rpcs, roundIndex);
2484
+ const tryOneRoundResult = await tryOneRound(context, rpcs);
1515
2485
  const isLastRound = roundIndex >= maxRounds - 1;
1516
- if (isLastRound || !shouldTryAnotherRound(result)) return result;
1517
- const abortError = await safeSleep(
2486
+ if (isLastRound || !shouldTryAnotherRound(tryOneRoundResult))
2487
+ return tryOneRoundResult;
2488
+ const sleepResult = await safeSleep(
1518
2489
  nextRoundDelayMs,
1519
2490
  combineAbortSignals([
1520
2491
  context.externalAbortSignal,
1521
2492
  context.requestTimeoutSignal
1522
2493
  ])
1523
2494
  );
1524
- if (abortError) {
1525
- context.errors.push(abortError);
1526
- return { error: abortError };
1527
- }
1528
- return round(roundIndex + 1);
2495
+ return sleepResult.ok ? round(roundIndex + 1) : sleepResult;
1529
2496
  };
1530
2497
  return round(0);
1531
2498
  };
@@ -1538,10 +2505,9 @@ var createExternalAbortSignal = (inputSignal) => {
1538
2505
  "abort",
1539
2506
  () => {
1540
2507
  controller.abort(
1541
- new TransportError({
1542
- code: "ExternalAbort",
1543
- message: `The request was aborted by user.`,
1544
- cause: inputSignal.reason
2508
+ createNatError({
2509
+ kind: "Client.Transport.SendRequest.Request.Aborted",
2510
+ context: { reason: inputSignal.reason }
1545
2511
  })
1546
2512
  );
1547
2513
  },
@@ -1555,10 +2521,9 @@ var createRequestTimeout = (requestTimeoutMs) => {
1555
2521
  const controller = new AbortController();
1556
2522
  const timeoutId = setTimeout(
1557
2523
  () => controller.abort(
1558
- new TransportError({
1559
- code: "RequestTimeout",
1560
- message: oneLine(`The request exceeded the configured timeout
1561
- and was aborted.`)
2524
+ createNatError({
2525
+ kind: "Client.Transport.SendRequest.Request.Timeout",
2526
+ context: { allowedMs: requestTimeoutMs }
1562
2527
  })
1563
2528
  ),
1564
2529
  requestTimeoutMs
@@ -1570,36 +2535,40 @@ var createRequestTimeout = (requestTimeoutMs) => {
1570
2535
  };
1571
2536
 
1572
2537
  // src/client/transport/sendRequest/1-createSendRequest/_common/getAvailableRpcs.ts
1573
- var getAvailableRpcs = (rpcEndpoints, rpcTypePriority) => {
1574
- const sortedList = rpcTypePriority.reduce((acc, type) => {
1575
- const normalizedType = type === "Regular" ? "regular" : "archival";
1576
- const value = rpcEndpoints[normalizedType] ?? [];
1577
- acc.push(...value);
1578
- return acc;
1579
- }, []);
1580
- if (sortedList.length === 0)
1581
- return {
1582
- error: new TransportError({
1583
- code: "NoAvailableRpc",
1584
- message: `Invalid request configuration: no RPC endpoints found for any of the preferred types (${rpcTypePriority.join(", ")}).`
1585
- })
1586
- };
1587
- return { result: sortedList };
2538
+ var getAvailableRpcs = (rpcEndpoints, rpcTypePreferences) => {
2539
+ const sortedList = rpcTypePreferences.reduce(
2540
+ (acc, type) => {
2541
+ const normalizedType = type === "Regular" ? "regular" : "archival";
2542
+ const value = rpcEndpoints[normalizedType] ?? [];
2543
+ acc.push(...value);
2544
+ return acc;
2545
+ },
2546
+ []
2547
+ );
2548
+ return sortedList.length > 0 ? result.ok(sortedList) : result.err(
2549
+ createNatError({
2550
+ kind: "Client.Transport.SendRequest.PreferredRpc.NotFound",
2551
+ context: {
2552
+ rpcEndpoints,
2553
+ rpcTypePreferences
2554
+ }
2555
+ })
2556
+ );
1588
2557
  };
1589
2558
 
1590
2559
  // src/client/transport/sendRequest/1-createSendRequest/handleMaybeUnknownBlock.ts
1591
2560
  var handleMaybeUnknownBlock = async ({
1592
- result: previousResult,
2561
+ requestResult: previousResult,
1593
2562
  rpcEndpoints,
1594
2563
  context
1595
2564
  }) => {
1596
- if (!(hasRpcErrorCode(previousResult.error, [
1597
- "UnknownBlock",
1598
- "GarbageCollectedBlock"
1599
- ]) && previousResult.error?.request?.rpcType === "regular" && context.transportPolicy.rpcTypePreferences.includes("Archival")))
2565
+ if (previousResult.ok || !(isNatErrorOf(previousResult.error, [
2566
+ "Client.Transport.SendRequest.Rpc.Block.GarbageCollected",
2567
+ "Client.Transport.SendRequest.Rpc.Block.NotFound"
2568
+ ]) && previousResult.error.context.rpc.type === "regular" && context.transportPolicy.rpcTypePreferences.includes("Archival")))
1600
2569
  return previousResult;
1601
2570
  const rpcs = getAvailableRpcs(rpcEndpoints, ["Archival"]);
1602
- if (rpcs.error) return previousResult;
2571
+ if (!rpcs.ok) return previousResult;
1603
2572
  return await tryOneRound(
1604
2573
  {
1605
2574
  ...context,
@@ -1607,8 +2576,7 @@ var handleMaybeUnknownBlock = async ({
1607
2576
  rpcTypePreferences: ["Archival"]
1608
2577
  })
1609
2578
  },
1610
- rpcs.result,
1611
- 0
2579
+ rpcs.value
1612
2580
  );
1613
2581
  };
1614
2582
 
@@ -1622,8 +2590,8 @@ var createSendRequest = (transportContext) => async (args) => {
1622
2590
  transportContext.rpcEndpoints,
1623
2591
  transportPolicy.rpcTypePreferences
1624
2592
  );
1625
- if (rpcs.error) throw rpcs.error;
1626
- const externalAbortSignal = createExternalAbortSignal(args.signal);
2593
+ if (!rpcs.ok) return rpcs;
2594
+ const maybeExternalAbortSignal = createExternalAbortSignal(args.signal);
1627
2595
  const requestTimeout = createRequestTimeout(
1628
2596
  transportPolicy.timeouts.requestMs
1629
2597
  );
@@ -1631,65 +2599,76 @@ var createSendRequest = (transportContext) => async (args) => {
1631
2599
  transportPolicy,
1632
2600
  method: args.method,
1633
2601
  params: args.params,
1634
- externalAbortSignal,
1635
- requestTimeoutSignal: requestTimeout.signal,
1636
- errors: []
2602
+ externalAbortSignal: maybeExternalAbortSignal,
2603
+ requestTimeoutSignal: requestTimeout.signal
1637
2604
  };
1638
- let result = await tryMultipleRounds(context, rpcs.result);
1639
- result = await handleMaybeUnknownBlock({
1640
- result,
2605
+ let requestResult = await tryMultipleRounds(context, rpcs.value);
2606
+ requestResult = await handleMaybeUnknownBlock({
2607
+ requestResult,
1641
2608
  context,
1642
2609
  rpcEndpoints: transportContext.rpcEndpoints
1643
2610
  });
1644
2611
  clearTimeout(requestTimeout.timeoutId);
1645
- if (context.errors.length > 0)
1646
- console.error(
1647
- "Errors during request: ",
1648
- context.errors.map(
1649
- (err) => oneLine(`R${err?.request?.roundIndex + 1};
1650
- A${err?.request?.attemptIndex + 1};
1651
- ${err.code};
1652
- ${err?.request?.url};`)
1653
- )
1654
- );
1655
- if (hasTransportErrorCode(result.error, ["ExternalAbort"]))
1656
- throw result?.error?.cause;
1657
- if (result.error) {
1658
- result.error.errors = context.errors;
1659
- throw result.error;
1660
- }
1661
- return result.result;
2612
+ if (requestResult.ok) return requestResult;
2613
+ if (isNatErrorOf(requestResult.error, [
2614
+ "Client.Transport.SendRequest.PreferredRpc.NotFound",
2615
+ "Client.Transport.SendRequest.Request.FetchFailed",
2616
+ "Client.Transport.SendRequest.Request.Attempt.Timeout",
2617
+ "Client.Transport.SendRequest.Request.Timeout",
2618
+ "Client.Transport.SendRequest.Request.Aborted",
2619
+ "Client.Transport.SendRequest.Response.JsonParseFailed",
2620
+ "Client.Transport.SendRequest.Response.InvalidSchema"
2621
+ ]))
2622
+ return result.err(requestResult.error);
2623
+ return result.ok(requestResult.error.context.rawRpcResponse);
1662
2624
  };
1663
2625
 
1664
2626
  // src/client/transport/createTransport.ts
1665
- var getRpcs = (list = [], type) => list.map((rpc) => ({
2627
+ var z30 = __toESM(require("zod/mini"), 1);
2628
+
2629
+ // src/client/transport/rpcEndpoints.ts
2630
+ var z29 = __toESM(require("zod/mini"), 1);
2631
+ var RpcEndpointSchema = z29.object({
2632
+ url: z29.url(),
2633
+ headers: z29.optional(z29.record(z29.string(), z29.string()))
2634
+ });
2635
+ var RpcEndpointsArgsSchema = z29.union([
2636
+ z29.object({
2637
+ regular: z29.array(RpcEndpointSchema).check(z29.minLength(1)),
2638
+ archival: z29.undefined()
2639
+ }),
2640
+ z29.object({
2641
+ regular: z29.undefined(),
2642
+ archival: z29.array(RpcEndpointSchema).check(z29.minLength(1))
2643
+ }),
2644
+ z29.object({
2645
+ regular: z29.array(RpcEndpointSchema).check(z29.minLength(1)),
2646
+ archival: z29.array(RpcEndpointSchema).check(z29.minLength(1))
2647
+ })
2648
+ ]);
2649
+ var getInnerRpcEndpoints = (list = [], type) => list.map((rpc) => ({
1666
2650
  type,
1667
2651
  url: rpc.url,
1668
2652
  headers: {
1669
2653
  ...rpc.headers,
1670
2654
  "Content-Type": "application/json"
1671
- },
1672
- inactiveUntil: null
2655
+ }
1673
2656
  }));
1674
- var validateRpcEndpoints = (rpcEndpoints, rpcTypePreferences) => {
1675
- const preferredType = rpcTypePreferences[0] === "Regular" ? "regular" : "archival";
1676
- const preferredList = rpcEndpoints[preferredType] ?? [];
1677
- if (rpcTypePreferences.length === 1 && preferredList.length === 0)
1678
- throw new TransportError({
1679
- code: "InvalidTransportConfiguration",
1680
- message: `Invalid transport configuration: no "${rpcTypePreferences[0]}" RPC endpoints found while it's the only preferred type.`
1681
- });
1682
- };
2657
+
2658
+ // src/client/transport/createTransport.ts
2659
+ var CreateTransportArgsSchema = z30.object({
2660
+ rpcEndpoints: RpcEndpointsArgsSchema,
2661
+ policy: PartialTransportPolicySchema
2662
+ });
1683
2663
  var createTransport = (args) => {
1684
2664
  const transportPolicy = mergeTransportPolicy(
1685
2665
  defaultTransportPolicy,
1686
2666
  args.policy
1687
2667
  );
1688
- validateRpcEndpoints(args.rpcEndpoints, transportPolicy.rpcTypePreferences);
1689
2668
  const context = {
1690
2669
  rpcEndpoints: {
1691
- regular: getRpcs(args.rpcEndpoints.regular, "regular"),
1692
- archival: getRpcs(args.rpcEndpoints.archival, "archival")
2670
+ regular: getInnerRpcEndpoints(args.rpcEndpoints.regular, "regular"),
2671
+ archival: getInnerRpcEndpoints(args.rpcEndpoints.archival, "archival")
1693
2672
  },
1694
2673
  transportPolicy
1695
2674
  };
@@ -1698,232 +2677,552 @@ var createTransport = (args) => {
1698
2677
  };
1699
2678
  };
1700
2679
 
1701
- // src/client/createClient.ts
1702
- var createClient = async (args) => {
1703
- const transport = createTransport(args.transport);
1704
- const context = {
1705
- sendRequest: transport.sendRequest
1706
- };
1707
- return {
1708
- getAccountState: createGetAccountState(context),
1709
- getAccountKey: createGetAccountKey(context),
1710
- getAccountKeys: createGetAccountKeys(context),
1711
- getContractState: createGetContractState(context),
1712
- callContractReadFunction: createCallContractReadFunction(context),
1713
- getBlock: createGetBlock(context),
1714
- getGasPrice: createGetGasPrice(context),
1715
- getProtocolConfig: createGetProtocolConfig(context),
1716
- sendSignedTransaction: createSendSignedTransaction(context)
2680
+ // src/client/methods/contract/callContractReadFunction/callContractReadFunction.ts
2681
+ var import_base4 = require("@scure/base");
2682
+ var z32 = __toESM(require("zod/mini"), 1);
2683
+
2684
+ // src/client/methods/contract/callContractReadFunction/handleError.ts
2685
+ var import_jsonrpc_types12 = require("@near-js/jsonrpc-types");
2686
+ var handleError6 = (rpcResponse) => {
2687
+ const rpcError = (0, import_jsonrpc_types12.ErrorWrapperFor_RpcQueryErrorSchema)().safeParse(
2688
+ rpcResponse.error
2689
+ );
2690
+ if (!rpcError.success)
2691
+ return result.err(
2692
+ createNatError({
2693
+ kind: "Client.CallContractReadFunction.SendRequest.Failed",
2694
+ context: {
2695
+ cause: createNatError({
2696
+ kind: "Client.Transport.SendRequest.Response.Error.InvalidSchema",
2697
+ context: { zodError: rpcError.error }
2698
+ })
2699
+ }
2700
+ })
2701
+ );
2702
+ const { name, cause } = rpcError.data;
2703
+ if (name === "HANDLER_ERROR") {
2704
+ if (cause.name === "NO_SYNCED_BLOCKS")
2705
+ return result.err(
2706
+ createNatError({
2707
+ kind: `Client.CallContractReadFunction.Rpc.NotSynced`,
2708
+ context: null
2709
+ })
2710
+ );
2711
+ if (cause.name === "UNAVAILABLE_SHARD")
2712
+ return result.err(
2713
+ createNatError({
2714
+ kind: `Client.CallContractReadFunction.Rpc.Shard.NotTracked`,
2715
+ context: { shardId: cause.info.requestedShardId }
2716
+ })
2717
+ );
2718
+ if (cause.name === "GARBAGE_COLLECTED_BLOCK")
2719
+ return result.err(
2720
+ createNatError({
2721
+ kind: `Client.CallContractReadFunction.Rpc.Block.GarbageCollected`,
2722
+ context: {
2723
+ blockHash: cause.info.blockHash,
2724
+ blockHeight: cause.info.blockHeight
2725
+ }
2726
+ })
2727
+ );
2728
+ if (cause.name === "UNKNOWN_BLOCK" && "blockId" in cause.info.blockReference)
2729
+ return result.err(
2730
+ createNatError({
2731
+ kind: `Client.CallContractReadFunction.Rpc.Block.NotFound`,
2732
+ context: {
2733
+ blockId: cause.info.blockReference.blockId
2734
+ }
2735
+ })
2736
+ );
2737
+ }
2738
+ return result.err(
2739
+ createNatError({
2740
+ kind: "Client.CallContractReadFunction.Internal",
2741
+ context: {
2742
+ cause: createNatError({
2743
+ kind: "Client.CallContractReadFunction.Rpc.Unclassified",
2744
+ context: { rpcResponse }
2745
+ })
2746
+ }
2747
+ })
2748
+ );
2749
+ };
2750
+
2751
+ // src/client/methods/contract/callContractReadFunction/handleResult/handleResult.ts
2752
+ var z31 = __toESM(require("zod/mini"), 1);
2753
+
2754
+ // src/client/methods/contract/callContractReadFunction/handleResult/deserializeCallResult.ts
2755
+ var deserializeCallResult = (args, rawResult) => {
2756
+ if (args.options?.deserializeResult) {
2757
+ const deserializeResult = args.options.deserializeResult;
2758
+ return wrapInternalError(
2759
+ "Client.CallContractReadFunction.DeserializeResult.Internal",
2760
+ () => result.ok(deserializeResult({ rawResult }))
2761
+ )();
2762
+ }
2763
+ try {
2764
+ const res = fromJsonBytes(rawResult);
2765
+ return result.ok(res);
2766
+ } catch (e) {
2767
+ return result.ok(void 0);
2768
+ }
2769
+ };
2770
+
2771
+ // src/client/methods/contract/callContractReadFunction/handleResult/handleResult.ts
2772
+ var ContractExecutionErrorSchema = z31.object({
2773
+ blockHash: z31.string(),
2774
+ blockHeight: z31.number(),
2775
+ error: z31.string(),
2776
+ logs: z31.array(z31.string())
2777
+ // will always an empty array
2778
+ });
2779
+ var RpcQueryCallReadFunctionOkResultSchema = z31.object({
2780
+ blockHash: z31.string(),
2781
+ blockHeight: z31.number(),
2782
+ result: z31.array(z31.number()),
2783
+ logs: z31.array(z31.string())
2784
+ });
2785
+ var RpcQueryCallReadFunctionResultSchema = z31.union([
2786
+ RpcQueryCallReadFunctionOkResultSchema,
2787
+ ContractExecutionErrorSchema
2788
+ ]);
2789
+ var handleResult6 = (rpcResponse, args) => {
2790
+ const rpcResult = RpcQueryCallReadFunctionResultSchema.safeParse(
2791
+ rpcResponse.result
2792
+ );
2793
+ if (!rpcResult.success)
2794
+ return result.err(
2795
+ createNatError({
2796
+ kind: "Client.CallContractReadFunction.SendRequest.Failed",
2797
+ context: {
2798
+ cause: createNatError({
2799
+ kind: "Client.Transport.SendRequest.Response.Result.InvalidSchema",
2800
+ context: { zodError: rpcResult.error }
2801
+ })
2802
+ }
2803
+ })
2804
+ );
2805
+ const { blockHash, blockHeight, logs } = rpcResult.data;
2806
+ if ("error" in rpcResult.data)
2807
+ return result.err(
2808
+ createNatError({
2809
+ kind: "Client.CallContractReadFunction.Rpc.Execution.Failed",
2810
+ context: {
2811
+ contractAccountId: args.contractAccountId,
2812
+ message: rpcResult.data.error,
2813
+ blockHash,
2814
+ blockHeight
2815
+ }
2816
+ })
2817
+ );
2818
+ const deserializedResult = deserializeCallResult(args, rpcResult.data.result);
2819
+ if (!deserializedResult.ok) return deserializedResult;
2820
+ const output = {
2821
+ blockHash,
2822
+ blockHeight,
2823
+ logs,
2824
+ result: deserializedResult.value,
2825
+ rawResult: rpcResult.data.result
1717
2826
  };
2827
+ return result.ok(output);
2828
+ };
2829
+
2830
+ // src/client/methods/contract/callContractReadFunction/serializeFunctionArgs.ts
2831
+ var serializeFunctionArgs = (args) => {
2832
+ if (args.options?.serializeArgs) {
2833
+ const serializeArgs = args.options.serializeArgs;
2834
+ return wrapInternalError(
2835
+ "Client.CallContractReadFunction.SerializeArgs.Internal",
2836
+ () => {
2837
+ const output = serializeArgs({
2838
+ functionArgs: args.functionArgs
2839
+ });
2840
+ if (!(output instanceof Uint8Array))
2841
+ return result.err(
2842
+ createNatError({
2843
+ kind: "Client.CallContractReadFunction.SerializeArgs.InvalidOutput",
2844
+ context: { output }
2845
+ })
2846
+ );
2847
+ return result.ok(output);
2848
+ }
2849
+ )();
2850
+ }
2851
+ if (args.functionArgs) {
2852
+ const jsonArgs = JsonSchema.safeParse(args.functionArgs);
2853
+ if (!jsonArgs.success)
2854
+ return result.err(
2855
+ createNatError({
2856
+ kind: "Client.CallContractReadFunction.Args.InvalidSchema",
2857
+ context: { zodError: jsonArgs.error }
2858
+ })
2859
+ );
2860
+ return result.ok(toJsonBytes(args.functionArgs));
2861
+ }
2862
+ return result.ok(new Uint8Array());
1718
2863
  };
1719
2864
 
2865
+ // src/client/methods/contract/callContractReadFunction/callContractReadFunction.ts
2866
+ var GetAccountAccessKeyArgsSchema2 = z32.object({
2867
+ contractAccountId: AccountIdSchema,
2868
+ functionName: ContractFunctionNameSchema,
2869
+ functionArgs: z32.optional(z32.unknown()),
2870
+ withStateAt: z32.optional(BlockReferenceSchema),
2871
+ policies: PoliciesSchema,
2872
+ options: z32.optional(
2873
+ z32.object({
2874
+ serializeArgs: z32.optional(z32.instanceof(Function)),
2875
+ deserializeResult: z32.optional(z32.instanceof(Function)),
2876
+ signal: z32.optional(z32.instanceof(AbortSignal))
2877
+ })
2878
+ )
2879
+ });
2880
+ var createSafeCallContractReadFunction = (context) => wrapInternalError(
2881
+ "Client.CallContractReadFunction.Internal",
2882
+ async (args) => {
2883
+ const validArgs = GetAccountAccessKeyArgsSchema2.safeParse(args);
2884
+ if (!validArgs.success)
2885
+ return result.err(
2886
+ createNatError({
2887
+ kind: "Client.CallContractReadFunction.Args.InvalidSchema",
2888
+ context: { zodError: validArgs.error }
2889
+ })
2890
+ );
2891
+ const functionArgs = serializeFunctionArgs(args);
2892
+ if (!functionArgs.ok) return functionArgs;
2893
+ const rpcResponse = await context.sendRequest({
2894
+ method: "query",
2895
+ params: {
2896
+ request_type: "call_function",
2897
+ account_id: args.contractAccountId,
2898
+ method_name: args.functionName,
2899
+ args_base64: import_base4.base64.encode(functionArgs.value),
2900
+ ...toNativeBlockReference(args.withStateAt)
2901
+ },
2902
+ transportPolicy: args.policies?.transport,
2903
+ signal: args.options?.signal
2904
+ });
2905
+ if (!rpcResponse.ok)
2906
+ return result.err(
2907
+ createNatError({
2908
+ kind: "Client.CallContractReadFunction.SendRequest.Failed",
2909
+ context: { cause: rpcResponse.error }
2910
+ })
2911
+ );
2912
+ return rpcResponse.value.error ? handleError6(rpcResponse.value) : handleResult6(rpcResponse.value, args);
2913
+ }
2914
+ );
2915
+
2916
+ // src/client/createClient.ts
2917
+ var ClientBrand = Symbol("Client");
2918
+ var isClient = (value) => typeof value === "object" && value !== null && ClientBrand in value;
2919
+ var CreateClientArgsSchema = z33.object({
2920
+ transport: CreateTransportArgsSchema
2921
+ });
2922
+ var safeCreateClient = wrapInternalError(
2923
+ "CreateClient.Internal",
2924
+ async (args) => {
2925
+ const validArgs = CreateClientArgsSchema.safeParse(args);
2926
+ if (!validArgs.success)
2927
+ return result.err(
2928
+ createNatError({
2929
+ kind: "CreateClient.Args.InvalidSchema",
2930
+ context: { zodError: validArgs.error }
2931
+ })
2932
+ );
2933
+ const transport = createTransport(args.transport);
2934
+ const context = {
2935
+ sendRequest: transport.sendRequest
2936
+ };
2937
+ const safeGetAccountInfo = createSafeGetAccountInfo(context);
2938
+ const safeGetAccountAccessKey = createSafeGetAccountAccessKey(context);
2939
+ const safeGetAccountAccessKeys = createSafeGetAccountAccessKeys(context);
2940
+ const safeCallContractReadFunction = createSafeCallContractReadFunction(context);
2941
+ const safeGetBlock = createSafeGetBlock(context);
2942
+ const safeSendSignedTransaction = createSafeSendSignedTransaction(context);
2943
+ return result.ok({
2944
+ [ClientBrand]: true,
2945
+ // TODO hide from console.log
2946
+ getAccountInfo: asThrowable(safeGetAccountInfo),
2947
+ getAccountAccessKey: asThrowable(safeGetAccountAccessKey),
2948
+ getAccountAccessKeys: asThrowable(safeGetAccountAccessKeys),
2949
+ callContractReadFunction: asThrowable(
2950
+ safeCallContractReadFunction
2951
+ ),
2952
+ // TODO Fix: asThrowable doesn't work fine with overloads
2953
+ getBlock: asThrowable(safeGetBlock),
2954
+ sendSignedTransaction: asThrowable(safeSendSignedTransaction),
2955
+ safeGetAccountInfo,
2956
+ safeGetAccountAccessKey,
2957
+ safeGetAccountAccessKeys,
2958
+ safeCallContractReadFunction,
2959
+ safeGetBlock,
2960
+ safeSendSignedTransaction
2961
+ });
2962
+ }
2963
+ );
2964
+ var throwableCreateClient = asThrowable(safeCreateClient);
2965
+
1720
2966
  // src/client/presets/testnet.ts
1721
- var createTestnetClient = () => createClient({
2967
+ var createTestnetClient = () => throwableCreateClient({
1722
2968
  transport: {
1723
2969
  rpcEndpoints: {
1724
2970
  regular: [
1725
- { url: "https://rpc.testnet.near.org" },
1726
- { url: "https://test.rpc.fastnear.com" }
2971
+ { url: "https://test.rpc.fastnear.com" },
2972
+ { url: "https://rpc.testnet.near.org" }
1727
2973
  ],
1728
- archival: []
2974
+ archival: [{ url: "https://neart.lava.build:443" }]
1729
2975
  }
1730
2976
  }
1731
2977
  });
1732
2978
 
1733
2979
  // src/client/presets/mainnet.ts
1734
- var createMainnetClient = () => createClient({
2980
+ var createMainnetClient = () => throwableCreateClient({
1735
2981
  transport: {
1736
2982
  rpcEndpoints: {
1737
2983
  regular: [
1738
2984
  { url: "https://free.rpc.fastnear.com" },
2985
+ { url: "https://rpc.intea.rs" },
1739
2986
  { url: "https://near.blockpi.network/v1/rpc/public" }
1740
2987
  ],
1741
- archival: []
2988
+ archival: [{ url: "https://near.lava.build:443" }]
1742
2989
  }
1743
2990
  }
1744
2991
  });
1745
2992
 
1746
- // src/helpers/crypto/getTransactionHash.ts
1747
- var import_sha2 = require("@noble/hashes/sha2");
1748
- var import_base8 = require("@scure/base");
2993
+ // src/keyServices/memoryKeyService/createMemoryKeyService.ts
2994
+ var z37 = __toESM(require("zod/mini"), 1);
1749
2995
 
1750
- // src/_common/transformers/toBorshBytes/transaction.ts
1751
- var import_borsh3 = require("borsh");
1752
- var serializeNativeTransaction = (nativeTransaction) => (0, import_borsh3.serialize)(transactionBorshSchema, nativeTransaction);
1753
- var serializeTransaction = (transaction) => serializeNativeTransaction(toNativeTransaction(transaction));
2996
+ // src/keyServices/memoryKeyService/createSignTransaction.ts
2997
+ var z34 = __toESM(require("zod/mini"), 1);
1754
2998
 
1755
- // src/helpers/crypto/getTransactionHash.ts
2999
+ // src/_common/utils/getTransactionHash.ts
3000
+ var import_sha2 = require("@noble/hashes/sha2");
3001
+ var import_base5 = require("@scure/base");
1756
3002
  var getTransactionHash = (transaction) => {
1757
- const transactionBorshBytes = serializeTransaction(transaction);
3003
+ const transactionBorshBytes = toBorshTransaction(transaction);
1758
3004
  const u8TransactionHash = (0, import_sha2.sha256)(transactionBorshBytes);
1759
3005
  return {
1760
- transactionHash: import_base8.base58.encode(u8TransactionHash),
3006
+ transactionHash: import_base5.base58.encode(u8TransactionHash),
1761
3007
  u8TransactionHash
1762
3008
  };
1763
3009
  };
1764
3010
 
1765
- // src/helpers/crypto/sign.ts
1766
- var v2 = __toESM(require("valibot"), 1);
3011
+ // src/keyServices/memoryKeyService/createSignTransaction.ts
3012
+ var SignTransactionArgsSchema = z34.object({
3013
+ transaction: TransactionSchema
3014
+ });
3015
+ var createSafeSignTransaction = (context) => wrapInternalError(
3016
+ "MemoryKeyService.SignTransaction.Internal",
3017
+ async (args) => {
3018
+ const validArgs = SignTransactionArgsSchema.safeParse(args);
3019
+ if (!validArgs.success)
3020
+ return result.err(
3021
+ createNatError({
3022
+ kind: "MemoryKeyService.SignTransaction.Args.InvalidSchema",
3023
+ context: { zodError: validArgs.error }
3024
+ })
3025
+ );
3026
+ const { transaction: innerTransaction } = validArgs.data;
3027
+ const keyPair = context.safeFindKeyPair({
3028
+ publicKey: innerTransaction.signerPublicKey.publicKey
3029
+ });
3030
+ if (!keyPair.ok) {
3031
+ if (keyPair.error.kind === "MemoryKeyService.FindKeyPair.NotFound")
3032
+ return result.err(
3033
+ createNatError({
3034
+ kind: "MemoryKeyService.SignTransaction.SigningKeyPair.NotFound",
3035
+ context: {
3036
+ signerPublicKey: innerTransaction.signerPublicKey.publicKey
3037
+ }
3038
+ })
3039
+ );
3040
+ throw keyPair.error;
3041
+ }
3042
+ const { transactionHash, u8TransactionHash } = getTransactionHash(innerTransaction);
3043
+ const { signature } = keyPair.value.sign(u8TransactionHash);
3044
+ return result.ok({
3045
+ transaction: args.transaction,
3046
+ transactionHash,
3047
+ signature
3048
+ });
3049
+ }
3050
+ );
3051
+
3052
+ // src/helpers/keyPair/_common/signByEd25519Key.ts
1767
3053
  var import_ed25519 = require("@noble/curves/ed25519");
1768
- var import_secp256k1 = require("@noble/curves/secp256k1");
1769
3054
 
1770
- // src/_common/schemas/valibot/privateKey.ts
1771
- var v = __toESM(require("valibot"), 1);
1772
- var { Ed25519, Secp256k1 } = BinaryCryptoKeyLengths;
1773
- var BinarySecp256k1PrivateKeySchema = v.pipe(
1774
- v.instance(Uint8Array),
1775
- v.length(
1776
- Secp256k1.PrivateKey,
1777
- `Length of binary secp256k1 private key should be ${Secp256k1.PrivateKey}`
1778
- )
1779
- );
1780
- var BinaryEd25519PrivateKeySchema = v.pipe(
1781
- v.instance(Uint8Array),
1782
- v.length(
1783
- Ed25519.PrivateKey,
1784
- `Length of binary ed25519 private key should be ${Ed25519.PrivateKey}`
1785
- )
1786
- );
3055
+ // src/_common/transformers/toCurveString.ts
3056
+ var import_base6 = require("@scure/base");
3057
+ var toEd25519CurveString = (u8Data) => `ed25519:${import_base6.base58.encode(u8Data)}`;
3058
+ var toSecp256k1CurveString = (u8Data) => `secp256k1:${import_base6.base58.encode(u8Data)}`;
1787
3059
 
1788
- // src/helpers/crypto/sign.ts
1789
- var { Ed25519: Ed255192, Secp256k1: Secp256k12 } = BinaryCryptoKeyLengths;
1790
- var getBinaryEd25519SecretKey = (u8PrivateKey) => v2.parse(BinaryEd25519PrivateKeySchema, u8PrivateKey).slice(0, Ed255192.SecretKey);
1791
- var signByEd25519Key = (message, u8PrivateKey) => {
1792
- const u8SecretKey = getBinaryEd25519SecretKey(u8PrivateKey);
3060
+ // src/helpers/keyPair/_common/signByEd25519Key.ts
3061
+ var signByEd25519Key = (u8PrivateKey, message) => {
3062
+ const u8SecretKey = u8PrivateKey.slice(0, BinaryLengths.Ed25519.SecretKey);
1793
3063
  const u8Signature = import_ed25519.ed25519.sign(message, u8SecretKey);
1794
- return {
3064
+ return result.ok({
1795
3065
  signature: toEd25519CurveString(u8Signature),
3066
+ curve: "ed25519",
1796
3067
  u8Signature
1797
- };
3068
+ });
1798
3069
  };
1799
- var getBinarySecp256k1SecretKey = (u8PrivateKey) => v2.parse(BinarySecp256k1PrivateKeySchema, u8PrivateKey).slice(0, Secp256k12.SecretKey);
1800
- var signBySecp256k1Key = (message, u8PrivateKey) => {
1801
- const u8SecretKey = getBinarySecp256k1SecretKey(u8PrivateKey);
3070
+
3071
+ // src/helpers/keyPair/_common/signBySecp256k1Key.ts
3072
+ var import_secp256k1 = require("@noble/curves/secp256k1");
3073
+ var signBySecp256k1Key = (u8PrivateKey, message) => {
3074
+ const u8SecretKey = u8PrivateKey.slice(0, BinaryLengths.Secp256k1.SecretKey);
1802
3075
  const signatureObj = import_secp256k1.secp256k1.sign(message, u8SecretKey);
1803
3076
  const u8Signature = new Uint8Array([
1804
3077
  ...signatureObj.toBytes(),
1805
3078
  signatureObj.recovery
1806
3079
  ]);
1807
- return {
3080
+ return result.ok({
1808
3081
  signature: toSecp256k1CurveString(u8Signature),
3082
+ curve: "secp256k1",
1809
3083
  u8Signature
1810
- };
1811
- };
1812
- var sign = ({ message, privateKey }) => {
1813
- const { curve, u8Data: u8PrivateKey } = fromCurveString(privateKey);
1814
- return curve === "ed25519" ? signByEd25519Key(message, u8PrivateKey) : signBySecp256k1Key(message, u8PrivateKey);
1815
- };
1816
-
1817
- // src/keyServices/memoryKeyService/createSignTransaction.ts
1818
- var createSignTransaction = (context) => async (transaction) => {
1819
- const privateKey = context.findPrivateKey(transaction.signerPublicKey);
1820
- const { transactionHash, u8TransactionHash } = getTransactionHash(transaction);
1821
- const { signature } = sign({ message: u8TransactionHash, privateKey });
1822
- return {
1823
- transaction,
1824
- transactionHash,
1825
- signature
1826
- };
3084
+ });
1827
3085
  };
1828
3086
 
1829
- // src/helpers/crypto/getPublicKey.ts
1830
- var v3 = __toESM(require("valibot"), 1);
1831
- var { Ed25519: Ed255193, Secp256k1: Secp256k13 } = BinaryCryptoKeyLengths;
1832
- var getBinaryEd25519PublicKey = (u8Ed25519PrivateKey) => {
1833
- const validEd25519PrivateKey = v3.parse(
1834
- BinaryEd25519PrivateKeySchema,
1835
- u8Ed25519PrivateKey
1836
- );
1837
- return validEd25519PrivateKey.slice(Ed255193.SecretKey);
1838
- };
1839
- var getEd25519PublicKey = (u8PrivateKey) => {
1840
- const u8PublicKey = getBinaryEd25519PublicKey(u8PrivateKey);
1841
- return toEd25519CurveString(u8PublicKey);
1842
- };
1843
- var getBinarySecp256k1PublicKey = (u8Secp256k1PrivateKey) => {
1844
- const validU8PrivateKey = v3.parse(
1845
- BinarySecp256k1PrivateKeySchema,
1846
- u8Secp256k1PrivateKey
1847
- );
1848
- return validU8PrivateKey.slice(Secp256k13.SecretKey);
1849
- };
1850
- var getSecp256k1PublicKey = (u8Secp256k1PrivateKey) => {
1851
- const u8PublicKey = getBinarySecp256k1PublicKey(u8Secp256k1PrivateKey);
1852
- return toSecp256k1CurveString(u8PublicKey);
1853
- };
1854
- var getPublicKey = (privateKey) => {
1855
- const { curve, u8Data: u8PrivateKey } = fromCurveString(privateKey);
1856
- return curve === "ed25519" ? getEd25519PublicKey(u8PrivateKey) : getSecp256k1PublicKey(u8PrivateKey);
1857
- };
3087
+ // src/_common/schemas/zod/common/privateKey.ts
3088
+ var z35 = __toESM(require("zod/mini"), 1);
3089
+ var { Ed25519: Ed255193, Secp256k1: Secp256k13 } = BinaryLengths;
3090
+ var PrivateKeySchema = z35.pipe(
3091
+ CurveStringSchema,
3092
+ z35.transform((val) => ({
3093
+ privateKey: val.curveString,
3094
+ u8PrivateKey: val.u8Data,
3095
+ curve: val.curve
3096
+ }))
3097
+ ).check(
3098
+ z35.refine(
3099
+ ({ curve, u8PrivateKey }) => curve === "ed25519" ? u8PrivateKey.length === Ed255193.PrivateKey : u8PrivateKey.length === Secp256k13.PrivateKey,
3100
+ { error: "Invalid private key length" }
3101
+ )
3102
+ );
1858
3103
 
1859
- // src/keyServices/memoryKeyService/parseKeySources.ts
1860
- var parseKeySource = (keySource) => {
1861
- if ("privateKey" in keySource) {
1862
- return {
1863
- publicKey: getPublicKey(keySource.privateKey),
1864
- privateKey: keySource.privateKey
1865
- };
1866
- }
1867
- if ("seedPhrase" in keySource) {
1868
- return {
1869
- publicKey: "ed25519:213",
1870
- privateKey: "ed25519:213"
1871
- };
3104
+ // src/helpers/keyPair/keyPair.ts
3105
+ var { Ed25519: Ed255194, Secp256k1: Secp256k14 } = BinaryLengths;
3106
+ var getPublicKey = ({ curve, u8PrivateKey }) => curve === "ed25519" ? toEd25519CurveString(u8PrivateKey.slice(Ed255194.SecretKey)) : toSecp256k1CurveString(u8PrivateKey.slice(Secp256k14.SecretKey));
3107
+ var createSafeSign = ({ curve, u8PrivateKey }) => wrapInternalError(
3108
+ "KeyPair.Sign.Internal",
3109
+ (message) => curve === "ed25519" ? signByEd25519Key(u8PrivateKey, message) : signBySecp256k1Key(u8PrivateKey, message)
3110
+ );
3111
+ var safeKeyPair = wrapInternalError(
3112
+ "CreateKeyPair.Internal",
3113
+ (privateKey) => {
3114
+ const validPrivateKey = PrivateKeySchema.safeParse(privateKey);
3115
+ if (!validPrivateKey.success)
3116
+ return result.err(
3117
+ createNatError({
3118
+ kind: "CreateKeyPair.Args.InvalidSchema",
3119
+ context: { zodError: validPrivateKey.error }
3120
+ })
3121
+ );
3122
+ const safeSign = createSafeSign(validPrivateKey.data);
3123
+ return result.ok({
3124
+ publicKey: getPublicKey(validPrivateKey.data),
3125
+ // TODO use Lazy getter, like NearToken
3126
+ privateKey,
3127
+ sign: asThrowable(safeSign),
3128
+ safeSign
3129
+ });
1872
3130
  }
1873
- throw new Error("Unknown keySource");
1874
- };
1875
- var parseKeySources = (params) => {
1876
- if (params.keySource) {
1877
- const { publicKey, privateKey } = parseKeySource(params.keySource);
1878
- return { [publicKey]: privateKey };
3131
+ );
3132
+ var throwableKeyPair = asThrowable(safeKeyPair);
3133
+
3134
+ // src/keyServices/memoryKeyService/getKeyPairs.ts
3135
+ var getKeyPairs = (args) => {
3136
+ if ("keySource" in args) {
3137
+ const keyPair = throwableKeyPair(args.keySource.privateKey.privateKey);
3138
+ return { [keyPair.publicKey]: keyPair };
1879
3139
  }
1880
- if (params.keySources)
1881
- return Object.fromEntries(
1882
- params.keySources.map((keySource) => {
1883
- const { publicKey, privateKey } = parseKeySource(keySource);
1884
- return [publicKey, privateKey];
1885
- })
1886
- );
1887
- throw new Error(
1888
- "Cannot create MemoryKeyService - no private keys were found"
3140
+ return Object.fromEntries(
3141
+ args.keySources.map((keySource) => {
3142
+ const keyPair = throwableKeyPair(keySource.privateKey.privateKey);
3143
+ return [keyPair.publicKey, keyPair];
3144
+ })
1889
3145
  );
1890
3146
  };
1891
3147
 
1892
- // src/keyServices/memoryKeyService/createFindPrivateKey.ts
1893
- var createFindPrivateKey = (keyPairs) => (publicKey) => {
1894
- const privateKey = keyPairs[publicKey];
1895
- if (keyPairs[publicKey]) return privateKey;
1896
- throw new Error(
1897
- `Cannot find a corresponding private key for '${publicKey}'`
3148
+ // src/keyServices/memoryKeyService/createFindKeyPair.ts
3149
+ var z36 = __toESM(require("zod/mini"), 1);
3150
+ var FindKeyPairArgsSchema = z36.object({
3151
+ publicKey: PublicKeySchema
3152
+ });
3153
+ var createSafeFindKeyPair = (context) => wrapInternalError("MemoryKeyService.FindKeyPair.Internal", (args) => {
3154
+ const validArgs = FindKeyPairArgsSchema.safeParse(args);
3155
+ if (!validArgs.success)
3156
+ return result.err(
3157
+ createNatError({
3158
+ kind: "MemoryKeyService.FindKeyPair.Args.InvalidSchema",
3159
+ context: { zodError: validArgs.error }
3160
+ })
3161
+ );
3162
+ const { publicKey } = validArgs.data.publicKey;
3163
+ const keyPair = context.keyPairs[publicKey];
3164
+ return context.keyPairs[publicKey] ? result.ok(keyPair) : result.err(
3165
+ createNatError({
3166
+ kind: "MemoryKeyService.FindKeyPair.NotFound",
3167
+ context: { publicKey }
3168
+ })
1898
3169
  );
1899
- };
3170
+ });
1900
3171
 
1901
3172
  // src/keyServices/memoryKeyService/createMemoryKeyService.ts
1902
- var createMemoryKeyService = async (params) => {
3173
+ var MemoryKeyServiceBrand = Symbol("MemoryKeyService");
3174
+ var isMemoryKeyService = (value) => typeof value === "object" && value !== null && MemoryKeyServiceBrand in value;
3175
+ var KeySourceSchema = z37.object({
3176
+ privateKey: PrivateKeySchema
3177
+ });
3178
+ var CreateMemoryKeyServiceArgsSchema = z37.union([
3179
+ z37.object({
3180
+ keySource: KeySourceSchema
3181
+ }),
3182
+ z37.object({
3183
+ keySources: z37.array(KeySourceSchema).check(z37.minLength(1))
3184
+ })
3185
+ ]);
3186
+ var safeCreateMemoryKeyService = wrapInternalError("CreateMemoryKeyService.Internal", async (args) => {
3187
+ const validArgs = CreateMemoryKeyServiceArgsSchema.safeParse(args);
3188
+ if (!validArgs.success)
3189
+ return result.err(
3190
+ createNatError({
3191
+ kind: "CreateMemoryKeyService.Args.InvalidSchema",
3192
+ context: { zodError: validArgs.error }
3193
+ })
3194
+ );
1903
3195
  const context = {
1904
- keyPairs: parseKeySources(params)
1905
- };
1906
- context.findPrivateKey = createFindPrivateKey(context.keyPairs);
1907
- return {
1908
- signTransaction: createSignTransaction(context),
1909
- getKeyPairs: () => context.keyPairs
3196
+ keyPairs: getKeyPairs(validArgs.data)
1910
3197
  };
1911
- };
3198
+ const safeFindKeyPair = createSafeFindKeyPair(context);
3199
+ const safeSignTransaction = createSafeSignTransaction(context);
3200
+ context.safeFindKeyPair = safeFindKeyPair;
3201
+ return result.ok({
3202
+ [MemoryKeyServiceBrand]: true,
3203
+ signTransaction: asThrowable(safeSignTransaction),
3204
+ safeSignTransaction,
3205
+ findKeyPair: asThrowable(safeFindKeyPair),
3206
+ safeFindKeyPair
3207
+ });
3208
+ });
3209
+ var throwableCreateMemoryKeyService = asThrowable(safeCreateMemoryKeyService);
3210
+
3211
+ // src/signers/memorySigner/createMemorySigner.ts
3212
+ var z40 = __toESM(require("zod/mini"), 1);
1912
3213
 
1913
3214
  // src/signers/memorySigner/keyPool/createFindKeyForTask.ts
1914
3215
  var findSigningKey = (keyPriority, keyList) => {
1915
- if (keyPriority.type === "FullAccess") {
3216
+ if (keyPriority.accessType === "FullAccess")
1916
3217
  return keyList.fullAccess.find((key) => !key.isLocked);
1917
- }
1918
3218
  return keyList.functionCall.find((key) => {
1919
- const isUnlocked = key.isLocked === false;
1920
3219
  const isContractIdMatch = key.contractAccountId === keyPriority.contractAccountId;
1921
3220
  const isFnCallAllowed = key.allowedFunctions === void 0 || key.allowedFunctions.includes(keyPriority.calledFnName);
1922
- return isUnlocked && isContractIdMatch && isFnCallAllowed;
3221
+ return !key.isLocked && isContractIdMatch && isFnCallAllowed;
1923
3222
  });
1924
3223
  };
1925
3224
  var createFindKeyForTask = (keyList) => (task) => {
1926
- for (const keyPriority of task.signingKeyPriority) {
3225
+ for (const keyPriority of task.accessTypePriority) {
1927
3226
  const key = findSigningKey(keyPriority, keyList);
1928
3227
  if (key) return key;
1929
3228
  }
@@ -1931,38 +3230,34 @@ var createFindKeyForTask = (keyList) => (task) => {
1931
3230
 
1932
3231
  // src/signers/memorySigner/keyPool/createIsKeyForTaskExist.ts
1933
3232
  var isKeyExist = (keyPriority, keyList) => {
1934
- if (keyPriority.type === "FullAccess") return keyList.fullAccess.length > 0;
3233
+ if (keyPriority.accessType === "FullAccess") return keyList.fullAccess.length > 0;
1935
3234
  return keyList.functionCall.find((key) => {
1936
3235
  const isContractIdMatch = key.contractAccountId === keyPriority.contractAccountId;
1937
3236
  const isFnCallAllowed = key.allowedFunctions === void 0 || key.allowedFunctions.includes(keyPriority.calledFnName);
1938
3237
  return isContractIdMatch && isFnCallAllowed;
1939
3238
  });
1940
3239
  };
1941
- var createIsKeyForTaskExist = (keyList) => (task) => task.signingKeyPriority.some(
3240
+ var createIsKeyForTaskExist = (keyList) => (task) => task.accessTypePriority.some(
1942
3241
  (keyPriority) => isKeyExist(keyPriority, keyList)
1943
3242
  );
1944
3243
 
1945
3244
  // src/signers/memorySigner/keyPool/helpers/keyUtils.ts
1946
3245
  var createLock = (key) => () => {
1947
3246
  key.isLocked = true;
1948
- console.log("Key locked", key.publicKey);
1949
3247
  };
1950
3248
  var createUnlock = (key) => () => {
1951
3249
  key.isLocked = false;
1952
- console.log("Key unlocked", key.publicKey);
1953
3250
  };
1954
3251
  var createSetNonce = (key) => (newNonce) => {
1955
3252
  key.nonce = newNonce;
1956
- console.log(`Set new nonce '${newNonce}' for the key '${key.publicKey}'`);
1957
3253
  };
1958
3254
 
1959
3255
  // src/signers/memorySigner/keyPool/getFullAccessKeyList.ts
1960
- var transformKey2 = (fullAccessKey, keyPairs) => {
3256
+ var transformKey = (fullAccessKey) => {
1961
3257
  const { publicKey, nonce } = fullAccessKey;
1962
3258
  const key = {
1963
- type: "FullAccess",
3259
+ accessType: "FullAccess",
1964
3260
  publicKey,
1965
- privateKey: keyPairs[publicKey],
1966
3261
  isLocked: false,
1967
3262
  nonce
1968
3263
  };
@@ -1971,21 +3266,16 @@ var transformKey2 = (fullAccessKey, keyPairs) => {
1971
3266
  key.setNonce = createSetNonce(key);
1972
3267
  return key;
1973
3268
  };
1974
- var getFullAccessKeyList = (accountKeys, signerContext) => {
1975
- const keyPairs = signerContext.keyService.getKeyPairs();
1976
- return accountKeys.filter(
1977
- ({ publicKey, accessType }) => Object.hasOwn(keyPairs, publicKey) && accessType === "FullAccess"
1978
- ).map((key) => transformKey2(key, keyPairs));
1979
- };
3269
+ var getFullAccessKeyList = (accountKeys, signerContext) => accountKeys.filter(
3270
+ ({ publicKey, accessType }) => signerContext.keyService.safeFindKeyPair({ publicKey }).ok && accessType === "FullAccess"
3271
+ ).map((key) => transformKey(key));
1980
3272
 
1981
3273
  // src/signers/memorySigner/keyPool/getFunctionCallKeyList.ts
1982
- var transformKey3 = (functionCallKey, keyPairs) => {
3274
+ var transformKey2 = (functionCallKey) => {
1983
3275
  const { publicKey, nonce, contractAccountId, allowedFunctions } = functionCallKey;
1984
3276
  const key = {
1985
- type: "FunctionCall",
1986
- // TODO Rename to accessType
3277
+ accessType: "FunctionCall",
1987
3278
  publicKey,
1988
- privateKey: keyPairs[publicKey],
1989
3279
  isLocked: false,
1990
3280
  nonce,
1991
3281
  contractAccountId,
@@ -1996,12 +3286,9 @@ var transformKey3 = (functionCallKey, keyPairs) => {
1996
3286
  key.setNonce = createSetNonce(key);
1997
3287
  return key;
1998
3288
  };
1999
- var getFunctionCallKeyList = (accountKeys, signerContext) => {
2000
- const keyPairs = signerContext.keyService.getKeyPairs();
2001
- return accountKeys.filter(
2002
- ({ publicKey, accessType }) => Object.hasOwn(keyPairs, publicKey) && accessType === "FunctionCall"
2003
- ).map((key) => transformKey3(key, keyPairs));
2004
- };
3289
+ var getFunctionCallKeyList = (accountKeys, signerContext) => accountKeys.filter(
3290
+ ({ publicKey, accessType }) => signerContext.keyService.safeFindKeyPair({ publicKey }).ok && accessType === "FunctionCall"
3291
+ ).map((key) => transformKey2(key));
2005
3292
 
2006
3293
  // src/signers/memorySigner/keyPool/createKeyPool.ts
2007
3294
  var getAllowedSigningKeys = (signerContext, accountKeys) => {
@@ -2010,46 +3297,71 @@ var getAllowedSigningKeys = (signerContext, accountKeys) => {
2010
3297
  return accountKeys.filter((key) => set.has(key.publicKey));
2011
3298
  };
2012
3299
  var createKeyPool = async (signerContext) => {
2013
- const { accountKeys } = await signerContext.client.getAccountKeys({
2014
- accountId: signerContext.signerAccountId
3300
+ const accountKeys = await signerContext.client.safeGetAccountAccessKeys({
3301
+ accountId: signerContext.signerAccountId,
3302
+ atMomentOf: "LatestFinalBlock"
2015
3303
  });
2016
- const filteredKeys = getAllowedSigningKeys(signerContext, accountKeys);
2017
- const keyList = {
3304
+ if (!accountKeys.ok)
3305
+ return result.err(
3306
+ createNatError({
3307
+ kind: "CreateMemorySigner.CreateKeyPool.Failed",
3308
+ context: { cause: accountKeys.error }
3309
+ })
3310
+ );
3311
+ const { accountAccessKeys } = accountKeys.value;
3312
+ if (accountAccessKeys.length === 0)
3313
+ return result.err(
3314
+ createNatError({
3315
+ kind: "CreateMemorySigner.Signer.AccessKeys.NotFound",
3316
+ context: {
3317
+ signerAccountId: signerContext.signerAccountId
3318
+ }
3319
+ })
3320
+ );
3321
+ const filteredKeys = getAllowedSigningKeys(signerContext, accountAccessKeys);
3322
+ if (filteredKeys.length === 0)
3323
+ return result.err(
3324
+ createNatError({
3325
+ kind: "CreateMemorySigner.KeyPool.Empty",
3326
+ context: null
3327
+ })
3328
+ );
3329
+ const context = {
2018
3330
  fullAccess: getFullAccessKeyList(filteredKeys, signerContext),
2019
3331
  functionCall: getFunctionCallKeyList(filteredKeys, signerContext)
2020
3332
  };
2021
- if (keyList.fullAccess.length === 0 && keyList.functionCall.length === 0)
2022
- throw new Error("Cannot create a signer with no account keys");
2023
- return {
2024
- findKeyForTask: createFindKeyForTask(keyList),
2025
- isKeyForTaskExist: createIsKeyForTaskExist(keyList)
2026
- };
3333
+ return result.ok({
3334
+ findKeyForTask: createFindKeyForTask(context),
3335
+ isKeyForTaskExist: createIsKeyForTaskExist(context)
3336
+ });
2027
3337
  };
2028
3338
 
2029
3339
  // src/signers/memorySigner/taskQueue/createFindTaskForKey.ts
2030
3340
  var checkIfKeyMatchRequirements = (keyPriority, key) => {
2031
- if (key.type !== keyPriority.type) return false;
2032
- if (key.type === "FullAccess") return true;
3341
+ if (key.accessType !== keyPriority.accessType) return false;
3342
+ if (key.accessType === "FullAccess") return true;
2033
3343
  const isContractIdMatch = key.contractAccountId === keyPriority.contractAccountId;
2034
- const isFnCallAllowed = key.allowedFunctions === void 0 || key.allowedFunctions.includes(keyPriority.calledFnName);
3344
+ const isFnCallAllowed = key.allowedFunctions === void 0 || key.allowedFunctions.includes(
3345
+ keyPriority.calledFnName
3346
+ );
2035
3347
  return isContractIdMatch && isFnCallAllowed;
2036
3348
  };
2037
3349
  var createFindTaskForKey = (context) => (key) => context.queue.find(
2038
- (task) => task.signingKeyPriority.some(
3350
+ (task) => task.accessTypePriority.some(
2039
3351
  (keyPriority) => checkIfKeyMatchRequirements(keyPriority, key)
2040
3352
  )
2041
3353
  );
2042
3354
 
2043
- // src/signers/memorySigner/taskQueue/addTask/helpers/getSigningKeyPriority.ts
3355
+ // src/signers/memorySigner/taskQueue/addTask/helpers/getAccessTypePriority.ts
2044
3356
  var getPriorityForFunctionCallTransaction = (action, receiverAccountId) => [
2045
- { type: "FullAccess" },
3357
+ { accessType: "FullAccess" },
2046
3358
  {
2047
- type: "FunctionCall",
3359
+ accessType: "FunctionCall",
2048
3360
  contractAccountId: receiverAccountId,
2049
- calledFnName: action.params.functionName
3361
+ calledFnName: action.functionName
2050
3362
  }
2051
3363
  ];
2052
- var getSigningKeyPriority = ({
3364
+ var getAccessTypePriority = ({
2053
3365
  action,
2054
3366
  actions,
2055
3367
  receiverAccountId
@@ -2058,94 +3370,39 @@ var getSigningKeyPriority = ({
2058
3370
  return getPriorityForFunctionCallTransaction(action, receiverAccountId);
2059
3371
  if (actions?.length === 1 && actions[0].actionType === "FunctionCall")
2060
3372
  return getPriorityForFunctionCallTransaction(actions[0], receiverAccountId);
2061
- return [{ type: "FullAccess" }];
3373
+ return [{ accessType: "FullAccess" }];
2062
3374
  };
2063
3375
 
2064
- // src/signers/memorySigner/taskQueue/addTask/signTransaction.ts
2065
- var createSignTransaction2 = (context) => async (transactionIntent) => {
3376
+ // src/signers/memorySigner/taskQueue/addTask/createAddSignTransactionTask.ts
3377
+ var createAddSignTransactionTask = (context) => async (transactionIntent) => {
2066
3378
  const { matcher, resolver } = context.signerContext;
2067
3379
  const task = {
2068
- type: "SignTransaction",
3380
+ taskType: "SignTransaction",
2069
3381
  taskId: crypto.randomUUID(),
2070
- signingKeyPriority: getSigningKeyPriority(transactionIntent),
3382
+ accessTypePriority: getAccessTypePriority(transactionIntent),
2071
3383
  transactionIntent
2072
3384
  };
2073
- matcher.canHandleTaskInFuture(task);
3385
+ const canHandle = matcher.canHandleTaskInFuture(task);
3386
+ if (!canHandle.ok) return canHandle;
2074
3387
  context.addTask(task);
2075
- queueMicrotask(() => {
2076
- matcher.handleAddTask(task);
2077
- });
2078
- return resolver.waitForTask(task.taskId);
3388
+ queueMicrotask(() => matcher.handleAddTask(task));
3389
+ return await resolver.waitForTask(task.taskId);
2079
3390
  };
2080
3391
 
2081
- // src/signers/memorySigner/taskQueue/addTask/executeTransaction.ts
2082
- var createExecuteTransaction = (context) => async (args) => {
3392
+ // src/signers/memorySigner/taskQueue/addTask/createAddExecuteTransactionTask.ts
3393
+ var createAddExecuteTransactionTask = (context) => async (transactionIntent) => {
2083
3394
  const { matcher, resolver } = context.signerContext;
2084
- const transactionIntent = {
2085
- receiverAccountId: args.receiverAccountId,
2086
- action: args.action,
2087
- actions: args.actions
2088
- };
2089
3395
  const task = {
2090
- type: "ExecuteTransaction",
3396
+ taskType: "ExecuteTransaction",
2091
3397
  taskId: crypto.randomUUID(),
2092
- signingKeyPriority: getSigningKeyPriority(transactionIntent),
3398
+ accessTypePriority: getAccessTypePriority(transactionIntent),
2093
3399
  transactionIntent
2094
3400
  };
2095
- matcher.canHandleTaskInFuture(task);
3401
+ const canHandle = matcher.canHandleTaskInFuture(task);
3402
+ if (!canHandle.ok) return canHandle;
2096
3403
  context.addTask(task);
2097
- queueMicrotask(() => {
2098
- matcher.handleAddTask(task);
2099
- });
2100
- return resolver.waitForTask(task.taskId);
2101
- };
2102
-
2103
- // src/signers/memorySigner/taskQueue/addTask/signMultipleTransactions.ts
2104
- var createSignMultipleTransactions = (context) => async (args) => {
2105
- const { transactionIntents } = args;
2106
- const { signTransaction: signTransaction2 } = context.signerContext.taskQueue;
2107
- const output = [];
2108
- let failed = false;
2109
- for (const intent of transactionIntents) {
2110
- if (failed) {
2111
- output.push({ status: "Canceled" });
2112
- continue;
2113
- }
2114
- try {
2115
- output.push({
2116
- status: "Success",
2117
- result: await signTransaction2(intent)
2118
- });
2119
- } catch (error) {
2120
- output.push({ status: "Error", error });
2121
- failed = true;
2122
- }
2123
- }
2124
- return output;
2125
- };
2126
-
2127
- // src/signers/memorySigner/taskQueue/addTask/executeMultipleTransactions.ts
2128
- var createExecuteMultipleTransactions = (context) => async (args) => {
2129
- const { transactionIntents } = args;
2130
- const { executeTransaction: executeTransaction2 } = context.signerContext.taskQueue;
2131
- const output = [];
2132
- let failed = false;
2133
- for (const intent of transactionIntents) {
2134
- if (failed) {
2135
- output.push({ status: "Canceled" });
2136
- continue;
2137
- }
2138
- try {
2139
- output.push({
2140
- status: "Success",
2141
- result: await executeTransaction2({ ...intent })
2142
- });
2143
- } catch (error) {
2144
- output.push({ status: "Error", error });
2145
- failed = true;
2146
- }
2147
- }
2148
- return output;
3404
+ queueMicrotask(() => matcher.handleAddTask(task));
3405
+ return await resolver.waitForTask(task.taskId);
2149
3406
  };
2150
3407
 
2151
3408
  // src/signers/memorySigner/taskQueue/createTaskQueue.ts
@@ -2153,7 +3410,11 @@ var createTaskQueue = (signerContext) => {
2153
3410
  const context = {
2154
3411
  queue: [],
2155
3412
  cleaners: {},
2156
- signerContext
3413
+ signerContext,
3414
+ addTask: (_) => {
3415
+ },
3416
+ removeTask: (_) => {
3417
+ }
2157
3418
  };
2158
3419
  context.addTask = (task) => {
2159
3420
  context.queue.push(task);
@@ -2162,10 +3423,18 @@ var createTaskQueue = (signerContext) => {
2162
3423
  ({ taskId }) => taskId !== task.taskId
2163
3424
  );
2164
3425
  delete context.cleaners[task.taskId];
2165
- context.signerContext.resolver.completeTask(task.taskId, {
2166
- error: "Task execution was rejected after timeout"
2167
- });
2168
- }, context.signerContext.taskTtlMs);
3426
+ context.signerContext.resolver.completeTask(
3427
+ task.taskId,
3428
+ result.err(
3429
+ createNatError({
3430
+ kind: "MemorySigner.TaskQueue.Task.MaxTimeInQueueReached",
3431
+ context: {
3432
+ maxWaitInQueueMs: context.signerContext.maxWaitInQueueMs
3433
+ }
3434
+ })
3435
+ )
3436
+ );
3437
+ }, context.signerContext.maxWaitInQueueMs);
2169
3438
  };
2170
3439
  const removeTask = (taskId) => {
2171
3440
  context.queue = context.queue.filter((task) => task.taskId !== taskId);
@@ -2173,113 +3442,82 @@ var createTaskQueue = (signerContext) => {
2173
3442
  delete context.cleaners[taskId];
2174
3443
  };
2175
3444
  return {
2176
- signTransaction: createSignTransaction2(context),
2177
- signMultipleTransactions: createSignMultipleTransactions(context),
2178
- executeTransaction: createExecuteTransaction(context),
2179
- executeeMultipleTransactions: createExecuteMultipleTransactions(context),
3445
+ addSignTransactionTask: createAddSignTransactionTask(context),
3446
+ addExecuteTransactionTask: createAddExecuteTransactionTask(context),
2180
3447
  findTaskForKey: createFindTaskForKey(context),
2181
3448
  removeTask
2182
3449
  };
2183
3450
  };
2184
3451
 
2185
- // src/signers/memorySigner/executors/helpers/getSignedTransaction.ts
2186
- var getSignedTransaction = (signerContext, task, key, nextNonce) => {
2187
- const transaction = {
2188
- ...task.transactionIntent,
2189
- signerAccountId: signerContext.signerAccountId,
2190
- signerPublicKey: key.publicKey,
2191
- nonce: nextNonce,
2192
- blockHash: signerContext.state.getBlockHash()
2193
- };
2194
- const { transactionHash, u8TransactionHash } = getTransactionHash(transaction);
2195
- const { signature } = sign({
2196
- message: u8TransactionHash,
2197
- privateKey: key.privateKey
2198
- });
2199
- return {
2200
- transaction,
2201
- transactionHash,
2202
- signature
2203
- };
2204
- };
2205
-
2206
3452
  // src/signers/memorySigner/executors/signTransaction.ts
2207
3453
  var signTransaction = async (signerContext, task, key) => {
2208
- try {
2209
- const nextNonce = key.nonce + 1;
2210
- const signedTransaction = getSignedTransaction(
2211
- signerContext,
2212
- task,
2213
- key,
2214
- nextNonce
2215
- );
2216
- key.setNonce(nextNonce);
2217
- signerContext.resolver.completeTask(task.taskId, {
2218
- result: signedTransaction
2219
- });
2220
- } catch (e) {
2221
- signerContext.resolver.completeTask(task.taskId, { error: e });
2222
- }
3454
+ const execute2 = wrapInternalError(
3455
+ "MemorySigner.SignTransaction.Internal",
3456
+ async () => {
3457
+ const nextNonce = key.nonce + 1;
3458
+ const transaction = {
3459
+ ...task.transactionIntent,
3460
+ signerAccountId: signerContext.signerAccountId,
3461
+ signerPublicKey: key.publicKey,
3462
+ nonce: nextNonce,
3463
+ blockHash: signerContext.state.getBlockHash()
3464
+ };
3465
+ const signedTransaction = await signerContext.keyService.signTransaction({
3466
+ transaction
3467
+ });
3468
+ key.setNonce(nextNonce);
3469
+ return result.ok(signedTransaction);
3470
+ }
3471
+ );
3472
+ const transactionResult = await execute2();
3473
+ signerContext.resolver.completeTask(task.taskId, transactionResult);
2223
3474
  };
2224
3475
 
2225
3476
  // src/signers/memorySigner/executors/executeTransaction.ts
2226
- var z11 = __toESM(require("zod/mini"), 1);
2227
- var NonceErrorSchema = z11.object({
2228
- __rawRpcError: z11.object({
2229
- data: z11.object({
2230
- TxExecutionError: z11.object({
2231
- InvalidTxError: z11.object({
2232
- InvalidNonce: z11.object({
2233
- akNonce: z11.number(),
2234
- txNonce: z11.number()
2235
- })
2236
- })
2237
- })
2238
- })
2239
- })
2240
- });
2241
- var maybeNonceError = (e) => {
2242
- const validated = NonceErrorSchema.safeParse(e);
2243
- if (hasRpcErrorCode(e, ["HandlerError"]) && validated.success)
2244
- return {
2245
- result: {
2246
- akNonce: validated.data.__rawRpcError.data.TxExecutionError.InvalidTxError.InvalidNonce.akNonce
2247
- }
2248
- };
2249
- return { error: void 0 };
2250
- };
2251
3477
  var executeTransaction = async (signerContext, task, key) => {
2252
3478
  const maxAttempts = 3;
2253
- const attempt = async (attemptIndex, newNonce) => {
2254
- try {
2255
- const signedTransaction = getSignedTransaction(
2256
- signerContext,
2257
- task,
2258
- key,
2259
- newNonce
2260
- );
2261
- const result2 = await signerContext.client.sendSignedTransaction({
3479
+ const attempt = wrapInternalError(
3480
+ "MemorySigner.ExecuteTransaction.Internal",
3481
+ async (attemptIndex, newNonce) => {
3482
+ const transaction = {
3483
+ ...task.transactionIntent,
3484
+ signerAccountId: signerContext.signerAccountId,
3485
+ signerPublicKey: key.publicKey,
3486
+ nonce: newNonce,
3487
+ blockHash: signerContext.state.getBlockHash()
3488
+ };
3489
+ const signedTransaction = await signerContext.keyService.signTransaction({
3490
+ transaction
3491
+ });
3492
+ const txResult = await signerContext.client.safeSendSignedTransaction({
2262
3493
  signedTransaction
2263
3494
  });
2264
- key.setNonce(newNonce);
2265
- return { result: result2 };
2266
- } catch (e) {
2267
- if (attemptIndex >= maxAttempts - 1) return { error: e };
2268
- const nonceError = maybeNonceError(e);
2269
- if (nonceError.result)
2270
- return await attempt(attemptIndex + 1, nonceError.result.akNonce + 1);
2271
- return { error: e };
3495
+ if (txResult.ok) {
3496
+ key.setNonce(newNonce);
3497
+ return txResult;
3498
+ }
3499
+ if (attemptIndex <= maxAttempts && txResult.error.kind === "Client.SendSignedTransaction.Rpc.Transaction.Nonce.Invalid") {
3500
+ return await attempt(
3501
+ attemptIndex + 1,
3502
+ txResult.error.context.accessKeyNonce + 1
3503
+ );
3504
+ }
3505
+ return result.err(
3506
+ createNatError({
3507
+ kind: "MemorySigner.Executors.ExecuteTransaction.Client.SendSignedTransaction",
3508
+ context: { cause: txResult.error }
3509
+ })
3510
+ );
2272
3511
  }
2273
- };
2274
- const result = await attempt(0, key.nonce + 1);
2275
- signerContext.resolver.completeTask(task.taskId, result);
3512
+ );
3513
+ const executeTransactionResult = await attempt(1, key.nonce + 1);
3514
+ signerContext.resolver.completeTask(task.taskId, executeTransactionResult);
2276
3515
  };
2277
3516
 
2278
3517
  // src/signers/memorySigner/matcher/createMatcher.ts
2279
3518
  var execute = (task) => {
2280
- if (task.type === "SignTransaction") return signTransaction;
2281
- if (task.type === "ExecuteTransaction") return executeTransaction;
2282
- throw new Error("Unsupported task type");
3519
+ if (task.taskType === "SignTransaction") return signTransaction;
3520
+ return executeTransaction;
2283
3521
  };
2284
3522
  var executeTask = async (signerContext, task, key) => {
2285
3523
  key.lock();
@@ -2299,8 +3537,12 @@ var createMatcher = (signerContext) => {
2299
3537
  };
2300
3538
  const canHandleTaskInFuture = (task) => {
2301
3539
  const canHandle = signerContext.keyPool.isKeyForTaskExist(task);
2302
- if (canHandle) return true;
2303
- throw new Error(`There is no key, which can sigh the task`);
3540
+ return canHandle ? result.ok(true) : result.err(
3541
+ createNatError({
3542
+ kind: "MemorySigner.Matcher.KeyForTaskNotFound",
3543
+ context: { accessTypePriority: task.accessTypePriority }
3544
+ })
3545
+ );
2304
3546
  };
2305
3547
  return {
2306
3548
  handleAddTask,
@@ -2312,14 +3554,14 @@ var createMatcher = (signerContext) => {
2312
3554
  // src/signers/memorySigner/resolver/createResolver.ts
2313
3555
  var createResolver = () => {
2314
3556
  const activeTasks = {};
2315
- const waitForTask = (taskId) => new Promise((resolve, reject) => {
2316
- activeTasks[taskId] = ({ result, error }) => {
2317
- typeof error === "undefined" ? resolve(result) : reject(error);
3557
+ const waitForTask = (taskId) => new Promise((resolve) => {
3558
+ activeTasks[taskId] = (taskResult) => {
3559
+ resolve(taskResult);
2318
3560
  delete activeTasks[taskId];
2319
3561
  };
2320
3562
  });
2321
- const completeTask = (taskId, data) => {
2322
- activeTasks[taskId](data);
3563
+ const completeTask = (taskId, taskResult) => {
3564
+ activeTasks[taskId](taskResult);
2323
3565
  };
2324
3566
  return {
2325
3567
  waitForTask,
@@ -2328,115 +3570,497 @@ var createResolver = () => {
2328
3570
  };
2329
3571
 
2330
3572
  // src/signers/memorySigner/state/createState.ts
2331
- var fetchBlockHash = async (signerContext) => {
2332
- const block = await signerContext.client.getBlock();
2333
- return block.header.hash;
3573
+ var getBlockHash = async (signerContext) => {
3574
+ const block = await signerContext.client.safeGetBlock();
3575
+ return block.ok ? result.ok(block.value.rawRpcResult.header.hash) : block;
2334
3576
  };
2335
3577
  var createState = async (signerContext) => {
2336
- const blockHash = await fetchBlockHash(signerContext);
3578
+ const blockHash = await getBlockHash(signerContext);
3579
+ if (!blockHash.ok)
3580
+ return result.err(
3581
+ createNatError({
3582
+ kind: "CreateMemorySigner.CreateState.Failed",
3583
+ context: { cause: blockHash.error }
3584
+ })
3585
+ );
2337
3586
  const state = {
2338
- blockHash
3587
+ blockHash: blockHash.value
2339
3588
  };
2340
3589
  const refetchBlockHashIntervalId = setInterval(async () => {
2341
- state.blockHash = await fetchBlockHash(signerContext);
2342
- }, RefetchBlockHashInterval);
3590
+ const blockHash2 = await getBlockHash(signerContext);
3591
+ if (!blockHash2.ok) return;
3592
+ state.blockHash = blockHash2.value;
3593
+ }, 9e5);
2343
3594
  const clearIntervals = () => {
2344
3595
  clearInterval(refetchBlockHashIntervalId);
2345
3596
  };
2346
- return {
3597
+ return result.ok({
2347
3598
  getBlockHash: () => state.blockHash,
2348
3599
  clearIntervals
2349
- };
3600
+ });
2350
3601
  };
2351
3602
 
2352
- // src/signers/memorySigner/createMemorySigner.ts
2353
- var createMemorySigner = async (args) => {
2354
- const context = {
2355
- signerAccountId: args.signerAccountId,
2356
- client: args.client,
2357
- keyService: args.keyService,
2358
- signingKeys: args?.keyPool?.signingKeys,
2359
- taskTtlMs: args?.queue?.taskTtlMs ?? SignerTaskTtlMs
2360
- };
2361
- const [keyPool, state] = await Promise.all([
2362
- createKeyPool(context),
2363
- createState(context)
2364
- ]);
2365
- context.keyPool = keyPool;
2366
- context.state = state;
2367
- context.taskQueue = createTaskQueue(context);
2368
- context.matcher = createMatcher(context);
2369
- context.resolver = createResolver();
2370
- return {
2371
- executeTransaction: context.taskQueue.executeTransaction,
2372
- executeMultipleTransactions: context.taskQueue.executeeMultipleTransactions,
2373
- signTransaction: context.taskQueue.signTransaction,
2374
- signMultipleTransactions: context.taskQueue.signMultipleTransactions
2375
- };
3603
+ // src/signers/memorySigner/createSignTransaction.ts
3604
+ var z38 = __toESM(require("zod/mini"), 1);
3605
+
3606
+ // src/_common/utils/repackError.ts
3607
+ var repackError = ({
3608
+ error,
3609
+ originPrefix,
3610
+ targetPrefix
3611
+ }) => {
3612
+ const newKind = `${targetPrefix}.${error.kind.slice(originPrefix.length + 1)}`;
3613
+ return result.err(
3614
+ createNatError({
3615
+ kind: newKind,
3616
+ // TODO fix any!
3617
+ context: error.context
3618
+ })
3619
+ );
2376
3620
  };
2377
3621
 
2378
- // src/helpers/actionCreators/transfer.ts
2379
- var transfer = (params) => ({
2380
- actionType: "Transfer",
2381
- params
3622
+ // src/signers/memorySigner/createSignTransaction.ts
3623
+ var SignTransactionArgsSchema2 = z38.object({
3624
+ intent: TransactionIntentSchema
3625
+ });
3626
+ var createSafeSignTransaction2 = (context) => wrapInternalError("MemorySigner.SignTransaction.Internal", async (args) => {
3627
+ const validArgs = SignTransactionArgsSchema2.safeParse(args);
3628
+ if (!validArgs.success)
3629
+ return result.err(
3630
+ createNatError({
3631
+ kind: "MemorySigner.SignTransaction.Args.InvalidSchema",
3632
+ context: { zodError: validArgs.error }
3633
+ })
3634
+ );
3635
+ const signedTransaction = await context.taskQueue.addSignTransactionTask(
3636
+ args.intent
3637
+ );
3638
+ if (signedTransaction.ok) return signedTransaction;
3639
+ if (signedTransaction.error.kind === "MemorySigner.Matcher.KeyForTaskNotFound") {
3640
+ return repackError({
3641
+ error: signedTransaction.error,
3642
+ originPrefix: "MemorySigner.Matcher",
3643
+ targetPrefix: "MemorySigner.SignTransaction"
3644
+ });
3645
+ }
3646
+ if (signedTransaction.error.kind === "MemorySigner.TaskQueue.Task.MaxTimeInQueueReached")
3647
+ return repackError({
3648
+ error: signedTransaction.error,
3649
+ originPrefix: "MemorySigner.TaskQueue.Task",
3650
+ targetPrefix: "MemorySigner.SignTransaction"
3651
+ });
3652
+ return result.err(signedTransaction.error);
2382
3653
  });
2383
3654
 
3655
+ // src/signers/memorySigner/createExecuteTransaction.ts
3656
+ var z39 = __toESM(require("zod/mini"), 1);
3657
+ var SignTransactionArgsSchema3 = z39.object({
3658
+ intent: TransactionIntentSchema
3659
+ });
3660
+ var createSafeExecuteTransaction = (context) => wrapInternalError(
3661
+ "MemorySigner.ExecuteTransaction.Internal",
3662
+ async (args) => {
3663
+ const validArgs = SignTransactionArgsSchema3.safeParse(args);
3664
+ if (!validArgs.success)
3665
+ return result.err(
3666
+ createNatError({
3667
+ kind: "MemorySigner.ExecuteTransaction.Args.InvalidSchema",
3668
+ context: { zodError: validArgs.error }
3669
+ })
3670
+ );
3671
+ const taskResult = await context.taskQueue.addExecuteTransactionTask(
3672
+ args.intent
3673
+ );
3674
+ if (taskResult.ok) return taskResult;
3675
+ if (taskResult.error.kind === "MemorySigner.Matcher.KeyForTaskNotFound")
3676
+ return repackError({
3677
+ error: taskResult.error,
3678
+ originPrefix: "MemorySigner.Matcher",
3679
+ targetPrefix: "MemorySigner.ExecuteTransaction"
3680
+ });
3681
+ if (taskResult.error.kind === "MemorySigner.TaskQueue.Task.MaxTimeInQueueReached")
3682
+ return repackError({
3683
+ error: taskResult.error,
3684
+ originPrefix: "MemorySigner.TaskQueue.Task",
3685
+ targetPrefix: "MemorySigner.ExecuteTransaction"
3686
+ });
3687
+ if (taskResult.error.kind === "MemorySigner.Executors.ExecuteTransaction.Client.SendSignedTransaction") {
3688
+ if (isNatErrorOf(taskResult.error.context.cause, [
3689
+ "Client.SendSignedTransaction.SendRequest.Failed",
3690
+ "Client.SendSignedTransaction.Rpc.Transaction.Timeout",
3691
+ "Client.SendSignedTransaction.Rpc.Transaction.Receiver.NotFound",
3692
+ "Client.SendSignedTransaction.Rpc.Transaction.Signer.Balance.TooLow",
3693
+ "Client.SendSignedTransaction.Rpc.Transaction.Action.CreateAccount.AlreadyExist"
3694
+ ])) {
3695
+ return repackError({
3696
+ error: taskResult.error.context.cause,
3697
+ originPrefix: "Client.SendSignedTransaction",
3698
+ targetPrefix: "MemorySigner.ExecuteTransaction"
3699
+ });
3700
+ }
3701
+ throw taskResult.error.context.cause;
3702
+ }
3703
+ return result.err(taskResult.error);
3704
+ }
3705
+ );
3706
+
3707
+ // src/signers/memorySigner/createMemorySigner.ts
3708
+ var CreateMemorySignerArgsSchema = z40.object({
3709
+ signerAccountId: AccountIdSchema,
3710
+ client: z40.custom((value) => isClient(value)),
3711
+ keyService: z40.custom((value) => isMemoryKeyService(value)),
3712
+ keyPool: z40.optional(
3713
+ z40.object({
3714
+ signingKeys: z40.optional(z40.array(PublicKeySchema).check(z40.minLength(1)))
3715
+ })
3716
+ ),
3717
+ taskQueue: z40.optional(
3718
+ z40.object({
3719
+ maxWaitInQueueMs: z40.optional(z40.number().check(z40.nonnegative()))
3720
+ })
3721
+ )
3722
+ });
3723
+ var safeCreateMemorySigner = wrapInternalError(
3724
+ "CreateMemorySigner.Internal",
3725
+ async (args) => {
3726
+ const validArgs = CreateMemorySignerArgsSchema.safeParse(args);
3727
+ if (!validArgs.success)
3728
+ return result.err(
3729
+ createNatError({
3730
+ kind: "CreateMemorySigner.Args.InvalidSchema",
3731
+ context: { zodError: validArgs.error }
3732
+ })
3733
+ );
3734
+ const { signerAccountId, client, keyService } = validArgs.data;
3735
+ const context = {
3736
+ signerAccountId,
3737
+ client,
3738
+ keyService,
3739
+ signingKeys: args.keyPool?.signingKeys,
3740
+ maxWaitInQueueMs: args.taskQueue?.maxWaitInQueueMs ?? 6e4
3741
+ // 1 min
3742
+ };
3743
+ const [keyPool, state] = await Promise.all([
3744
+ createKeyPool(context),
3745
+ createState(context)
3746
+ ]);
3747
+ if (!keyPool.ok) {
3748
+ if (keyPool.error.kind === "CreateMemorySigner.CreateKeyPool.Failed")
3749
+ return result.err(
3750
+ createNatError({
3751
+ kind: "CreateMemorySigner.Internal",
3752
+ context: { cause: keyPool.error }
3753
+ })
3754
+ );
3755
+ return result.err(keyPool.error);
3756
+ }
3757
+ if (!state.ok)
3758
+ return result.err(
3759
+ createNatError({
3760
+ kind: "CreateMemorySigner.Internal",
3761
+ context: { cause: state.error }
3762
+ })
3763
+ );
3764
+ context.keyPool = keyPool.value;
3765
+ context.state = state.value;
3766
+ context.taskQueue = createTaskQueue(context);
3767
+ context.matcher = createMatcher(context);
3768
+ context.resolver = createResolver();
3769
+ const safeSignTransaction = createSafeSignTransaction2(context);
3770
+ const safeExecuteTransaction = createSafeExecuteTransaction(context);
3771
+ const stop = () => {
3772
+ context.state.clearIntervals();
3773
+ };
3774
+ return result.ok({
3775
+ signerAccountId,
3776
+ signTransaction: asThrowable(safeSignTransaction),
3777
+ executeTransaction: asThrowable(safeExecuteTransaction),
3778
+ safeSignTransaction,
3779
+ safeExecuteTransaction,
3780
+ stop
3781
+ });
3782
+ }
3783
+ );
3784
+ var throwableCreateMemorySigner = asThrowable(
3785
+ safeCreateMemorySigner
3786
+ );
3787
+ var createSafeMemorySignerFactory = (args) => (signerAccountId) => safeCreateMemorySigner({ ...args, signerAccountId });
3788
+ var createThrowableMemorySignerFactory = (args) => (signerAccountId) => throwableCreateMemorySigner({ ...args, signerAccountId });
3789
+
2384
3790
  // src/helpers/actionCreators/createAccount.ts
2385
3791
  var createAccount = () => ({
2386
3792
  actionType: "CreateAccount"
2387
3793
  });
2388
3794
 
3795
+ // src/helpers/actionCreators/transfer.ts
3796
+ var z41 = __toESM(require("zod/mini"), 1);
3797
+ var CreateTransferActionArgsSchema = z41.object({
3798
+ amount: NearTokenArgsSchema
3799
+ });
3800
+ var safeTransfer = wrapInternalError(
3801
+ "CreateAction.Transfer.Internal",
3802
+ (args) => {
3803
+ const validArgs = CreateTransferActionArgsSchema.safeParse(args);
3804
+ if (!validArgs.success)
3805
+ return result.err(
3806
+ createNatError({
3807
+ kind: "CreateAction.Transfer.Args.InvalidSchema",
3808
+ context: { zodError: validArgs.error }
3809
+ })
3810
+ );
3811
+ return result.ok({
3812
+ actionType: "Transfer",
3813
+ amount: args.amount
3814
+ });
3815
+ }
3816
+ );
3817
+ var throwableTransfer = asThrowable(safeTransfer);
3818
+
2389
3819
  // src/helpers/actionCreators/addFullAccessKey.ts
2390
- var addFullAccessKey = ({
2391
- publicKey
2392
- }) => ({
2393
- actionType: "AddKey",
2394
- params: {
3820
+ var z42 = __toESM(require("zod/mini"), 1);
3821
+ var CreateAddFullAccessKeyActionArgsSchema = z42.object({
3822
+ publicKey: PublicKeySchema
3823
+ });
3824
+ var safeAddFullAccessKey = wrapInternalError("CreateAction.AddFullAccessKey.Internal", (args) => {
3825
+ const validArgs = CreateAddFullAccessKeyActionArgsSchema.safeParse(args);
3826
+ if (!validArgs.success)
3827
+ return result.err(
3828
+ createNatError({
3829
+ kind: "CreateAction.AddFullAccessKey.Args.InvalidSchema",
3830
+ context: { zodError: validArgs.error }
3831
+ })
3832
+ );
3833
+ return result.ok({
3834
+ actionType: "AddKey",
2395
3835
  accessType: "FullAccess",
2396
- publicKey
2397
- }
3836
+ publicKey: args.publicKey
3837
+ });
2398
3838
  });
3839
+ var throwableAddFullAccessKey = asThrowable(safeAddFullAccessKey);
2399
3840
 
2400
3841
  // src/helpers/actionCreators/addFunctionCallKey.ts
2401
- var addFunctionCallKey = ({
2402
- publicKey,
2403
- contractAccountId,
2404
- gasBudget,
2405
- allowedFunctions
2406
- }) => ({
2407
- actionType: "AddKey",
2408
- params: {
3842
+ var z43 = __toESM(require("zod/mini"), 1);
3843
+ var CreateAddFunctionCallKeyActionArgsSchema = z43.object({
3844
+ publicKey: PublicKeySchema,
3845
+ contractAccountId: AccountIdSchema,
3846
+ gasBudget: z43.optional(NearTokenArgsSchema),
3847
+ allowedFunctions: z43.optional(
3848
+ z43.array(ContractFunctionNameSchema).check(z43.minLength(1))
3849
+ )
3850
+ });
3851
+ var safeAddFunctionCallKey = wrapInternalError("CreateAction.AddFunctionCallKey.Internal", (args) => {
3852
+ const validArgs = CreateAddFunctionCallKeyActionArgsSchema.safeParse(args);
3853
+ if (!validArgs.success)
3854
+ return result.err(
3855
+ createNatError({
3856
+ kind: "CreateAction.AddFunctionCallKey.Args.InvalidSchema",
3857
+ context: { zodError: validArgs.error }
3858
+ })
3859
+ );
3860
+ return result.ok({
3861
+ actionType: "AddKey",
2409
3862
  accessType: "FunctionCall",
2410
- publicKey,
2411
- contractAccountId,
2412
- gasBudget,
2413
- allowedFunctions
2414
- }
3863
+ publicKey: args.publicKey,
3864
+ contractAccountId: args.contractAccountId,
3865
+ gasBudget: args.gasBudget,
3866
+ allowedFunctions: args.allowedFunctions
3867
+ });
2415
3868
  });
3869
+ var throwableAddFunctionCallKey = asThrowable(safeAddFunctionCallKey);
2416
3870
 
2417
3871
  // src/helpers/actionCreators/functionCall.ts
2418
- var functionCall = (params) => ({
2419
- actionType: "FunctionCall",
2420
- params
3872
+ var z44 = __toESM(require("zod/mini"), 1);
3873
+ var serializeFunctionArgs2 = (args) => {
3874
+ if (args.options?.serializeArgs) {
3875
+ const serializeArgs = args.options.serializeArgs;
3876
+ return wrapInternalError(
3877
+ "CreateAction.FunctionCall.SerializeArgs.Internal",
3878
+ () => {
3879
+ const output = serializeArgs({
3880
+ functionArgs: args.functionArgs
3881
+ });
3882
+ if (!(output instanceof Uint8Array))
3883
+ return result.err(
3884
+ createNatError({
3885
+ kind: "CreateAction.FunctionCall.SerializeArgs.InvalidOutput",
3886
+ context: { output }
3887
+ })
3888
+ );
3889
+ return result.ok(output);
3890
+ }
3891
+ )();
3892
+ }
3893
+ if (args?.functionArgs) {
3894
+ const jsonArgs = JsonSchema.safeParse(args.functionArgs);
3895
+ if (!jsonArgs.success)
3896
+ return result.err(
3897
+ createNatError({
3898
+ kind: "CreateAction.FunctionCall.Args.InvalidSchema",
3899
+ context: { zodError: jsonArgs.error }
3900
+ })
3901
+ );
3902
+ return result.ok(toJsonBytes(args.functionArgs));
3903
+ }
3904
+ return result.ok(new Uint8Array());
3905
+ };
3906
+ var CreateFunctionCallActionArgsSchema = z44.object({
3907
+ functionName: ContractFunctionNameSchema,
3908
+ functionArgs: z44.optional(z44.unknown()),
3909
+ gasLimit: NearGasArgsSchema,
3910
+ attachedDeposit: z44.optional(NearTokenArgsSchema),
3911
+ options: z44.optional(
3912
+ z44.object({
3913
+ serializeArgs: z44.optional(z44.instanceof(Function))
3914
+ })
3915
+ )
3916
+ });
3917
+ var safeFunctionCall = wrapInternalError(
3918
+ "CreateAction.FunctionCall.Internal",
3919
+ (args) => {
3920
+ const validArgs = CreateFunctionCallActionArgsSchema.safeParse(args);
3921
+ if (!validArgs.success)
3922
+ return result.err(
3923
+ createNatError({
3924
+ kind: "CreateAction.FunctionCall.Args.InvalidSchema",
3925
+ context: { zodError: validArgs.error }
3926
+ })
3927
+ );
3928
+ const functionArgs = serializeFunctionArgs2(args);
3929
+ if (!functionArgs.ok) return functionArgs;
3930
+ return result.ok({
3931
+ actionType: "FunctionCall",
3932
+ functionName: args.functionName,
3933
+ gasLimit: args.gasLimit,
3934
+ functionArgs: functionArgs.value,
3935
+ attachedDeposit: args.attachedDeposit
3936
+ });
3937
+ }
3938
+ );
3939
+ var throwableFunctionCall = asThrowable(
3940
+ safeFunctionCall
3941
+ );
3942
+
3943
+ // src/helpers/actionCreators/deployContract.ts
3944
+ var z45 = __toESM(require("zod/mini"), 1);
3945
+ var import_base7 = require("@scure/base");
3946
+ var CreateDeployContractActionArgsSchema = z45.union([
3947
+ z45.object({
3948
+ wasmBase64: z45.base64(),
3949
+ wasmBytes: z45.optional(z45.never())
3950
+ }),
3951
+ z45.object({
3952
+ wasmBase64: z45.optional(z45.never()),
3953
+ wasmBytes: z45.instanceof(Uint8Array)
3954
+ })
3955
+ ]);
3956
+ var safeDeployContract = wrapInternalError("CreateAction.DeployContract.Internal", (args) => {
3957
+ const validArgs = CreateDeployContractActionArgsSchema.safeParse(args);
3958
+ if (!validArgs.success)
3959
+ return result.err(
3960
+ createNatError({
3961
+ kind: "CreateAction.DeployContract.Args.InvalidSchema",
3962
+ context: { zodError: validArgs.error }
3963
+ })
3964
+ );
3965
+ const u8Wasm = validArgs.data.wasmBytes ? validArgs.data.wasmBytes : import_base7.base64.decode(validArgs.data.wasmBase64);
3966
+ return result.ok({
3967
+ actionType: "DeployContract",
3968
+ wasmBytes: u8Wasm
3969
+ });
2421
3970
  });
3971
+ var throwableDeployContract = asThrowable(safeDeployContract);
2422
3972
 
2423
3973
  // src/helpers/actionCreators/deleteKey.ts
2424
- var deleteKey = (params) => ({
2425
- actionType: "DeleteKey",
2426
- params
3974
+ var z46 = __toESM(require("zod/mini"), 1);
3975
+ var CreateDeleteKeyActionArgsSchema = z46.object({
3976
+ publicKey: PublicKeySchema
2427
3977
  });
3978
+ var safeDeleteKey = wrapInternalError(
3979
+ "CreateAction.DeleteKey.Internal",
3980
+ (args) => {
3981
+ const validArgs = CreateDeleteKeyActionArgsSchema.safeParse(args);
3982
+ if (!validArgs.success)
3983
+ return result.err(
3984
+ createNatError({
3985
+ kind: "CreateAction.DeleteKey.Args.InvalidSchema",
3986
+ context: { zodError: validArgs.error }
3987
+ })
3988
+ );
3989
+ return result.ok({
3990
+ actionType: "DeleteKey",
3991
+ publicKey: args.publicKey
3992
+ });
3993
+ }
3994
+ );
3995
+ var throwableDeleteKey = asThrowable(safeDeleteKey);
2428
3996
 
2429
3997
  // src/helpers/actionCreators/deleteAccount.ts
2430
- var deleteAccount = (params) => ({
2431
- actionType: "DeleteAccount",
2432
- params
3998
+ var z47 = __toESM(require("zod/mini"), 1);
3999
+ var CreateDeleteAccountActionArgsSchema = z47.object({
4000
+ beneficiaryAccountId: AccountIdSchema
4001
+ });
4002
+ var safeDeleteAccount = wrapInternalError("CreateAction.DeleteAccount.Internal", (args) => {
4003
+ const validArgs = CreateDeleteAccountActionArgsSchema.safeParse(args);
4004
+ if (!validArgs.success)
4005
+ return result.err(
4006
+ createNatError({
4007
+ kind: "CreateAction.DeleteAccount.Args.InvalidSchema",
4008
+ context: { zodError: validArgs.error }
4009
+ })
4010
+ );
4011
+ return result.ok({
4012
+ actionType: "DeleteAccount",
4013
+ beneficiaryAccountId: args.beneficiaryAccountId
4014
+ });
2433
4015
  });
4016
+ var throwableDeleteAccount = asThrowable(safeDeleteAccount);
2434
4017
 
2435
- // src/helpers/actionCreators/deployContract.ts
2436
- var deployContract = (params) => ({
2437
- actionType: "DeployContract",
2438
- params
4018
+ // src/helpers/keyPair/randomEd25519KeyPair.ts
4019
+ var import_ed255192 = require("@noble/curves/ed25519");
4020
+ var createSafeSignByEd25519Key = (u8PrivateKey) => wrapInternalError(
4021
+ "Ed25519KeyPair.Sign.Internal",
4022
+ (message) => signByEd25519Key(u8PrivateKey, message)
4023
+ );
4024
+ var safeRandomEd25519KeyPair = wrapInternalError("CreateRandomEd25519KeyPair.Internal", () => {
4025
+ const { secretKey: u8SecretKey, publicKey: u8PublicKey } = import_ed255192.ed25519.keygen();
4026
+ const u8PrivateKey = new Uint8Array([...u8SecretKey, ...u8PublicKey]);
4027
+ const publicKey = toEd25519CurveString(u8PublicKey);
4028
+ const privateKey = toEd25519CurveString(u8PrivateKey);
4029
+ const safeSign = createSafeSignByEd25519Key(u8PrivateKey);
4030
+ return result.ok({
4031
+ publicKey,
4032
+ privateKey,
4033
+ sign: asThrowable(safeSign),
4034
+ safeSign
4035
+ });
4036
+ });
4037
+ var throwableRandomEd25519KeyPair = asThrowable(safeRandomEd25519KeyPair);
4038
+
4039
+ // src/helpers/keyPair/randomSecp256k1KeyPair.ts
4040
+ var import_secp256k12 = require("@noble/curves/secp256k1");
4041
+ var createSafeSignBySecp256k1Key = (u8PrivateKey) => wrapInternalError(
4042
+ "Secp256k1KeyPair.Sign.Internal",
4043
+ (message) => signBySecp256k1Key(u8PrivateKey, message)
4044
+ );
4045
+ var safeRandomSecp256k1KeyPair = wrapInternalError("CreateRandomSecp256k1KeyPair.Internal", () => {
4046
+ const u8SecretKey = import_secp256k12.secp256k1.utils.randomSecretKey();
4047
+ const u8PublicKey = import_secp256k12.secp256k1.getPublicKey(u8SecretKey, false);
4048
+ const u8PublicKeyWithoutHeader = u8PublicKey.slice(1);
4049
+ const u8PrivateKey = new Uint8Array([
4050
+ ...u8SecretKey,
4051
+ ...u8PublicKeyWithoutHeader
4052
+ ]);
4053
+ const publicKey = toSecp256k1CurveString(u8PublicKeyWithoutHeader);
4054
+ const privateKey = toSecp256k1CurveString(u8PrivateKey);
4055
+ const safeSign = createSafeSignBySecp256k1Key(u8PrivateKey);
4056
+ return result.ok({
4057
+ publicKey,
4058
+ privateKey,
4059
+ sign: asThrowable(safeSign),
4060
+ safeSign
4061
+ });
2439
4062
  });
4063
+ var throwableRandomSecp256k1KeyPair = asThrowable(safeRandomSecp256k1KeyPair);
2440
4064
  // Annotate the CommonJS export names for ESM import in node:
2441
4065
  0 && (module.exports = {
2442
4066
  addFullAccessKey,
@@ -2446,13 +4070,42 @@ var deployContract = (params) => ({
2446
4070
  createMainnetClient,
2447
4071
  createMemoryKeyService,
2448
4072
  createMemorySigner,
4073
+ createMemorySignerFactory,
4074
+ createSafeMemorySignerFactory,
2449
4075
  createTestnetClient,
2450
4076
  deleteAccount,
2451
4077
  deleteKey,
2452
4078
  deployContract,
2453
4079
  functionCall,
2454
4080
  gas,
4081
+ isNatError,
4082
+ isNearGas,
4083
+ isNearToken,
4084
+ keyPair,
2455
4085
  near,
4086
+ nearGas,
4087
+ nearToken,
4088
+ randomEd25519KeyPair,
4089
+ randomSecp256k1KeyPair,
4090
+ safeAddFullAccessKey,
4091
+ safeAddFunctionCallKey,
4092
+ safeCreateClient,
4093
+ safeCreateMemoryKeyService,
4094
+ safeCreateMemorySigner,
4095
+ safeDeleteAccount,
4096
+ safeDeleteKey,
4097
+ safeDeployContract,
4098
+ safeFunctionCall,
4099
+ safeGas,
4100
+ safeKeyPair,
4101
+ safeNear,
4102
+ safeNearGas,
4103
+ safeNearToken,
4104
+ safeRandomEd25519KeyPair,
4105
+ safeRandomSecp256k1KeyPair,
4106
+ safeTeraGas,
4107
+ safeTransfer,
4108
+ safeYoctoNear,
2456
4109
  teraGas,
2457
4110
  transfer,
2458
4111
  yoctoNear