@shapeshiftoss/unchained-client 10.15.0 → 10.16.0

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.
@@ -20,6 +20,9 @@ export interface EstimateGasRequest {
20
20
  export interface GetAccountRequest {
21
21
  pubkey: string;
22
22
  }
23
+ export interface GetRfoxStakingDurationRequest {
24
+ address: string;
25
+ }
23
26
  export interface GetTransactionRequest {
24
27
  txid: string;
25
28
  }
@@ -77,6 +80,18 @@ export declare class V1Api extends runtime.BaseAPI {
77
80
  * Get information about the running coinstack
78
81
  */
79
82
  getInfo(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<BaseInfo>;
83
+ /**
84
+ * Get rFOX staking duration by contract address
85
+ */
86
+ getRfoxStakingDurationRaw(requestParameters: GetRfoxStakingDurationRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<{
87
+ [key: string]: number;
88
+ }>>;
89
+ /**
90
+ * Get rFOX staking duration by contract address
91
+ */
92
+ getRfoxStakingDuration(requestParameters: GetRfoxStakingDurationRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<{
93
+ [key: string]: number;
94
+ }>;
80
95
  /**
81
96
  * Get transaction details
82
97
  */
@@ -136,6 +136,30 @@ export class V1Api extends runtime.BaseAPI {
136
136
  const response = await this.getInfoRaw(initOverrides);
137
137
  return await response.value();
138
138
  }
139
+ /**
140
+ * Get rFOX staking duration by contract address
141
+ */
142
+ async getRfoxStakingDurationRaw(requestParameters, initOverrides) {
143
+ if (requestParameters.address === null || requestParameters.address === undefined) {
144
+ throw new runtime.RequiredError('address', 'Required parameter requestParameters.address was null or undefined when calling getRfoxStakingDuration.');
145
+ }
146
+ const queryParameters = {};
147
+ const headerParameters = {};
148
+ const response = await this.request({
149
+ path: `/api/v1/rfox/staking-duration/{address}`.replace(`{${"address"}}`, encodeURIComponent(String(requestParameters.address))),
150
+ method: 'GET',
151
+ headers: headerParameters,
152
+ query: queryParameters,
153
+ }, initOverrides);
154
+ return new runtime.JSONApiResponse(response);
155
+ }
156
+ /**
157
+ * Get rFOX staking duration by contract address
158
+ */
159
+ async getRfoxStakingDuration(requestParameters, initOverrides) {
160
+ const response = await this.getRfoxStakingDurationRaw(requestParameters, initOverrides);
161
+ return await response.value();
162
+ }
139
163
  /**
140
164
  * Get transaction details
141
165
  */
@@ -240,6 +240,131 @@ describe('TronApi', () => {
240
240
  expect(trigger).toHaveBeenCalledWith('TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', 'balanceOf(address)', {}, [{ type: 'address', value: 'TE6oHVdTbcp1Q9XBYx5VzjWbZEg3t3Jrnc' }], 'TE6oHVdTbcp1Q9XBYx5VzjWbZEg3t3Jrnc');
241
241
  });
242
242
  });
243
+ describe('getTrc20Decimals', () => {
244
+ const USDT = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';
245
+ const eighteen = '0000000000000000000000000000000000000000000000000000000000000012';
246
+ it('reads decimals() with a single constant call', async () => {
247
+ const freshApi = new TronApi({ rpcUrl: 'https://tron.example' });
248
+ const tronWeb = freshApi.getTronWeb();
249
+ const trigger = vi
250
+ .spyOn(tronWeb.transactionBuilder, 'triggerConstantContract')
251
+ .mockResolvedValue({ result: { result: true }, constant_result: [eighteen] });
252
+ expect(await freshApi.getTrc20Decimals({ contractAddress: USDT })).toBe(18);
253
+ expect(trigger).toHaveBeenCalledWith(USDT, 'decimals()', {}, [], USDT);
254
+ });
255
+ it('reads a reverted decimals() as unknown', async () => {
256
+ const freshApi = new TronApi({ rpcUrl: 'https://tron.example' });
257
+ const tronWeb = freshApi.getTronWeb();
258
+ const trigger = vi
259
+ .spyOn(tronWeb.transactionBuilder, 'triggerConstantContract')
260
+ .mockResolvedValueOnce({
261
+ result: { result: true, message: 'REVERT opcode executed' },
262
+ constant_result: ['08c379a0' + '0'.repeat(56)],
263
+ transaction: { ret: [{ ret: 'FAILED' }] },
264
+ })
265
+ .mockResolvedValue({ result: { result: true }, constant_result: [eighteen] });
266
+ expect(await freshApi.getTrc20Decimals({ contractAddress: USDT })).toBeUndefined();
267
+ expect(await freshApi.getTrc20Decimals({ contractAddress: USDT })).toBe(18);
268
+ expect(trigger).toHaveBeenCalledTimes(2);
269
+ });
270
+ it('reads a value outside a uint8 as unknown', async () => {
271
+ const freshApi = new TronApi({ rpcUrl: 'https://tron.example' });
272
+ const tronWeb = freshApi.getTronWeb();
273
+ vi.spyOn(tronWeb.transactionBuilder, 'triggerConstantContract').mockResolvedValue({
274
+ result: { result: true },
275
+ constant_result: ['0'.repeat(61) + '100'],
276
+ });
277
+ expect(await freshApi.getTrc20Decimals({ contractAddress: USDT })).toBeUndefined();
278
+ });
279
+ it('gives up on a call that hangs', async () => {
280
+ vi.useFakeTimers();
281
+ try {
282
+ const freshApi = new TronApi({ rpcUrl: 'https://tron.example' });
283
+ const tronWeb = freshApi.getTronWeb();
284
+ vi.spyOn(tronWeb.transactionBuilder, 'triggerConstantContract').mockReturnValue(new Promise(() => undefined));
285
+ const pending = freshApi.getTrc20Decimals({ contractAddress: USDT });
286
+ await vi.runAllTimersAsync();
287
+ expect(await pending).toBeUndefined();
288
+ }
289
+ finally {
290
+ vi.useRealTimers();
291
+ }
292
+ });
293
+ it('reads a failed call as unknown', async () => {
294
+ const freshApi = new TronApi({ rpcUrl: 'https://tron.example' });
295
+ const tronWeb = freshApi.getTronWeb();
296
+ const trigger = vi
297
+ .spyOn(tronWeb.transactionBuilder, 'triggerConstantContract')
298
+ .mockRejectedValueOnce(new Error('429'))
299
+ .mockResolvedValue({ result: { result: true }, constant_result: [eighteen] });
300
+ expect(await freshApi.getTrc20Decimals({ contractAddress: USDT })).toBeUndefined();
301
+ expect(await freshApi.getTrc20Decimals({ contractAddress: USDT })).toBe(18);
302
+ expect(trigger).toHaveBeenCalledTimes(2);
303
+ });
304
+ });
305
+ describe('getTrc10Precision', () => {
306
+ const respond = (body) => {
307
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: () => body });
308
+ vi.stubGlobal('fetch', fetchMock);
309
+ return fetchMock;
310
+ };
311
+ it('reads the precision of an issued token', async () => {
312
+ const freshApi = new TronApi({ rpcUrl: 'https://tron.example' });
313
+ const fetchMock = respond({ success: true, data: [{ id: '1002000', precision: 6 }] });
314
+ expect(await freshApi.getTrc10Precision({ id: '1002000' })).toBe(6);
315
+ expect(fetchMock).toHaveBeenCalledWith('https://tron.example/v1/assets/1002000', expect.objectContaining({ headers: expect.anything() }));
316
+ });
317
+ it('reads a zero precision as issued', async () => {
318
+ const freshApi = new TronApi({ rpcUrl: 'https://tron.example' });
319
+ respond({ success: true, data: [{ id: '1000001', precision: 0 }] });
320
+ expect(await freshApi.getTrc10Precision({ id: '1000001' })).toBe(0);
321
+ });
322
+ it('reads an unknown id as unknown', async () => {
323
+ const freshApi = new TronApi({ rpcUrl: 'https://tron.example' });
324
+ respond({ success: false, error: 'A valid account address or asset id is required.' });
325
+ expect(await freshApi.getTrc10Precision({ id: '9999999' })).toBeUndefined();
326
+ });
327
+ it('reads an empty listing as unknown', async () => {
328
+ const freshApi = new TronApi({ rpcUrl: 'https://tron.example' });
329
+ respond({ success: true, data: [] });
330
+ expect(await freshApi.getTrc10Precision({ id: '1009999' })).toBeUndefined();
331
+ });
332
+ it('gives up on a request that hangs', async () => {
333
+ vi.useFakeTimers();
334
+ try {
335
+ const freshApi = new TronApi({ rpcUrl: 'https://tron.example' });
336
+ vi.stubGlobal('fetch', vi.fn().mockReturnValue(new Promise(() => undefined)));
337
+ const pending = freshApi.getTrc10Precision({ id: '1002000' });
338
+ await vi.runAllTimersAsync();
339
+ expect(await pending).toBeUndefined();
340
+ }
341
+ finally {
342
+ vi.useRealTimers();
343
+ }
344
+ });
345
+ it('gives up on a response whose body stalls', async () => {
346
+ vi.useFakeTimers();
347
+ try {
348
+ const freshApi = new TronApi({ rpcUrl: 'https://tron.example' });
349
+ const fetchMock = vi
350
+ .fn()
351
+ .mockResolvedValue({ ok: true, json: () => new Promise(() => undefined) });
352
+ vi.stubGlobal('fetch', fetchMock);
353
+ const pending = freshApi.getTrc10Precision({ id: '1002000' });
354
+ await vi.runAllTimersAsync();
355
+ expect(await pending).toBeUndefined();
356
+ expect(fetchMock).toHaveBeenCalledWith('https://tron.example/v1/assets/1002000', expect.objectContaining({ signal: expect.any(AbortSignal) }));
357
+ }
358
+ finally {
359
+ vi.useRealTimers();
360
+ }
361
+ });
362
+ it('reads a failed request as unknown', async () => {
363
+ const freshApi = new TronApi({ rpcUrl: 'https://tron.example' });
364
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('429')));
365
+ expect(await freshApi.getTrc10Precision({ id: '1002000' })).toBeUndefined();
366
+ });
367
+ });
243
368
  describe('getTrc20Allowance', () => {
244
369
  it('reads allowance(owner, spender) with a single constant call', async () => {
245
370
  const tronWeb = api.getTronWeb();
@@ -32,6 +32,12 @@ export declare class TronApi {
32
32
  balance: string;
33
33
  }[];
34
34
  }>;
35
+ getTrc20Decimals(params: {
36
+ contractAddress: string;
37
+ }): Promise<number | undefined>;
38
+ getTrc10Precision(params: {
39
+ id: string;
40
+ }): Promise<number | undefined>;
35
41
  getTrc20Balance(params: {
36
42
  contractAddress: string;
37
43
  address: string;
@@ -85,5 +91,6 @@ export declare class TronApi {
85
91
  callValue?: string;
86
92
  requireEnergyShare?: boolean;
87
93
  }): Promise<string>;
94
+ private isReverted;
88
95
  private getSimulatedEnergy;
89
96
  }
@@ -1,4 +1,6 @@
1
+ import { timeout } from '@shapeshiftoss/utils';
1
2
  import { TronWeb } from 'tronweb';
3
+ const PRECISION_READ_TIMEOUT_MS = 10_000;
2
4
  const TRON_CALLER_PAYS_ALL = {
3
5
  callerPercent: 100,
4
6
  originEnergyLimit: 0,
@@ -140,6 +142,36 @@ export class TronApi {
140
142
  tokens,
141
143
  };
142
144
  }
145
+ async getTrc20Decimals(params) {
146
+ try {
147
+ const result = await timeout(this.getTronWeb().transactionBuilder.triggerConstantContract(params.contractAddress, 'decimals()', {}, [], params.contractAddress), PRECISION_READ_TIMEOUT_MS, undefined);
148
+ if (!result)
149
+ return;
150
+ const [decimalsHex] = result.constant_result ?? [];
151
+ if (this.isReverted(result) || !decimalsHex)
152
+ return;
153
+ // decimals() is a uint8; anything larger is a contract answering something else
154
+ const decimals = Number(BigInt(`0x${decimalsHex}`));
155
+ return decimals > 255 ? undefined : decimals;
156
+ }
157
+ catch (err) {
158
+ console.error(`[tron] failed to read decimals of ${params.contractAddress}`, err);
159
+ return;
160
+ }
161
+ }
162
+ async getTrc10Precision(params) {
163
+ try {
164
+ const data = await timeout(fetch(`${this.rpcUrl}/v1/assets/${params.id}`, {
165
+ headers: this.tronGridHeaders,
166
+ signal: AbortSignal.timeout(PRECISION_READ_TIMEOUT_MS),
167
+ }).then(response => response.json()), PRECISION_READ_TIMEOUT_MS, undefined);
168
+ return data?.data?.[0]?.precision;
169
+ }
170
+ catch (err) {
171
+ console.error(`[tron] failed to read precision of trc10 ${params.id}`, err);
172
+ return;
173
+ }
174
+ }
143
175
  async getTrc20Balance(params) {
144
176
  const result = await this.getTronWeb().transactionBuilder.triggerConstantContract(params.contractAddress, 'balanceOf(address)', {}, [{ type: 'address', value: params.address }], params.address);
145
177
  const [balance] = result.constant_result ?? [];
@@ -374,10 +406,14 @@ export class TronApi {
374
406
  const energy = this.getSimulatedEnergy(result, 'contract call');
375
407
  return String(getCallerEnergy(energy, share) * energyPrice);
376
408
  }
377
- // A revert still reports result.result: true with the partial energy burned - trusting it would underestimate
409
+ // A revert still reports result.result: true - the failure is only visible on the transaction's ret
410
+ isReverted(result) {
411
+ const failed = result.transaction?.ret?.some(ret => ret.ret === 'FAILED');
412
+ return result.result?.result !== true || Boolean(failed);
413
+ }
414
+ // Trusting a revert's partial energy would underestimate
378
415
  getSimulatedEnergy(result, label) {
379
- const isReverted = result.transaction?.ret?.some(ret => ret.ret === 'FAILED');
380
- if (result.result?.result !== true || isReverted || !result.energy_used) {
416
+ if (this.isReverted(result) || !result.energy_used) {
381
417
  throw new Error(`[tron] ${label} simulation failed: ${result.result?.message ?? 'unknown error'}`);
382
418
  }
383
419
  return result.energy_used;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shapeshiftoss/unchained-client",
3
- "version": "10.15.0",
3
+ "version": "10.16.0",
4
4
  "repository": "https://github.com/shapeshift/web",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -29,9 +29,9 @@
29
29
  "isomorphic-ws": "^4.0.1",
30
30
  "viem": "2.55.11",
31
31
  "ws": "^8.17.1",
32
- "@shapeshiftoss/caip": "^8.17.1",
33
32
  "@shapeshiftoss/contracts": "^1.1.0",
34
- "@shapeshiftoss/utils": "^1.3.1"
33
+ "@shapeshiftoss/caip": "^8.17.2",
34
+ "@shapeshiftoss/utils": "^1.4.0"
35
35
  },
36
36
  "devDependencies": {
37
37
  "@openapitools/openapi-generator-cli": "^2.5.1"