n3-sdk 0.1.9 → 0.1.11

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.
@@ -404,4 +404,142 @@ declare function depositHYPE({ clients, pool, chainId, amountWei, seed, store, }
404
404
  note: NoteV1;
405
405
  }>;
406
406
 
407
- export { type AssetId as A, type N3Env as N, Receiver as R, Topics as T, makeCandlesInfo as a, makeDepthInfo as b, makeTradesInfo as c, makeBatchesInfo as d, makeIndicatives as e, makeCandles as f, makeDepth as g, makeTrades as h, makeBatches as i, type TopicName as j, index$1 as k, index as l, makeIndicativesInfo as m, NoteStore as n, type N3Clients as o, toReceiverFromBlock as p, depositERC20 as q, depositHYPE as r, toViemFromBlock as t };
407
+ type Tif = "Alo" | "Ioc" | "Gtc";
408
+ type OrderType = {
409
+ limit: {
410
+ tif: Tif;
411
+ };
412
+ } | {
413
+ trigger: {
414
+ isMarket: boolean;
415
+ triggerPx: string;
416
+ tpsl: "tp" | "sl";
417
+ };
418
+ };
419
+ type Cloid = `0x${string}`;
420
+ interface HlOrderWire {
421
+ a: number;
422
+ b: boolean;
423
+ p: string;
424
+ s: string;
425
+ r: boolean;
426
+ t: OrderType;
427
+ c?: Cloid;
428
+ }
429
+ type Grouping = "na" | "normalTpsl" | "positionTpsl";
430
+ interface BuilderFee {
431
+ b: `0x${string}`;
432
+ f: number;
433
+ }
434
+ interface HlActionOrder {
435
+ type: "order";
436
+ orders: HlOrderWire[];
437
+ grouping: Grouping;
438
+ builder?: BuilderFee;
439
+ }
440
+ interface HlSignature {
441
+ vaultAddress?: `0x${string}`;
442
+ expiresAfter: number;
443
+ [k: string]: unknown;
444
+ }
445
+ interface HlOrderRequest {
446
+ action: HlActionOrder;
447
+ nonce: number;
448
+ signature: HlSignature;
449
+ [k: string]: unknown;
450
+ }
451
+ type SettlementMode = "pool" | "core" | "hybrid";
452
+ type PoolId = number;
453
+ interface HybridPolicy {
454
+ internalFirst?: boolean;
455
+ internalCap?: string;
456
+ coreCap?: string;
457
+ }
458
+ interface SpendNoteRef {
459
+ commitment: string;
460
+ leafIndex?: number;
461
+ assetId?: number;
462
+ maxSpend?: string;
463
+ }
464
+ interface RfqConstraints {
465
+ validUntilMs?: number;
466
+ minFill?: string;
467
+ slippageBps?: number;
468
+ makerOnlyInternal?: boolean;
469
+ counterpartyAllow?: string[];
470
+ counterpartyDeny?: string[];
471
+ }
472
+ interface PoolAccess {
473
+ allowPools?: PoolId[];
474
+ denyPools?: PoolId[];
475
+ attestations?: string[];
476
+ }
477
+ interface CoreExecPrefs {
478
+ route?: string;
479
+ extData?: string;
480
+ }
481
+ interface N3Extensions {
482
+ settlement: SettlementMode;
483
+ pools?: PoolAccess;
484
+ hybrid?: HybridPolicy;
485
+ spendNotes?: SpendNoteRef[];
486
+ rfq?: RfqConstraints;
487
+ core?: CoreExecPrefs;
488
+ meta?: Record<string, unknown>;
489
+ }
490
+ interface N3OrderIntent extends HlOrderRequest {
491
+ n3: N3Extensions;
492
+ }
493
+ interface PlannableOrder {
494
+ assetId: number;
495
+ isBuy: boolean;
496
+ price: string;
497
+ size: string;
498
+ reduceOnly: boolean;
499
+ tif: Tif | null;
500
+ trigger?: {
501
+ isMarket: boolean;
502
+ triggerPx: string;
503
+ tpsl: "tp" | "sl";
504
+ };
505
+ cloid?: Cloid;
506
+ grouping: Grouping;
507
+ builder?: BuilderFee;
508
+ settlement: SettlementMode;
509
+ pools: Required<PoolAccess>;
510
+ hybrid: Required<HybridPolicy>;
511
+ spendNotes: SpendNoteRef[];
512
+ rfq: Required<RfqConstraints>;
513
+ core: Required<CoreExecPrefs>;
514
+ internalRemaining: string;
515
+ coreRemaining: string;
516
+ userAddress?: `0x${string}`;
517
+ receivedAtMs: number;
518
+ }
519
+ type SubmitOrderIntentParams = {
520
+ hl: HlOrderWire;
521
+ grouping: Grouping;
522
+ builder?: BuilderFee;
523
+ n3?: N3Extensions;
524
+ ctx?: {
525
+ defaultPools?: number[];
526
+ nowMs?: number;
527
+ userAddress?: `0x${string}`;
528
+ };
529
+ domain: {
530
+ pool: `0x${string}`;
531
+ chainIdDec: number | string;
532
+ DOMAIN_DEC: number | string;
533
+ };
534
+ nonce?: number;
535
+ signature?: any;
536
+ };
537
+
538
+ type WDOut = {
539
+ assetId: bigint;
540
+ amount: bigint;
541
+ pubkey: bigint;
542
+ blinding: bigint;
543
+ };
544
+
545
+ export { type AssetId as A, type N3OrderIntent as N, type PlannableOrder as P, type RfqConstraints as R, type SubmitOrderIntentParams as S, Topics as T, type WDOut as W, type SpendNoteRef as a, NoteStore as b, type N3Env as c, makeCandlesInfo as d, makeDepthInfo as e, makeTradesInfo as f, makeBatchesInfo as g, makeIndicatives as h, makeCandles as i, makeDepth as j, makeTrades as k, makeBatches as l, makeIndicativesInfo as m, type TopicName as n, index$1 as o, index as p, Receiver as q, type N3Clients as r, toReceiverFromBlock as s, toViemFromBlock as t, depositERC20 as u, depositHYPE as v };
@@ -2819,9 +2819,9 @@ var FR = 21888242871839275222246405745257275088548364400416034343698204186575808
2819
2819
  async function babyjubCtx() {
2820
2820
  const babyjub = await buildBabyjub();
2821
2821
  const poseidon = await buildPoseidon();
2822
- const eddsa = await buildEddsa();
2822
+ const eddsa2 = await buildEddsa();
2823
2823
  const F = babyjub.F;
2824
- return { babyjub, poseidon, eddsa, F };
2824
+ return { babyjub, poseidon, eddsa: eddsa2, F };
2825
2825
  }
