@carrot-protocol/boost-http-client 0.1.1 → 0.1.2-test-api-dev-1a330b5

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.d.ts CHANGED
@@ -7,35 +7,51 @@ export * from "./types";
7
7
  export declare class Client {
8
8
  private readonly baseUrl;
9
9
  private readonly http;
10
- private readonly provider?;
10
+ private readonly provider;
11
11
  /**
12
12
  * Create a new Carrot Boost API client
13
13
  * @param baseUrl Base URL for the API
14
14
  */
15
15
  constructor(baseUrl: string, provider?: AnchorProvider);
16
+ address(): web3.PublicKey;
16
17
  private send;
18
+ /**
19
+ * Get index details
20
+ * @returns Index details
21
+ */
22
+ index(): Promise<any>;
17
23
  /**
18
24
  * Get obligation details for a wallet
19
25
  * @param owner Owner wallet public key
20
26
  * @returns Obligation details
21
27
  */
22
28
  getObligation(owner: web3.PublicKey): Promise<any>;
29
+ /**
30
+ * Get market details for the carrot boost market
31
+ * @returns Market details
32
+ */
33
+ getMarket(): Promise<any>;
34
+ /**
35
+ * Create an obligation for the client
36
+ * @returns Transaction signature
37
+ */
38
+ createObligation(): Promise<string>;
23
39
  /**
24
40
  * Deposit collateral and create a leveraged position
25
41
  * @param request Deposit leverage request parameters
26
42
  * @returns Deposit leverage operation result
27
43
  */
28
- depositLeverage(request: DepositLeverageRequest): Promise<string>;
44
+ depositLeverage(params: DepositLeverageRequest): Promise<string>;
29
45
  /**
30
46
  * Modify the leverage of an existing position
31
47
  * @param request Modify leverage request parameters
32
48
  * @returns Modify leverage operation result
33
49
  */
34
- modifyLeverage(request: ModifyLeverageRequest): Promise<any>;
50
+ modifyLeverage(params: ModifyLeverageRequest): Promise<any>;
35
51
  /**
36
52
  * Withdraw from or close a leveraged position
37
53
  * @param request Withdraw leverage request parameters
38
54
  * @returns Withdraw leverage operation result
39
55
  */
40
- withdrawLeverage(request: WithdrawLeverageRequest): Promise<any>;
56
+ withdrawLeverage(params: WithdrawLeverageRequest): Promise<any>;
41
57
  }
package/dist/index.js CHANGED
@@ -10,6 +10,28 @@ var __createBinding = (this && this.__createBinding) || (Object.create ? (functi
10
10
  if (k2 === undefined) k2 = k;
11
11
  o[k2] = m[k];
12
12
  }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
13
35
  var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
36
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
37
  };
@@ -18,7 +40,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
18
40
  };
19
41
  Object.defineProperty(exports, "__esModule", { value: true });
20
42
  exports.Client = void 0;
21
- const axios_1 = __importDefault(require("axios"));
43
+ const axios_1 = __importStar(require("axios"));
22
44
  const anchor_1 = require("@coral-xyz/anchor");
23
45
  const bs58_1 = __importDefault(require("bs58"));
24
46
  // Re-export types
@@ -39,12 +61,16 @@ class Client {
39
61
  "Content-Type": "application/json",
40
62
  },
41
63
  });
64
+ if (!provider) {
65
+ provider = getDummyProvider();
66
+ }
42
67
  this.provider = provider;
43
68
  }
69
+ address() {
70
+ return this.provider.wallet.publicKey;
71
+ }
44
72
  // sign and send tx to api for sending to network
45
73
  async send(base64Tx) {
46
- // error if provider is undefined
47
- requireProvider(this.provider);
48
74
  // deserialize into tx obj
49
75
  const txBytes = Buffer.from(base64Tx, "base64");
50
76
  const tx = anchor_1.web3.VersionedTransaction.deserialize(new Uint8Array(txBytes));
@@ -58,34 +84,53 @@ class Client {
58
84
  tx: encodedAndSignedTx,
59
85
  };
60
86
  // send to api
61
- const response = await this.http.post(`${this.baseUrl}/send`, sendRequest);
62
- handleStatusCode(response.status);
87
+ await handleApiCall(() => this.http.post(`send`, sendRequest));
63
88
  // return txsig
64
89
  return bs58_1.default.encode(txSig);
65
90
  }
