@raac/rpc 2.0.0-beta.11 → 2.0.0-beta.13

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 (82) hide show
  1. package/dist/RPCLibrary.js +53 -22
  2. package/dist/configs/chains/11155111.json +16 -28
  3. package/dist/contracts/complianceRegistry/getStatuses.js +40 -0
  4. package/dist/contracts/crvUSDToUSDOracle/getState.js +58 -0
  5. package/dist/contracts/curve/common/_helpers.js +57 -0
  6. package/dist/contracts/curve/common/addLiquidity.js +30 -0
  7. package/dist/contracts/curve/common/calcTokenAmount.js +23 -0
  8. package/dist/contracts/curve/common/calcWithdrawOneCoin.js +21 -0
  9. package/dist/contracts/curve/common/exchange.js +33 -0
  10. package/dist/contracts/curve/common/getDy.js +22 -0
  11. package/dist/contracts/curve/common/index.js +7 -0
  12. package/dist/contracts/curve/common/removeLiquidity.js +30 -0
  13. package/dist/contracts/curve/common/removeLiquidityOneCoin.js +31 -0
  14. package/dist/contracts/faucet/claim.js +37 -0
  15. package/dist/contracts/faucet/index.js +17 -0
  16. package/dist/contracts/feeCollector/getState.js +100 -0
  17. package/dist/contracts/getRoles.js +35 -0
  18. package/dist/contracts/housePrices/getState.js +41 -0
  19. package/dist/contracts/psm/getVaultSettings.js +60 -0
  20. package/dist/contracts/treasury/getState.js +46 -0
  21. package/dist/minter/emissionSchedule.js +90 -0
  22. package/dist/pools/lendingPool/getAdminState.js +47 -0
  23. package/dist/pools/rwaVault/getRegisteredAdapters.js +78 -0
  24. package/dist/pools/rwaVault/getSeedStatus.js +45 -0
  25. package/dist/pools/stabilityPool/getAdminState.js +42 -0
  26. package/dist/pools/stabilityPool/liquidation.js +297 -0
  27. package/dist/prices/tokenPricesUSD.js +0 -2
  28. package/dist/types/RPCLibrary.d.ts +44 -14
  29. package/dist/types/contracts/complianceRegistry/getStatuses.d.ts +25 -0
  30. package/dist/types/contracts/crvUSDToUSDOracle/getState.d.ts +36 -0
  31. package/dist/types/contracts/curve/common/_helpers.d.ts +10 -1
  32. package/dist/types/contracts/curve/common/addLiquidity.d.ts +14 -0
  33. package/dist/types/contracts/curve/common/calcTokenAmount.d.ts +10 -0
  34. package/dist/types/contracts/curve/common/calcWithdrawOneCoin.d.ts +8 -0
  35. package/dist/types/contracts/curve/common/exchange.d.ts +16 -0
  36. package/dist/types/contracts/curve/common/getDy.d.ts +8 -0
  37. package/dist/types/contracts/curve/common/index.d.ts +7 -0
  38. package/dist/types/contracts/curve/common/removeLiquidity.d.ts +14 -0
  39. package/dist/types/contracts/curve/common/removeLiquidityOneCoin.d.ts +15 -0
  40. package/dist/types/contracts/faucet/claim.d.ts +18 -0
  41. package/dist/types/contracts/faucet/index.d.ts +1 -0
  42. package/dist/types/contracts/feeCollector/getState.d.ts +42 -0
  43. package/dist/types/contracts/getRoles.d.ts +15 -0
  44. package/dist/types/contracts/housePrices/getState.d.ts +24 -0
  45. package/dist/types/contracts/psm/getVaultSettings.d.ts +38 -0
  46. package/dist/types/contracts/treasury/getState.d.ts +24 -0
  47. package/dist/types/minter/emissionSchedule.d.ts +53 -0
  48. package/dist/types/pools/lendingPool/getAdminState.d.ts +26 -0
  49. package/dist/types/pools/rwaVault/getRegisteredAdapters.d.ts +33 -0
  50. package/dist/types/pools/rwaVault/getSeedStatus.d.ts +27 -0
  51. package/dist/types/pools/stabilityPool/getAdminState.d.ts +25 -0
  52. package/dist/types/pools/stabilityPool/liquidation.d.ts +112 -0
  53. package/dist/types/typechain-types/contracts/core/collectors/index.d.ts +0 -2
  54. package/dist/types/typechain-types/contracts/mocks/core/tokens/index.d.ts +0 -1
  55. package/dist/types/typechain-types/factories/contracts/core/collectors/index.d.ts +0 -1
  56. package/dist/types/typechain-types/factories/contracts/mocks/core/tokens/index.d.ts +0 -1
  57. package/dist/types/typechain-types/index.d.ts +0 -4
  58. package/dist/types/utils/artifacts.d.ts +0 -198
  59. package/dist/utils/artifacts.js +0 -4
  60. package/package.json +14 -4
  61. package/dist/artifacts/core/collectors/fee-streamer/RentStreamer.sol/RentStreamer.json +0 -838
  62. package/dist/artifacts/mocks/core/tokens/USDCTokenLimited.sol/USDCTokenLimited.json +0 -558
  63. package/dist/contracts/rentStreamer/_helpers.js +0 -19
  64. package/dist/contracts/rentStreamer/getEpochProjection.js +0 -91
  65. package/dist/contracts/rentStreamer/getScheduled.js +0 -19
  66. package/dist/contracts/rentStreamer/getState.js +0 -40
  67. package/dist/contracts/rentStreamer/previewRelease.js +0 -23
  68. package/dist/contracts/rentStreamer/release.js +0 -22
  69. package/dist/contracts/rentStreamer/sync.js +0 -21
  70. package/dist/types/contracts/rentStreamer/_helpers.d.ts +0 -4
  71. package/dist/types/contracts/rentStreamer/getEpochProjection.d.ts +0 -40
  72. package/dist/types/contracts/rentStreamer/getScheduled.d.ts +0 -12
  73. package/dist/types/contracts/rentStreamer/getState.d.ts +0 -33
  74. package/dist/types/contracts/rentStreamer/previewRelease.d.ts +0 -20
  75. package/dist/types/contracts/rentStreamer/release.d.ts +0 -12
  76. package/dist/types/contracts/rentStreamer/sync.d.ts +0 -11
  77. package/dist/types/typechain-types/contracts/core/collectors/fee-streamer/RentStreamer.d.ts +0 -422
  78. package/dist/types/typechain-types/contracts/core/collectors/fee-streamer/index.d.ts +0 -1
  79. package/dist/types/typechain-types/contracts/mocks/core/tokens/USDCTokenLimited.d.ts +0 -238
  80. package/dist/types/typechain-types/factories/contracts/core/collectors/fee-streamer/RentStreamer__factory.d.ts +0 -665
  81. package/dist/types/typechain-types/factories/contracts/core/collectors/fee-streamer/index.d.ts +0 -1
  82. package/dist/types/typechain-types/factories/contracts/mocks/core/tokens/USDCTokenLimited__factory.d.ts +0 -439
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.removeLiquidityOneCoin = void 0;
4
+ const rpcError_1 = require("../../../utils/rpcError");
5
+ const _helpers_1 = require("./_helpers");
6
+ /**
7
+ * Burns LP tokens for a single coin of a Curve pool.
8
+ *
9
+ * @param chainId - The chain/network to use.
10
+ * @param poolAddressOrId - The pool's key in the chain config's `curve` section, or its address.
11
+ * @param lpAmount - LP tokens to burn (18 decimals).
12
+ * @param i - Index of the coin to receive, in pool order.
13
+ * @param minAmount - The least of coin `i` to accept, in its base units. See `calcWithdrawOneCoin`.
14
+ * @param receiver - Who receives the coin.
15
+ * @param signer - The signer sending the transaction.
16
+ * @returns The mined transaction receipt.
17
+ */
18
+ const removeLiquidityOneCoin = async (chainId, poolAddressOrId, lpAmount, i, minAmount, receiver, signer) => {
19
+ if (!signer)
20
+ throw new Error("Signer is required");
21
+ const { entry, contract } = (0, _helpers_1.getCurvePoolFlavourContract)(chainId, poolAddressOrId, signer);
22
+ (0, _helpers_1.assertCoinIndex)(entry, i);
23
+ try {
24
+ const tx = await contract.remove_liquidity_one_coin(lpAmount, i, minAmount, receiver);
25
+ return await tx.wait();
26
+ }
27
+ catch (error) {
28
+ throw (0, rpcError_1.toRpcError)("curve.removeLiquidityOneCoin", error, { chainId, address: entry.contract });
29
+ }
30
+ };
31
+ exports.removeLiquidityOneCoin = removeLiquidityOneCoin;
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.claim = void 0;
4
+ const ethers_1 = require("ethers");
5
+ const contracts_1 = require("../../utils/contracts");
6
+ const rpcError_1 = require("../../utils/rpcError");
7
+ const FAUCET_CLAIM_ABI = [
8
+ "function claim(address token, uint256 amount)",
9
+ "function claimMultiple(address[] tokens, uint256[] amounts)",
10
+ ];
11
+ /**
12
+ * Claims testnet tokens from the faucet: one `claim` for a single token, one `claimMultiple` for several.
13
+ *
14
+ * @param chainId - The chain/network to use; only chains with a `faucet` contract in their config.
15
+ * @param claims - The tokens and amounts to claim.
16
+ * @param signer - The signer sending the transaction; the tokens go to its address.
17
+ * @returns The mined transaction receipt.
18
+ * @throws If the chain has no faucet, `claims` is empty, or the transaction fails.
19
+ */
20
+ const claim = async (chainId, claims, signer) => {
21
+ if (!signer)
22
+ throw new Error("Signer is required");
23
+ if (claims.length === 0)
24
+ throw new Error("Nothing to claim");
25
+ const address = (0, contracts_1.getContractAddress)(chainId, "faucet");
26
+ try {
27
+ const faucet = new ethers_1.ethers.Contract(address, FAUCET_CLAIM_ABI, signer);
28
+ const tx = claims.length === 1
29
+ ? await faucet.claim(claims[0].token, claims[0].amount)
30
+ : await faucet.claimMultiple(claims.map(({ token }) => token), claims.map(({ amount }) => amount));
31
+ return await tx.wait();
32
+ }
33
+ catch (error) {
34
+ throw (0, rpcError_1.toRpcError)("faucet.claim", error, { chainId, address });
35
+ }
36
+ };
37
+ exports.claim = claim;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./claim"), exports);
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KNOWN_FEE_TYPES = exports.FEE_TARGETS = void 0;
4
+ const ethers_1 = require("ethers");
5
+ const contracts_1 = require("../../utils/contracts");
6
+ const artifacts_1 = require("../../utils/artifacts");
7
+ const amount_1 = require("../../utils/amount");
8
+ const rpcError_1 = require("../../utils/rpcError");
9
+ /** The six places a fee type splits into, as FeeCollector names them. */
10
+ exports.FEE_TARGETS = ["TREASURY", "REPAIR_FUND", "BURN", "VERAAC", "RAAC_CORP", "OTHER"];
11
+ /** Fee type names used across the protocol; others show as their raw bytes32. */
12
+ exports.KNOWN_FEE_TYPES = [
13
+ "LENDING_POOL_YIELD",
14
+ "RAAC_NFT_SALE",
15
+ "ROYALTY_FEE",
16
+ "SWAP_FEE",
17
+ "INSURANCE_FEE",
18
+ "PROTOCOL_FEE",
19
+ "LENDING_FEE",
20
+ "MINT_FEE",
21
+ "RWA_INDEX_TOKEN_SWAP_FEE",
22
+ "RWA_INDEX_TOKEN_LIQUIDITY_REWARDS",
23
+ ];
24
+ const TARGET_GETTERS = {
25
+ TREASURY: "treasuryAddress",
26
+ REPAIR_FUND: "repairFundAddress",
27
+ BURN: "burnAddress",
28
+ VERAAC: "veRAACAddress",
29
+ RAAC_CORP: "raacCorpAddress",
30
+ OTHER: "otherAddress",
31
+ };
32
+ const AMOUNT_FIELDS = {
33
+ TREASURY: "treasuryAmount",
34
+ REPAIR_FUND: "repairFundAmount",
35
+ BURN: "burnAmount",
36
+ VERAAC: "veRAACTokenAmount",
37
+ RAAC_CORP: "raacCorpAmount",
38
+ OTHER: "otherAmount",
39
+ };
40
+ const SHARE_FIELDS = {
41
+ TREASURY: "treasuryShare",
42
+ REPAIR_FUND: "repairFundShare",
43
+ BURN: "burnShare",
44
+ VERAAC: "veRAACTokenShare",
45
+ RAAC_CORP: "raacCorpShare",
46
+ OTHER: "otherShare",
47
+ };
48
+ /**
49
+ * Reads the FeeCollector: pause state, targets, fee types and their splits, supported tokens, and what is still owed
50
+ * per token, fee type and target. Walks `supportedTokens(i)` until the index reverts.
51
+ * @param chainId The chain id.
52
+ * @param provider The provider to read with.
53
+ */
54
+ async function getState(chainId, provider) {
55
+ const address = (0, contracts_1.getContractAddress)(chainId, "feecollector");
56
+ try {
57
+ const fc = new ethers_1.ethers.Contract(address, (0, artifacts_1.getABI)("feecollector"), provider);
58
+ const [paused, targetList, rawTypes] = await Promise.all([
59
+ fc.paused(),
60
+ Promise.all(exports.FEE_TARGETS.map((t) => fc[TARGET_GETTERS[t]]())),
61
+ fc.getFeeTypes(),
62
+ ]);
63
+ const names = new Map(exports.KNOWN_FEE_TYPES.map((n) => [ethers_1.ethers.id(n), n]));
64
+ const feeTypes = rawTypes.map((t) => ({
65
+ id: t.feeType,
66
+ name: names.get(t.feeType) ?? null,
67
+ shares: Object.fromEntries(exports.FEE_TARGETS.map((target) => [target, BigInt(t[SHARE_FIELDS[target]])])),
68
+ }));
69
+ const list = [];
70
+ for (let i = 0; i < 200; i++) {
71
+ try {
72
+ list.push(ethers_1.ethers.getAddress(await fc.supportedTokens(i)));
73
+ }
74
+ catch (error) {
75
+ if (ethers_1.ethers.isError(error, "CALL_EXCEPTION"))
76
+ break;
77
+ throw error;
78
+ }
79
+ }
80
+ const tokens = await Promise.all(list.map(async (token) => {
81
+ const erc20 = new ethers_1.ethers.Contract(token, ["function symbol() view returns (string)", "function decimals() view returns (uint8)"], provider);
82
+ const [symbol, decimals] = await Promise.all([erc20.symbol().catch(() => "?"), erc20.decimals().then(Number).catch(() => 18)]);
83
+ return { address: token, symbol, decimals };
84
+ }));
85
+ const pairs = tokens.flatMap((token) => feeTypes.map((feeType) => ({ token, feeType })));
86
+ const collected = (await Promise.all(pairs.map(async ({ token, feeType }) => {
87
+ const c = await fc.getCollectedFees(token.address, feeType.id);
88
+ return {
89
+ token: token.address,
90
+ feeType: feeType.id,
91
+ amounts: Object.fromEntries(exports.FEE_TARGETS.map((t) => [t, (0, amount_1.toAmount)(c[AMOUNT_FIELDS[t]], token.decimals, token.symbol)])),
92
+ };
93
+ }))).filter((c) => exports.FEE_TARGETS.some((t) => c.amounts[t].value > BigInt(0)));
94
+ return { paused, targets: Object.fromEntries(exports.FEE_TARGETS.map((t, i) => [t, targetList[i]])), feeTypes, tokens, collected };
95
+ }
96
+ catch (error) {
97
+ throw (0, rpcError_1.toRpcError)("feeCollector.getState", error, { chainId, address });
98
+ }
99
+ }
100
+ exports.default = getState;
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.roleId = roleId;
4
+ const ethers_1 = require("ethers");
5
+ const rpcError_1 = require("../utils/rpcError");
6
+ const ACCESS_ABI = ["function hasRole(bytes32 role, address account) view returns (bool)"];
7
+ /** OpenZeppelin role ids: DEFAULT_ADMIN_ROLE is zero, every other role is the keccak of its name. */
8
+ function roleId(role) {
9
+ if (/^0x[0-9a-fA-F]{64}$/.test(role))
10
+ return role;
11
+ return role === "DEFAULT_ADMIN_ROLE" ? ethers_1.ethers.ZeroHash : ethers_1.ethers.id(role);
12
+ }
13
+ /**
14
+ * Which of an AccessControl contract's roles each account holds, e.g. to show what a Safe and a wallet may do.
15
+ * @param chainId The chain id, for error context.
16
+ * @param contractAddress The AccessControl contract.
17
+ * @param roles Role names ("GUARDIAN_ROLE", "DEFAULT_ADMIN_ROLE") or raw 32-byte ids.
18
+ * @param accounts The accounts to check.
19
+ * @param provider The provider to read with.
20
+ * @returns Keyed by lowercased account address, then by role as passed in.
21
+ */
22
+ async function getRoles(chainId, contractAddress, roles, accounts, provider) {
23
+ try {
24
+ const contract = new ethers_1.ethers.Contract(contractAddress, ACCESS_ABI, provider);
25
+ const entries = await Promise.all(accounts.map(async (account) => {
26
+ const held = await Promise.all(roles.map((role) => contract.hasRole(roleId(role), account)));
27
+ return [account.toLowerCase(), Object.fromEntries(roles.map((role, i) => [role, held[i]]))];
28
+ }));
29
+ return Object.fromEntries(entries);
30
+ }
31
+ catch (error) {
32
+ throw (0, rpcError_1.toRpcError)("contracts.getRoles", error, { chainId, address: contractAddress });
33
+ }
34
+ }
35
+ exports.default = getRoles;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const ethers_1 = require("ethers");
4
+ const contracts_1 = require("../../utils/contracts");
5
+ const artifacts_1 = require("../../utils/artifacts");
6
+ const rpcError_1 = require("../../utils/rpcError");
7
+ /**
8
+ * Reads who administers RAACHousePrices, who may set prices, and its syncers.
9
+ * @param chainId The chain id.
10
+ * @param provider The provider to read with.
11
+ */
12
+ async function getState(chainId, provider) {
13
+ const address = (0, contracts_1.getContractAddress)(chainId, "raachouseprices");
14
+ try {
15
+ const hp = new ethers_1.ethers.Contract(address, (0, artifacts_1.getABI)("raachouseprices"), provider);
16
+ const [owner, oracle, crvUSDToUSDOracle, count, lastUpdateTimestamp, maxSyncers] = await Promise.all([
17
+ hp.owner(),
18
+ hp.oracle(),
19
+ hp.crvUSDToUSDOracle(),
20
+ hp.count(),
21
+ hp.lastUpdateTimestamp(),
22
+ hp.MAX_SYNCERS(),
23
+ ]);
24
+ const syncers = [];
25
+ for (let i = 0; i < Number(maxSyncers); i++) {
26
+ try {
27
+ syncers.push(ethers_1.ethers.getAddress(await hp.syncers(i)));
28
+ }
29
+ catch (error) {
30
+ if (ethers_1.ethers.isError(error, "CALL_EXCEPTION"))
31
+ break;
32
+ throw error;
33
+ }
34
+ }
35
+ return { owner, oracle, crvUSDToUSDOracle, count: Number(count), lastUpdateTimestamp: Number(lastUpdateTimestamp), syncers, maxSyncers: Number(maxSyncers) };
36
+ }
37
+ catch (error) {
38
+ throw (0, rpcError_1.toRpcError)("housePrices.getState", error, { chainId, address });
39
+ }
40
+ }
41
+ exports.default = getState;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getVaultSettings = getVaultSettings;
4
+ const _helpers_1 = require("./_helpers");
5
+ const rpcError_1 = require("../../utils/rpcError");
6
+ /**
7
+ * Reads a PSM vault's settings from its storage getters only. Unlike `getVaultInfo`, nothing here touches the rate
8
+ * provider, so it still answers when the savings token price is stale (`StalePrice`), which is when an operator
9
+ * needs to see and change these settings.
10
+ * @param chainId - The chain/network to use.
11
+ * @param vaultKeyOrAddress - The vault's config key (e.g. "rpsm-susds") or its deployed address.
12
+ * @param provider - Optional ethers.js Provider instance.
13
+ */
14
+ async function getVaultSettings(chainId, vaultKeyOrAddress, provider) {
15
+ const { entry } = (0, _helpers_1.resolvePsmVault)(chainId, vaultKeyOrAddress);
16
+ try {
17
+ const vault = (0, _helpers_1.getPsmVaultContract)(chainId, vaultKeyOrAddress, provider ?? (0, _helpers_1.getDefaultProvider)(chainId));
18
+ const [paused, swapFee, minWithdrawFee, maxWithdrawFee, withdrawTime, withdrawTimeLimit, circuitBreakerEnabled, navFloor, reserveRatioFloor, rebalanceThreshold, depositCap, savingsTokenDecimals, baseAsset, savingsToken, rateProvider, rebalancer, baseAssetModule,] = await Promise.all([
19
+ vault.paused(),
20
+ vault.swapFee(),
21
+ vault.minWithdrawFee(),
22
+ vault.maxWithdrawFee(),
23
+ vault.withdrawTime(),
24
+ vault.withdrawTimeLimit(),
25
+ vault.circuitBreakerEnabled(),
26
+ vault.navFloor(),
27
+ vault.reserveRatioFloor(),
28
+ vault.rebalanceThreshold(),
29
+ vault.depositCap(),
30
+ vault.savingsTokenDecimals(),
31
+ vault.baseAsset(),
32
+ vault.savingsToken(),
33
+ vault.rateProvider(),
34
+ vault.rebalancer(),
35
+ vault.baseAssetModule(),
36
+ ]);
37
+ return {
38
+ paused,
39
+ swapFee,
40
+ minWithdrawFee,
41
+ maxWithdrawFee,
42
+ withdrawTime,
43
+ withdrawTimeLimit,
44
+ circuitBreakerEnabled,
45
+ navFloor,
46
+ reserveRatioFloor,
47
+ rebalanceThreshold,
48
+ depositCap,
49
+ savingsTokenDecimals: Number(savingsTokenDecimals),
50
+ baseAsset,
51
+ savingsToken,
52
+ rateProvider,
53
+ rebalancer,
54
+ baseAssetModule,
55
+ };
56
+ }
57
+ catch (error) {
58
+ throw (0, rpcError_1.toRpcError)("psm.getVaultSettings", error, { chainId, address: entry.contract });
59
+ }
60
+ }
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const ethers_1 = require("ethers");
4
+ const contracts_1 = require("../../utils/contracts");
5
+ const artifacts_1 = require("../../utils/artifacts");
6
+ const amount_1 = require("../../utils/amount");
7
+ const rpcError_1 = require("../../utils/rpcError");
8
+ const ERC20 = ["function symbol() view returns (string)", "function decimals() view returns (uint8)", "function balanceOf(address) view returns (uint256)"];
9
+ /**
10
+ * Reads every token the Treasury supports, with its tracked and actual balances. Walks `supportedTokens(i)` until the
11
+ * index reverts; any other error is thrown so a flaky node never returns a shortened list.
12
+ * @param chainId The chain id.
13
+ * @param provider The provider to read with.
14
+ */
15
+ async function getState(chainId, provider) {
16
+ const address = (0, contracts_1.getContractAddress)(chainId, "treasury");
17
+ try {
18
+ const treasury = new ethers_1.ethers.Contract(address, (0, artifacts_1.getABI)("treasury"), provider);
19
+ const list = [];
20
+ for (let i = 0; i < 200; i++) {
21
+ try {
22
+ list.push(ethers_1.ethers.getAddress(await treasury.supportedTokens(i)));
23
+ }
24
+ catch (error) {
25
+ if (ethers_1.ethers.isError(error, "CALL_EXCEPTION"))
26
+ break;
27
+ throw error;
28
+ }
29
+ }
30
+ const tokens = await Promise.all(list.map(async (token) => {
31
+ const erc20 = new ethers_1.ethers.Contract(token, ERC20, provider);
32
+ const [symbol, decimals, tracked, held] = await Promise.all([
33
+ erc20.symbol().catch(() => "?"),
34
+ erc20.decimals().then(Number).catch(() => null),
35
+ treasury.getBalance(token),
36
+ erc20.balanceOf(address).catch(() => null),
37
+ ]);
38
+ return { address: token, symbol, decimals, tracked: (0, amount_1.toAmount)(tracked, decimals ?? 18, symbol), held: held === null ? null : (0, amount_1.toAmount)(held, decimals ?? 18, symbol) };
39
+ }));
40
+ return { tokens };
41
+ }
42
+ catch (error) {
43
+ throw (0, rpcError_1.toRpcError)("treasury.getState", error, { chainId, address });
44
+ }
45
+ }
46
+ exports.default = getState;
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ /**
3
+ * TypeScript port of contracts/libraries/minters/EmissionSchedule.sol. The schedule is pure (no storage), so the
4
+ * whole curve can be drawn without one RPC call per week; the only on-chain input is the activation timestamp
5
+ * (`mintingStartAtTimestamp`). All amounts are RAAC base units (18 decimals).
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.LAST_EMISSION_WEEK = exports.WEEKS_PER_PERIOD = exports.WEEK_REDUCTION_START = exports.BASE_PER_SECOND = exports.BASE_WEEKLY_EMISSION = void 0;
9
+ exports.getEmissionPerSecondForWeek = getEmissionPerSecondForWeek;
10
+ exports.getMintingWeekForTimestamp = getMintingWeekForTimestamp;
11
+ exports.getEmissionSchedule = getEmissionSchedule;
12
+ exports.getSchedulePosition = getSchedulePosition;
13
+ const E18 = BigInt("1000000000000000000");
14
+ const WEEK = BigInt(7 * 24 * 3600);
15
+ /** RAAC emitted in each of the first 104 weeks. Divisible by 604800, so the per-second rate is exact. */
16
+ exports.BASE_WEEKLY_EMISSION = BigInt("23852798580398015692800");
17
+ exports.BASE_PER_SECOND = exports.BASE_WEEKLY_EMISSION / WEEK;
18
+ /** First week of the reduction phase. */
19
+ exports.WEEK_REDUCTION_START = 105;
20
+ /** The rate drops by 5% every this many weeks. */
21
+ exports.WEEKS_PER_PERIOD = 13;
22
+ /** Weeks 781 and later emit nothing. */
23
+ exports.LAST_EMISSION_WEEK = 780;
24
+ /** 0.95^exponent with 1e18 precision, rounding exactly as the contract's `pow95`. */
25
+ function pow95(exponent) {
26
+ let base = BigInt("950000000000000000");
27
+ let result = E18;
28
+ let e = exponent;
29
+ while (e !== BigInt(0)) {
30
+ if ((e & BigInt(1)) === BigInt(1))
31
+ result = (result * base) / E18;
32
+ base = (base * base) / E18;
33
+ e >>= BigInt(1);
34
+ }
35
+ return result;
36
+ }
37
+ /**
38
+ * RAAC emitted per second during a 1-based schedule week.
39
+ * @param week The schedule week; 0 and weeks after 780 emit nothing.
40
+ */
41
+ function getEmissionPerSecondForWeek(week) {
42
+ if (week <= 0 || week > exports.LAST_EMISSION_WEEK)
43
+ return BigInt(0);
44
+ if (week < exports.WEEK_REDUCTION_START)
45
+ return exports.BASE_PER_SECOND;
46
+ const periods = BigInt(Math.floor((week - exports.WEEK_REDUCTION_START) / exports.WEEKS_PER_PERIOD) + 1);
47
+ return (exports.BASE_PER_SECOND * pow95(periods)) / E18;
48
+ }
49
+ /**
50
+ * The 1-based schedule week a timestamp falls in, 0 before activation.
51
+ * @param activationTimestamp `mintingStartAtTimestamp`, in UNIX seconds.
52
+ * @param timestamp The moment to place, in UNIX seconds.
53
+ */
54
+ function getMintingWeekForTimestamp(activationTimestamp, timestamp) {
55
+ if (!activationTimestamp || timestamp < activationTimestamp)
56
+ return 0;
57
+ return Math.floor((timestamp - activationTimestamp) / Number(WEEK)) + 1;
58
+ }
59
+ let schedule = null;
60
+ /** Every week of the schedule, 1 through 780, with running totals. The last `cumulative` is the lifetime emission. */
61
+ function getEmissionSchedule() {
62
+ if (schedule)
63
+ return schedule;
64
+ let cumulative = BigInt(0);
65
+ schedule = Array.from({ length: exports.LAST_EMISSION_WEEK }, (_, i) => {
66
+ const week = i + 1;
67
+ const perSecond = getEmissionPerSecondForWeek(week);
68
+ const weekly = perSecond * WEEK;
69
+ cumulative += weekly;
70
+ return { week, perSecond, weekly, cumulative };
71
+ });
72
+ return schedule;
73
+ }
74
+ /**
75
+ * Places a moment on the schedule, e.g. to compare what has been minted with what the schedule allowed.
76
+ * @param activationTimestamp `mintingStartAtTimestamp`, in UNIX seconds.
77
+ * @param timestamp The moment to place, in UNIX seconds.
78
+ */
79
+ function getSchedulePosition(activationTimestamp, timestamp) {
80
+ const week = getMintingWeekForTimestamp(activationTimestamp, timestamp);
81
+ if (week === 0)
82
+ return { week, secondsIntoWeek: 0, perSecond: BigInt(0), scheduledToDate: BigInt(0) };
83
+ const weeks = getEmissionSchedule();
84
+ if (week > exports.LAST_EMISSION_WEEK)
85
+ return { week, secondsIntoWeek: 0, perSecond: BigInt(0), scheduledToDate: weeks[exports.LAST_EMISSION_WEEK - 1].cumulative };
86
+ const secondsIntoWeek = (timestamp - activationTimestamp) % Number(WEEK);
87
+ const perSecond = getEmissionPerSecondForWeek(week);
88
+ const before = week > 1 ? weeks[week - 2].cumulative : BigInt(0);
89
+ return { week, secondsIntoWeek, perSecond, scheduledToDate: before + perSecond * BigInt(secondsIntoWeek) };
90
+ }
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const ethers_1 = require("ethers");
7
+ const getContractAddress_1 = __importDefault(require("../../contracts/getContractAddress"));
8
+ const artifacts_1 = require("../../utils/artifacts");
9
+ const rpcError_1 = require("../../utils/rpcError");
10
+ /**
11
+ * Reads what an operator administers on the lending pool, next to `getParameters` (risk and fee values) and
12
+ * `getLendingPoolInfo` (liquidity and rates).
13
+ * @param chainId The chain id.
14
+ * @param provider The provider to read with.
15
+ */
16
+ async function getAdminState(chainId, provider) {
17
+ const address = (0, getContractAddress_1.default)(chainId, "lendingpool");
18
+ try {
19
+ const pool = new ethers_1.ethers.Contract(address, (0, artifacts_1.getABI)("lendingpool"), provider);
20
+ const [paused, primeRateOracle, stabilityPool, liquidationProxy, vault, feeCollector, adapters, reserve] = await Promise.all([
21
+ pool.paused(),
22
+ pool.primeRateOracle(),
23
+ pool.stabilityPool(),
24
+ pool.liquidationProxy(),
25
+ pool.vault(),
26
+ pool.feeCollector(),
27
+ pool.getAdapters(),
28
+ pool.reserve(),
29
+ ]);
30
+ return {
31
+ paused,
32
+ primeRateOracle,
33
+ stabilityPool,
34
+ liquidationProxy,
35
+ vault,
36
+ feeCollector,
37
+ adapters: [...adapters].map((a) => ethers_1.ethers.getAddress(a)),
38
+ reserveAsset: reserve.reserveAssetAddress,
39
+ rToken: reserve.reserveRTokenAddress,
40
+ debtToken: reserve.reserveDebtTokenAddress,
41
+ };
42
+ }
43
+ catch (error) {
44
+ throw (0, rpcError_1.toRpcError)("lendingPool.getAdminState", error, { chainId, address });
45
+ }
46
+ }
47
+ exports.default = getAdminState;
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const ethers_1 = require("ethers");
7
+ const getContractAddress_1 = __importDefault(require("../../contracts/getContractAddress"));
8
+ const artifacts_1 = require("../../utils/artifacts");
9
+ const amount_1 = require("../../utils/amount");
10
+ const rpcError_1 = require("../../utils/rpcError");
11
+ /**
12
+ * Walks a public address array (`adapters(i)`) until the index reverts. Any other error (network, RPC) is thrown,
13
+ * so a flaky node never returns a shortened list as if it were complete.
14
+ */
15
+ async function readList(vault, method) {
16
+ const out = [];
17
+ for (let i = 0; i < 100; i++) {
18
+ let item;
19
+ try {
20
+ item = await vault[method](i);
21
+ }
22
+ catch (error) {
23
+ if (ethers_1.ethers.isError(error, "CALL_EXCEPTION"))
24
+ break;
25
+ throw error;
26
+ }
27
+ if (item === ethers_1.ethers.ZeroAddress)
28
+ break;
29
+ out.push(ethers_1.ethers.getAddress(item));
30
+ }
31
+ return out;
32
+ }
33
+ async function readAdapter(address, provider) {
34
+ const erc20 = new ethers_1.ethers.Contract(address, (0, artifacts_1.getABI)("erc20vaultadapter"), provider);
35
+ const [type, token] = await Promise.all([erc20.getAssetType(), erc20.getAssetToken()]);
36
+ const erc721 = type === "ERC721";
37
+ const adapter = erc721 ? new ethers_1.ethers.Contract(address, (0, artifacts_1.getABI)("erc721vaultadapter"), provider) : erc20;
38
+ const asset = new ethers_1.ethers.Contract(token, ["function symbol() view returns (string)", "function decimals() view returns (uint8)"], provider);
39
+ const [tokenSymbol, tokenDecimals, value, tokenIds] = await Promise.all([
40
+ asset.symbol().catch(() => (erc721 ? "NFTs" : "tokens")),
41
+ erc721 ? 0 : asset.decimals().then(Number),
42
+ adapter.totalValue().catch(() => null),
43
+ erc721 ? adapter.getDepositedTokens() : Promise.resolve([]),
44
+ ]);
45
+ return { type, token, tokenSymbol, tokenDecimals, value: value === null ? null : (0, amount_1.toAmount)(value, amount_1.WAD_DECIMALS, "crvUSD"), tokenIds: [...tokenIds] };
46
+ }
47
+ /**
48
+ * Every adapter registered on the RWA vault, read from the vault's own arrays rather than the chain config (which
49
+ * `getAdapters` returns), with deposit and redemption flags and what each adapter holds. One adapter failing to read
50
+ * gives a row with `error` instead of failing the whole list.
51
+ * @param chainId The chain id.
52
+ * @param provider The provider to read with.
53
+ */
54
+ async function getRegisteredAdapters(chainId, provider) {
55
+ const vaultAddress = (0, getContractAddress_1.default)(chainId, "rwavault");
56
+ try {
57
+ const vault = new ethers_1.ethers.Contract(vaultAddress, (0, artifacts_1.getABI)("rwavault"), provider);
58
+ const [all, depositable, redeemable] = await Promise.all([
59
+ readList(vault, "adapters"),
60
+ readList(vault, "depositableAdapters"),
61
+ readList(vault, "redeemableERC721Adapters"),
62
+ ]);
63
+ return Promise.all(all.map(async (address) => {
64
+ const flags = { address, depositable: depositable.includes(address), redeemable: redeemable.includes(address) };
65
+ try {
66
+ return { ...flags, ...(await readAdapter(address, provider)) };
67
+ }
68
+ catch (error) {
69
+ const message = error instanceof Error ? error.message : String(error);
70
+ return { ...flags, type: "unknown", token: ethers_1.ethers.ZeroAddress, tokenSymbol: "?", tokenDecimals: 0, value: null, tokenIds: [], error: message };
71
+ }
72
+ }));
73
+ }
74
+ catch (error) {
75
+ throw (0, rpcError_1.toRpcError)("rwaVault.getRegisteredAdapters", error, { chainId, address: vaultAddress });
76
+ }
77
+ }
78
+ exports.default = getRegisteredAdapters;
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const ethers_1 = require("ethers");
7
+ const getContractAddress_1 = __importDefault(require("../../contracts/getContractAddress"));
8
+ const artifacts_1 = require("../../utils/artifacts");
9
+ const rpcError_1 = require("../../utils/rpcError");
10
+ /**
11
+ * Reads the RWA vault's VRF consumer: the last request and fulfilment and the stall window, plus the vault's own
12
+ * request rules. With no consumer set, the time fields are 0.
13
+ * @param chainId The chain id.
14
+ * @param provider The provider to read with.
15
+ */
16
+ async function getSeedStatus(chainId, provider) {
17
+ const vaultAddress = (0, getContractAddress_1.default)(chainId, "rwavault");
18
+ try {
19
+ const vault = new ethers_1.ethers.Contract(vaultAddress, (0, artifacts_1.getABI)("rwavault"), provider);
20
+ const [consumer, delay, allowed] = await Promise.all([vault.vrfConsumer(), vault.vrfRequestDelay(), vault.allowVRFRequest()]);
21
+ if (consumer === ethers_1.ethers.ZeroAddress) {
22
+ return { consumer, lastRequest: 0, lastFulfil: 0, pending: false, maxStall: 0, delay: Number(delay), allowed };
23
+ }
24
+ const vrf = new ethers_1.ethers.Contract(consumer, (0, artifacts_1.getABI)("vrfconsumer"), provider);
25
+ const [lastRequest, lastFulfil, status, maxStall] = await Promise.all([
26
+ vrf.lastRequestTimestamp(),
27
+ vrf.getLastFulfillTimestamp(),
28
+ vrf.getRequestStatus(),
29
+ vrf.MAX_STALL(),
30
+ ]);
31
+ return {
32
+ consumer,
33
+ lastRequest: Number(lastRequest),
34
+ lastFulfil: Number(lastFulfil),
35
+ pending: status.exists && !status.fulfilled,
36
+ maxStall: Number(maxStall),
37
+ delay: Number(delay),
38
+ allowed,
39
+ };
40
+ }
41
+ catch (error) {
42
+ throw (0, rpcError_1.toRpcError)("rwaVault.getSeedStatus", error, { chainId, address: vaultAddress });
43
+ }
44
+ }
45
+ exports.default = getSeedStatus;