@morpho-org/blue-sdk 1.0.2 → 1.0.4

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 (159) hide show
  1. package/lib/addresses.d.ts +156 -0
  2. package/lib/addresses.js +160 -0
  3. package/lib/chain/chain.constants.d.ts +3 -0
  4. package/lib/chain/chain.constants.js +232 -0
  5. package/lib/chain/chain.test.d.ts +1 -0
  6. package/lib/chain/chain.test.js +37 -0
  7. package/lib/chain/chain.types.d.ts +20 -0
  8. package/lib/chain/chain.types.js +30 -0
  9. package/lib/chain/chain.utils.d.ts +14 -0
  10. package/lib/chain/chain.utils.js +30 -0
  11. package/lib/chain/index.js +18 -0
  12. package/lib/constants.d.ts +8 -0
  13. package/lib/constants.js +13 -0
  14. package/lib/errors.d.ts +37 -0
  15. package/lib/errors.js +71 -0
  16. package/lib/ethers/ethers.test.d.ts +1 -0
  17. package/lib/ethers/ethers.test.js +11 -0
  18. package/lib/ethers/index.js +18 -0
  19. package/lib/ethers/safeGetAddress.d.ts +1 -0
  20. package/lib/ethers/safeGetAddress.js +6 -0
  21. package/lib/ethers/safeParseUnits.d.ts +2 -0
  22. package/lib/ethers/safeParseUnits.js +25 -0
  23. package/lib/evm.d.ts +36 -0
  24. package/lib/evm.js +113 -0
  25. package/lib/helpers/format/format.d.ts +98 -0
  26. package/lib/helpers/format/format.js +301 -0
  27. package/lib/helpers/format/format.test.d.ts +1 -0
  28. package/lib/helpers/format/format.test.js +257 -0
  29. package/lib/helpers/format/index.js +17 -0
  30. package/lib/helpers/getChecksumedAddress.d.ts +7 -0
  31. package/lib/helpers/getChecksumedAddress.js +17 -0
  32. package/lib/helpers/index.js +20 -0
  33. package/{src/helpers/isZeroAddressOrUnset.ts → lib/helpers/isZeroAddressOrUnset.d.ts} +1 -7
  34. package/lib/helpers/isZeroAddressOrUnset.js +14 -0
  35. package/lib/helpers/locale.d.ts +36 -0
  36. package/lib/helpers/locale.js +86 -0
  37. package/lib/holding/Holding.d.ts +60 -0
  38. package/lib/holding/Holding.js +31 -0
  39. package/lib/holding/index.js +17 -0
  40. package/{src/index.ts → lib/index.d.ts} +0 -1
  41. package/lib/index.js +62 -0
  42. package/lib/market/Market.d.ts +159 -0
  43. package/lib/market/Market.js +240 -0
  44. package/lib/market/MarketConfig.d.ts +44 -0
  45. package/lib/market/MarketConfig.js +56 -0
  46. package/lib/market/MarketUtils.d.ts +165 -0
  47. package/lib/market/MarketUtils.js +182 -0
  48. package/lib/market/MarketUtils.test.d.ts +1 -0
  49. package/lib/market/MarketUtils.test.js +19 -0
  50. package/lib/market/index.js +19 -0
  51. package/lib/maths/AdaptiveCurveIrmLib.d.ts +37 -0
  52. package/lib/maths/AdaptiveCurveIrmLib.js +116 -0
  53. package/lib/maths/MathLib.d.ts +94 -0
  54. package/lib/maths/MathLib.js +153 -0
  55. package/lib/maths/MathUtils.d.ts +15 -0
  56. package/lib/maths/MathUtils.js +33 -0
  57. package/lib/maths/SharesMath.d.ts +12 -0
  58. package/lib/maths/SharesMath.js +22 -0
  59. package/lib/maths/index.js +20 -0
  60. package/lib/notifications.d.ts +98 -0
  61. package/lib/notifications.js +52 -0
  62. package/lib/position/Position.d.ts +118 -0
  63. package/lib/position/Position.js +145 -0
  64. package/lib/position/index.js +17 -0
  65. package/lib/signatures/index.d.ts +12 -0
  66. package/lib/signatures/index.js +39 -0
  67. package/lib/signatures/manager.d.ts +10 -0
  68. package/lib/signatures/manager.js +37 -0
  69. package/lib/signatures/permit.d.ts +21 -0
  70. package/lib/signatures/permit.js +101 -0
  71. package/lib/signatures/permit2.d.ts +20 -0
  72. package/lib/signatures/permit2.js +91 -0
  73. package/lib/signatures/types.d.ts +13 -0
  74. package/lib/signatures/types.js +2 -0
  75. package/lib/signatures/utils.d.ts +6 -0
  76. package/lib/signatures/utils.js +44 -0
  77. package/lib/tests/mocks/markets.d.ts +17 -0
  78. package/lib/tests/mocks/markets.js +108 -0
  79. package/lib/token/ERC20Metadata.d.ts +249 -0
  80. package/lib/token/ERC20Metadata.js +81 -0
  81. package/lib/token/Token.d.ts +45 -0
  82. package/lib/token/Token.js +39 -0
  83. package/lib/token/TokenNamespace.d.ts +18 -0
  84. package/lib/token/TokenNamespace.js +55 -0
  85. package/lib/token/WrappedToken.d.ts +42 -0
  86. package/lib/token/WrappedToken.js +87 -0
  87. package/lib/token/index.js +18 -0
  88. package/lib/types.d.ts +29 -0
  89. package/lib/types.js +23 -0
  90. package/lib/user/User.d.ts +20 -0
  91. package/lib/user/User.js +11 -0
  92. package/lib/user/index.js +18 -0
  93. package/lib/user/user.types.d.ts +18 -0
  94. package/lib/user/user.types.js +2 -0
  95. package/lib/vault/Vault.d.ts +167 -0
  96. package/lib/vault/Vault.js +156 -0
  97. package/lib/vault/VaultAllocation.d.ts +38 -0
  98. package/lib/vault/VaultAllocation.js +18 -0
  99. package/lib/vault/VaultConfig.d.ts +23 -0
  100. package/lib/vault/VaultConfig.js +26 -0
  101. package/lib/vault/VaultUtils.d.ts +17 -0
  102. package/lib/vault/VaultUtils.js +17 -0
  103. package/lib/vault/index.js +20 -0
  104. package/package.json +7 -11
  105. package/src/addresses.ts +0 -261
  106. package/src/chain/chain.constants.ts +0 -235
  107. package/src/chain/chain.test.ts +0 -51
  108. package/src/chain/chain.types.ts +0 -42
  109. package/src/chain/chain.utils.ts +0 -44
  110. package/src/constants.ts +0 -18
  111. package/src/errors.ts +0 -75
  112. package/src/ethers/ethers.test.ts +0 -17
  113. package/src/ethers/safeGetAddress.ts +0 -4
  114. package/src/ethers/safeParseUnits.ts +0 -29
  115. package/src/evm.ts +0 -172
  116. package/src/helpers/format/format.test.ts +0 -340
  117. package/src/helpers/format/format.ts +0 -416
  118. package/src/helpers/getChecksumedAddress.ts +0 -15
  119. package/src/helpers/locale.ts +0 -108
  120. package/src/holding/Holding.ts +0 -109
  121. package/src/market/Market.ts +0 -479
  122. package/src/market/MarketConfig.ts +0 -108
  123. package/src/market/MarketUtils.test.ts +0 -25
  124. package/src/market/MarketUtils.ts +0 -467
  125. package/src/maths/AdaptiveCurveIrmLib.ts +0 -143
  126. package/src/maths/MathLib.ts +0 -208
  127. package/src/maths/MathUtils.ts +0 -31
  128. package/src/maths/SharesMath.ts +0 -40
  129. package/src/notifications.ts +0 -167
  130. package/src/position/Position.ts +0 -251
  131. package/src/signatures/index.ts +0 -18
  132. package/src/signatures/manager.ts +0 -50
  133. package/src/signatures/permit.ts +0 -126
  134. package/src/signatures/permit2.ts +0 -120
  135. package/src/signatures/types.ts +0 -18
  136. package/src/signatures/utils.ts +0 -83
  137. package/src/tests/mocks/markets.ts +0 -110
  138. package/src/token/ERC20Metadata.ts +0 -124
  139. package/src/token/Token.ts +0 -83
  140. package/src/token/TokenNamespace.ts +0 -76
  141. package/src/token/WrappedToken.ts +0 -142
  142. package/src/types.ts +0 -37
  143. package/src/user/User.ts +0 -32
  144. package/src/user/user.types.ts +0 -23
  145. package/src/vault/Vault.ts +0 -370
  146. package/src/vault/VaultAllocation.ts +0 -58
  147. package/src/vault/VaultConfig.ts +0 -55
  148. package/src/vault/VaultUtils.ts +0 -47
  149. /package/{src/chain/index.ts → lib/chain/index.d.ts} +0 -0
  150. /package/{src/ethers/index.ts → lib/ethers/index.d.ts} +0 -0
  151. /package/{src/helpers/format/index.ts → lib/helpers/format/index.d.ts} +0 -0
  152. /package/{src/helpers/index.ts → lib/helpers/index.d.ts} +0 -0
  153. /package/{src/holding/index.ts → lib/holding/index.d.ts} +0 -0
  154. /package/{src/market/index.ts → lib/market/index.d.ts} +0 -0
  155. /package/{src/maths/index.ts → lib/maths/index.d.ts} +0 -0
  156. /package/{src/position/index.ts → lib/position/index.d.ts} +0 -0
  157. /package/{src/token/index.ts → lib/token/index.d.ts} +0 -0
  158. /package/{src/user/index.ts → lib/user/index.d.ts} +0 -0
  159. /package/{src/vault/index.ts → lib/vault/index.d.ts} +0 -0
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ChainUtils = void 0;
4
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
5
+ const errors_1 = require("../errors");
6
+ const chain_constants_1 = require("./chain.constants");
7
+ const chain_types_1 = require("./chain.types");
8
+ var ChainUtils;
9
+ (function (ChainUtils) {
10
+ ChainUtils.blueAvailableChains = chain_constants_1.BLUE_AVAILABLE_CHAINS;
11
+ ChainUtils.chainMetadata = chain_constants_1.CHAIN_METADATA;
12
+ ChainUtils.ChainId = chain_types_1.ChainId;
13
+ ChainUtils.toHexChainId = (chainId) => {
14
+ return `0x${chainId.toString(16)}`;
15
+ };
16
+ ChainUtils.getAllChainIds = () => (0, morpho_ts_1.values)(ChainUtils.ChainId).filter((value) => typeof value === "number");
17
+ ChainUtils.getAllChainLabels = () => Object.values(ChainUtils.ChainId).filter((value) => typeof value === "string");
18
+ ChainUtils.getTestnets = () => ChainUtils.getAllChainIds().filter((chainId) => chain_constants_1.CHAIN_METADATA[chainId].isTestnet);
19
+ function isSupported(chainId) {
20
+ return ChainUtils.blueAvailableChains.includes(chainId);
21
+ }
22
+ ChainUtils.isSupported = isSupported;
23
+ function parseSupportedChainId(candidate) {
24
+ const chainId = parseInt(candidate);
25
+ if (!isSupported(chainId))
26
+ throw new errors_1.UnsupportedChainIdError(candidate);
27
+ return chainId;
28
+ }
29
+ ChainUtils.parseSupportedChainId = parseSupportedChainId;
30
+ })(ChainUtils || (exports.ChainUtils = ChainUtils = {}));
@@ -0,0 +1,18 @@
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("./chain.utils"), exports);
18
+ __exportStar(require("./chain.types"), exports);
@@ -0,0 +1,8 @@
1
+ export declare const LIQUIDATION_CURSOR: bigint;
2
+ export declare const MAX_LIQUIDATION_INCENTIVE_FACTOR: bigint;
3
+ export declare const ORACLE_PRICE_OFFSET = 36;
4
+ export declare const ORACLE_PRICE_SCALE: bigint;
5
+ export declare const MAX_FEE: bigint;
6
+ export declare const DEFAULT_SLIPPAGE_TOLERANCE: bigint;
7
+ export declare const DEFAULT_TARGET_UTILIZATION: bigint;
8
+ export declare const SECONDS_PER_YEAR: bigint;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SECONDS_PER_YEAR = exports.DEFAULT_TARGET_UTILIZATION = exports.DEFAULT_SLIPPAGE_TOLERANCE = exports.MAX_FEE = exports.ORACLE_PRICE_SCALE = exports.ORACLE_PRICE_OFFSET = exports.MAX_LIQUIDATION_INCENTIVE_FACTOR = exports.LIQUIDATION_CURSOR = void 0;
4
+ const ethers_1 = require("ethers");
5
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
+ exports.LIQUIDATION_CURSOR = (0, ethers_1.parseEther)("0.3");
7
+ exports.MAX_LIQUIDATION_INCENTIVE_FACTOR = (0, ethers_1.parseEther)("1.15");
8
+ exports.ORACLE_PRICE_OFFSET = 36;
9
+ exports.ORACLE_PRICE_SCALE = (0, ethers_1.parseUnits)("1", exports.ORACLE_PRICE_OFFSET);
10
+ exports.MAX_FEE = (0, ethers_1.parseEther)("0.25"); // 25%
11
+ exports.DEFAULT_SLIPPAGE_TOLERANCE = (0, ethers_1.parseEther)("0.0003"); // 0.03%
12
+ exports.DEFAULT_TARGET_UTILIZATION = (0, ethers_1.parseEther)("0.92"); // 92%
13
+ exports.SECONDS_PER_YEAR = morpho_ts_1.Time.s.from.y(1n);
@@ -0,0 +1,37 @@
1
+ import { Address, MarketId } from "./types";
2
+ export declare class UnknownDataError extends Error {
3
+ }
4
+ export declare class UnknownTokenError extends UnknownDataError {
5
+ readonly address: Address;
6
+ constructor(address: Address);
7
+ }
8
+ export declare class UnknownTokenPriceError extends UnknownDataError {
9
+ readonly address: Address;
10
+ constructor(address: Address);
11
+ }
12
+ export declare class UnknownMarketConfigError extends UnknownDataError {
13
+ readonly marketId: MarketId;
14
+ constructor(marketId: MarketId);
15
+ }
16
+ export declare class UnknownVaultConfigError extends UnknownDataError {
17
+ readonly vault: Address;
18
+ constructor(vault: Address);
19
+ }
20
+ export declare class UnsupportedChainIdError extends Error {
21
+ readonly chainId: number;
22
+ constructor(chainId: number);
23
+ }
24
+ export declare class InvalidInterestAccrualError extends UnknownDataError {
25
+ readonly marketId: MarketId;
26
+ readonly timestamp: bigint;
27
+ readonly lastUpdate: bigint;
28
+ constructor(marketId: MarketId, timestamp: bigint, lastUpdate: bigint);
29
+ }
30
+ export declare class InvalidSignatureError extends Error {
31
+ readonly hash: string;
32
+ readonly signer: Address;
33
+ readonly recovered: Address;
34
+ constructor(hash: string, signer: Address, recovered: Address);
35
+ }
36
+ export type ErrorClass = new (...args: any[]) => Error;
37
+ export declare function _try<T>(accessor: () => T, ...errorClasses: ErrorClass[]): T | undefined;
package/lib/errors.js ADDED
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports._try = exports.InvalidSignatureError = exports.InvalidInterestAccrualError = exports.UnsupportedChainIdError = exports.UnknownVaultConfigError = exports.UnknownMarketConfigError = exports.UnknownTokenPriceError = exports.UnknownTokenError = exports.UnknownDataError = void 0;
4
+ class UnknownDataError extends Error {
5
+ }
6
+ exports.UnknownDataError = UnknownDataError;
7
+ class UnknownTokenError extends UnknownDataError {
8
+ constructor(address) {
9
+ super(`unknown token ${address}`);
10
+ this.address = address;
11
+ }
12
+ }
13
+ exports.UnknownTokenError = UnknownTokenError;
14
+ class UnknownTokenPriceError extends UnknownDataError {
15
+ constructor(address) {
16
+ super(`unknown price of token ${address}`);
17
+ this.address = address;
18
+ }
19
+ }
20
+ exports.UnknownTokenPriceError = UnknownTokenPriceError;
21
+ class UnknownMarketConfigError extends UnknownDataError {
22
+ constructor(marketId) {
23
+ super(`unknown config for market ${marketId}`);
24
+ this.marketId = marketId;
25
+ }
26
+ }
27
+ exports.UnknownMarketConfigError = UnknownMarketConfigError;
28
+ class UnknownVaultConfigError extends UnknownDataError {
29
+ constructor(vault) {
30
+ super(`unknown config for vault ${vault}`);
31
+ this.vault = vault;
32
+ }
33
+ }
34
+ exports.UnknownVaultConfigError = UnknownVaultConfigError;
35
+ class UnsupportedChainIdError extends Error {
36
+ constructor(chainId) {
37
+ super(`unsupported chain ${chainId}`);
38
+ this.chainId = chainId;
39
+ }
40
+ }
41
+ exports.UnsupportedChainIdError = UnsupportedChainIdError;
42
+ class InvalidInterestAccrualError extends UnknownDataError {
43
+ constructor(marketId, timestamp, lastUpdate) {
44
+ super(`invalid interest accrual on market ${marketId}: accrual timestamp ${timestamp} can't be prior to last update ${lastUpdate}`);
45
+ this.marketId = marketId;
46
+ this.timestamp = timestamp;
47
+ this.lastUpdate = lastUpdate;
48
+ }
49
+ }
50
+ exports.InvalidInterestAccrualError = InvalidInterestAccrualError;
51
+ class InvalidSignatureError extends Error {
52
+ constructor(hash, signer, recovered) {
53
+ super(`invalid signature for hash ${hash}: expected ${signer}, recovered ${recovered}`);
54
+ this.hash = hash;
55
+ this.signer = signer;
56
+ this.recovered = recovered;
57
+ }
58
+ }
59
+ exports.InvalidSignatureError = InvalidSignatureError;
60
+ function _try(accessor, ...errorClasses) {
61
+ try {
62
+ return accessor();
63
+ }
64
+ catch (error) {
65
+ if (errorClasses.length === 0 ||
66
+ errorClasses.some((errorClass) => error instanceof errorClass))
67
+ return;
68
+ throw error;
69
+ }
70
+ }
71
+ exports._try = _try;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const safeParseUnits_1 = require("./safeParseUnits");
4
+ describe("safeParseNumber", () => {
5
+ it("should parse excessively small number", () => {
6
+ expect((0, safeParseUnits_1.safeParseNumber)(0.000000000000000000000000000000042, 18)).toEqual(0n);
7
+ });
8
+ it("should parse excessively large number", () => {
9
+ expect((0, safeParseUnits_1.safeParseNumber)(4200000000000000000000000000000000000, 18).toString()).toEqual(4200000000000000000000000000000000000000000000000000000n.toString());
10
+ });
11
+ });
@@ -0,0 +1,18 @@
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("./safeGetAddress"), exports);
18
+ __exportStar(require("./safeParseUnits"), exports);
@@ -0,0 +1 @@
1
+ export declare const safeGetAddress: (address: string) => string;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.safeGetAddress = void 0;
4
+ const ethers_1 = require("ethers");
5
+ const safeGetAddress = (address) => (0, ethers_1.getAddress)(address.toLowerCase());
6
+ exports.safeGetAddress = safeGetAddress;
@@ -0,0 +1,2 @@
1
+ export declare const safeParseUnits: (strValue: string, decimals?: number) => bigint;
2
+ export declare function safeParseNumber(value: number, decimals?: number): bigint;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.safeParseNumber = exports.safeParseUnits = void 0;
4
+ const ethers_1 = require("ethers");
5
+ const safeParseUnits = (strValue, decimals = 18) => {
6
+ if (!/[-+]?[0-9]*\.?[0-9]+/.test(strValue))
7
+ throw new Error("invalid number: " + strValue);
8
+ let [whole, dec = ""] = strValue.split(".");
9
+ dec = dec.slice(0, decimals);
10
+ return (0, ethers_1.parseUnits)([whole || "0", dec].filter((v) => v.length > 0).join("."), decimals);
11
+ };
12
+ exports.safeParseUnits = safeParseUnits;
13
+ // Alternative to Number.toFixed that doesn't use scientific notation for excessively small or large numbers
14
+ function toFixed(x, decimals) {
15
+ return new Intl.NumberFormat("en-US", {
16
+ style: "decimal",
17
+ useGrouping: false,
18
+ maximumFractionDigits: decimals,
19
+ minimumFractionDigits: decimals,
20
+ }).format(x);
21
+ }
22
+ function safeParseNumber(value, decimals = 18) {
23
+ return (0, exports.safeParseUnits)(toFixed(value, decimals), decimals);
24
+ }
25
+ exports.safeParseNumber = safeParseNumber;
package/lib/evm.d.ts ADDED
@@ -0,0 +1,36 @@
1
+ import { TransactionRequest, Signer } from "ethers";
2
+ import { ChainId } from "./chain";
3
+ import { NotificationProducer, NotificationTopic } from "./notifications";
4
+ import { SignatureMessage } from "./signatures/types";
5
+ export interface NotificationOptions<Topic extends NotificationTopic> {
6
+ producer: NotificationProducer<Topic>;
7
+ id: string;
8
+ args: Record<PropertyKey, any>;
9
+ }
10
+ /**
11
+ * Sends a transaction via the provided signer, optionnally waiting for the corresponding transaction receipt.
12
+ * @param signer The signer to send the tx with.
13
+ * @param tx The transaction request.
14
+ * @param wait Whether to wait for the transaction receipt. Defaults to true.
15
+ * @param notificationOptions The optional notification options. Warning: if `wait` is set to true, the provided topic will never complete.
16
+ */
17
+ export declare const sendTransactionWithProducer: (signer: Signer, req: TransactionRequest, defaultGasLimit?: bigint, confirms?: number, notificationOptions?: NotificationOptions<NotificationTopic.tx>) => Promise<void>;
18
+ /**
19
+ * Sends a transaction via the provided signer, optionnally waiting for the corresponding transaction receipt.
20
+ * @param signer The signer to send the tx with.
21
+ * @param tx The transaction request.
22
+ * @param wait Whether to wait for the transaction receipt. Defaults to true.
23
+ * @param topic The type of notifications to emit.
24
+ * @param args The optional notification arguments.
25
+ * @return The notification consumer which receives the transaction notifications.
26
+ */
27
+ export declare const sendTransaction: (signer: Signer, tx: TransactionRequest, defaultGasLimit?: bigint, confirms?: number, args?: Record<PropertyKey, any>) => import("./notifications").NotificationConsumer<NotificationTopic.tx>;
28
+ export declare const signMessageWithProducer: (signer: Signer, message: SignatureMessage, notificationOptions?: NotificationOptions<NotificationTopic.signature>) => Promise<void>;
29
+ /**
30
+ * Sends a signature request to the provided signer.
31
+ * @param signer The signer to send the approval with.
32
+ * @param args The approval parameters.
33
+ * @param encodeMessage The approval encoder to pass the approval parameters to get the approval transactions.
34
+ * @return The notification consumer which receives the transaction notifications.
35
+ */
36
+ export declare const signMessage: <T extends object>(signer: Signer, args: T, encodeMessage: (args: T, chainId: ChainId) => SignatureMessage, chainId: ChainId) => import("./notifications").NotificationConsumer<NotificationTopic.signature>;
package/lib/evm.js ADDED
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.signMessage = exports.signMessageWithProducer = exports.sendTransaction = exports.sendTransactionWithProducer = void 0;
4
+ const ethers_1 = require("ethers");
5
+ const maths_1 = require("./maths");
6
+ const notifications_1 = require("./notifications");
7
+ const signatures_1 = require("./signatures");
8
+ /**
9
+ * Sends a transaction via the provided signer, optionnally waiting for the corresponding transaction receipt.
10
+ * @param signer The signer to send the tx with.
11
+ * @param tx The transaction request.
12
+ * @param wait Whether to wait for the transaction receipt. Defaults to true.
13
+ * @param notificationOptions The optional notification options. Warning: if `wait` is set to true, the provided topic will never complete.
14
+ */
15
+ const sendTransactionWithProducer = async (signer, req, defaultGasLimit, confirms = 1, notificationOptions) => {
16
+ let response;
17
+ try {
18
+ let gasLimit;
19
+ try {
20
+ gasLimit = maths_1.MathLib.wMulUp(await signer.estimateGas(req), (0, ethers_1.parseUnits)("1.1"));
21
+ }
22
+ catch (error) {
23
+ if (defaultGasLimit == null)
24
+ throw error;
25
+ gasLimit = defaultGasLimit;
26
+ }
27
+ const tx = { ...req, gasLimit };
28
+ notificationOptions?.producer.next({
29
+ id: notificationOptions.id,
30
+ status: notifications_1.NotificationStatus.signing,
31
+ context: { tx },
32
+ });
33
+ response = await signer.sendTransaction(tx);
34
+ notificationOptions?.producer.next({
35
+ id: notificationOptions.id,
36
+ status: notifications_1.NotificationStatus.pending,
37
+ context: { args: notificationOptions.args, tx, response },
38
+ });
39
+ const receipt = await response.wait(confirms);
40
+ notificationOptions?.producer.next({
41
+ id: notificationOptions.id,
42
+ status: notifications_1.NotificationStatus.success,
43
+ context: { args: notificationOptions.args, tx, response, receipt },
44
+ });
45
+ }
46
+ catch (error) {
47
+ notificationOptions?.producer.next({
48
+ id: notificationOptions.id,
49
+ status: notifications_1.NotificationStatus.error,
50
+ context: { args: notificationOptions.args, tx: req, response, error },
51
+ });
52
+ }
53
+ };
54
+ exports.sendTransactionWithProducer = sendTransactionWithProducer;
55
+ /**
56
+ * Sends a transaction via the provided signer, optionnally waiting for the corresponding transaction receipt.
57
+ * @param signer The signer to send the tx with.
58
+ * @param tx The transaction request.
59
+ * @param wait Whether to wait for the transaction receipt. Defaults to true.
60
+ * @param topic The type of notifications to emit.
61
+ * @param args The optional notification arguments.
62
+ * @return The notification consumer which receives the transaction notifications.
63
+ */
64
+ const sendTransaction = (signer, tx, defaultGasLimit, confirms, args = {}) => {
65
+ const producer = new notifications_1.NotificationProducer(notifications_1.NotificationTopic.tx);
66
+ (0, exports.sendTransactionWithProducer)(signer, tx, defaultGasLimit, confirms, {
67
+ producer,
68
+ id: Date.now().toString(),
69
+ args,
70
+ });
71
+ return producer.consumer;
72
+ };
73
+ exports.sendTransaction = sendTransaction;
74
+ const signMessageWithProducer = async (signer, message, notificationOptions) => {
75
+ notificationOptions?.producer.next({
76
+ id: notificationOptions.id,
77
+ status: notifications_1.NotificationStatus.signing,
78
+ });
79
+ try {
80
+ const signature = await signatures_1.SignatureUtils.safeSignTypedData(signer, message.data.domain, message.data.types, message.data.value);
81
+ signatures_1.SignatureUtils.verifySignature(signature, message.hash, await signer.getAddress());
82
+ notificationOptions?.producer.next({
83
+ id: notificationOptions.id,
84
+ status: notifications_1.NotificationStatus.success,
85
+ context: { message, args: notificationOptions.args, signature },
86
+ });
87
+ }
88
+ catch (error) {
89
+ notificationOptions?.producer.next({
90
+ id: notificationOptions.id,
91
+ status: notifications_1.NotificationStatus.error,
92
+ context: { message, args: notificationOptions.args, error },
93
+ });
94
+ }
95
+ };
96
+ exports.signMessageWithProducer = signMessageWithProducer;
97
+ /**
98
+ * Sends a signature request to the provided signer.
99
+ * @param signer The signer to send the approval with.
100
+ * @param args The approval parameters.
101
+ * @param encodeMessage The approval encoder to pass the approval parameters to get the approval transactions.
102
+ * @return The notification consumer which receives the transaction notifications.
103
+ */
104
+ const signMessage = (signer, args, encodeMessage, chainId) => {
105
+ const producer = new notifications_1.NotificationProducer(notifications_1.NotificationTopic.signature);
106
+ (0, exports.signMessageWithProducer)(signer, encodeMessage(args, chainId), {
107
+ producer,
108
+ id: Date.now().toString(),
109
+ args,
110
+ });
111
+ return producer.consumer;
112
+ };
113
+ exports.signMessage = signMessage;
@@ -0,0 +1,98 @@
1
+ declare enum Format {
2
+ number = "number",
3
+ commas = "commas",
4
+ short = "short",
5
+ hex = "hex",
6
+ percent = "percent"
7
+ }
8
+ interface BaseFormatOptions {
9
+ format: Format;
10
+ digits?: number;
11
+ removeTrailingZero?: boolean;
12
+ min?: number;
13
+ max?: number;
14
+ sign?: boolean;
15
+ unit?: string;
16
+ readable?: boolean;
17
+ locale?: string;
18
+ }
19
+ interface FormatShortOptions extends BaseFormatOptions {
20
+ format: Format.short;
21
+ smallValuesWithCommas?: boolean;
22
+ }
23
+ interface FormatHexOptions {
24
+ format: Format.hex;
25
+ }
26
+ interface FormatCommasOptions extends BaseFormatOptions {
27
+ format: Format.commas;
28
+ }
29
+ interface FormatNumberOptions extends BaseFormatOptions {
30
+ format: Format.number;
31
+ }
32
+ interface FormatPercentOptions extends BaseFormatOptions {
33
+ format: Format.percent;
34
+ }
35
+ type FormatOptions = FormatHexOptions | FormatShortOptions | FormatNumberOptions | FormatCommasOptions | FormatPercentOptions;
36
+ declare global {
37
+ interface String {
38
+ insert(index: number, substr: string, fillWith?: string): string;
39
+ }
40
+ }
41
+ export declare abstract class BaseFormatter {
42
+ protected abstract _options: FormatOptions;
43
+ constructor();
44
+ of(value: bigint, decimals: number): string;
45
+ of(value: number): string;
46
+ }
47
+ export declare class HexFormatter extends BaseFormatter {
48
+ protected _options: {
49
+ format: Format;
50
+ };
51
+ }
52
+ export declare abstract class CommonFormatter extends BaseFormatter {
53
+ protected abstract _options: BaseFormatOptions;
54
+ digits(_d: number): this;
55
+ removeTrailingZero(): this;
56
+ readable(): this;
57
+ min(_m: number): this;
58
+ max(_m: number): this;
59
+ sign(): this;
60
+ unit(_u: string): this;
61
+ locale(_l: string): this;
62
+ }
63
+ export declare class NumberFormatter extends CommonFormatter {
64
+ protected _options: FormatNumberOptions;
65
+ }
66
+ export declare class CommasFormatter extends CommonFormatter {
67
+ protected _options: FormatCommasOptions;
68
+ }
69
+ export declare class ShortFormatter extends CommonFormatter {
70
+ protected _options: FormatShortOptions;
71
+ smallValuesWithCommas(): this;
72
+ }
73
+ export declare class PercentFormatter extends CommonFormatter {
74
+ protected _options: FormatPercentOptions;
75
+ }
76
+ export declare const format: {
77
+ /**
78
+ * Return the value as an integer in hex format
79
+ */
80
+ readonly hex: HexFormatter;
81
+ /**
82
+ * Return the value as a stringified number (12345.6789)
83
+ */
84
+ readonly number: NumberFormatter;
85
+ /**
86
+ * Return the value as a commas-separated stringified number (12,345.6789)
87
+ */
88
+ readonly commas: CommasFormatter;
89
+ /**
90
+ * Return the value as a shorted stringified number (12.3456789k)
91
+ */
92
+ readonly short: ShortFormatter;
93
+ /**
94
+ * Return the value as a percent based stringified number (10.00 instead of 0.1)
95
+ */
96
+ readonly percent: PercentFormatter;
97
+ };
98
+ export {};