@0dotxyz/p0-ts-sdk 2.2.0-alpha.4 → 2.2.0-alpha.6

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/vendor.cjs CHANGED
@@ -10,6 +10,8 @@ var buffer = require('buffer');
10
10
  var anchor = require('@coral-xyz/anchor');
11
11
  var borsh = require('@coral-xyz/borsh');
12
12
  var Decimal3 = require('decimal.js');
13
+ var WebSocket = require('ws');
14
+ var msgpack = require('@msgpack/msgpack');
13
15
 
14
16
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
15
17
 
@@ -34,6 +36,7 @@ function _interopNamespace(e) {
34
36
  var BN2__default = /*#__PURE__*/_interopDefault(BN2);
35
37
  var borsh__namespace = /*#__PURE__*/_interopNamespace(borsh);
36
38
  var Decimal3__default = /*#__PURE__*/_interopDefault(Decimal3);
39
+ var WebSocket__default = /*#__PURE__*/_interopDefault(WebSocket);
37
40
 
38
41
  // src/vendor/pyth_legacy/readBig.ts
39
42
  var ERR_BUFFER_OUT_OF_BOUNDS = () => new Error("Attempt to access memory outside buffer bounds");
@@ -29190,6 +29193,358 @@ function makeUpdateJupLendRate({ lendingState }) {
29190
29193
  lendingState.rewardsRateModel
29191
29194
  );
29192
29195
  }
