@shapeshiftoss/unchained-client 10.14.11 → 10.15.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.
Files changed (57) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/cosmossdk/thorchain/parser/__tests__/thorchain.test.js +1 -1
  3. package/dist/cjs/cosmossdk/thorchain/parser/rfox.js +1 -1
  4. package/dist/cjs/evm/arbitrum/parser/index.js +2 -2
  5. package/dist/cjs/evm/ethereum/parser/index.js +6 -0
  6. package/dist/cjs/generated/mayachain/apis/V1Api.d.ts +1 -13
  7. package/dist/cjs/generated/mayachain/apis/V1Api.js +0 -27
  8. package/dist/cjs/generated/mayachain/models/index.d.ts +0 -2
  9. package/dist/cjs/generated/mayachain/models/index.js +0 -2
  10. package/dist/cjs/generated/thorchain/apis/V1Api.d.ts +1 -25
  11. package/dist/cjs/generated/thorchain/apis/V1Api.js +0 -54
  12. package/dist/cjs/generated/thorchain/models/index.d.ts +0 -3
  13. package/dist/cjs/generated/thorchain/models/index.js +0 -3
  14. package/dist/cjs/tron/__tests__/api.test.d.ts +1 -0
  15. package/dist/cjs/tron/__tests__/api.test.js +300 -0
  16. package/dist/cjs/tron/api.d.ts +35 -15
  17. package/dist/cjs/tron/api.js +189 -81
  18. package/dist/cjs/tron/types.d.ts +4 -0
  19. package/dist/esm/.tsbuildinfo +1 -1
  20. package/dist/esm/cosmossdk/thorchain/parser/__tests__/thorchain.test.js +2 -2
  21. package/dist/esm/cosmossdk/thorchain/parser/rfox.js +2 -2
  22. package/dist/esm/evm/arbitrum/parser/index.js +3 -3
  23. package/dist/esm/evm/ethereum/parser/index.js +7 -1
  24. package/dist/esm/generated/mayachain/apis/V1Api.d.ts +1 -13
  25. package/dist/esm/generated/mayachain/apis/V1Api.js +1 -28
  26. package/dist/esm/generated/mayachain/models/index.d.ts +0 -2
  27. package/dist/esm/generated/mayachain/models/index.js +0 -2
  28. package/dist/esm/generated/thorchain/apis/V1Api.d.ts +1 -25
  29. package/dist/esm/generated/thorchain/apis/V1Api.js +1 -55
  30. package/dist/esm/generated/thorchain/models/index.d.ts +0 -3
  31. package/dist/esm/generated/thorchain/models/index.js +0 -3
  32. package/dist/esm/tron/__tests__/api.test.d.ts +1 -0
  33. package/dist/esm/tron/__tests__/api.test.js +298 -0
  34. package/dist/esm/tron/api.d.ts +35 -15
  35. package/dist/esm/tron/api.js +187 -80
  36. package/dist/esm/tron/types.d.ts +4 -0
  37. package/package.json +5 -5
  38. package/dist/cjs/generated/mayachain/models/AffiliateFee.d.ts +0 -67
  39. package/dist/cjs/generated/mayachain/models/AffiliateFee.js +0 -63
  40. package/dist/cjs/generated/mayachain/models/AffiliateFees.d.ts +0 -32
  41. package/dist/cjs/generated/mayachain/models/AffiliateFees.js +0 -52
  42. package/dist/cjs/generated/thorchain/models/AffiliateFee.d.ts +0 -67
  43. package/dist/cjs/generated/thorchain/models/AffiliateFee.js +0 -63
  44. package/dist/cjs/generated/thorchain/models/AffiliateFees.d.ts +0 -32
  45. package/dist/cjs/generated/thorchain/models/AffiliateFees.js +0 -52
  46. package/dist/cjs/generated/thorchain/models/AffiliateRevenue.d.ts +0 -45
  47. package/dist/cjs/generated/thorchain/models/AffiliateRevenue.js +0 -57
  48. package/dist/esm/generated/mayachain/models/AffiliateFee.d.ts +0 -67
  49. package/dist/esm/generated/mayachain/models/AffiliateFee.js +0 -56
  50. package/dist/esm/generated/mayachain/models/AffiliateFees.d.ts +0 -32
  51. package/dist/esm/generated/mayachain/models/AffiliateFees.js +0 -45
  52. package/dist/esm/generated/thorchain/models/AffiliateFee.d.ts +0 -67
  53. package/dist/esm/generated/thorchain/models/AffiliateFee.js +0 -56
  54. package/dist/esm/generated/thorchain/models/AffiliateFees.d.ts +0 -32
  55. package/dist/esm/generated/thorchain/models/AffiliateFees.js +0 -45
  56. package/dist/esm/generated/thorchain/models/AffiliateRevenue.d.ts +0 -45
  57. package/dist/esm/generated/thorchain/models/AffiliateRevenue.js +0 -50
