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

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,342 @@ 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
+ ws.on("open", () => {
29265
+ resolve(new _V1Client(ws));
29266
+ });
29267
+ ws.on("error", (err) => {
29268
+ reject(err);
29269
+ });
29270
+ });
29271
+ }
29272
+ // --- Constructor ---
29273
+ constructor(socket) {
29274
+ this.socket = socket;
29275
+ this.socket.on("message", (data) => {
29276
+ this.handleMessage(data);
29277
+ });
29278
+ this.socket.on("close", (code, reason) => {
29279
+ this.handleClose(code, reason.toString());
29280
+ });
29281
+ this.socket.on("error", (err) => {
29282
+ this.handleError(err);
29283
+ });
29284
+ }
29285
+ nextRequestId() {
29286
+ return this.nextId++;
29287
+ }
29288
+ // --- Public API ---
29289
+ get closed() {
29290
+ return this._closed;
29291
+ }
29292
+ close() {
29293
+ if (this._closed) return Promise.resolve();
29294
+ return new Promise((resolve, reject) => {
29295
+ this.closeListeners.push({ resolve, reject });
29296
+ if (!this._closing) {
29297
+ this._closing = true;
29298
+ this.socket.close();
29299
+ }
29300
+ });
29301
+ }
29302
+ newSwapQuoteStream(params) {
29303
+ const requestId = this.nextRequestId();
29304
+ const promise = new Promise(
29305
+ (resolve, reject) => {
29306
+ this.pending.set(requestId, {
29307
+ resolve,
29308
+ reject,
29309
+ kind: "NewSwapQuoteStream"
29310
+ });
29311
+ }
29312
+ );
29313
+ const normalized = {
29314
+ ...params,
29315
+ swap: { ...params.swap, amount: toBigInt(params.swap.amount) }
29316
+ };
29317
+ const message = {
29318
+ id: requestId,
29319
+ data: { NewSwapQuoteStream: normalized }
29320
+ };
29321
+ this.send(message);
29322
+ return promise;
29323
+ }
29324
+ stopStream(streamId) {
29325
+ const requestId = this.nextRequestId();
29326
+ const promise = new Promise((resolve, reject) => {
29327
+ this.pending.set(requestId, {
29328
+ resolve,
29329
+ reject,
29330
+ kind: "StopStream"
29331
+ });
29332
+ });
29333
+ const message = {
29334
+ id: requestId,
29335
+ data: { StopStream: { id: streamId } }
29336
+ };
29337
+ this.send(message);
29338
+ return promise;
29339
+ }
29340
+ // --- Send ---
29341
+ send(message) {
29342
+ try {
29343
+ const encoded = encoder.encode(message);
29344
+ this.socket.send(encoded);
29345
+ } catch (err) {
29346
+ const req = this.pending.get(message.id);
29347
+ if (req) {
29348
+ this.pending.delete(message.id);
29349
+ req.reject(err);
29350
+ }
29351
+ }
29352
+ }
29353
+ // --- Message handling ---
29354
+ handleMessage(raw) {
29355
+ let buf;
29356
+ if (raw instanceof ArrayBuffer) {
29357
+ buf = new Uint8Array(raw);
29358
+ } else if (Buffer.isBuffer(raw)) {
29359
+ buf = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);
29360
+ } else if (Array.isArray(raw)) {
29361
+ buf = new Uint8Array(Buffer.concat(raw));
29362
+ } else {
29363
+ return;
29364
+ }
29365
+ let message;
29366
+ try {
29367
+ message = decoder.decode(buf);
29368
+ } catch {
29369
+ this.socket.close(3002, "failed to decode message");
29370
+ return;
29371
+ }
29372
+ if ("Response" in message) {
29373
+ this.handleResponse(message.Response);
29374
+ } else if ("Error" in message) {
29375
+ this.handleResponseError(message.Error);
29376
+ } else if ("StreamData" in message) {
29377
+ this.handleStreamData(message.StreamData);
29378
+ } else if ("StreamEnd" in message) {
29379
+ this.handleStreamEnd(message.StreamEnd);
29380
+ }
29381
+ }
29382
+ handleResponse(msg) {
29383
+ const req = this.pending.get(msg.requestId);
29384
+ if (!req) return;
29385
+ this.pending.delete(msg.requestId);
29386
+ if ("NewSwapQuoteStream" in msg.data && req.kind === "NewSwapQuoteStream") {
29387
+ const streamInfo = msg.stream;
29388
+ if (!streamInfo) {
29389
+ req.reject(new Error("No stream associated with NewSwapQuoteStream response"));
29390
+ return;
29391
+ }
29392
+ const stream = new ReadableStream({
29393
+ start: (controller) => {
29394
+ this.streams.set(streamInfo.id, controller);
29395
+ },
29396
+ cancel: () => {
29397
+ return this.cancelStream(streamInfo.id);
29398
+ }
29399
+ });
29400
+ const result = {
29401
+ response: msg.data.NewSwapQuoteStream,
29402
+ stream,
29403
+ streamId: streamInfo.id
29404
+ };
29405
+ req.resolve(result);
29406
+ } else if ("StreamStopped" in msg.data && req.kind === "StopStream") {
29407
+ req.resolve(msg.data.StreamStopped);
29408
+ } else {
29409
+ req.reject(new Error(`Unexpected response type for ${req.kind}`));
29410
+ }
29411
+ }
29412
+ handleResponseError(error) {
29413
+ const req = this.pending.get(error.requestId);
29414
+ if (!req) return;
29415
+ this.pending.delete(error.requestId);
29416
+ req.reject(new ErrorResponse(error));
29417
+ }
29418
+ handleStreamData(packet) {
29419
+ const controller = this.streams.get(packet.id);
29420
+ if (!controller) return;
29421
+ if (packet.payload.SwapQuotes !== void 0) {
29422
+ controller.enqueue(packet.payload.SwapQuotes);
29423
+ }
29424
+ }
29425
+ handleStreamEnd(packet) {
29426
+ const controller = this.streams.get(packet.id);
29427
+ if (!controller) return;
29428
+ this.streams.delete(packet.id);
29429
+ this.streamStopping.delete(packet.id);
29430
+ if (packet.errorCode !== void 0) {
29431
+ controller.error(new StreamError(packet));
29432
+ } else {
29433
+ controller.close();
29434
+ }
29435
+ }
29436
+ async cancelStream(streamId) {
29437
+ if (this.streamStopping.get(streamId) || !this.streams.has(streamId)) return;
29438
+ this.streamStopping.set(streamId, true);
29439
+ await this.stopStream(streamId);
29440
+ }
29441
+ // --- Connection lifecycle ---
29442
+ rejectAll(error) {
29443
+ for (const req of this.pending.values()) {
29444
+ req.reject(error);
29445
+ }
29446
+ this.pending.clear();
29447
+ for (const controller of this.streams.values()) {
29448
+ controller.error(error);
29449
+ }
29450
+ this.streams.clear();
29451
+ this.streamStopping.clear();
29452
+ }
29453
+ handleClose(code, reason) {
29454
+ this._closed = true;
29455
+ this.rejectAll(new ConnectionClosed(code, reason));
29456
+ for (const listener of this.closeListeners) {
29457
+ listener.resolve();
29458
+ }
29459
+ this.closeListeners = [];
29460
+ }
29461
+ handleError(err) {
29462
+ this.rejectAll(err);
29463
+ this.socket.close(3002);
29464
+ }
29465
+ };
29466
+
29467
+ // src/vendor/titan/types.ts
29468
+ var SwapMode = /* @__PURE__ */ ((SwapMode2) => {
29469
+ SwapMode2["ExactIn"] = "ExactIn";
29470
+ SwapMode2["ExactOut"] = "ExactOut";
29471
+ return SwapMode2;
29472
+ })(SwapMode || {});
29473
+ var SwapVersion = /* @__PURE__ */ ((SwapVersion2) => {
29474
+ SwapVersion2[SwapVersion2["V2"] = 2] = "V2";
29475
+ SwapVersion2[SwapVersion2["V3"] = 3] = "V3";
29476
+ return SwapVersion2;
29477
+ })(SwapVersion || {});
29478
+ function deserializeSerializedInstruction(ix) {
29479
+ return new web3_js.TransactionInstruction({
29480
+ programId: new web3_js.PublicKey(Buffer.from(ix.p, "base64")),
29481
+ keys: ix.a.map((account) => ({
29482
+ pubkey: new web3_js.PublicKey(Buffer.from(account.p, "base64")),
29483
+ isSigner: account.s,
29484
+ isWritable: account.w
29485
+ })),
29486
+ data: Buffer.from(ix.d, "base64")
29487
+ });
29488
+ }
29489
+ function selectBestRoute(quotes, swapMode) {
29490
+ const routes = Object.values(quotes);
29491
+ if (routes.length === 0) return null;
29492
+ return routes.reduce((best, route) => {
29493
+ if (swapMode === "ExactIn") {
29494
+ return route.outAmount > best.outAmount ? route : best;
29495
+ } else {
29496
+ return route.inAmount < best.inAmount ? route : best;
29497
+ }
29498
+ });
29499
+ }
29500
+ function buildSwapQuoteResult(route, swapMode) {
29501
+ const slippageBps = route.slippageBps;
29502
+ let otherAmountThreshold;
29503
+ if (swapMode === "ExactIn") {
29504
+ otherAmountThreshold = String(Math.floor(route.outAmount * (1 - slippageBps / 1e4)));
29505
+ } else {
29506
+ otherAmountThreshold = String(Math.ceil(route.inAmount * (1 + slippageBps / 1e4)));
29507
+ }
29508
+ return {
29509
+ inAmount: String(route.inAmount),
29510
+ outAmount: String(route.outAmount),
29511
+ otherAmountThreshold,
29512
+ slippageBps,
29513
+ platformFee: route.platformFee ? {
29514
+ amount: String(route.platformFee.amount),
29515
+ feeBps: route.platformFee.fee_bps
29516
+ } : void 0,
29517
+ contextSlot: route.contextSlot,
29518
+ timeTaken: route.timeTaken
29519
+ };
29520
+ }
29521
+ async function resolveLookupTables(connection, lutPubkeys) {
29522
+ if (lutPubkeys.length === 0) return [];
29523
+ const lutAccountsRaw = await connection.getMultipleAccountsInfo(lutPubkeys);
29524
+ return lutAccountsRaw.map((accountInfo, index) => {
29525
+ if (!accountInfo) return null;
29526
+ return new web3_js.AddressLookupTableAccount({
29527
+ key: lutPubkeys[index],
29528
+ state: web3_js.AddressLookupTableAccount.deserialize(accountInfo.data)
29529
+ });
29530
+ }).filter((account) => account !== null);
29531
+ }
29193
29532
 