29196
+ var SUBPROTOCOL = "v1.api.titan.ag";
29197
+ var UINT64_MAX = (1n << 64n) - 1n;
29198
+ function toBigInt(value) {
29199
+ if (typeof value === "bigint") {
29200
+ if (value < 0n || value > UINT64_MAX) {
29201
+ throw new RangeError(`Amount out of uint64 range: ${value}`);
29202
+ }
29203
+ return value;
29204
+ }
29205
+ if (!Number.isInteger(value)) {
29206
+ throw new TypeError(`Amount must be a whole number, got ${value}`);
29207
+ }
29208
+ if (value < 0) {
29209
+ throw new RangeError(`Amount must be non-negative, got ${value}`);
29210
+ }
29211
+ return BigInt(value);
29212
+ }
29213
+ var ConnectionClosed = class _ConnectionClosed extends Error {
29214
+ code;
29215
+ reason;
29216
+ constructor(code, reason) {
29217
+ super(`Client WebSocket closed with code ${code}: ${reason}`);
29218
+ this.name = "ConnectionClosed";
29219
+ Object.setPrototypeOf(this, _ConnectionClosed.prototype);
29220
+ this.code = code;
29221
+ this.reason = reason;
29222
+ }
29223
+ };
29224
+ var ErrorResponse = class _ErrorResponse extends Error {
29225
+ response;
29226
+ constructor(response) {
29227
+ super(`Request ${response.requestId} failed with code ${response.code}: ${response.message}`);
29228
+ this.name = "ErrorResponse";
29229
+ Object.setPrototypeOf(this, _ErrorResponse.prototype);
29230
+ this.response = response;
29231
+ }
29232
+ };
29233
+ var StreamError = class _StreamError extends Error {
29234
+ streamId;
29235
+ errorCode;
29236
+ errorMessage;
29237
+ constructor(packet) {
29238
+ const code = packet.errorCode ?? 0;
29239
+ const message = packet.errorMessage ?? "";
29240
+ super(`Stream ${packet.id} ended with error code ${code}: ${message}`);
29241
+ this.name = "StreamError";
29242
+ Object.setPrototypeOf(this, _StreamError.prototype);
29243
+ this.streamId = packet.id;
29244
+ this.errorCode = code;
29245
+ this.errorMessage = message;
29246
+ }
29247
+ };
29248
+ var encoder = new msgpack.Encoder({ useBigInt64: true });
29249
+ var decoder = new msgpack.Decoder({ useBigInt64: true });
29250
+ var V1Client = class _V1Client {
29251
+ socket;
29252
+ nextId = 0;
29253
+ _closed = false;
29254
+ _closing = false;
29255
+ pending = /* @__PURE__ */ new Map();
29256
+ streams = /* @__PURE__ */ new Map();
29257
+ streamStopping = /* @__PURE__ */ new Map();
29258
+ closeListeners = [];
29259
+ // --- Static connect ---
29260
+ static connect(url) {
29261
+ return new Promise((resolve, reject) => {
29262
+ const ws = new WebSocket__default.default(url, [SUBPROTOCOL]);
29263
+ ws.binaryType = "arraybuffer";
29264
+ const onOpen = () => {
29265
+ ws.off("error", onError);
29266
+ ws.off("close", onClose);
29267
+ resolve(new _V1Client(ws));
29268
+ };
29269
+ const onError = (err) => {
29270
+ ws.off("open", onOpen);
29271
+ ws.off("close", onClose);
29272
+ reject(err);
29273
+ };
29274
+ const onClose = (code, reason) => {
29275
+ ws.off("open", onOpen);
29276
+ ws.off("error", onError);
29277
+ reject(
29278
+ new Error(
29279
+ `WebSocket closed before open (code=${code}${reason.length ? `, reason=${reason.toString()}` : ""})`
29280
+ )
29281
+ );
29282
+ };
29283
+ ws.once("open", onOpen);
29284
+ ws.once("error", onError);
29285
+ ws.once("close", onClose);
29286
+ });
29287
+ }
29288
+ // --- Constructor ---
29289
+ constructor(socket) {
29290
+ this.socket = socket;
29291
+ this.socket.on("message", (data) => {
29292
+ this.handleMessage(data);
29293
+ });
29294
+ this.socket.on("close", (code, reason) => {
29295
+ this.handleClose(code, reason.toString());
29296
+ });
29297
+ this.socket.on("error", (err) => {
29298
+ this.handleError(err);
29299
+ });
29300
+ }
29301
+ nextRequestId() {
29302
+ return this.nextId++;
29303
+ }
29304
+ // --- Public API ---
29305
+ get closed() {
29306
+ return this._closed;
29307
+ }
29308
+ close() {
29309
+ if (this._closed) return Promise.resolve();
29310
+ return new Promise((resolve, reject) => {
29311
+ this.closeListeners.push({ resolve, reject });
29312
+ if (!this._closing) {
29313
+ this._closing = true;
29314
+ this.socket.close();
29315
+ }
29316
+ });
29317
+ }
29318
+ newSwapQuoteStream(params) {
29319
+ const requestId = this.nextRequestId();
29320
+ const promise = new Promise(
29321
+ (resolve, reject) => {
29322
+ this.pending.set(requestId, {
29323
+ resolve,
29324
+ reject,
29325
+ kind: "NewSwapQuoteStream"
29326
+ });
29327
+ }
29328
+ );
29329
+ const normalized = {
29330
+ ...params,
29331
+ swap: { ...params.swap, amount: toBigInt(params.swap.amount) }
29332
+ };
29333
+ const message = {
29334
+ id: requestId,
29335
+ data: { NewSwapQuoteStream: normalized }
29336
+ };
29337
+ this.send(message);
29338
+ return promise;
29339
+ }
29340
+ stopStream(streamId) {
29341
+ const requestId = this.nextRequestId();
29342
+ const promise = new Promise((resolve, reject) => {
29343
+ this.pending.set(requestId, {
29344
+ resolve,
29345
+ reject,
29346
+ kind: "StopStream"
29347
+ });
29348
+ });
29349
+ const message = {
29350
+ id: requestId,
29351
+ data: { StopStream: { id: streamId } }
29352
+ };
29353
+ this.send(message);
29354
+ return promise;
29355
+ }
29356
+ // --- Send ---
29357
+ send(message) {
29358
+ try {
29359
+ const encoded = encoder.encode(message);
29360
+ this.socket.send(encoded);
29361
+ } catch (err) {
29362
+ const req = this.pending.get(message.id);
29363
+ if (req) {
29364
+ this.pending.delete(message.id);
29365
+ req.reject(err);
29366
+ }
29367
+ }
29368
+ }
29369
+ // --- Message handling ---
29370
+ handleMessage(raw) {
29371
+ let buf;
29372
+ if (raw instanceof ArrayBuffer) {
29373
+ buf = new Uint8Array(raw);
29374
+ } else if (Buffer.isBuffer(raw)) {
29375
+ buf = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);
29376
+ } else if (Array.isArray(raw)) {
29377
+ buf = new Uint8Array(Buffer.concat(raw));
29378
+ } else {
29379
+ return;
29380
+ }
29381
+ let message;
29382
+ try {
29383
+ message = decoder.decode(buf);
29384
+ } catch {
29385
+ this.socket.close(3002, "failed to decode message");
29386
+ return;
29387
+ }
29388
+ if ("Response" in message) {
29389
+ this.handleResponse(message.Response);
29390
+ } else if ("Error" in message) {
29391
+ this.handleResponseError(message.Error);
29392
+ } else if ("StreamData" in message) {
29393
+ this.handleStreamData(message.StreamData);
29394
+ } else if ("StreamEnd" in message) {
29395
+ this.handleStreamEnd(message.StreamEnd);
29396
+ }
29397
+ }
29398
+ handleResponse(msg) {
29399
+ const req = this.pending.get(msg.requestId);
29400
+ if (!req) return;
29401
+ this.pending.delete(msg.requestId);
29402
+ if ("NewSwapQuoteStream" in msg.data && req.kind === "NewSwapQuoteStream") {
29403
+ const streamInfo = msg.stream;
29404
+ if (!streamInfo) {
29405
+ req.reject(new Error("No stream associated with NewSwapQuoteStream response"));
29406
+ return;
29407
+ }
29408
+ const stream = new ReadableStream({
29409
+ start: (controller) => {
29410
+ this.streams.set(streamInfo.id, controller);
29411
+ },
29412
+ cancel: () => {
29413
+ return this.cancelStream(streamInfo.id);
29414
+ }
29415
+ });
29416
+ const result = {
29417
+ response: msg.data.NewSwapQuoteStream,
29418
+ stream,
29419
+ streamId: streamInfo.id
29420
+ };
29421
+ req.resolve(result);
29422
+ } else if ("StreamStopped" in msg.data && req.kind === "StopStream") {
29423
+ req.resolve(msg.data.StreamStopped);
29424
+ } else {
29425
+ req.reject(new Error(`Unexpected response type for ${req.kind}`));
29426
+ }
29427
+ }
29428
+ handleResponseError(error) {
29429
+ const req = this.pending.get(error.requestId);
29430
+ if (!req) return;
29431
+ this.pending.delete(error.requestId);
29432
+ req.reject(new ErrorResponse(error));
29433
+ }
29434
+ handleStreamData(packet) {
29435
+ const controller = this.streams.get(packet.id);
29436
+ if (!controller) return;
29437
+ if (packet.payload.SwapQuotes !== void 0) {
29438
+ controller.enqueue(packet.payload.SwapQuotes);
29439
+ }
29440
+ }
29441
+ handleStreamEnd(packet) {
29442
+ const controller = this.streams.get(packet.id);
29443
+ if (!controller) return;
29444
+ this.streams.delete(packet.id);
29445
+ this.streamStopping.delete(packet.id);
29446
+ if (packet.errorCode !== void 0) {
29447
+ controller.error(new StreamError(packet));
29448
+ } else {
29449
+ controller.close();
29450
+ }
29451
+ }
29452
+ async cancelStream(streamId) {
29453
+ if (this.streamStopping.get(streamId) || !this.streams.has(streamId)) return;
29454
+ this.streamStopping.set(streamId, true);
29455
+ await this.stopStream(streamId);
29456
+ }
29457
+ // --- Connection lifecycle ---
29458
+ rejectAll(error) {
29459
+ for (const req of this.pending.values()) {
29460
+ req.reject(error);
29461
+ }
29462
+ this.pending.clear();
29463
+ for (const controller of this.streams.values()) {
29464
+ controller.error(error);
29465
+ }
29466
+ this.streams.clear();
29467
+ this.streamStopping.clear();
29468
+ }
29469
+ handleClose(code, reason) {
29470
+ this._closed = true;
29471
+ this.rejectAll(new ConnectionClosed(code, reason));
29472
+ for (const listener of this.closeListeners) {
29473
+ listener.resolve();
29474
+ }
29475
+ this.closeListeners = [];
29476
+ }
29477
+ handleError(err) {
29478
+ this.rejectAll(err);
29479
+ this.socket.close(3002);
29480
+ }
29481
+ };
29482
+
29483
+ // src/vendor/titan/types.ts
29484
+ var SwapMode = /* @__PURE__ */ ((SwapMode2) => {
29485
+ SwapMode2["ExactIn"] = "ExactIn";
29486
+ SwapMode2["ExactOut"] = "ExactOut";
29487
+ return SwapMode2;
29488
+ })(SwapMode || {});
29489
+ var SwapVersion = /* @__PURE__ */ ((SwapVersion2) => {
29490
+ SwapVersion2[SwapVersion2["V2"] = 2] = "V2";
29491
+ SwapVersion2[SwapVersion2["V3"] = 3] = "V3";
29492
+ return SwapVersion2;
29493
+ })(SwapVersion || {});
29494
+ function deserializeSerializedInstruction(ix) {
29495
+ return new web3_js.TransactionInstruction({
29496
+ programId: new web3_js.PublicKey(Buffer.from(ix.p, "base64")),
29497
+ keys: ix.a.map((account) => ({
29498
+ pubkey: new web3_js.PublicKey(Buffer.from(account.p, "base64")),
29499
+ isSigner: account.s,
29500
+ isWritable: account.w
29501
+ })),
29502
+ data: Buffer.from(ix.d, "base64")
29503
+ });
29504
+ }
29505
+ function selectBestRoute(quotes, swapMode) {
29506
+ const routes = Object.values(quotes);
29507
+ if (routes.length === 0) return null;
29508
+ return routes.reduce((best, route) => {
29509
+ if (swapMode === "ExactIn") {
29510
+ return route.outAmount > best.outAmount ? route : best;
29511
+ } else {
29512
+ return route.inAmount < best.inAmount ? route : best;
29513
+ }
29514
+ });
29515
+ }
29516
+ function buildSwapQuoteResult(route, swapMode) {
29517
+ const slippageBps = route.slippageBps;
29518
+ let otherAmountThreshold;
29519
+ if (swapMode === "ExactIn") {
29520
+ otherAmountThreshold = String(Math.floor(route.outAmount * (1 - slippageBps / 1e4)));
29521
+ } else {
29522
+ otherAmountThreshold = String(Math.ceil(route.inAmount * (1 + slippageBps / 1e4)));
29523
+ }
29524
+ return {
29525
+ inAmount: String(route.inAmount),
29526
+ outAmount: String(route.outAmount),
29527
+ otherAmountThreshold,
29528
+ slippageBps,
29529
+ platformFee: route.platformFee ? {
29530
+ amount: String(route.platformFee.amount),
29531
+ feeBps: route.platformFee.fee_bps
29532
+ } : void 0,
29533
+ contextSlot: route.contextSlot,
29534
+ timeTaken: route.timeTaken
29535
+ };
29536
+ }
29537
+ async function resolveLookupTables(connection, lutPubkeys) {
29538
+ if (lutPubkeys.length === 0) return [];
29539
+ const lutAccountsRaw = await connection.getMultipleAccountsInfo(lutPubkeys);
29540
+ return lutAccountsRaw.map((accountInfo, index) => {
29541
+ if (!accountInfo) return null;
29542
+ return new web3_js.AddressLookupTableAccount({
29543
+ key: lutPubkeys[index],
29544
+ state: web3_js.AddressLookupTableAccount.deserialize(accountInfo.data)
29545
+ });
29546
+ }).filter((account) => account !== null);
29547
+ }
29193
29548
 