@@ -1,5 +1,5 @@
1
1
  import { tcyAssetId, thorchainAssetId, thorchainChainId } from '@shapeshiftoss/caip';
2
- import { RFOX_PROXY_CONTRACT } from '@shapeshiftoss/contracts';
2
+ import { RFOX_ARB_PROXY_CONTRACT } from '@shapeshiftoss/contracts';
3
3
  import { beforeEach, describe, expect, it, vi } from 'vitest';
4
4
  import { Dex, TradeType, TransferType, TxStatus } from '../../../../types.js';
5
5
  import { TransactionParser } from '../index.js';
@@ -627,7 +627,7 @@ describe('parseTx', () => {
627
627
  epoch: 0,
628
628
  ipfsHash: 'QmYUiUq9UWK5NPF1h2BGdatw95psNtW8seGQpXZYoQYK1s',
629
629
  stakingAddress: '0x32DBc9Cf9E8FbCebE1e0a2ecF05Ed86Ca3096Cb6',
630
- stakingContract: RFOX_PROXY_CONTRACT,
630
+ stakingContract: RFOX_ARB_PROXY_CONTRACT,
631
631
  },
632
632
  };
633
633
  const actual = await txParser.parse(tx, address);
@@ -1,4 +1,4 @@
1
- import { RFOX_PROXY_CONTRACT } from '@shapeshiftoss/contracts';
1
+ import { RFOX_ARB_PROXY_CONTRACT } from '@shapeshiftoss/contracts';
2
2
  export class Parser {
3
3
  async parse(tx) {
4
4
  if (!tx.memo?.startsWith('rFOX reward'))
@@ -16,7 +16,7 @@ export class Parser {
16
16
  method: 'reward',
17
17
  epoch: parseInt(match.groups.epoch, 10),
18
18
  stakingAddress: match.groups.stakingAddress,
19
- stakingContract: stakingContract || RFOX_PROXY_CONTRACT,
19
+ stakingContract: stakingContract || RFOX_ARB_PROXY_CONTRACT,
20
20
  ipfsHash: match.groups.ipfsHash,
21
21
  },
22
22
  });
@@ -1,5 +1,5 @@
1
1
  import { foxOnArbitrumOneAssetId, uniV2EthFoxArbitrumAssetId } from '@shapeshiftoss/caip';
2
- import { RFOX_PROXY_CONTRACT, RFOX_UNI_V2_ETH_FOX_PROXY_CONTRACT, ZRX_ETHEREUM_PROXY_CONTRACT, } from '@shapeshiftoss/contracts';
2
+ import { RFOX_ARB_PROXY_CONTRACT, RFOX_ARB_UNI_V2_ETH_FOX_PROXY_CONTRACT, ZRX_ETHEREUM_PROXY_CONTRACT, } from '@shapeshiftoss/contracts';
3
3
  import { BaseTransactionParser } from '../../parser/index.js';
4
4
  import * as arbitrumBridge from '../../parser/arbitrumBridge.js';
5
5
  import * as erc20 from '../../parser/erc20.js';
@@ -17,11 +17,11 @@ export class TransactionParser extends BaseTransactionParser {
17
17
  }),
18
18
  new zrx.Parser({ proxyContract: ZRX_ETHEREUM_PROXY_CONTRACT }),
19
19
  new rfox.Parser({
20
- proxyContract: RFOX_PROXY_CONTRACT,
20
+ proxyContract: RFOX_ARB_PROXY_CONTRACT,
21
21
  stakingAssetId: foxOnArbitrumOneAssetId,
22
22
  }),
23
23
  new rfox.Parser({
24
- proxyContract: RFOX_UNI_V2_ETH_FOX_PROXY_CONTRACT,
24
+ proxyContract: RFOX_ARB_UNI_V2_ETH_FOX_PROXY_CONTRACT,
25
25
  stakingAssetId: uniV2EthFoxArbitrumAssetId,
26
26
  }),