29194
29533
  exports.ACCOUNT_SIZE = ACCOUNT_SIZE;
29195
29534
  exports.ACCOUNT_TYPE_SIZE = ACCOUNT_TYPE_SIZE;
@@ -29197,11 +29536,13 @@ exports.ASSOCIATED_TOKEN_PROGRAM_ID = ASSOCIATED_TOKEN_PROGRAM_ID;
29197
29536
  exports.AccountLayout = AccountLayout;
29198
29537
  exports.AccountState = AccountState;
29199
29538
  exports.AccountType = AccountType;
29539
+ exports.ConnectionClosed = ConnectionClosed;
29200
29540
  exports.CorpAction = CorpAction;
29201
29541
  exports.DEFAULT_RECENT_SLOT_DURATION_MS = DEFAULT_RECENT_SLOT_DURATION_MS;
29202
29542
  exports.DRIFT_IDL = DRIFT_IDL;
29203
29543
  exports.DRIFT_PROGRAM_ID = DRIFT_PROGRAM_ID;
29204
29544
  exports.DriftSpotBalanceType = DriftSpotBalanceType;
29545
+ exports.ErrorResponse = ErrorResponse;
29205
29546
  exports.ExtensionType = ExtensionType;
29206
29547
  exports.FARMS_PROGRAM_ID = FARMS_PROGRAM_ID;