29194
29549
  exports.ACCOUNT_SIZE = ACCOUNT_SIZE;
29195
29550
  exports.ACCOUNT_TYPE_SIZE = ACCOUNT_TYPE_SIZE;
@@ -29197,11 +29552,13 @@ exports.ASSOCIATED_TOKEN_PROGRAM_ID = ASSOCIATED_TOKEN_PROGRAM_ID;
29197
29552
  exports.AccountLayout = AccountLayout;
29198
29553
  exports.AccountState = AccountState;
29199
29554
  exports.AccountType = AccountType;
29555
+ exports.ConnectionClosed = ConnectionClosed;
29200
29556
  exports.CorpAction = CorpAction;
29201
29557
  exports.DEFAULT_RECENT_SLOT_DURATION_MS = DEFAULT_RECENT_SLOT_DURATION_MS;
29202
29558
  exports.DRIFT_IDL = DRIFT_IDL;
29203
29559
  exports.DRIFT_PROGRAM_ID = DRIFT_PROGRAM_ID;
29204
29560
  exports.DriftSpotBalanceType = DriftSpotBalanceType;
29561
+ exports.ErrorResponse = ErrorResponse;
29205
29562
  exports.ExtensionType = ExtensionType;
29206
29563
  exports.FARMS_PROGRAM_ID = FARMS_PROGRAM_ID;
