@defillama/sdk 5.0.236 → 5.0.240

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 (131) hide show
  1. package/package.json +3 -3
  2. package/build/Balances.d.ts +0 -139
  3. package/build/Balances.js +0 -363
  4. package/build/ChainApi.d.ts +0 -142
  5. package/build/ChainApi.js +0 -297
  6. package/build/abi/abi2.d.ts +0 -5
  7. package/build/abi/abi2.js +0 -215
  8. package/build/abi/cachedABIs.d.ts +0 -4
  9. package/build/abi/cachedABIs.js +0 -8
  10. package/build/abi/convertResults.d.ts +0 -5
  11. package/build/abi/convertResults.js +0 -60
  12. package/build/abi/index.d.ts +0 -31
  13. package/build/abi/index.js +0 -327
  14. package/build/abi/multicall.d.ts +0 -23
  15. package/build/abi/multicall.js +0 -382
  16. package/build/abi/multicall3.d.ts +0 -7
  17. package/build/abi/multicall3.js +0 -397
  18. package/build/abi/rpcCall.d.ts +0 -4
  19. package/build/abi/rpcCall.js +0 -62
  20. package/build/abi/tron.d.ts +0 -33
  21. package/build/abi/tron.js +0 -110
  22. package/build/api.d.ts +0 -10
  23. package/build/api.js +0 -45
  24. package/build/api2.d.ts +0 -5
  25. package/build/api2.js +0 -41
  26. package/build/chains/algorand.d.ts +0 -277
  27. package/build/chains/algorand.js +0 -618
  28. package/build/chains/aptos.d.ts +0 -230
  29. package/build/chains/aptos.js +0 -612
  30. package/build/chains/cardano.d.ts +0 -242
  31. package/build/chains/cardano.js +0 -407
  32. package/build/chains/cosmos.d.ts +0 -252
  33. package/build/chains/cosmos.js +0 -618
  34. package/build/chains/icp.d.ts +0 -235
  35. package/build/chains/icp.js +0 -1040
  36. package/build/chains/index.d.ts +0 -23
  37. package/build/chains/index.js +0 -59
  38. package/build/chains/near.d.ts +0 -192
  39. package/build/chains/near.js +0 -446
  40. package/build/chains/rpc.d.ts +0 -125
  41. package/build/chains/rpc.js +0 -326
  42. package/build/chains/starknet.d.ts +0 -205
  43. package/build/chains/starknet.js +0 -884
  44. package/build/chains/stellar.d.ts +0 -410
  45. package/build/chains/stellar.js +0 -1082
  46. package/build/chains/substrate.d.ts +0 -333
  47. package/build/chains/substrate.js +0 -1042
  48. package/build/chains/sui.d.ts +0 -365
  49. package/build/chains/sui.js +0 -1135
  50. package/build/chains/svm.d.ts +0 -340
  51. package/build/chains/svm.js +0 -760
  52. package/build/chains/tezos.d.ts +0 -225
  53. package/build/chains/tezos.js +0 -412
  54. package/build/chains/ton.d.ts +0 -353
  55. package/build/chains/ton.js +0 -788
  56. package/build/chains/tron.d.ts +0 -45
  57. package/build/chains/tron.js +0 -110
  58. package/build/chains/utxo.d.ts +0 -202
  59. package/build/chains/utxo.js +0 -592
  60. package/build/chains/xrpl.d.ts +0 -179
  61. package/build/chains/xrpl.js +0 -467
  62. package/build/computeTVL/blocks.d.ts +0 -1
  63. package/build/computeTVL/blocks.js +0 -12
  64. package/build/computeTVL/humanizeNumber.d.ts +0 -1
  65. package/build/computeTVL/humanizeNumber.js +0 -19
  66. package/build/erc20/index.d.ts +0 -31
  67. package/build/erc20/index.js +0 -56
  68. package/build/eth/index.d.ts +0 -22
  69. package/build/eth/index.js +0 -118
  70. package/build/general.d.ts +0 -5
  71. package/build/general.js +0 -20
  72. package/build/generalUtil.d.ts +0 -8
  73. package/build/generalUtil.js +0 -73
  74. package/build/index.d.ts +0 -32
  75. package/build/index.js +0 -74
  76. package/build/providers.json +0 -1
  77. package/build/types.d.ts +0 -76
  78. package/build/types.js +0 -2
  79. package/build/util/LlamaProvider.d.ts +0 -46
  80. package/build/util/LlamaProvider.js +0 -365
  81. package/build/util/blocks.d.ts +0 -36
  82. package/build/util/blocks.js +0 -292
  83. package/build/util/cache.d.ts +0 -45
  84. package/build/util/cache.js +0 -309
  85. package/build/util/chainUtils/data.json +0 -1356
  86. package/build/util/chainUtils/index.d.ts +0 -11
  87. package/build/util/chainUtils/index.js +0 -136
  88. package/build/util/coins.d.ts +0 -19
  89. package/build/util/coins.js +0 -113
  90. package/build/util/common.d.ts +0 -34
  91. package/build/util/common.js +0 -373
  92. package/build/util/computeTVL.d.ts +0 -19
  93. package/build/util/computeTVL.js +0 -102
  94. package/build/util/cosmos.d.ts +0 -1
  95. package/build/util/cosmos.js +0 -8
  96. package/build/util/debugLog.d.ts +0 -4
  97. package/build/util/debugLog.js +0 -18
  98. package/build/util/discord.d.ts +0 -1
  99. package/build/util/discord.js +0 -33
  100. package/build/util/elastic.d.ts +0 -43
  101. package/build/util/elastic.js +0 -113
  102. package/build/util/env.d.ts +0 -19
  103. package/build/util/env.js +0 -158
  104. package/build/util/graph.d.ts +0 -8
  105. package/build/util/graph.js +0 -50
  106. package/build/util/index.d.ts +0 -32
  107. package/build/util/index.js +0 -227
  108. package/build/util/indexer.compatibility.d.ts +0 -6
  109. package/build/util/indexer.compatibility.js +0 -64
  110. package/build/util/indexer.d.ts +0 -92
  111. package/build/util/indexer.js +0 -744
  112. package/build/util/indexerSql.d.ts +0 -9
  113. package/build/util/indexerSql.js +0 -102
  114. package/build/util/internal-cache.d.ts +0 -11
  115. package/build/util/internal-cache.js +0 -77
  116. package/build/util/logs.d.ts +0 -55
  117. package/build/util/logs.decode.shared.d.ts +0 -8
  118. package/build/util/logs.decode.shared.js +0 -289
  119. package/build/util/logs.js +0 -401
  120. package/build/util/promisePool.d.ts +0 -8
  121. package/build/util/promisePool.js +0 -31
  122. package/build/util/r2.d.ts +0 -4
  123. package/build/util/r2.js +0 -52
  124. package/build/util/removeRedundantRPCs.d.ts +0 -1
  125. package/build/util/removeRedundantRPCs.js +0 -49
  126. package/build/util/transactions.d.ts +0 -35
  127. package/build/util/transactions.js +0 -22
  128. package/build/util/updateChainLabels.d.ts +0 -1
  129. package/build/util/updateChainLabels.js +0 -5
  130. package/build/util/updateProviderList.d.ts +0 -1
  131. package/build/util/updateProviderList.js +0 -274