91
+ /**
92
+ * Get index details
93
+ * @returns Index details
94
+ */
95
+ async index() {
96
+ return handleApiCall(() => this.http.get(""));
97
+ }
66
98
  /**
67
99
  * Get obligation details for a wallet
68
100
  * @param owner Owner wallet public key
69
101
  * @returns Obligation details
70
102
  */
71
103
  async getObligation(owner) {
72
- const response = await this.http.get(`/obligation?owner=${owner.toString()}`);
73
- handleStatusCode(response.status);
74
- return JSON.stringify(response.data);
104
+ const body = await handleApiCall(() => this.http.get(`/obligation?owner=${owner.toString()}`));
105
+ return body;
106
+ }
107
+ /**
108
+ * Get market details for the carrot boost market
109
+ * @returns Market details
110
+ */
111
+ async getMarket() {
112
+ const body = await handleApiCall(() => this.http.get(`market`));
113
+ return body;
114
+ }
115
+ /**
116
+ * Create an obligation for the client
117
+ * @returns Transaction signature
118
+ */
119
+ async createObligation() {
120
+ const body = await handleApiCall(() => this.http.post("createObligation", JSON.stringify({ owner: this.address() })));
121
+ const createObligationResponse = JSON.parse(body);
122
+ const txSig = await this.send(createObligationResponse.unsignedBase64Tx);
123
+ return txSig;
75
124
  }
76
125
  /**
77
126
  * Deposit collateral and create a leveraged position
78
127
  * @param request Deposit leverage request parameters
79
128
  * @returns Deposit leverage operation result
80
129
  */