29207
29564
  exports.JUP_EXCHANGE_PRICES_PRECISION = JUP_EXCHANGE_PRICES_PRECISION;
@@ -29269,6 +29626,9 @@ exports.SWITCHBOARD_ONDEMANDE_PRICE_PRECISION = SWITCHBOARD_ONDEMANDE_PRICE_PREC
29269
29626
  exports.SinglePoolInstruction = SinglePoolInstruction;
29270
29627
  exports.SplAccountType = SplAccountType;
29271
29628
  exports.SpotBalanceType = SpotBalanceType;
29629
+ exports.StreamError = StreamError;
29630
+ exports.SwapMode = SwapMode;
29631
+ exports.SwapVersion = SwapVersion;
29272
29632
  exports.TEN = TEN;
29273
29633
  exports.TOKEN_2022_PROGRAM_ID = TOKEN_2022_PROGRAM_ID;
29274
29634
  exports.TOKEN_PROGRAM_ID = TOKEN_PROGRAM_ID;
@@ -29287,9 +29647,11 @@ exports.TokenInvalidMintError = TokenInvalidMintError;
29287
29647
  exports.TokenInvalidOwnerError = TokenInvalidOwnerError;
29288
29648
  exports.TokenOwnerOffCurveError = TokenOwnerOffCurveError;