@@ -1,179 +0,0 @@
1
- /** Public XRPL nodes that answer bursts without throttling (xrpl.ws / xrpl.link 429 after a few calls). */
2
- export declare const DEFAULT_ENDPOINTS: string[];
3
- /** Seconds between the unix epoch and the ripple epoch (2000-01-01T00:00:00Z). */
4
- export declare const RIPPLE_EPOCH_OFFSET = 946684800;
5
- export declare function getEndpoints(): string[];
6
- export type LedgerIndex = number | string | 'validated' | 'closed' | 'current';
7
- export interface TokenId {
8
- /** 3-char ISO-like code or 40-char hex for non-standard codes */
9
- currency: string;
10
- /** issuer account (rXXX) */
11
- issuer: string;
12
- }
13
- export interface AccountLine {
14
- account: string;
15
- balance: string;
16
- currency: string;
17
- limit: string;
18
- limit_peer: string;
19
- quality_in: number;
20
- quality_out: number;
21
- no_ripple?: boolean;
22
- no_ripple_peer?: boolean;
23
- authorized?: boolean;
24
- peer_authorized?: boolean;
25
- freeze?: boolean;
26
- freeze_peer?: boolean;
27
- [key: string]: any;
28
- }
29
- export interface LedgerInfo {
30
- number: number;
31
- /** unix seconds (ripple epoch already converted) */
32
- timestamp: number;
33
- hash: string;
34
- }
35
- export declare class XrplRpcError extends Error {
36
- method: string;
37
- /** node error code, e.g. `actNotFound`, `tooBusy`, `lgrNotFound` */
38
- error?: string;
39
- constructor(method: string, message: string, error?: string);
40
- }
41
- /**
42
- * Decode a ledger currency code: 3-char codes pass through, 40-char hex blobs
43
- * (non-standard codes longer than 3 chars) are decoded to ascii with the trailing
44
- * null padding stripped. Anything else is returned unchanged.
45
- */
46
- export declare function decodeCurrency(code: string): string;
47
- /**
48
- * Encode a human-readable currency code for the ledger: 3-char codes pass through,
49
- * longer codes become the 40-char uppercase hex the ledger uses (ascii, null padded).
50
- * A code that already is 40-char hex is returned uppercased.
51
- */
52
- export declare function encodeCurrency(str: string): string;
53
- /** Accept `'CODE.rISSUER'` or `{ currency, issuer }` and return `{ currency, issuer }`. */
54
- export declare function parseToken(token: string | TokenId): TokenId;
55
- /** Format `{ currency, issuer }` as `'CODE.rISSUER'`. */
56
- export declare function formatToken({ currency, issuer }: TokenId): string;
57
- /**
58
- * xrplcluster answers `tooBusy` / `rate limit` under load, and a paged walk trips its
59
- * units quota on its own. Those are retryable; a malformed request or a real ledger
60
- * error (`actNotFound`, `lgrNotFound`, `invalidParams`, ...) is not.
61
- */
62
- export declare function isRetryableError(message: string): boolean;
63
- export declare function rippleTimeToUnix(rippleTime: number): number;
64
- export declare function unixToRippleTime(timestamp: number): number;
65
- /**
66
- * Classic address check: ripple base58 alphabet, 25..35 chars, decodes to 25 bytes
67
- * with the account-id type prefix (0x00) and a valid double-sha256 checksum.
68
- */
69
- export declare function isValidAddress(str: string): boolean;
70
- export interface RpcOptions {
71
- ledgerIndex?: LedgerIndex;
72
- /** total attempts, default 4 */
73
- retries?: number;
74
- timeout?: number;
75
- }
76
- /**
77
- * Single XRPL JSON-RPC call. Returns `result`; throws `XrplRpcError` (with the
78
- * node's `error_message` / `error`) when the node reports `status: 'error'`.
79
- * Rotates over the endpoint list and retries only the transient error shapes
80
- * (`tooBusy`, `slowDown`, rate limits, timeouts, 5xx, network errors).
81
- */
82
- export declare function rpc(method: string, params?: Record<string, any>, options?: RpcOptions): Promise<any>;
83
- /** `account_info` result (`account_data`, `ledger_index`, ...). Throws `actNotFound` for unfunded accounts. */
84
- export declare function getAccountInfo({ account, ledgerIndex }: {
85
- account: string;
86
- ledgerIndex?: LedgerIndex;
87
- }): Promise<any>;
88
- /** XRP balance in drops as a string. Unfunded / malformed accounts resolve to `'0'`. */
89
- export declare function getXrpBalance({ account, ledgerIndex }: {
90
- account: string;
91
- ledgerIndex?: LedgerIndex;
92
- }): Promise<string>;
93
- /** All trust lines of `account` (walks `marker` pages). Unfunded accounts resolve to `[]`. */
94
- export declare function getAccountLines({ account, peer, ledgerIndex, limit, maxPages }: {
95
- account: string;
96
- peer?: string;
97
- ledgerIndex?: LedgerIndex;
98
- limit?: number;
99
- maxPages?: number;
100
- }): Promise<AccountLine[]>;
101
- /** All ledger objects owned by `account` (walks `marker` pages). `type` filters e.g. `'state'`, `'offer'`, `'escrow'`. */
102
- export declare function getAccountObjects({ account, type, ledgerIndex, limit }: {
103
- account: string;
104
- type?: string;
105
- ledgerIndex?: LedgerIndex;
106
- limit?: number;
107
- }): Promise<any[]>;
108
- /**
109
- * Raw `gateway_balances` result for an issuer: `obligations` (currency -> total
110
- * owed to non-hot-wallet holders), `balances` (hot wallet holdings), `assets`.
111
- * `hotWallets` are the issuer's own operational accounts; an address equal to the
112
- * issuer is dropped (an issuer is never its own hot wallet and the node errors on it).
113
- */
114
- export declare function getGatewayBalances({ account, hotWallets, ledgerIndex }: {
115
- account: string;
116
- hotWallets?: string[];
117
- ledgerIndex?: LedgerIndex;
118
- }): Promise<any>;
119
- /**
120
- * Issuer obligations keyed by decoded currency code (circulating supply per
121
- * currency). Obligations owed to `hotWallets` are un-issued float and excluded by
122
- * the node. Throws rather than returning `{}` on a failed read, so an unreadable
123
- * issuer never looks like a zero-supply one.
124
- */
125
- export declare function getObligations({ issuer, hotWallets, ledgerIndex }: {
126
- issuer: string;
127
- hotWallets?: string[];
128
- ledgerIndex?: LedgerIndex;
129
- }): Promise<{
130
- [currency: string]: string;
131
- }>;
132
- /**
133
- * Circulating supply of one issued currency as a decimal string (`'0'` when the
134
- * issuer has no such obligation). `currency` may be the 3-char / human code or the
135
- * 40-char hex form; `'CODE.rISSUER'` is accepted too.
136
- */
137
- export declare function getTokenSupply(token: string | (TokenId & {
138
- hotWallets?: string[];
139
- ledgerIndex?: LedgerIndex;
140
- }), { hotWallets, ledgerIndex }?: {
141
- hotWallets?: string[];
142
- ledgerIndex?: LedgerIndex;
143
- }): Promise<string>;
144
- /**
145
- * Balance of an issued currency held by `account` (trust line with `issuer`), as
146
- * the human-readable decimal string reported by `account_lines`. `'0'` when there is
147
- * no such line. Negative values mean `account` is itself the issuer of that line.
148
- */
149
- export declare function getTokenBalance({ account, currency, issuer, ledgerIndex }: {
150
- account: string;
151
- currency: string;
152
- issuer: string;
153
- ledgerIndex?: LedgerIndex;
154
- }): Promise<string>;
155
- /**
156
- * All issued-currency balances of `account` keyed by `'CODE.rISSUER'` (currency
157
- * kept in ledger form). Amounts are human-readable decimal strings.
158
- */
159
- export declare function getTokenBalances({ account, ledgerIndex }: {
160
- account: string;
161
- ledgerIndex?: LedgerIndex;
162
- }): Promise<{
163
- [token: string]: string;
164
- }>;
165
- /** Ledger header: `{ number, timestamp (unix seconds), hash }`. */
166
- export declare function getLedger({ ledgerIndex }?: {
167
- ledgerIndex?: LedgerIndex;
168
- }): Promise<LedgerInfo>;
169
- export declare function getLatestLedger(): Promise<LedgerInfo>;
170
- /**
171
- * Last validated ledger closed at or before `timestamp` (unix seconds). Binary
172
- * search on `ledger_index`, starting from a bracket estimated with the ~3s minimum
173
- * close interval. Requires a full-history node for old timestamps.
174
- */
175
- export declare function getLedgerAtTimestamp({ timestamp }: {
176
- timestamp: number;
177
- }): Promise<LedgerInfo>;
178
- /** `server_info` result (`info.validated_ledger`, `info.complete_ledgers`, ...). */
179
- export declare function getServerInfo(): Promise<any>;
@@ -1,467 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.XrplRpcError = exports.RIPPLE_EPOCH_OFFSET = exports.DEFAULT_ENDPOINTS = void 0;
4
- exports.getEndpoints = getEndpoints;
5
- exports.decodeCurrency = decodeCurrency;
6
- exports.encodeCurrency = encodeCurrency;
7
- exports.parseToken = parseToken;
8
- exports.formatToken = formatToken;
9
- exports.isRetryableError = isRetryableError;
10
- exports.rippleTimeToUnix = rippleTimeToUnix;
11
- exports.unixToRippleTime = unixToRippleTime;
12
- exports.isValidAddress = isValidAddress;
13
- exports.rpc = rpc;
14
- exports.getAccountInfo = getAccountInfo;
15
- exports.getXrpBalance = getXrpBalance;
16
- exports.getAccountLines = getAccountLines;
17
- exports.getAccountObjects = getAccountObjects;
18
- exports.getGatewayBalances = getGatewayBalances;
19
- exports.getObligations = getObligations;
20
- exports.getTokenSupply = getTokenSupply;
21
- exports.getTokenBalance = getTokenBalance;
22
- exports.getTokenBalances = getTokenBalances;
23
- exports.getLedger = getLedger;
24
- exports.getLatestLedger = getLatestLedger;
25
- exports.getLedgerAtTimestamp = getLedgerAtTimestamp;
26
- exports.getServerInfo = getServerInfo;
27
- /**
28
- * XRP Ledger JSON-RPC client.
29
- *
30
- * Replaces the per-repo XRPL helpers:
31
- * - server/defi/l2/utils.ts (XRPL_RPC, decodeXrplCurrency, isRetryableXrplError,
32
- * xrplRpc, fetchXrplObligations, getXrplSupplies)
33
- * - DefiLlama-Adapters/projects/helper/sumTokens.js (getRippleBalance, ripplePost,
34
- * addRippleTokenBalance, rippleTokenDecimals)
35
- * - peggedassets-server/src/adapters/peggedAssets/helper/getSupply.ts (rippleGetTotalSupply)
36
- * - peggedassets-server/src/adapters/peggedAssets/xsgd/index.ts (rippleMinted)
37
- * - dimension-adapters/helpers/ripple.ts (rpcCall)
38
- *
39
- * XRPL JSON-RPC is not JSON-RPC 2.0: the body is `{ method, params: [{...}] }` and
40
- * the node answers `{ result: { ..., status: 'success' | 'error', error, error_message } }`,
41
- * so `rpc` is implemented directly over `httpPost` instead of `jsonRpc`.
42
- *
43
- * Endpoints: `XRPL_RPC` env (comma separated) overrides `DEFAULT_ENDPOINTS`.
44
- *
45
- * Amount conventions: XRP balances are returned in drops (string, 1 XRP = 1e6 drops);
46
- * issued-currency amounts (`account_lines`, `gateway_balances`) are human-readable
47
- * decimal strings as reported by the ledger (IOUs have no on-chain `decimals`).
48
- */
49
- const crypto_1 = require("crypto");
50
- const rpc_1 = require("./rpc");
51
- const debugLog_1 = require("../util/debugLog");
52
- // ---------------------------------------------------------------------------
53
- // config
54
- // ---------------------------------------------------------------------------
55
- /** Public XRPL nodes that answer bursts without throttling (xrpl.ws / xrpl.link 429 after a few calls). */
56
- exports.DEFAULT_ENDPOINTS = [
57
- 'https://xrplcluster.com',
58
- 'https://s1.ripple.com:51234',
59
- 'https://s2.ripple.com:51234',
60
- ];
61
- /** Seconds between the unix epoch and the ripple epoch (2000-01-01T00:00:00Z). */
62
- exports.RIPPLE_EPOCH_OFFSET = 946684800;
63
- /** Earliest ledger kept by full-history nodes (ledgers before this were lost). */
64
- const EARLIEST_LEDGER = 32570;
65
- const CHAIN = 'xrpl';
66
- const MAX_ATTEMPTS = 4;
67
- const REQUEST_TIMEOUT = 30000;
68
- /** Per-request delay multiplier; 1500ms * attempt covers the ~7s quota window xrplcluster reports on a rate limit. */
69
- const RETRY_DELAY = 1500;
70
- function getEndpoints() {
71
- return (0, rpc_1.getEndpoints)(CHAIN, exports.DEFAULT_ENDPOINTS);
72
- }
73
- class XrplRpcError extends Error {
74
- constructor(method, message, error) {
75
- super(`xrpl ${method} failed: ${message}`);
76
- this.name = 'XrplRpcError';
77
- this.method = method;
78
- this.error = error;
79
- }
80
- }
81
- exports.XrplRpcError = XrplRpcError;
82
- // ---------------------------------------------------------------------------
83
- // pure helpers
84
- // ---------------------------------------------------------------------------
85
- /**
86
- * Decode a ledger currency code: 3-char codes pass through, 40-char hex blobs
87
- * (non-standard codes longer than 3 chars) are decoded to ascii with the trailing
88
- * null padding stripped. Anything else is returned unchanged.
89
- */
90
- function decodeCurrency(code) {
91
- if (typeof code !== 'string')
92
- return code;
93
- if (code.length === 3)
94
- return code;
95
- if (/^[0-9A-Fa-f]{40}$/.test(code)) {
96
- const buf = Buffer.from(code, 'hex');
97
- let end = buf.length;
98
- while (end > 0 && buf[end - 1] === 0)
99
- end--;
100
- return buf.slice(0, end).toString('ascii');
101
- }
102
- return code;
103
- }
104
- /**
105
- * Encode a human-readable currency code for the ledger: 3-char codes pass through,
106
- * longer codes become the 40-char uppercase hex the ledger uses (ascii, null padded).
107
- * A code that already is 40-char hex is returned uppercased.
108
- */
109
- function encodeCurrency(str) {
110
- if (str.length === 3)
111
- return str;
112
- if (/^[0-9A-Fa-f]{40}$/.test(str))
113
- return str.toUpperCase();
114
- if (str.length > 20)
115
- throw new Error(`xrpl currency code too long (max 20 bytes): ${str}`);
116
- return Buffer.from(str, 'ascii').toString('hex').toUpperCase().padEnd(40, '0');
117
- }
118
- /** Accept `'CODE.rISSUER'` or `{ currency, issuer }` and return `{ currency, issuer }`. */
119
- function parseToken(token) {
120
- if (typeof token === 'object' && token !== null) {
121
- if (!token.currency || !token.issuer)
122
- throw new Error(`xrpl: invalid token ${JSON.stringify(token)}`);
123
- return { currency: token.currency, issuer: token.issuer };
124
- }
125
- if (typeof token !== 'string')
126
- throw new Error(`xrpl: invalid token ${String(token)}`);
127
- const dotIdx = token.indexOf('.');
128
- if (dotIdx === -1)
129
- throw new Error(`xrpl: invalid token "${token}", expected "CODE.rISSUER"`);
130
- const currency = token.substring(0, dotIdx);
131
- const issuer = token.substring(dotIdx + 1);
132
- if (!currency || !issuer)
133
- throw new Error(`xrpl: invalid token "${token}", expected "CODE.rISSUER"`);
134
- return { currency, issuer };
135
- }
136
- /** Format `{ currency, issuer }` as `'CODE.rISSUER'`. */
137
- function formatToken({ currency, issuer }) {
138
- return `${currency}.${issuer}`;
139
- }
140
- /**
141
- * xrplcluster answers `tooBusy` / `rate limit` under load, and a paged walk trips its
142
- * units quota on its own. Those are retryable; a malformed request or a real ledger
143
- * error (`actNotFound`, `lgrNotFound`, `invalidParams`, ...) is not.
144
- */
145
- function isRetryableError(message) {
146
- return /rate ?limit|tooBusy|too busy|slowDown|quota|timeout|ECONN|ETIMEDOUT|EAI_AGAIN|socket|network|fetch failed|502|503|504|429|noNetwork|noCurrent|noClosed|empty response/i.test(String(message !== null && message !== void 0 ? message : ''));
147
- }
148
- function rippleTimeToUnix(rippleTime) {
149
- return Number(rippleTime) + exports.RIPPLE_EPOCH_OFFSET;
150
- }
151
- function unixToRippleTime(timestamp) {
152
- return Number(timestamp) - exports.RIPPLE_EPOCH_OFFSET;
153
- }
154
- const RIPPLE_ALPHABET = 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz';
155
- const RIPPLE_ALPHABET_MAP = {};
156
- for (let i = 0; i < RIPPLE_ALPHABET.length; i++)
157
- RIPPLE_ALPHABET_MAP[RIPPLE_ALPHABET[i]] = i;
158
- function base58Decode(str) {
159
- let value = BigInt(0);
160
- const base = BigInt(58);
161
- for (const ch of str) {
162
- const digit = RIPPLE_ALPHABET_MAP[ch];
163
- if (digit === undefined)
164
- return undefined;
165
- value = value * base + BigInt(digit);
166
- }
167
- let hex = value.toString(16);
168
- if (hex.length % 2)
169
- hex = '0' + hex;
170
- let bytes = Buffer.from(hex, 'hex');
171
- // leading zero bytes are encoded as leading 'r' (alphabet index 0)
172
- let leadingZeros = 0;
173
- for (const ch of str) {
174
- if (ch !== RIPPLE_ALPHABET[0])
175
- break;
176
- leadingZeros++;
177
- }
178
- if (value === BigInt(0))
179
- bytes = Buffer.alloc(0);
180
- return Buffer.concat([Buffer.alloc(leadingZeros, 0), bytes]);
181
- }
182
- /**
183
- * Classic address check: ripple base58 alphabet, 25..35 chars, decodes to 25 bytes
184
- * with the account-id type prefix (0x00) and a valid double-sha256 checksum.
185
- */
186
- function isValidAddress(str) {
187
- if (typeof str !== 'string')
188
- return false;
189
- if (str.length < 25 || str.length > 35)
190
- return false;
191
- if (str[0] !== 'r')
192
- return false;
193
- const bytes = base58Decode(str);
194
- if (!bytes || bytes.length !== 25)
195
- return false;
196
- if (bytes[0] !== 0x00)
197
- return false;
198
- const payload = bytes.slice(0, 21);
199
- const checksum = bytes.slice(21);
200
- const hash = (0, crypto_1.createHash)('sha256').update((0, crypto_1.createHash)('sha256').update(payload).digest()).digest();
201
- return hash.slice(0, 4).equals(checksum);
202
- }
203
- /**
204
- * Single XRPL JSON-RPC call. Returns `result`; throws `XrplRpcError` (with the
205
- * node's `error_message` / `error`) when the node reports `status: 'error'`.
206
- * Rotates over the endpoint list and retries only the transient error shapes
207
- * (`tooBusy`, `slowDown`, rate limits, timeouts, 5xx, network errors).
208
- */
209
- async function rpc(method, params = {}, options = {}) {
210
- var _a, _b, _c, _d;
211
- const { ledgerIndex, retries = MAX_ATTEMPTS, timeout = REQUEST_TIMEOUT } = options;
212
- const endpoints = getEndpoints();
213
- const attempts = Math.max(1, retries, endpoints.length);
214
- const call = { ...params };
215
- if (ledgerIndex !== undefined && call.ledger_index === undefined && call.ledger_hash === undefined)
216
- call.ledger_index = ledgerIndex;
217
- const body = { method, params: [call] };
218
- const label = (_b = (_a = params.account) !== null && _a !== void 0 ? _a : call.ledger_index) !== null && _b !== void 0 ? _b : '';
219
- const limiter = (0, rpc_1.getLimiter)(CHAIN, 5);
220
- const start = Math.floor(Math.random() * endpoints.length);
221
- let lastError;
222
- for (let attempt = 0; attempt < attempts; attempt++) {
223
- const url = endpoints[(start + attempt) % endpoints.length];
224
- try {
225
- return await limiter(async () => {
226
- const data = await (0, rpc_1.httpPost)(url, body, { timeout, retries: 1 });
227
- const result = data === null || data === void 0 ? void 0 : data.result;
228
- if (!result || typeof result !== 'object')
229
- throw new XrplRpcError(method, `empty response from ${url}`);
230
- if (result.status === 'error' || result.error) {
231
- // keep both the code (`slowDown`) and the text (`... too busy ...`) so the retry classifier sees either
232
- const text = [result.error, result.error_message].filter(Boolean).join(': ') || 'unknown error';
233
- throw new XrplRpcError(method, text, result.error);
234
- }
235
- return result;
236
- });
237
- }
238
- catch (e) {
239
- lastError = e;
240
- const message = (_c = e === null || e === void 0 ? void 0 : e.message) !== null && _c !== void 0 ? _c : String(e);
241
- const isLast = attempt === attempts - 1;
242
- if (isLast || !isRetryableError(message))
243
- break;
244
- const wait = RETRY_DELAY * (attempt + 1);
245
- (0, debugLog_1.debugLog)(`[chains.xrpl] ${method} ${label} failed (attempt ${attempt + 1}/${attempts}) on ${url}, retrying in ${wait}ms: ${String(message).slice(0, 200)}`);
246
- await (0, rpc_1.sleep)(wait);
247
- }
248
- }
249
- if (lastError instanceof XrplRpcError)
250
- throw lastError;
251
- throw new XrplRpcError(method, `${label} ${(_d = lastError === null || lastError === void 0 ? void 0 : lastError.message) !== null && _d !== void 0 ? _d : String(lastError)}`.trim());
252
- }
253
- function isMissingAccount(e) {
254
- return e instanceof XrplRpcError && (e.error === 'actNotFound' || e.error === 'actMalformed');
255
- }
256
- // ---------------------------------------------------------------------------
257
- // accounts
258
- // ---------------------------------------------------------------------------
259
- /** `account_info` result (`account_data`, `ledger_index`, ...). Throws `actNotFound` for unfunded accounts. */
260
- async function getAccountInfo({ account, ledgerIndex = 'validated' }) {
261
- return rpc('account_info', { account, strict: true }, { ledgerIndex });
262
- }
263
- /** XRP balance in drops as a string. Unfunded / malformed accounts resolve to `'0'`. */
264
- async function getXrpBalance({ account, ledgerIndex = 'validated' }) {
265
- var _a, _b;
266
- try {
267
- const res = await getAccountInfo({ account, ledgerIndex });
268
- return String((_b = (_a = res === null || res === void 0 ? void 0 : res.account_data) === null || _a === void 0 ? void 0 : _a.Balance) !== null && _b !== void 0 ? _b : '0');
269
- }
270
- catch (e) {
271
- if (isMissingAccount(e))
272
- return '0';
273
- throw e;
274
- }
275
- }
276
- /** All trust lines of `account` (walks `marker` pages). Unfunded accounts resolve to `[]`. */
277
- async function getAccountLines({ account, peer, ledgerIndex = 'validated', limit = 400, maxPages = Infinity }) {
278
- const lines = [];
279
- let marker;
280
- let pinnedLedger = ledgerIndex;
281
- let pages = 0;
282
- try {
283
- do {
284
- const params = { account, limit };
285
- if (peer)
286
- params.peer = peer;
287
- if (marker !== undefined)
288
- params.marker = marker;
289
- const res = await rpc('account_lines', params, { ledgerIndex: pinnedLedger });
290
- if (Array.isArray(res.lines))
291
- lines.push(...res.lines);
292
- // pin the ledger after the first page so paging is consistent
293
- if (res.ledger_index !== undefined)
294
- pinnedLedger = res.ledger_index;
295
- marker = res.marker;
296
- pages++;
297
- if (pages >= maxPages && marker) {
298
- (0, debugLog_1.debugLog)(`[chains.xrpl] account_lines ${account}: stopped after ${pages} page(s), more available`);
299
- break;
300
- }
301
- } while (marker !== undefined && marker !== null);
302
- }
303
- catch (e) {
304
- if (isMissingAccount(e) && !lines.length)
305
- return [];
306
- throw e;
307
- }
308
- return lines;
309
- }
310
- /** All ledger objects owned by `account` (walks `marker` pages). `type` filters e.g. `'state'`, `'offer'`, `'escrow'`. */
311
- async function getAccountObjects({ account, type, ledgerIndex = 'validated', limit = 400 }) {
312
- const objects = [];
313
- let marker;
314
- let pinnedLedger = ledgerIndex;
315
- try {
316
- do {
317
- const params = { account, limit };
318
- if (type)
319
- params.type = type;
320
- if (marker !== undefined)
321
- params.marker = marker;
322
- const res = await rpc('account_objects', params, { ledgerIndex: pinnedLedger });
323
- if (Array.isArray(res.account_objects))
324
- objects.push(...res.account_objects);
325
- if (res.ledger_index !== undefined)
326
- pinnedLedger = res.ledger_index;
327
- marker = res.marker;
328
- } while (marker !== undefined && marker !== null);
329
- }
330
- catch (e) {
331
- if (isMissingAccount(e) && !objects.length)
332
- return [];
333
- throw e;
334
- }
335
- return objects;
336
- }
337
- /**
338
- * Raw `gateway_balances` result for an issuer: `obligations` (currency -> total
339
- * owed to non-hot-wallet holders), `balances` (hot wallet holdings), `assets`.
340
- * `hotWallets` are the issuer's own operational accounts; an address equal to the
341
- * issuer is dropped (an issuer is never its own hot wallet and the node errors on it).
342
- */
343
- async function getGatewayBalances({ account, hotWallets = [], ledgerIndex = 'validated' }) {
344
- const hotwallet = hotWallets.filter(w => w && w !== account);
345
- const params = { account, strict: true };
346
- if (hotwallet.length)
347
- params.hotwallet = hotwallet;
348
- return rpc('gateway_balances', params, { ledgerIndex });
349
- }
350
- /**
351
- * Issuer obligations keyed by decoded currency code (circulating supply per
352
- * currency). Obligations owed to `hotWallets` are un-issued float and excluded by
353
- * the node. Throws rather than returning `{}` on a failed read, so an unreadable
354
- * issuer never looks like a zero-supply one.
355
- */
356
- async function getObligations({ issuer, hotWallets = [], ledgerIndex = 'validated' }) {
357
- var _a;
358
- const res = await getGatewayBalances({ account: issuer, hotWallets, ledgerIndex });
359
- const obligations = (_a = res === null || res === void 0 ? void 0 : res.obligations) !== null && _a !== void 0 ? _a : {};
360
- const decoded = {};
361
- for (const [code, amount] of Object.entries(obligations)) {
362
- const key = decodeCurrency(code);
363
- if (decoded[key] === undefined)
364
- decoded[key] = String(amount);
365
- else
366
- decoded[key] = String(Number(decoded[key]) + Number(amount)); // two encodings of the same code, extremely rare
367
- }
368
- return decoded;
369
- }
370
- /**
371
- * Circulating supply of one issued currency as a decimal string (`'0'` when the
372
- * issuer has no such obligation). `currency` may be the 3-char / human code or the
373
- * 40-char hex form; `'CODE.rISSUER'` is accepted too.
374
- */
375
- async function getTokenSupply(token, { hotWallets, ledgerIndex } = {}) {
376
- var _a;
377
- const { currency, issuer } = parseToken(token);
378
- if (typeof token === 'object') {
379
- hotWallets = hotWallets !== null && hotWallets !== void 0 ? hotWallets : token.hotWallets;
380
- ledgerIndex = ledgerIndex !== null && ledgerIndex !== void 0 ? ledgerIndex : token.ledgerIndex;
381
- }
382
- const obligations = await getObligations({ issuer, hotWallets, ledgerIndex });
383
- return (_a = obligations[decodeCurrency(currency)]) !== null && _a !== void 0 ? _a : '0';
384
- }
385
- /**
386
- * Balance of an issued currency held by `account` (trust line with `issuer`), as
387
- * the human-readable decimal string reported by `account_lines`. `'0'` when there is
388
- * no such line. Negative values mean `account` is itself the issuer of that line.
389
- */
390
- async function getTokenBalance({ account, currency, issuer, ledgerIndex = 'validated' }) {
391
- const lines = await getAccountLines({ account, peer: issuer, ledgerIndex });
392
- const wanted = decodeCurrency(currency);
393
- const line = lines.find(l => l.account === issuer && decodeCurrency(l.currency) === wanted);
394
- return line ? String(line.balance) : '0';
395
- }
396
- /**
397
- * All issued-currency balances of `account` keyed by `'CODE.rISSUER'` (currency
398
- * kept in ledger form). Amounts are human-readable decimal strings.
399
- */
400
- async function getTokenBalances({ account, ledgerIndex = 'validated' }) {
401
- const lines = await getAccountLines({ account, ledgerIndex });
402
- const balances = {};
403
- for (const line of lines)
404
- balances[formatToken({ currency: line.currency, issuer: line.account })] = String(line.balance);
405
- return balances;
406
- }
407
- // ---------------------------------------------------------------------------
408
- // ledgers
409
- // ---------------------------------------------------------------------------
410
- /** Ledger header: `{ number, timestamp (unix seconds), hash }`. */
411
- async function getLedger({ ledgerIndex = 'validated' } = {}) {
412
- var _a, _b, _c, _d, _e;
413
- const res = await rpc('ledger', { transactions: false, expand: false, accounts: false }, { ledgerIndex });
414
- const ledger = (_c = (_a = res.ledger) !== null && _a !== void 0 ? _a : (_b = res.closed) === null || _b === void 0 ? void 0 : _b.ledger) !== null && _c !== void 0 ? _c : {};
415
- const number = Number((_d = ledger.ledger_index) !== null && _d !== void 0 ? _d : res.ledger_index);
416
- const closeTime = ledger.close_time;
417
- if (!Number.isFinite(number) || closeTime === undefined)
418
- throw new XrplRpcError('ledger', `unexpected response for ledger ${ledgerIndex}`);
419
- return {
420
- number,
421
- timestamp: rippleTimeToUnix(Number(closeTime)),
422
- hash: (_e = ledger.ledger_hash) !== null && _e !== void 0 ? _e : res.ledger_hash,
423
- };
424
- }
425
- async function getLatestLedger() {
426
- return getLedger({ ledgerIndex: 'validated' });
427
- }
428
- /**
429
- * Last validated ledger closed at or before `timestamp` (unix seconds). Binary
430
- * search on `ledger_index`, starting from a bracket estimated with the ~3s minimum
431
- * close interval. Requires a full-history node for old timestamps.
432
- */
433
- async function getLedgerAtTimestamp({ timestamp }) {
434
- const latest = await getLatestLedger();
435
- if (timestamp >= latest.timestamp)
436
- return latest;
437
- let high = latest.number;
438
- // ledgers close no faster than ~3s, so this many ledgers back is guaranteed to be at/before the target
439
- const estimate = Math.max(EARLIEST_LEDGER, high - Math.ceil((latest.timestamp - timestamp) / 3) - 10);
440
- let low = EARLIEST_LEDGER;
441
- if (estimate > EARLIEST_LEDGER) {
442
- const guess = await getLedger({ ledgerIndex: estimate });
443
- if (guess.timestamp <= timestamp)
444
- low = guess.number;
445
- else
446
- high = guess.number;
447
- }
448
- let best;
449
- while (low <= high) {
450
- const mid = Math.floor((low + high) / 2);
451
- const ledger = await getLedger({ ledgerIndex: mid });
452
- if (ledger.timestamp <= timestamp) {
453
- best = ledger;
454
- low = mid + 1;
455
- }
456
- else {
457
- high = mid - 1;
458
- }
459
- }
460
- if (!best)
461
- throw new Error(`xrpl: no ledger found at or before timestamp ${timestamp}`);
462
- return best;
463
- }
464
- /** `server_info` result (`info.validated_ledger`, `info.complete_ledgers`, ...). */
465
- async function getServerInfo() {
466
- return rpc('server_info');
467
- }
@@ -1 +0,0 @@
1
- export { getChainBlocks, getBlocks, getBlock, getCurrentBlocks, chainsForBlocks, getBlockNumber, getLatestBlock, lookupBlock, } from "../util/blocks";
@@ -1,12 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.lookupBlock = exports.getLatestBlock = exports.getBlockNumber = exports.chainsForBlocks = exports.getCurrentBlocks = exports.getBlock = exports.getBlocks = exports.getChainBlocks = void 0;
4
- var blocks_1 = require("../util/blocks");
5
- Object.defineProperty(exports, "getChainBlocks", { enumerable: true, get: function () { return blocks_1.getChainBlocks; } });
6
- Object.defineProperty(exports, "getBlocks", { enumerable: true, get: function () { return blocks_1.getBlocks; } });
7
- Object.defineProperty(exports, "getBlock", { enumerable: true, get: function () { return blocks_1.getBlock; } });
8
- Object.defineProperty(exports, "getCurrentBlocks", { enumerable: true, get: function () { return blocks_1.getCurrentBlocks; } });
9
- Object.defineProperty(exports, "chainsForBlocks", { enumerable: true, get: function () { return blocks_1.chainsForBlocks; } });
10
- Object.defineProperty(exports, "getBlockNumber", { enumerable: true, get: function () { return blocks_1.getBlockNumber; } });
11
- Object.defineProperty(exports, "getLatestBlock", { enumerable: true, get: function () { return blocks_1.getLatestBlock; } });
12
- Object.defineProperty(exports, "lookupBlock", { enumerable: true, get: function () { return blocks_1.lookupBlock; } });
@@ -1 +0,0 @@
1
- export declare function humanizeNumber(amount: number): string;
@@ -1,19 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.humanizeNumber = humanizeNumber;
4
- function humanizeNumber(amount) {
5
- if (amount < 0)
6
- return '-' + humanizeNumber(-amount);
7
- const quantifiers = [
8
- [10 ** 12, "T"],
9
- [10 ** 9, "B"],
10
- [10 ** 6, "M"],
11
- [10 ** 3, "k"],
12
- ];
13
- for (const [denominator, letter] of quantifiers) {
14
- if (amount > denominator) {
15
- return `${(amount / denominator).toFixed(2)} ${letter}`;
16
- }
17
- }
18
- return Number(amount).toFixed(2);
19
- }