27
27
  new arbitrumBridge.Parser({
@@ -1,8 +1,10 @@
1
- import { ZRX_ETHEREUM_PROXY_CONTRACT } from '@shapeshiftoss/contracts';
1
+ import { foxAssetId } from '@shapeshiftoss/caip';
2
+ import { RFOX_ETH_PROXY_CONTRACT, ZRX_ETHEREUM_PROXY_CONTRACT } from '@shapeshiftoss/contracts';
2
3
  import { BaseTransactionParser } from '../../parser/index.js';
3
4
  import * as arbitrumBridge from '../../parser/arbitrumBridge.js';
4
5
  import * as erc20 from '../../parser/erc20.js';
5
6
  import * as mayachain from '../../parser/mayachain.js';
7
+ import * as rfox from '../../parser/rfox.js';
6
8
  import * as thorchain from '../../parser/thorchain.js';
7
9
  import * as zrx from '../../parser/zrx.js';
8
10
  import * as cowswap from './cowswap.js';
@@ -27,6 +29,10 @@ export class TransactionParser extends BaseTransactionParser {
27
29
  midgardUrl: args.thorMidgardUrl,
28
30
  }),
29
31
  new zrx.Parser({ proxyContract: ZRX_ETHEREUM_PROXY_CONTRACT }),
32
+ new rfox.Parser({
33
+ proxyContract: RFOX_ETH_PROXY_CONTRACT,
34
+ stakingAssetId: foxAssetId,
35
+ }),
30
36
  new cowswap.Parser(),
31
37
  new arbitrumBridge.Parser({ chainId: this.chainId }),
32
38
  ]);
@@ -10,17 +10,13 @@
10
10
  * Do not edit the class manually.
11
11
  */
12
12
  import * as runtime from '../runtime.js';
13
- import type { Account, AffiliateFees, EstimateGasRequest, Info, Tx, TxHistory } from '../models/index.js';
13
+ import type { Account, EstimateGasRequest, Info, Tx, TxHistory } from '../models/index.js';
14
14
  export interface EstimateGasOperationRequest {
15
15
  body?: EstimateGasRequest;
16
16
  }
17
17
  export interface GetAccountRequest {
18
18
  pubkey: string;
19
19
  }
20
- export interface GetAffiliateFeesRequest {
21
- start?: string;
22
- end?: string;
23
- }
24
20
  export interface GetTxRequest {
25
21
  txid: string;
26
22
  }