29207
29548
  exports.JUP_EXCHANGE_PRICES_PRECISION = JUP_EXCHANGE_PRICES_PRECISION;
@@ -29269,6 +29610,9 @@ exports.SWITCHBOARD_ONDEMANDE_PRICE_PRECISION = SWITCHBOARD_ONDEMANDE_PRICE_PREC
29269
29610
  exports.SinglePoolInstruction = SinglePoolInstruction;
29270
29611
  exports.SplAccountType = SplAccountType;
29271
29612
  exports.SpotBalanceType = SpotBalanceType;
29613
+ exports.StreamError = StreamError;
29614
+ exports.SwapMode = SwapMode;
29615
+ exports.SwapVersion = SwapVersion;
29272
29616
  exports.TEN = TEN;
29273
29617
  exports.TOKEN_2022_PROGRAM_ID = TOKEN_2022_PROGRAM_ID;
29274
29618
  exports.TOKEN_PROGRAM_ID = TOKEN_PROGRAM_ID;
@@ -29287,9 +29631,11 @@ exports.TokenInvalidMintError = TokenInvalidMintError;
29287
29631
  exports.TokenInvalidOwnerError = TokenInvalidOwnerError;
29288
29632
  exports.TokenOwnerOffCurveError = TokenOwnerOffCurveError;