81
- async depositLeverage(request) {
82
- const response = await this.http.post("/leverage/deposit", request);
83
- // check http status code
84
- handleStatusCode(response.status);
85
- // parse response
86
- const responseData = JSON.parse(response.data);
87
- // sign and send signed tx back to api for sending to network
88
- const txSig = await this.send(responseData.unsignedBase64Tx);
130
+ async depositLeverage(params) {
131
+ const body = await handleApiCall(() => this.http.post("leverage/deposit", JSON.stringify(params)));
132
+ const depositLeverageResponse = JSON.parse(body);
133
+ const txSig = await this.send(depositLeverageResponse.unsignedBase64Tx);
89
134
  return txSig;
90
135
  }
91
136
  /**
@@ -93,14 +138,10 @@ class Client {
93
138
  * @param request Modify leverage request parameters
94
139
  * @returns Modify leverage operation result
95
140
  */
96
- async modifyLeverage(request) {
97
- const response = await this.http.post("/leverage/modify", request);
98
- // check http status code
99
- handleStatusCode(response.status);
100
- // parse response
101
- const responseData = JSON.parse(response.data);
102
- // sign and send signed tx back to api for sending to network
103
- const txSig = await this.send(responseData.unsignedBase64Tx);
141
+ async modifyLeverage(params) {
142
+ const body = await handleApiCall(() => this.http.post("leverage/modify", JSON.stringify(params)));
143
+ const modifyLeverageResponse = JSON.parse(body);
144
+ const txSig = await this.send(modifyLeverageResponse.unsignedBase64Tx);
104
145
  return txSig;
105
146
  }
106
147
  /**
@@ -108,14 +149,10 @@ class Client {
108
149
  * @param request Withdraw leverage request parameters
109
150
  * @returns Withdraw leverage operation result
110
151
  */
111
- async withdrawLeverage(request) {
112
- const response = await this.http.post("/leverage/withdraw", request);
113
- // check http status code
114
- handleStatusCode(response.status);
115
- // parse response
116
- const responseData = JSON.parse(response.data);
117
- // sign and send signed tx back to api for sending to network
118
- const txSig = await this.send(responseData.unsignedBase64Tx);
152
+ async withdrawLeverage(params) {
153
+ const body = await handleApiCall(() => this.http.post("leverage/withdraw", JSON.stringify(params)));
154
+ const withdrawLeverageResponse = JSON.parse(body);
155
+ const txSig = await this.send(withdrawLeverageResponse.unsignedBase64Tx);
119
156
  return txSig;
120
157
  }
121
158
  }
@@ -125,13 +162,31 @@ function handleStatusCode(statusCode) {
125
162
  case 200:
126
163
  break;
127
164
  default:
128
- throw new Error(`unexpected status code${statusCode}`);
165
+ throw new Error(`unexpected status code: ${statusCode}`);
129
166
  }
130
167
  }
131
- // Ensures that a provider is defined
132
- function requireProvider(provider) {
133
- if (provider) {
134
- return;
168
+ // Helper function to handle API calls
169
+ async function handleApiCall(apiCall) {
170
+ try {
171
+ const response = await apiCall();
172
+ handleStatusCode(response.status);
173
+ return JSON.stringify(response.data);
135
174
  }
136
- throw new Error(`provider is undefined`);
175
+ catch (error) {
176
+ if (error instanceof axios_1.AxiosError) {
177
+ const simplifiedError = {
178
+ status: error.response?.status,
179
+ message: error.message,
180
+ url: error.config?.url,
181
+ };
182
+ console.error(simplifiedError);
183
+ throw new Error(JSON.stringify(simplifiedError));
184
+ }
185
+ throw error;
186
+ }
187
+ }
188
+ function getDummyProvider() {
189
+ return new anchor_1.AnchorProvider(new anchor_1.web3.Connection("http://localhost:8899"), new anchor_1.Wallet(anchor_1.web3.Keypair.generate()), {
190
+ skipPreflight: false,
191
+ });
137
192
  }
package/dist/types.d.ts CHANGED
@@ -3,6 +3,12 @@ import Decimal from "decimal.js";
3
3
  export interface SendRequest {
4
4
  tx: string;
5
5
  }
6
+ export interface CreateObligationRequest {
7
+ owner: web3.PublicKey;
8
+ }
9
+ export interface CreateObligationResponse {
10
+ unsignedBase64Tx: string;
11
+ }
6
12
  /**
7
13
  * Request to deposit collateral and create a leveraged position
8
14
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@carrot-protocol/boost-http-client",
3
- "version": "0.1.1",
3
+ "version": "0.1.2-test-api-dev-1a330b5",
4
4
  "description": "HTTP client for Carrot Boost API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
- import axios, { AxiosInstance } from "axios";
2
- import { AnchorProvider, web3 } from "@coral-xyz/anchor";
1
+ import axios, { AxiosInstance, AxiosError, AxiosResponse } from "axios";
2
+ import { AnchorProvider, Wallet, web3 } from "@coral-xyz/anchor";
3
3
  import {
4
+ CreateObligationResponse,
4
5
  DepositLeverageRequest,
5
6
  DepositLeverageResponse,
6
7
  ModifyLeverageRequest,
@@ -20,7 +21,7 @@ export * from "./types";
20
21
  export class Client {
21
22
  private readonly baseUrl: string;
22
23
  private readonly http: AxiosInstance;
23
- private readonly provider?: AnchorProvider;
24
+ private readonly provider: AnchorProvider;
24
25
 
25
26
  /**
26
27
  * Create a new Carrot Boost API client
@@ -34,14 +35,18 @@ export class Client {
34
35
  "Content-Type": "application/json",
35
36
  },
36
37
  });
38
+ if (!provider) {
39
+ provider = getDummyProvider();
40
+ }
37
41
  this.provider = provider;
38
42
  }
39
43
 
44
+ address(): web3.PublicKey {
45
+ return this.provider!.wallet.publicKey;
46
+ }
47
+
40
48
  // sign and send tx to api for sending to network
41
49
  private async send(base64Tx: string): Promise<string> {
42
- // error if provider is undefined
43
- requireProvider(this.provider);
44
-
45
50
  // deserialize into tx obj
46
51
  const txBytes = Buffer.from(base64Tx, "base64");
47
52
  const tx = web3.VersionedTransaction.deserialize(new Uint8Array(txBytes));
@@ -61,24 +66,58 @@ export class Client {
61
66
  };
62
67
 
63
68
  // send to api
64
- const response = await this.http.post(`${this.baseUrl}/send`, sendRequest);
65
- handleStatusCode(response.status);
69
+ await handleApiCall(() => this.http.post(`send`, sendRequest));
66
70
 
67
71
  // return txsig
68
72
  return encode.encode(txSig);
69
73
  }
70
74
 
75
+ /**
76
+ * Get index details
77
+ * @returns Index details
78
+ */
79
+ async index(): Promise<any> {
80
+ return handleApiCall(() => this.http.get(""));
81
+ }
82
+
71
83
  /**
72
84
  * Get obligation details for a wallet
73
85
  * @param owner Owner wallet public key
74
86
  * @returns Obligation details
75
87
  */
76
88
  async getObligation(owner: web3.PublicKey): Promise<any> {
77
- const response = await this.http.get(
78
- `/obligation?owner=${owner.toString()}`,
89
+ const body = await handleApiCall(() =>
90
+ this.http.get(`/obligation?owner=${owner.toString()}`),
79
91
  );
80
- handleStatusCode(response.status);
81
- return JSON.stringify(response.data);
92
+ return body;
93
+ }
94
+
95
+ /**
96
+ * Get market details for the carrot boost market
97
+ * @returns Market details
98
+ */
99
+ async getMarket(): Promise<any> {
100
+ const body = await handleApiCall(() => this.http.get(`market`));
101
+ return body;
102
+ }
103
+
104
+ /**
105
+ * Create an obligation for the client
106
+ * @returns Transaction signature
107
+ */
108
+ async createObligation(): Promise<string> {
109
+ const body = await handleApiCall(() =>
110
+ this.http.post(
111
+ "createObligation",
112
+ JSON.stringify({ owner: this.address() }),
113
+ ),
114
+ );
115
+
116
+ const createObligationResponse: CreateObligationResponse = JSON.parse(body);
117
+
118
+ const txSig = await this.send(createObligationResponse.unsignedBase64Tx);
119
+
120
+ return txSig;
82
121
  }
83
122
 
84
123
  /**
@@ -86,17 +125,14 @@ export class Client {
86
125
  * @param request Deposit leverage request parameters
87
126
  * @returns Deposit leverage operation result
88
127
  */
89
- async depositLeverage(request: DepositLeverageRequest): Promise<string> {
90
- const response = await this.http.post("/leverage/deposit", request);
91
-
92
- // check http status code
93
- handleStatusCode(response.status);
128
+ async depositLeverage(params: DepositLeverageRequest): Promise<string> {
129
+ const body = await handleApiCall(() =>
130
+ this.http.post("leverage/deposit", JSON.stringify(params)),
131
+ );
94
132
 
95
- // parse response
96
- const responseData: DepositLeverageResponse = JSON.parse(response.data);
133
+ const depositLeverageResponse: DepositLeverageResponse = JSON.parse(body);
97
134
 
98
- // sign and send signed tx back to api for sending to network
99
- const txSig = await this.send(responseData.unsignedBase64Tx);
135
+ const txSig = await this.send(depositLeverageResponse.unsignedBase64Tx);
100
136
 
101
137
  return txSig;
102
138
  }
@@ -106,17 +142,14 @@ export class Client {
106
142
  * @param request Modify leverage request parameters
107
143
  * @returns Modify leverage operation result
108
144
  */
109
- async modifyLeverage(request: ModifyLeverageRequest): Promise<any> {
110
- const response = await this.http.post("/leverage/modify", request);
111
-
112
- // check http status code
113
- handleStatusCode(response.status);
145
+ async modifyLeverage(params: ModifyLeverageRequest): Promise<any> {
146
+ const body = await handleApiCall(() =>
147
+ this.http.post("leverage/modify", JSON.stringify(params)),
148
+ );
114
149
 
115
- // parse response
116
- const responseData: ModifyLeverageResponse = JSON.parse(response.data);
150
+ const modifyLeverageResponse: ModifyLeverageResponse = JSON.parse(body);
117
151
 
118
- // sign and send signed tx back to api for sending to network
119
- const txSig = await this.send(responseData.unsignedBase64Tx);
152
+ const txSig = await this.send(modifyLeverageResponse.unsignedBase64Tx);
120
153
 
121
154
  return txSig;
122
155
  }
@@ -126,17 +159,14 @@ export class Client {
126
159
  * @param request Withdraw leverage request parameters
127
160
  * @returns Withdraw leverage operation result
128
161
  */
129
- async withdrawLeverage(request: WithdrawLeverageRequest): Promise<any> {
130
- const response = await this.http.post("/leverage/withdraw", request);
131
-
132
- // check http status code
133
- handleStatusCode(response.status);
162
+ async withdrawLeverage(params: WithdrawLeverageRequest): Promise<any> {
163
+ const body = await handleApiCall(() =>
164
+ this.http.post("leverage/withdraw", JSON.stringify(params)),
165
+ );
134
166
 
135
- // parse response
136
- const responseData: WithdrawLeverageResponse = JSON.parse(response.data);
167
+ const withdrawLeverageResponse: WithdrawLeverageResponse = JSON.parse(body);
137
168
 
138
- // sign and send signed tx back to api for sending to network
139
- const txSig = await this.send(responseData.unsignedBase64Tx);
169
+ const txSig = await this.send(withdrawLeverageResponse.unsignedBase64Tx);
140
170
 
141
171
  return txSig;
142
172
  }
@@ -147,14 +177,38 @@ function handleStatusCode(statusCode: number): void {
147
177
  case 200:
148
178
  break;
149
179
  default:
150
- throw new Error(`unexpected status code${statusCode}`);
180
+ throw new Error(`unexpected status code: ${statusCode}`);
151
181
  }
152
182
  }
153
183
 
154
- // Ensures that a provider is defined
155
- function requireProvider(provider?: AnchorProvider): void {
156
- if (provider) {
157
- return;
184
+ // Helper function to handle API calls
185
+ async function handleApiCall<T>(
186
+ apiCall: () => Promise<AxiosResponse<T>>,
187
+ ): Promise<any> {
188
+ try {
189
+ const response = await apiCall();
190
+ handleStatusCode(response.status);
191
+ return JSON.stringify(response.data);
192
+ } catch (error) {
193
+ if (error instanceof AxiosError) {
194
+ const simplifiedError = {
195
+ status: error.response?.status,
196
+ message: error.message,
197
+ url: error.config?.url,
198
+ };
199
+ console.error(simplifiedError);
200
+ throw new Error(JSON.stringify(simplifiedError));
201
+ }
202
+ throw error;
158
203
  }
159
- throw new Error(`provider is undefined`);
204
+ }
205
+
206
+ function getDummyProvider(): AnchorProvider {
207
+ return new AnchorProvider(
208
+ new web3.Connection("http://localhost:8899"),
209
+ new Wallet(web3.Keypair.generate()),
210
+ {
211
+ skipPreflight: false,
212
+ },
213
+ );
160
214
  }
package/src/types.ts CHANGED
@@ -6,6 +6,14 @@ export interface SendRequest {
6
6
  tx: string;
7
7
  }
8
8
 
9
+ export interface CreateObligationRequest {
10
+ owner: web3.PublicKey;
11
+ }
12
+
13
+ export interface CreateObligationResponse {
14
+ unsignedBase64Tx: string;
15
+ }
16
+
9
17
  /**
10
18
  * Request to deposit collateral and create a leveraged position
11
19
  */