2826
2826
  function toField(x) {
2827
2827
  let v = x % FR;
@@ -2835,7 +2835,7 @@ function hexTo32Bytes(hex) {
2835
2835
  return bytes;
2836
2836
  }
2837
2837
  async function genNote(seed) {
2838
- const { eddsa, poseidon, F } = await babyjubCtx();
2838
+ const { eddsa: eddsa2, poseidon, F } = await babyjubCtx();
2839
2839
  const rnd = seed ?? BigInt.asUintN(
2840
2840
  256,
2841
2841
  BigInt(Date.now()) * 0x100000000n + BigInt(Math.floor(Math.random() * 1e9))
@@ -2844,7 +2844,7 @@ async function genNote(seed) {
2844
2844
  const blinding = toField(sk ^ 0xB1E55n);
2845
2845
  const skHex = "0x" + sk.toString(16).padStart(64, "0");
2846
2846
  const skBytes = hexTo32Bytes(skHex);
2847
- const pub = eddsa.prv2pub(skBytes);
2847
+ const pub = eddsa2.prv2pub(skBytes);
2848
2848
  const Ax = F.toObject(pub[0]);
2849
2849
  const Ay = F.toObject(pub[1]);
2850
2850
  const pubkey = F.toObject(poseidon([Ax, Ay]));
@@ -2989,6 +2989,274 @@ async function depositHYPE({
2989
2989
  return { hash, receipt, note };
2990
2990
  }
2991
2991
 
2992
+ // src/lib/utils/fetchPinFromIndexer.ts
2993
+ async function fetchPinFromIndexer(indexerUrl, poolAddr) {
2994
+ const q = `
2995
+ query Head($pool: String!) {
2996
+ poolStates(where: { id: $pool }, limit: 1) {
2997
+ items { currentRoot depAppliedHash depAppliedLen nextIndex updatedAt }
2998
+ }
2999
+ }`;
3000
+ const r = await fetch(indexerUrl, {
3001
+ method: "POST",
3002
+ headers: { "content-type": "application/json" },
3003
+ body: JSON.stringify({ query: q, variables: { pool: poolAddr.toLowerCase() } })
3004
+ });
3005
+ const j = await r.json();
3006
+ const head = j?.data?.poolStates?.items?.[0];
3007
+ if (!head) throw new Error("indexer head not found for pool");
3008
+ return {
3009
+ depEnqHash: String(head.depAppliedHash),
3010
+ depEnqLen: Number(head.depAppliedLen),
3011
+ nextIndex: Number(head.nextIndex),
3012
+ currentRoot: head.currentRoot,
3013
+ updatedAt: Number(head.updatedAt)
3014
+ };
3015
+ }
3016
+
3017
+ // src/lib/utils/withN3Defaults.ts
3018
+ function withN3Defaults(n3, ctx = {}) {
3019
+ const settlement = n3?.settlement ?? "pool";
3020
+ const pools = {
3021
+ allowPools: n3?.pools?.allowPools ?? (ctx.defaultPools ?? []),
3022
+ denyPools: n3?.pools?.denyPools ?? [],
3023
+ attestations: n3?.pools?.attestations ?? []
3024
+ };
3025
+ const hybrid = {
3026
+ internalFirst: n3?.hybrid?.internalFirst ?? true,
3027
+ internalCap: n3?.hybrid?.internalCap ?? (ctx.size ?? "0"),
3028
+ coreCap: n3?.hybrid?.coreCap ?? (ctx.size ?? "0")
3029
+ };
3030
+ const spendNotes = n3?.spendNotes ?? [];
3031
+ const now = ctx.nowMs ?? Date.now();
3032
+ const rfq = {
3033
+ validUntilMs: n3?.rfq?.validUntilMs ?? now + 5 * 6e4,
3034
+ // default 5 min
3035
+ minFill: n3?.rfq?.minFill ?? "0",
3036
+ slippageBps: n3?.rfq?.slippageBps ?? 0,
3037
+ makerOnlyInternal: n3?.rfq?.makerOnlyInternal ?? false,
3038
+ counterpartyAllow: n3?.rfq?.counterpartyAllow ?? [],
3039
+ counterpartyDeny: n3?.rfq?.counterpartyDeny ?? []
3040
+ };
3041
+ const core = {
3042
+ route: n3?.core?.route ?? "",
3043
+ extData: n3?.core?.extData ?? ""
3044
+ };
3045
+ const meta = n3?.meta ?? {};
3046
+ return { settlement, pools, hybrid, spendNotes, rfq, core, meta };
3047
+ }
3048
+
3049
+ // src/lib/utils/normalizeOrder.ts
3050
+ function normalizeOrder(hl, grouping, builder, n3Full, extra) {
3051
+ const tif = "limit" in hl.t ? hl.t.limit.tif : null;
3052
+ const trigger = "trigger" in hl.t ? hl.t.trigger : void 0;
3053
+ const it = {
3054
+ assetId: hl.a,
3055
+ isBuy: hl.b,
3056
+ price: hl.p,
3057
+ size: hl.s,
3058
+ reduceOnly: hl.r,
3059
+ tif,
3060
+ trigger,
3061
+ cloid: hl.c,
3062
+ grouping,
3063
+ builder,
3064
+ settlement: n3Full.settlement,
3065
+ pools: n3Full.pools,
3066
+ hybrid: n3Full.hybrid,
3067
+ spendNotes: n3Full.spendNotes,
3068
+ rfq: n3Full.rfq,
3069
+ core: n3Full.core,
3070
+ internalRemaining: n3Full.hybrid.internalFirst ? n3Full.hybrid.internalCap : "0",
3071
+ coreRemaining: n3Full.hybrid.coreCap,
3072
+ userAddress: extra.userAddress,
3073
+ receivedAtMs: extra.receivedAtMs ?? Date.now()
3074
+ };
3075
+ return it;
3076
+ }
3077
+
3078
+ // src/lib/utils/stripForHyperliquid.ts
3079
+ function stripForHyperliquid(intent) {
3080
+ const { n3: _omit, ...rest } = intent;
3081
+ return rest;
3082
+ }
3083
+
3084
+ // src/lib/utils/toUint160Dec.ts
3085
+ function toUint160Dec(addr) {
3086
+ if (!addr) throw new Error("empty address");
3087
+ const hex = addr.toLowerCase();
3088
+ if (!hex.startsWith("0x") || hex.length !== 42) throw new Error(`bad address: ${addr}`);
3089
+ return BigInt(hex).toString();
3090
+ }
3091
+
3092
+ // src/lib/utils/getDomains.ts
3093
+ function getDomains(params) {
3094
+ return {
3095
+ domainA: toUint160Dec(params.pool),
3096
+ domainB: String(params.chainIdDec),
3097
+ DOMAIN: String(params.DOMAIN_DEC)
3098
+ };
3099
+ }
3100
+
3101
+ // src/lib/utils/notesSelect.ts
3102
+ function greedySelectNotes(store, params) {
3103
+ const assetIdBI = BigInt(params.assetId);
3104
+ const need = params.amount;
3105
+ const spendables = store.listSpendable({ assetId: assetIdBI }).filter((n) => n.index != null && !!n.commitment);
3106
+ const sorted = spendables.slice().sort((a, b) => b.amount > a.amount ? 1 : b.amount < a.amount ? -1 : 0);
3107
+ const out = [];
3108
+ let acc = 0n;
3109
+ for (const n of sorted) {
3110
+ out.push(n);
3111
+ acc += n.amount;
3112
+ if (acc >= need) break;
3113
+ }
3114
+ return { notes: out, totalSelected: acc, shortfall: acc >= need ? 0n : need - acc };
3115
+ }
3116
+ function buildSpendNotesFromStore(store, params) {
3117
+ const sel = greedySelectNotes(store, params);
3118
+ const spendNotes = sel.notes.map((n) => ({
3119
+ commitment: n.commitment,
3120
+ leafIndex: n.index,
3121
+ // anchored by filter above
3122
+ assetId: Number(n.assetId),
3123
+ maxSpend: n.amount.toString()
3124
+ // spend full note; change handled downstream
3125
+ }));
3126
+ return { spendNotes, totalSelected: sel.totalSelected, shortfall: sel.shortfall };
3127
+ }
3128
+
3129
+ // src/lib/utils/pureSigner.ts
3130
+ import { buildBabyjub as buildBabyjub2, buildEddsa as buildEddsa2, buildPoseidonReference } from "circomlibjs";
3131
+ globalThis.ffjsconfig = { wasm: "disable" };
3132
+ process.env.FFJS_FORCE_NO_WASM = "1";
3133
+ process.env.FFJSCONFIG = '{"wasm":"disable"}';
3134
+ var babyJub = await buildBabyjub2();
3135
+ var eddsa = await buildEddsa2();
3136
+ var poseidonRef = await buildPoseidonReference();
3137
+ var Fr = babyJub.F;
3138
+ function toBI(x) {
3139
+ return typeof x === "bigint" ? x : BigInt(x);
3140
+ }
3141
+ function be32FromDec(dec) {
3142
+ let x = toBI(dec);
3143
+ const out = new Uint8Array(32);
3144
+ for (let i = 31; i >= 0; i--) {
3145
+ out[i] = Number(x & 0xffn);
3146
+ x >>= 8n;
3147
+ }
3148
+ return out;
3149
+ }
3150
+ function hexToBytes(hex) {
3151
+ const h = hex.startsWith("0x") ? hex.slice(2) : hex;
3152
+ const s = h.padStart(64, "0");
3153
+ return Uint8Array.from(Buffer.from(s, "hex"));
3154
+ }
3155
+ function H2(a, b) {
3156
+ return Fr.toObject(poseidonRef([Fr.e(a), Fr.e(b)]));
3157
+ }
3158
+ function noteCommit(assetId, amount, pubkey, blinding) {
3159
+ const h2 = (x, y) => Fr.toObject(poseidonRef([Fr.e(x), Fr.e(y)]));
3160
+ return h2(h2(assetId, amount), h2(pubkey, blinding));
3161
+ }
3162
+ function msgHash(domain, chainDec, poolDec, c_in, oldRoot) {
3163
+ return Fr.toObject(
3164
+ poseidonRef([
3165
+ Fr.e(domain),
3166
+ Fr.e(chainDec),
3167
+ Fr.e(poolDec),
3168
+ Fr.e(c_in),
3169
+ Fr.e(oldRoot)
3170
+ ])
3171
+ );
3172
+ }
3173
+ function poseidonAxAy(Ax, Ay) {
3174
+ return Fr.toObject(
3175
+ poseidonRef([Fr.e(toBI(Ax)), Fr.e(toBI(Ay))])
3176
+ );
3177
+ }
3178
+ function signPoseidonCompat(prvSeed, M, Ax_from_note, Ay_from_note) {
3179
+ const raw = prvSeed.startsWith("0x") ? hexToBytes(prvSeed) : be32FromDec(prvSeed);
3180
+ if (raw.length !== 32) {
3181
+ throw new Error(`signPoseidonCompat: prvSeed must be 32 bytes, got ${raw.length}`);
3182
+ }
3183
+ const prv = Buffer.from(raw);
3184
+ if (Ax_from_note && Ay_from_note) {
3185
+ const A = eddsa.prv2pub(prv);
3186
+ const Ax = Fr.toObject(A[0]);
3187
+ const Ay = Fr.toObject(A[1]);
3188
+ if (Ax.toString() !== Ax_from_note || Ay.toString() !== Ay_from_note) {
3189
+ console.warn("[warn] prv->pub mismatch", {
3190
+ derivedAx: Ax.toString(),
3191
+ derivedAy: Ay.toString(),
3192
+ noteAx: Ax_from_note,
3193
+ noteAy: Ay_from_note
3194
+ });
3195
+ }
3196
+ }
3197
+ const Mfield = Fr.e(M);
3198
+ const sig = eddsa.signPoseidon(prv, Mfield);
3199
+ const R8x = Fr.toObject(sig.R8[0]);
3200
+ const R8y = Fr.toObject(sig.R8[1]);
3201
+ const S = toBI(sig.S);
3202
+ return { R8x: R8x.toString(), R8y: R8y.toString(), S: S.toString() };
3203
+ }
3204
+ function verifyPoseidonCompat(Ax, Ay, M, sig) {
3205
+ const A = [babyJub.F.e(toBI(Ax)), babyJub.F.e(toBI(Ay))];
3206
+ const R8 = [babyJub.F.e(toBI(sig.R8x)), babyJub.F.e(toBI(sig.R8y))];
3207
+ const S = toBI(sig.S);
3208
+ return eddsa.verifyPoseidon(M, { R8, S }, A);
3209
+ }
3210
+
3211
+ // src/lib/utils/formattingHelpers.ts
3212
+ import crypto3 from "crypto";
3213
+ var BI = (x) => typeof x === "bigint" ? x : BigInt(x);
3214
+ var mask160 = (1n << 160n) - 1n;
3215
+ var toHex32Lower = (x) => {
3216
+ const bi = typeof x === "bigint" ? x : x.toString().startsWith("0x") ? BigInt(x) : BigInt(x);
3217
+ return "0x" + bi.toString(16).padStart(64, "0");
3218
+ };
3219
+ function toU8(objOrHexOrU8) {
3220
+ if (objOrHexOrU8 instanceof Uint8Array) return objOrHexOrU8;
3221
+ if (typeof objOrHexOrU8 === "string") {
3222
+ const hex = objOrHexOrU8.startsWith("0x") ? objOrHexOrU8.slice(2) : objOrHexOrU8;
3223
+ if (hex.length % 2) throw new Error("hex string must have even length");
3224
+ const out = new Uint8Array(hex.length / 2);
3225
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);
3226
+ return out;
3227
+ }
3228
+ if (objOrHexOrU8 && typeof objOrHexOrU8 === "object") {
3229
+ const keys = Object.keys(objOrHexOrU8).map(Number).sort((a, b) => a - b);
3230
+ const out = new Uint8Array(keys.length);
3231
+ for (let i = 0; i < keys.length; i++) out[i] = Number(objOrHexOrU8[keys[i]]);
3232
+ return out;
3233
+ }
3234
+ throw new Error("toU8: unsupported input");
3235
+ }
3236
+ var u8ToHex = (u82) => "0x" + [...u82].map((b) => b.toString(16).padStart(2, "0")).join("");
3237
+ var u8ToBigIntBE = (u82) => BigInt(u8ToHex(u82));
3238
+ var randU256 = () => u8ToBigIntBE(crypto3.randomBytes(32));
3239
+
3240
+ // src/lib/utils/foldToRoot.ts
3241
+ function foldToRoot(leaf, pathElements, pathIndex, depth) {
3242
+ let acc = leaf;
3243
+ for (let lvl = 0; lvl < depth; lvl++) {
3244
+ const sib = BI(pathElements[lvl]);
3245
+ const bit = pathIndex[lvl] & 1;
3246
+ acc = bit === 0 ? H2(acc, sib) : H2(sib, acc);
3247
+ }
3248
+ return acc;
3249
+ }
3250
+
3251
+ // src/lib/utils/computeNullifier.ts
3252
+ async function computeNullifierExact(params) {
3253
+ await initPoseidon();
3254
+ const H22 = getH2();
3255
+ const inner = H22(params.commit, params.index);
3256
+ const nf = H22(params.sk, inner);
3257
+ return nf;
3258
+ }
3259
+
2992
3260
  export {
2993
3261
  __export,
2994
3262
  Topics,
@@ -3009,13 +3277,32 @@ export {
3009
3277
  toViemFromBlock,
3010
3278
  toReceiverFromBlock,
3011
3279
  initPoseidon,
3012
- getH2,
3013
3280
  PrivatePoolAbi,
3014
3281
  EV_NewRoot,
3015
3282
  EV_LeavesInserted,
3016
3283
  EV_Spent,
3017
3284
  depositERC20,
3018
- depositHYPE
3285
+ depositHYPE,
3286
+ fetchPinFromIndexer,
3287
+ withN3Defaults,
3288
+ normalizeOrder,
3289
+ stripForHyperliquid,
3290
+ toUint160Dec,
3291
+ getDomains,
3292
+ buildSpendNotesFromStore,
3293
+ H2,
3294
+ noteCommit,
3295
+ msgHash,
3296
+ poseidonAxAy,
3297
+ signPoseidonCompat,
3298
+ verifyPoseidonCompat,
3299
+ BI,
3300
+ toHex32Lower,
3301
+ toU8,
3302
+ u8ToBigIntBE,
3303
+ randU256,
3304
+ foldToRoot,
3305
+ computeNullifierExact
3019
3306
  };
3020
3307
  /*! Bundled license information:
3021
3308
 
@@ -3025,4 +3312,4 @@ export {
3025
3312
  @noble/hashes/esm/utils.js:
3026
3313
  (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3027
3314
  */
3028
- //# sourceMappingURL=chunk-MPHJAU3W.js.map
3315
+ //# sourceMappingURL=chunk-7XKOPXQE.js.map