29289
29633
  exports.TokenUnsupportedInstructionError = TokenUnsupportedInstructionError;
29634
+ exports.V1Client = V1Client;
29290
29635
  exports.ZERO = ZERO;
29291
29636
  exports.addSigners = addSigners;
29292
29637
  exports.approveInstructionData = approveInstructionData;
29638
+ exports.buildSwapQuoteResult = buildSwapQuoteResult;
29293
29639
  exports.calculateAPYFromAPR = calculateAPYFromAPR;
29294
29640
  exports.calculateDriftBorrowAPR = calculateDriftBorrowAPR;
29295
29641
  exports.calculateDriftBorrowAPY = calculateDriftBorrowAPY;
@@ -29365,6 +29711,7 @@ exports.deriveReserveLiquiditySupply = deriveReserveLiquiditySupply;
29365
29711
  exports.deriveShortUrl = deriveShortUrl;
29366
29712
  exports.deriveUserMetadata = deriveUserMetadata;
29367
29713
  exports.deriveUserState = deriveUserState;
29714
+ exports.deserializeSerializedInstruction = deserializeSerializedInstruction;
29368
29715
  exports.driftRewardsRawToDto = driftRewardsRawToDto;
29369
29716
  exports.driftSpotMarketRawToDto = driftSpotMarketRawToDto;
29370
29717
  exports.driftStateRawToDto = driftStateRawToDto;
@@ -29439,7 +29786,9 @@ exports.parsePriceData = parsePriceData;
29439
29786
  exports.parsePriceInfo = parsePriceInfo2;
29440
29787
  exports.replenishPoolIx = replenishPoolIx;
29441
29788
  exports.reserveRawToDto = reserveRawToDto;
29789
+ exports.resolveLookupTables = resolveLookupTables;
29442
29790
  exports.scaledSupplies = scaledSupplies;
29791
+ exports.selectBestRoute = selectBestRoute;
29443
29792
  exports.slotAdjustmentFactor = slotAdjustmentFactor;
29444
29793
  exports.switchboardAccountCoder = switchboardAccountCoder;
29445
29794
  exports.syncNativeInstructionData = syncNativeInstructionData;