29289
29649
  exports.TokenUnsupportedInstructionError = TokenUnsupportedInstructionError;
29650
+ exports.V1Client = V1Client;
29290
29651
  exports.ZERO = ZERO;
29291
29652
  exports.addSigners = addSigners;
29292
29653
  exports.approveInstructionData = approveInstructionData;
29654
+ exports.buildSwapQuoteResult = buildSwapQuoteResult;
29293
29655
  exports.calculateAPYFromAPR = calculateAPYFromAPR;
29294
29656
  exports.calculateDriftBorrowAPR = calculateDriftBorrowAPR;
29295
29657
  exports.calculateDriftBorrowAPY = calculateDriftBorrowAPY;
@@ -29365,6 +29727,7 @@ exports.deriveReserveLiquiditySupply = deriveReserveLiquiditySupply;
29365
29727
  exports.deriveShortUrl = deriveShortUrl;
29366
29728
  exports.deriveUserMetadata = deriveUserMetadata;
29367
29729
  exports.deriveUserState = deriveUserState;
29730
+ exports.deserializeSerializedInstruction = deserializeSerializedInstruction;
29368
29731
  exports.driftRewardsRawToDto = driftRewardsRawToDto;
29369
29732
  exports.driftSpotMarketRawToDto = driftSpotMarketRawToDto;
29370
29733
  exports.driftStateRawToDto = driftStateRawToDto;
@@ -29439,7 +29802,9 @@ exports.parsePriceData = parsePriceData;
29439
29802
  exports.parsePriceInfo = parsePriceInfo2;
29440
29803
  exports.replenishPoolIx = replenishPoolIx;
29441
29804
  exports.reserveRawToDto = reserveRawToDto;
29805
+ exports.resolveLookupTables = resolveLookupTables;
29442
29806
  exports.scaledSupplies = scaledSupplies;
29807
+ exports.selectBestRoute = selectBestRoute;
29443
29808
  exports.slotAdjustmentFactor = slotAdjustmentFactor;
29444
29809
  exports.switchboardAccountCoder = switchboardAccountCoder;
29445
29810
  exports.syncNativeInstructionData = syncNativeInstructionData;