@@ -52,14 +48,6 @@ export declare class V1Api extends runtime.BaseAPI {
52
48
  * Get account details.
53
49
  */
54
50
  getAccount(requestParameters: GetAccountRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<Account>;
55
- /**
56
- * Get ss affiliate fee history.
57
- */
58
- getAffiliateFeesRaw(requestParameters: GetAffiliateFeesRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<AffiliateFees>>;
59
- /**
60
- * Get ss affiliate fee history.
61
- */
62
- getAffiliateFees(requestParameters?: GetAffiliateFeesRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<AffiliateFees>;
63
51
  /**
64
52
  * Get information about the running coinstack.
65
53
  */
@@ -13,7 +13,7 @@
13
13
  * Do not edit the class manually.
14
14
  */
15
15
  import * as runtime from '../runtime.js';
16
- import { AccountFromJSON, AffiliateFeesFromJSON, EstimateGasRequestToJSON, InfoFromJSON, TxFromJSON, TxHistoryFromJSON, } from '../models/index.js';
16
+ import { AccountFromJSON, EstimateGasRequestToJSON, InfoFromJSON, TxFromJSON, TxHistoryFromJSON, } from '../models/index.js';
17
17
  /**
18
18
  *
19
19
  */
@@ -65,33 +65,6 @@ export class V1Api extends runtime.BaseAPI {
65
65
  const response = await this.getAccountRaw(requestParameters, initOverrides);
66
66
  return await response.value();
67
67
  }
68
- /**
69
- * Get ss affiliate fee history.
70
- */
71
- async getAffiliateFeesRaw(requestParameters, initOverrides) {
72
- const queryParameters = {};
73
- if (requestParameters.start !== undefined) {
74
- queryParameters['start'] = requestParameters.start;
75
- }
76
- if (requestParameters.end !== undefined) {
77
- queryParameters['end'] = requestParameters.end;
78
- }
79
- const headerParameters = {};
80
- const response = await this.request({
81
- path: `/api/v1/affiliate/fees`,
82
- method: 'GET',
83
- headers: headerParameters,
84
- query: queryParameters,
85
- }, initOverrides);
86
- return new runtime.JSONApiResponse(response, (jsonValue) => AffiliateFeesFromJSON(jsonValue));
87
- }
88
- /**
89
- * Get ss affiliate fee history.
90
- */
91
- async getAffiliateFees(requestParameters = {}, initOverrides) {
92
- const response = await this.getAffiliateFeesRaw(requestParameters, initOverrides);
93
- return await response.value();
94
- }
95
68
  /**
96
69
  * Get information about the running coinstack.
97
70
  */
@@ -1,6 +1,4 @@
1
1
  export * from './Account.js';
2
- export * from './AffiliateFee.js';
3
- export * from './AffiliateFees.js';
4
2
  export * from './ApiError.js';
5
3
  export * from './Attribute.js';
6
4
  export * from './BadRequestError.js';
@@ -2,8 +2,6 @@
2
2
  /* tslint:disable */
3
3
  /* eslint-disable */
4
4
  export * from './Account.js';
5
- export * from './AffiliateFee.js';
6
- export * from './AffiliateFees.js';
7
5
  export * from './ApiError.js';
8
6
  export * from './Attribute.js';
9
7
  export * from './BadRequestError.js';
@@ -10,21 +10,13 @@
10
10
  * Do not edit the class manually.
11
11
  */
12
12
  import * as runtime from '../runtime.js';
13
- import type { Account, AffiliateFees, AffiliateRevenue, EstimateGasRequest, Info, Tx, TxHistory } from '../models/index.js';
13
+ import type { Account, EstimateGasRequest, Info, Tx, TxHistory } from '../models/index.js';
14
14
  export interface EstimateGasOperationRequest {
15
15
  body?: EstimateGasRequest;
16
16
  }
17
17
  export interface GetAccountRequest {
18
18
  pubkey: string;
19
19
  }
20
- export interface GetAffiliateFeesRequest {
21
- start?: string;
22
- end?: string;
23
- }
24
- export interface GetAffiliateRevenueRequest {
25
- start?: string;
26
- end?: string;
27
- }
28
20
  export interface GetTxRequest {
29
21
  txid: string;
30
22
  }
@@ -56,22 +48,6 @@ export declare class V1Api extends runtime.BaseAPI {
56
48
  * Get account details.
57
49
  */
58
50
  getAccount(requestParameters: GetAccountRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<Account>;
59
- /**
60
- * Get ss affiliate fee history.
61
- */
62
- getAffiliateFeesRaw(requestParameters: GetAffiliateFeesRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<AffiliateFees>>;
63
- /**
64
- * Get ss affiliate fee history.
65
- */
66
- getAffiliateFees(requestParameters?: GetAffiliateFeesRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<AffiliateFees>;
67
- /**
68
- * Get total ss affiliate revenue earned.
69
- */
70
- getAffiliateRevenueRaw(requestParameters: GetAffiliateRevenueRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<AffiliateRevenue>>;
71
- /**
72
- * Get total ss affiliate revenue earned.
73
- */
74
- getAffiliateRevenue(requestParameters?: GetAffiliateRevenueRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<AffiliateRevenue>;
75
51
  /**
76
52
  * Get information about the running coinstack.
77
53
  */
@@ -13,7 +13,7 @@
13
13
  * Do not edit the class manually.
14
14
  */
15
15
  import * as runtime from '../runtime.js';
16
- import { AccountFromJSON, AffiliateFeesFromJSON, AffiliateRevenueFromJSON, EstimateGasRequestToJSON, InfoFromJSON, TxFromJSON, TxHistoryFromJSON, } from '../models/index.js';
16
+ import { AccountFromJSON, EstimateGasRequestToJSON, InfoFromJSON, TxFromJSON, TxHistoryFromJSON, } from '../models/index.js';
17
17
  /**
18
18
  *
19
19
  */
@@ -65,60 +65,6 @@ export class V1Api extends runtime.BaseAPI {
65
65
  const response = await this.getAccountRaw(requestParameters, initOverrides);
66
66
  return await response.value();
67
67
  }
68
- /**
69
- * Get ss affiliate fee history.
70
- */
71
- async getAffiliateFeesRaw(requestParameters, initOverrides) {
72
- const queryParameters = {};
73
- if (requestParameters.start !== undefined) {
74
- queryParameters['start'] = requestParameters.start;
75
- }
76
- if (requestParameters.end !== undefined) {
77
- queryParameters['end'] = requestParameters.end;
78
- }
79
- const headerParameters = {};
80
- const response = await this.request({
81
- path: `/api/v1/affiliate/fees`,
82
- method: 'GET',
83
- headers: headerParameters,
84
- query: queryParameters,
85
- }, initOverrides);
86
- return new runtime.JSONApiResponse(response, (jsonValue) => AffiliateFeesFromJSON(jsonValue));
87
- }
88
- /**
89
- * Get ss affiliate fee history.
90
- */
91
- async getAffiliateFees(requestParameters = {}, initOverrides) {
92
- const response = await this.getAffiliateFeesRaw(requestParameters, initOverrides);
93
- return await response.value();
94
- }
95
- /**
96
- * Get total ss affiliate revenue earned.
97
- */
98
- async getAffiliateRevenueRaw(requestParameters, initOverrides) {
99
- const queryParameters = {};
100
- if (requestParameters.start !== undefined) {
101
- queryParameters['start'] = requestParameters.start;
102
- }
103
- if (requestParameters.end !== undefined) {
104
- queryParameters['end'] = requestParameters.end;
105
- }
106
- const headerParameters = {};
107
- const response = await this.request({
108
- path: `/api/v1/affiliate/revenue`,
109
- method: 'GET',
110
- headers: headerParameters,
111
- query: queryParameters,
112
- }, initOverrides);
113
- return new runtime.JSONApiResponse(response, (jsonValue) => AffiliateRevenueFromJSON(jsonValue));
114
- }
115
- /**
116
- * Get total ss affiliate revenue earned.
117
- */
118
- async getAffiliateRevenue(requestParameters = {}, initOverrides) {
119
- const response = await this.getAffiliateRevenueRaw(requestParameters, initOverrides);
120
- return await response.value();
121
- }
122
68
  /**
123
69
  * Get information about the running coinstack.
124
70
  */
@@ -1,7 +1,4 @@
1
1
  export * from './Account.js';
2
- export * from './AffiliateFee.js';
3
- export * from './AffiliateFees.js';
4
- export * from './AffiliateRevenue.js';
5
2
  export * from './ApiError.js';
6
3
  export * from './Attribute.js';
7
4
  export * from './BadRequestError.js';
@@ -2,9 +2,6 @@
2
2
  /* tslint:disable */
3
3
  /* eslint-disable */
4
4
  export * from './Account.js';
5
- export * from './AffiliateFee.js';
6
- export * from './AffiliateFees.js';
7
- export * from './AffiliateRevenue.js';
8
5
  export * from './ApiError.js';
9
6
  export * from './Attribute.js';
10
7
  export * from './BadRequestError.js';
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,298 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { getCallerEnergy, TronApi } from '../api.js';
3
+ const successResponse = {
4
+ result: { result: true },
5
+ energy_used: 64285,
6
+ energy_penalty: 49635,
7
+ constant_result: ['0000000000000000000000000000000000000000000000000000000000000000'],
8
+ transaction: { ret: [{}] },
9
+ };
10
+ // A reverted simulation still reports result.result: true - the failure is only visible on
11
+ // transaction.ret and the message
12
+ const revertResponse = {
13
+ result: { result: true, message: 'REVERT opcode executed' },
14
+ energy_used: 7896,
15
+ energy_penalty: 6079,
16
+ constant_result: [''],
17
+ transaction: { ret: [{ ret: 'FAILED' }] },
18
+ };
19
+ describe('TronApi', () => {
20
+ const api = new TronApi({ rpcUrl: 'https://tron.example' });
21
+ beforeEach(() => {
22
+ vi.spyOn(api, 'getChainPrices').mockResolvedValue({
23
+ bandwidthPrice: 1000,
24
+ energyPrice: 100,
25
+ memoFee: 1_000_000,
26
+ });
27
+ vi.spyOn(api, 'getContractEnergyShare').mockResolvedValue({
28
+ callerPercent: 100,
29
+ originEnergyLimit: 0,
30
+ originEnergyAvailable: 0,
31
+ });
32
+ });
33
+ afterEach(() => {
34
+ vi.restoreAllMocks();
35
+ vi.unstubAllGlobals();
36
+ });
37
+ describe('estimateContractCallFee', () => {
38
+ const params = {
39
+ contractAddress: 'TAfbit1ENsRmtZbPQfYU3srURpfYuWYS7K',
40
+ from: 'TT2T17KZhoDu47i2E4FWxfG79zdkEWkU9N',
41
+ data: '0x2213bc0b',
42
+ };
43
+ it('prices a successful simulation at energy_used * energyPrice', async () => {
44
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: () => successResponse }));
45
+ expect(await api.estimateContractCallFee(params)).toBe('6428500');
46
+ });
47
+ it('prices the caller in full when the share lookup fails', async () => {
48
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: () => successResponse }));
49
+ vi.mocked(api.getContractEnergyShare).mockRejectedValue(new Error('429'));
50
+ expect(await api.estimateContractCallFee(params)).toBe('6428500');
51
+ });
52
+ it('fails instead when the caller requires the share', async () => {
53
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: () => successResponse }));
54
+ vi.mocked(api.getContractEnergyShare).mockRejectedValue(new Error('429'));
55
+ await expect(api.estimateContractCallFee({ ...params, requireEnergyShare: true })).rejects.toThrow('429');
56
+ });
57
+ it('bills the caller only their share when the deployer covers the rest', async () => {
58
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: () => successResponse }));
59
+ vi.mocked(api.getContractEnergyShare).mockResolvedValue({
60
+ callerPercent: 5,
61
+ originEnergyLimit: 10_000_000,
62
+ originEnergyAvailable: 5_000_000,
63
+ });
64
+ // 64285 - floor(64285 * 0.95) = 3215
65
+ expect(await api.estimateContractCallFee(params)).toBe('321500');
66
+ });
67
+ it('throws on a reverted simulation rather than trusting the partial energy', async () => {
68
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: () => revertResponse }));
69
+ await expect(api.estimateContractCallFee(params)).rejects.toThrow('REVERT opcode executed');
70
+ });
71
+ it('reports a failed request as such rather than as a revert', async () => {
72
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 429, json: () => ({}) }));
73
+ await expect(api.estimateContractCallFee(params)).rejects.toThrow('request failed: 429');
74
+ });
75
+ });
76
+ describe('getCallerEnergy', () => {
77
+ it('charges the caller in full when the contract sets no deployer share', () => {
78
+ const share = {
79
+ callerPercent: 100,
80
+ originEnergyLimit: 0,
81
+ originEnergyAvailable: 0,
82
+ };
83
+ expect(getCallerEnergy(901_682, share)).toBe(901_682);
84
+ });
85
+ it('charges the caller their percent when the deployer has the energy staked', () => {
86
+ const share = {
87
+ callerPercent: 5,
88
+ originEnergyLimit: 10_000_000,
89
+ originEnergyAvailable: 5_000_000,
90
+ };
91
+ expect(getCallerEnergy(901_682, share)).toBe(45_085);
92
+ });
93
+ it('charges the caller in full when the deployer has nothing staked', () => {
94
+ const share = {
95
+ callerPercent: 30,
96
+ originEnergyLimit: 10_000_000,
97
+ originEnergyAvailable: 0,
98
+ };
99
+ expect(getCallerEnergy(130_285, share)).toBe(130_285);
100
+ });
101
+ it('caps the deployer share at their per-call limit', () => {
102
+ const share = {
103
+ callerPercent: 0,
104
+ originEnergyLimit: 100_000,
105
+ originEnergyAvailable: 5_000_000,
106
+ };
107
+ expect(getCallerEnergy(300_000, share)).toBe(200_000);
108
+ });
109
+ it('caps the deployer share at what they have left', () => {
110
+ const share = {
111
+ callerPercent: 0,
112
+ originEnergyLimit: 10_000_000,
113
+ originEnergyAvailable: 40_000,
114
+ };
115
+ expect(getCallerEnergy(300_000, share)).toBe(260_000);
116
+ });
117
+ });
118
+ describe('getContractEnergyShare', () => {
119
+ const contractResponse = {
120
+ consume_user_resource_percent: 5,
121
+ origin_energy_limit: 10_000_000,
122
+ origin_address: 'TDeployer',
123
+ };
124
+ const resourceResponse = { EnergyLimit: 6_000_000, EnergyUsed: 1_000_000 };
125
+ const respond = (...bodies) => {
126
+ const fetchMock = vi.fn();
127
+ bodies.forEach(body => fetchMock.mockResolvedValueOnce({ ok: true, json: () => body }));
128
+ vi.stubGlobal('fetch', fetchMock);
129
+ return fetchMock;
130
+ };
131
+ // the contract record is cached per instance, so each case gets its own
132
+ const freshApi = () => new TronApi({ rpcUrl: 'https://tron.example' });
133
+ it('reads the caller percent, per-call limit and the unspent deployer energy', async () => {
134
+ respond(contractResponse, resourceResponse);
135
+ expect(await freshApi().getContractEnergyShare('TRouter')).toEqual({
136
+ callerPercent: 5,
137
+ originEnergyLimit: 10_000_000,
138
+ originEnergyAvailable: 5_000_000,
139
+ });
140
+ });
141
+ it('reads an omitted percent as the deployer paying everything', async () => {
142
+ respond({ origin_energy_limit: 10_000_000, origin_address: 'TDeployer' }, resourceResponse);
143
+ expect(await freshApi().getContractEnergyShare('TRouter')).toMatchObject({ callerPercent: 0 });
144
+ });
145
+ it('reads an omitted per-call limit as the creator default', async () => {
146
+ respond({ consume_user_resource_percent: 5, origin_address: 'TDeployer' }, resourceResponse);
147
+ expect(await freshApi().getContractEnergyShare('TRouter')).toMatchObject({
148
+ originEnergyLimit: 10_000_000,
149
+ });
150
+ });
151
+ it('reads a plain address as a call the caller pays in full without a resource lookup', async () => {
152
+ const fetchMock = respond({});
153
+ expect(await freshApi().getContractEnergyShare('TPlain')).toEqual({
154
+ callerPercent: 100,
155
+ originEnergyLimit: 0,
156
+ originEnergyAvailable: 0,
157
+ });
158
+ expect(fetchMock).toHaveBeenCalledTimes(1);
159
+ });
160
+ it('re-reads an empty body rather than caching it as a plain address', async () => {
161
+ const fetchMock = respond({}, contractResponse, resourceResponse);
162
+ const api = freshApi();
163
+ await api.getContractEnergyShare('TRouter');
164
+ expect(await api.getContractEnergyShare('TRouter')).toMatchObject({ callerPercent: 5 });
165
+ expect(fetchMock).toHaveBeenCalledTimes(3);
166
+ });
167
+ it('rejects a failed lookup rather than guessing the split', async () => {
168
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 429 }));
169
+ await expect(freshApi().getContractEnergyShare('TRouter')).rejects.toThrow('429');
170
+ });
171
+ it('does not cache an error body the node returns with a 200', async () => {
172
+ const fetchMock = respond({ Error: 'class org.tron.core.exception' }, contractResponse, resourceResponse);
173
+ const api = freshApi();
174
+ await expect(api.getContractEnergyShare('TRouter')).rejects.toThrow('getcontract failed');
175
+ expect(await api.getContractEnergyShare('TRouter')).toMatchObject({ callerPercent: 5 });
176
+ expect(fetchMock).toHaveBeenCalledTimes(3);
177
+ });
178
+ it('reads the contract once and the deployer energy once per refresh window', async () => {
179
+ vi.useFakeTimers();
180
+ const fetchMock = respond(contractResponse, resourceResponse, resourceResponse);
181
+ const api = freshApi();
182
+ await api.getContractEnergyShare('TRouter');
183
+ await api.getContractEnergyShare('TRouter');
184
+ expect(fetchMock).toHaveBeenCalledTimes(2);
185
+ vi.advanceTimersByTime(16_000);
186
+ await api.getContractEnergyShare('TRouter');
187
+ expect(fetchMock).toHaveBeenCalledTimes(3);
188
+ const contractReads = fetchMock.mock.calls.filter(([url]) => String(url).endsWith('/wallet/getcontract'));
189
+ expect(contractReads).toHaveLength(1);
190
+ vi.useRealTimers();
191
+ });
192
+ it('re-reads the contract after a minute, since its split can change', async () => {
193
+ vi.useFakeTimers();
194
+ const fetchMock = respond(contractResponse, resourceResponse, contractResponse, resourceResponse);
195
+ const api = freshApi();
196
+ await api.getContractEnergyShare('TRouter');
197
+ vi.advanceTimersByTime(61_000);
198
+ await api.getContractEnergyShare('TRouter');
199
+ const contractReads = fetchMock.mock.calls.filter(([url]) => String(url).endsWith('/wallet/getcontract'));
200
+ expect(contractReads).toHaveLength(2);
201
+ vi.useRealTimers();
202
+ });
203
+ });
204
+ describe('getChainPrices', () => {
205
+ it('reads the energy, bandwidth and memo parameters', async () => {
206
+ vi.restoreAllMocks();
207
+ const tronWeb = api.getTronWeb();
208
+ vi.spyOn(tronWeb.trx, 'getChainParameters').mockResolvedValue([
209
+ { key: 'getTransactionFee', value: 1000 },
210
+ { key: 'getEnergyFee', value: 100 },
211
+ { key: 'getMemoFee', value: 1_000_000 },
212
+ ]);
213
+ expect(await api.getChainPrices()).toEqual({
214
+ bandwidthPrice: 1000,
215
+ energyPrice: 100,
216
+ memoFee: 1_000_000,
217
+ });
218
+ });
219
+ it('throws rather than defaulting when the node is unreachable', async () => {
220
+ vi.restoreAllMocks();
221
+ const tronWeb = api.getTronWeb();
222
+ vi.spyOn(tronWeb.trx, 'getChainParameters').mockRejectedValue(new Error('ECONNREFUSED'));
223
+ await expect(api.getChainPrices()).rejects.toThrow('ECONNREFUSED');
224
+ });
225
+ });
226
+ describe('getTrc20Balance', () => {
227
+ it('reads balanceOf(address) with a single constant call', async () => {
228
+ const tronWeb = api.getTronWeb();
229
+ const trigger = vi
230
+ .spyOn(tronWeb.transactionBuilder, 'triggerConstantContract')
231
+ .mockResolvedValue({
232
+ result: { result: true },
233
+ constant_result: ['00000000000000000000000000000000000000000000000000000000028e6fb0'],
234
+ });
235
+ const actual = await api.getTrc20Balance({
236
+ contractAddress: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
237
+ address: 'TE6oHVdTbcp1Q9XBYx5VzjWbZEg3t3Jrnc',
238
+ });
239
+ expect(actual).toBe('42889136');
240
+ expect(trigger).toHaveBeenCalledWith('TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', 'balanceOf(address)', {}, [{ type: 'address', value: 'TE6oHVdTbcp1Q9XBYx5VzjWbZEg3t3Jrnc' }], 'TE6oHVdTbcp1Q9XBYx5VzjWbZEg3t3Jrnc');
241
+ });
242
+ });
243
+ describe('getTrc20Allowance', () => {
244
+ it('reads allowance(owner, spender) with a single constant call', async () => {
245
+ const tronWeb = api.getTronWeb();
246
+ const trigger = vi
247
+ .spyOn(tronWeb.transactionBuilder, 'triggerConstantContract')
248
+ .mockResolvedValue({
249
+ result: { result: true },
250
+ constant_result: ['000000000000000000000000000000000000000000000000000000000000007b'],
251
+ });
252
+ const actual = await api.getTrc20Allowance({
253
+ contractAddress: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
254
+ owner: 'TT2T17KZhoDu47i2E4FWxfG79zdkEWkU9N',
255
+ spender: 'TAfbit1ENsRmtZbPQfYU3srURpfYuWYS7K',
256
+ });
257
+ expect(actual).toBe('123');
258
+ expect(trigger).toHaveBeenCalledWith('TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', 'allowance(address,address)', {}, [
259
+ { type: 'address', value: 'TT2T17KZhoDu47i2E4FWxfG79zdkEWkU9N' },
260
+ { type: 'address', value: 'TAfbit1ENsRmtZbPQfYU3srURpfYuWYS7K' },
261
+ ], 'TT2T17KZhoDu47i2E4FWxfG79zdkEWkU9N');
262
+ });
263
+ });
264
+ describe('isAccountActivated', () => {
265
+ it('is true for an account the node knows', async () => {
266
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: () => ({ address: '41abc', balance: 1 }) }));
267
+ expect(await api.isAccountActivated('TT2T17KZhoDu47i2E4FWxfG79zdkEWkU9N')).toBe(true);
268
+ });
269
+ it('is false for a fresh address', async () => {
270
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: () => ({}) }));
271
+ expect(await api.isAccountActivated('TT2T17KZhoDu47i2E4FWxfG79zdkEWkU9N')).toBe(false);
272
+ });
273
+ it('throws on an error response rather than reading it as not activated', async () => {
274
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 429, json: () => ({ Error: 'throttled' }) }));
275
+ await expect(api.isAccountActivated('TT2T17KZhoDu47i2E4FWxfG79zdkEWkU9N')).rejects.toThrow('429');
276
+ });
277
+ });
278
+ describe('estimateTrc20TransferFee', () => {
279
+ const params = {
280
+ contractAddress: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
281
+ from: 'TT2T17KZhoDu47i2E4FWxfG79zdkEWkU9N',
282
+ to: 'TT2T17KZhoDu47i2E4FWxfG79zdkEWkU9N',
283
+ amount: '1',
284
+ };
285
+ const stubTriggerConstantContract = (response) => {
286
+ const tronWeb = api.getTronWeb();
287
+ vi.spyOn(tronWeb.transactionBuilder, 'triggerConstantContract').mockResolvedValue(response);
288
+ };
289
+ it('prices a successful simulation at energy_used * energyPrice', async () => {
290
+ stubTriggerConstantContract(successResponse);
291
+ expect(await api.estimateTrc20TransferFee(params)).toBe('6428500');
292
+ });
293
+ it('throws on a reverted simulation rather than trusting the partial energy', async () => {
294
+ stubTriggerConstantContract(revertResponse);
295
+ await expect(api.estimateTrc20TransferFee(params)).rejects.toThrow('REVERT opcode executed');
296
+ });
297
+ });
298
+ });