@mento-protocol/mento-sdk 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,72 +2,16 @@
2
2
 
3
3
  The official Mento Protocol SDK for interacting with Multi-Collateral Mento smart contracts on the Celo network.
4
4
 
5
- # Example Usage
5
+ ## Installation
6
6
 
7
- ```javascript
8
- import { Wallet, providers, utils } from 'ethers'
7
+ ```sh
8
+ # Install with npm
9
+ npm install @mento-protocol/mento-sdk
9
10
 
10
- import { Mento } from '@mento-protocol/mento-sdk'
11
-
12
- async function main() {
13
- const provider = new providers.JsonRpcProvider(
14
- 'https://baklava-forno.celo-testnet.org'
15
- )
16
- const pKey =
17
- 'b214fcf9673dc1a880f8041a8c8952c2dc7daff41fb64cf7715919df095c3fce'
18
- const wallet = new Wallet(pKey, provider)
19
-
20
- const mento = await Mento.create(wallet)
21
- console.log('available pairs: ', await mento.getTradeablePairs())
22
- /*
23
- [
24
- [
25
- {
26
- address: '0x62492A644A588FD904270BeD06ad52B9abfEA1aE',
27
- symbol: 'cUSD'
28
- },
29
- {
30
- address: '0xdDc9bE57f553fe75752D61606B94CBD7e0264eF8',
31
- symbol: 'CELO'
32
- }
33
- ],
34
- ...
35
- ]
36
- */
37
-
38
- // swap 1 CELO for cUSD
39
- const one = 1
40
- const tokenIn = '0xdDc9bE57f553fe75752D61606B94CBD7e0264eF8' // CELO
41
- const tokenOut = '0x62492A644A588FD904270BeD06ad52B9abfEA1aE' // cUSD
42
- const amountIn = utils.parseUnits(one.toString(), 18)
43
- const expectedAmountOut = await mento.getAmountOut(
44
- tokenIn,
45
- tokenOut,
46
- utils.parseUnits(one.toString(), 18)
47
- )
48
- // 95% of the quote to allow some slippage
49
- const minAmountOut = expectedAmountOut.mul(95).div(100)
50
-
51
- // allow the broker contract to spend CELO on behalf of the wallet
52
- const allowanceTxObj = await mento.increaseTradingAllowance(tokenIn, amountIn)
53
- const allowanceTx = await wallet.sendTransaction(allowanceTxObj)
54
- const allowanceReceipt = await allowanceTx.wait()
55
- console.log('increaseAllowance receipt', allowanceReceipt)
56
-
57
- // execute the swap
58
- const swapTxObj = await mento.swapIn(
59
- tokenIn,
60
- tokenOut,
61
- amountIn,
62
- minAmountOut
63
- )
64
- const swapTx = await wallet.sendTransaction(swapTxObj)
65
- const swapReceipt = await swapTx.wait()
11
+ # Or install with yarn
12
+ yarn add @mento-protocol/mento-sdk
13
+ ```
66
14
 
67
- console.log('swapIn receipt', swapReceipt)
68
- }
15
+ # Learn more
69
16
 
70
- main()
71
- .then(() => console.log('Done'))
72
- .catch((e) => console.error('Error:', e))
73
- ```
17
+ You can find example usages of the SDK in the [mento-sdk-examples](https://github.com/mento-protocol/mento-sdk-examples) repository. For in-depth documentation and walk through explanations please see the [SDK section](https://docs.mento.org/mento/developers/mento-sdk) of the Mento docs.
@@ -0,0 +1,9 @@
1
+ import { PopulatedTransaction, ethers, providers } from "ethers";
2
+ import { IChainClient } from "./types";
3
+ export declare class ChainClient implements IChainClient {
4
+ private readonly signerOrProvider;
5
+ constructor(signerOrProvider: ethers.Signer | providers.Provider);
6
+ getSigner(): Promise<ethers.Signer | providers.Provider>;
7
+ getChainId(): Promise<number>;
8
+ populateTransaction(tx: PopulatedTransaction): Promise<providers.TransactionRequest>;
9
+ }
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.ChainClient = void 0;
13
+ const ethers_1 = require("ethers");
14
+ const utils_1 = require("./utils");
15
+ class ChainClient {
16
+ constructor(signerOrProvider) {
17
+ (0, utils_1.validateSignerOrProvider)(signerOrProvider);
18
+ this.signerOrProvider = signerOrProvider;
19
+ }
20
+ getSigner() {
21
+ return __awaiter(this, void 0, void 0, function* () {
22
+ return this.signerOrProvider;
23
+ });
24
+ }
25
+ getChainId() {
26
+ var _a;
27
+ return __awaiter(this, void 0, void 0, function* () {
28
+ let chainId = 0;
29
+ if (ethers_1.Signer.isSigner(this.signerOrProvider)) {
30
+ const network = yield ((_a = this.signerOrProvider.provider) === null || _a === void 0 ? void 0 : _a.getNetwork());
31
+ if (network) {
32
+ chainId = network.chainId;
33
+ }
34
+ }
35
+ else if (ethers_1.providers.Provider.isProvider(this.signerOrProvider)) {
36
+ const network = yield this.signerOrProvider.getNetwork();
37
+ if (network) {
38
+ chainId = network.chainId;
39
+ }
40
+ }
41
+ if (chainId === 0) {
42
+ throw new Error('Could not get chainId from signer or provider');
43
+ }
44
+ return chainId;
45
+ });
46
+ }
47
+ populateTransaction(tx) {
48
+ return __awaiter(this, void 0, void 0, function* () {
49
+ if (ethers_1.Signer.isSigner(this.signerOrProvider)) {
50
+ return this.signerOrProvider.populateTransaction(tx);
51
+ }
52
+ else {
53
+ return tx;
54
+ }
55
+ });
56
+ }
57
+ }
58
+ exports.ChainClient = ChainClient;
@@ -0,0 +1,7 @@
1
+ import { PopulatedTransaction, ethers, providers } from 'ethers';
2
+ import { IChainClient } from './types';
3
+ export declare class TestChainClient implements IChainClient {
4
+ getSigner(): Promise<ethers.Signer | providers.Provider>;
5
+ getChainId(): Promise<number>;
6
+ populateTransaction(tx: PopulatedTransaction): Promise<providers.TransactionRequest>;
7
+ }
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.TestChainClient = void 0;
13
+ class TestChainClient {
14
+ getSigner() {
15
+ return __awaiter(this, void 0, void 0, function* () {
16
+ const fakeProvider = {};
17
+ return fakeProvider;
18
+ });
19
+ }
20
+ getChainId() {
21
+ return __awaiter(this, void 0, void 0, function* () {
22
+ return 1;
23
+ });
24
+ }
25
+ populateTransaction(tx) {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ const fakeTx = {
28
+ to: tx.to,
29
+ from: tx.from,
30
+ data: tx.data,
31
+ value: tx.value,
32
+ nonce: 0,
33
+ gasLimit: 0,
34
+ gasPrice: 0,
35
+ chainId: 1,
36
+ };
37
+ return fakeTx;
38
+ });
39
+ }
40
+ }
41
+ exports.TestChainClient = TestChainClient;
@@ -0,0 +1,26 @@
1
+ {
2
+ "42220": {
3
+ "Airgrab": "",
4
+ "Emission": "",
5
+ "MentoGovernor": "",
6
+ "MentoToken": "",
7
+ "TimelockController": "",
8
+ "Locking": ""
9
+ },
10
+ "62320": {
11
+ "Airgrab": "0x349aa8910577A6fE16cA7b98b5A135d14CE4dF9f",
12
+ "Emission": "0xcd427DDB27D835E5353312e7897bb9ad35F0E214",
13
+ "MentoGovernor": "0x5dFE8CC7743C636a86bED8F8d0de982d502E22fC",
14
+ "MentoToken": "0xD2f4f160BAF7D88a7A9189b03D0B3AA6A5D9775B",
15
+ "TimelockController": "0xb5977b1d208ef35FAf97A9534Dd849c356F362C5",
16
+ "Locking": "0x831DAfC0912e1c2aBa2Da90668c0856d48a8C06b"
17
+ },
18
+ "44787": {
19
+ "Airgrab": "0x281fA47f59456fA04DF699539fA4b1F25e7769A3",
20
+ "Emission": "0x8D1267bFf3f8166AEB2B58217b74188d1fe326f3",
21
+ "MentoGovernor": "0x84382a356c1Dc6ada21997E64dc72e5a7AcF5826",
22
+ "MentoToken": "0x53De3F938c64baB8C621c8A3C5000b385afE2404",
23
+ "TimelockController": "0x2AFC4a1e7928Fb3bfC81076740d3142FF8B1DE05",
24
+ "Locking": "0x65a1271ce7B2ec8D564A4Bc752E13A36a46e81B8"
25
+ }
26
+ }
@@ -0,0 +1,62 @@
1
+ import { BigNumberish, Signer, providers } from 'ethers';
2
+ import { MentoGovernor } from '@mento-protocol/mento-core-ts';
3
+ import { IChainClient } from './types';
4
+ export declare class Governance {
5
+ private chainClient;
6
+ constructor(chainClient: IChainClient);
7
+ constructor(signerOrProvider: Signer | providers.Provider);
8
+ /**
9
+ * This function retrieves the MentoGovernor contract.
10
+ * @returns The MentoGovernor contract.
11
+ */
12
+ getGovernorContract(): Promise<MentoGovernor>;
13
+ /**
14
+ * Generates a transaction that submits a proposal to be created to the Mento Governor contract using the specified values.
15
+ * @param targets The addresses of the contracts to be called during proposal execution.
16
+ * @param values The values to be passed to the calls to the target contracts.
17
+ * @param calldatas The calldata to be passed to the calls to the target contracts.
18
+ * @param description A human readable description of the proposal.
19
+ * @returns The transaction request.
20
+ */
21
+ createProposal(targets: string[], values: BigNumberish[], calldatas: string[], description: string): Promise<providers.TransactionRequest>;
22
+ /**
23
+ * Generates a transaction that will queue the proposal with the specified id to be executed.
24
+ * @param proposalId The id of the proposal to queue.
25
+ * @returns The transaction request.
26
+ */
27
+ queueProposal(proposalId: BigNumberish): Promise<providers.TransactionRequest>;
28
+ /**
29
+ * Executes the proposal with the specified id.
30
+ * @param proposalId The id of the proposal to execute.
31
+ * @returns The transaction request.
32
+ */
33
+ executeProposal(proposalId: BigNumberish): Promise<providers.TransactionRequest>;
34
+ /**
35
+ * Submits a vote to the Mento Governor contract for the specified proposal.
36
+ * @param proposalId The id of the proposal to vote on.
37
+ * @param support Whether or not to support the proposal.
38
+ * @returns The transaction request.
39
+ */
40
+ castVote(proposalId: BigNumberish, support: BigNumberish): Promise<providers.TransactionRequest>;
41
+ /**
42
+ * Cancels the proposal with the specified id.
43
+ * @param proposalId The id of the proposal to vote on.
44
+ * @param support Whether or not to support the proposal.
45
+ * @returns The transaction request.
46
+ */
47
+ cancelProposal(proposalId: BigNumberish): Promise<providers.TransactionRequest>;
48
+ /**
49
+ * Returns the state of the proposal with the specified id.
50
+ * @param proposalId The id of the proposal to get the state of.
51
+ * @returns The state of the proposal.
52
+ */
53
+ getProposalState(proposalId: BigNumberish): Promise<string>;
54
+ /**
55
+ * This function validates the args that are to be used in the createProposal function.
56
+ * @param targets The addresses of the contracts to be called during proposal execution.
57
+ * @param values The values to be passed to the calls to the target contracts.
58
+ * @param calldatas The calldata to be passed to the calls to the target contracts.
59
+ * @param description A human readable description of the proposal.
60
+ */
61
+ private validateProposalArgs;
62
+ }
@@ -0,0 +1,147 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.Governance = void 0;
13
+ const ethers_1 = require("ethers");
14
+ const utils_1 = require("./utils");
15
+ const mento_core_ts_1 = require("@mento-protocol/mento-core-ts");
16
+ const types_1 = require("./types");
17
+ const ChainClient_1 = require("./ChainClient");
18
+ const TestChainClient_1 = require("./TestChainClient");
19
+ class Governance {
20
+ constructor(arg) {
21
+ // TODO: Remove use of TestChainClient in future this is only meant for testing
22
+ if (arg instanceof ChainClient_1.ChainClient || arg instanceof TestChainClient_1.TestChainClient) {
23
+ this.chainClient = arg;
24
+ }
25
+ else if (ethers_1.Signer.isSigner(arg) || ethers_1.providers.Provider.isProvider(arg)) {
26
+ this.chainClient = new ChainClient_1.ChainClient(arg);
27
+ }
28
+ else {
29
+ throw new Error('Invalid constructor argument');
30
+ }
31
+ }
32
+ /**
33
+ * This function retrieves the MentoGovernor contract.
34
+ * @returns The MentoGovernor contract.
35
+ */
36
+ getGovernorContract() {
37
+ return __awaiter(this, void 0, void 0, function* () {
38
+ const contracts = (0, utils_1.getContractsByChainId)(yield this.chainClient.getChainId());
39
+ const mentoGovernorAddress = contracts.MentoGovernor;
40
+ return mento_core_ts_1.MentoGovernor__factory.connect(mentoGovernorAddress, yield this.chainClient.getSigner());
41
+ });
42
+ }
43
+ /**
44
+ * Generates a transaction that submits a proposal to be created to the Mento Governor contract using the specified values.
45
+ * @param targets The addresses of the contracts to be called during proposal execution.
46
+ * @param values The values to be passed to the calls to the target contracts.
47
+ * @param calldatas The calldata to be passed to the calls to the target contracts.
48
+ * @param description A human readable description of the proposal.
49
+ * @returns The transaction request.
50
+ */
51
+ createProposal(targets, values, calldatas, description) {
52
+ return __awaiter(this, void 0, void 0, function* () {
53
+ this.validateProposalArgs(targets, values, calldatas, description);
54
+ const governor = yield this.getGovernorContract();
55
+ const tx = yield governor.populateTransaction['propose(address[],uint256[],bytes[],string)'](targets, values, calldatas, description);
56
+ return yield this.chainClient.populateTransaction(tx);
57
+ });
58
+ }
59
+ /**
60
+ * Generates a transaction that will queue the proposal with the specified id to be executed.
61
+ * @param proposalId The id of the proposal to queue.
62
+ * @returns The transaction request.
63
+ */
64
+ queueProposal(proposalId) {
65
+ return __awaiter(this, void 0, void 0, function* () {
66
+ const governor = yield this.getGovernorContract();
67
+ const tx = yield governor.populateTransaction['queue(uint256)'](proposalId);
68
+ return yield this.chainClient.populateTransaction(tx);
69
+ });
70
+ }
71
+ /**
72
+ * Executes the proposal with the specified id.
73
+ * @param proposalId The id of the proposal to execute.
74
+ * @returns The transaction request.
75
+ */
76
+ executeProposal(proposalId) {
77
+ return __awaiter(this, void 0, void 0, function* () {
78
+ const governor = yield this.getGovernorContract();
79
+ const tx = yield governor.populateTransaction['execute(uint256)'](proposalId);
80
+ return yield this.chainClient.populateTransaction(tx);
81
+ });
82
+ }
83
+ /**
84
+ * Submits a vote to the Mento Governor contract for the specified proposal.
85
+ * @param proposalId The id of the proposal to vote on.
86
+ * @param support Whether or not to support the proposal.
87
+ * @returns The transaction request.
88
+ */
89
+ castVote(proposalId, support) {
90
+ return __awaiter(this, void 0, void 0, function* () {
91
+ const governor = yield this.getGovernorContract();
92
+ const tx = yield governor.populateTransaction.castVote(proposalId, support);
93
+ return yield this.chainClient.populateTransaction(tx);
94
+ });
95
+ }
96
+ /**
97
+ * Cancels the proposal with the specified id.
98
+ * @param proposalId The id of the proposal to vote on.
99
+ * @param support Whether or not to support the proposal.
100
+ * @returns The transaction request.
101
+ */
102
+ cancelProposal(proposalId) {
103
+ return __awaiter(this, void 0, void 0, function* () {
104
+ const governor = yield this.getGovernorContract();
105
+ const tx = yield governor.populateTransaction.cancel(proposalId);
106
+ return yield this.chainClient.populateTransaction(tx);
107
+ });
108
+ }
109
+ /**
110
+ * Returns the state of the proposal with the specified id.
111
+ * @param proposalId The id of the proposal to get the state of.
112
+ * @returns The state of the proposal.
113
+ */
114
+ getProposalState(proposalId) {
115
+ return __awaiter(this, void 0, void 0, function* () {
116
+ const governor = yield this.getGovernorContract();
117
+ const state = (yield governor.functions.state(proposalId))[0];
118
+ return types_1.ProposalState[state];
119
+ });
120
+ }
121
+ /**
122
+ * This function validates the args that are to be used in the createProposal function.
123
+ * @param targets The addresses of the contracts to be called during proposal execution.
124
+ * @param values The values to be passed to the calls to the target contracts.
125
+ * @param calldatas The calldata to be passed to the calls to the target contracts.
126
+ * @param description A human readable description of the proposal.
127
+ */
128
+ validateProposalArgs(targets, values, calldatas, description) {
129
+ if (!targets || targets.length === 0) {
130
+ throw new Error('Targets must be specified');
131
+ }
132
+ if (!values || values.length === 0) {
133
+ throw new Error('Values must be specified');
134
+ }
135
+ if (!calldatas || calldatas.length === 0) {
136
+ throw new Error('Calldatas must be specified');
137
+ }
138
+ if (!description) {
139
+ throw new Error('Description must be specified');
140
+ }
141
+ if (targets.length !== values.length ||
142
+ targets.length !== calldatas.length) {
143
+ throw new Error('Targets, values, and calldatas must all have the same length');
144
+ }
145
+ }
146
+ }
147
+ exports.Governance = Governance;
@@ -1 +1,3 @@
1
1
  export * from './mento';
2
+ export * from './governance';
3
+ export * from './utils';
package/dist/cjs/index.js CHANGED
@@ -16,3 +16,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  };
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  __exportStar(require("./mento"), exports);
19
+ __exportStar(require("./governance"), exports);
20
+ __exportStar(require("./utils"), exports);
@@ -0,0 +1,33 @@
1
+ import { Address, TradingLimit, TradingLimitsConfig, TradingLimitsState } from './types';
2
+ import { Broker } from '@mento-protocol/mento-core-ts';
3
+ /**
4
+ * Returns the limit configuration in the broker for the given exchange and asset
5
+ * @param broker an instance of the broker
6
+ * @param exchangeId the id of the exchange
7
+ * @param asset the address of the limited asset
8
+ * @returns the limit configuration
9
+ */
10
+ export declare function getLimitsConfig(broker: Broker, exchangeId: string, asset: Address): Promise<TradingLimitsConfig>;
11
+ /**
12
+ * Returns the limit state in the broker for the given exchange and asset
13
+ * @param broker an instance of the broker
14
+ * @param exchangeId the id of the exchange
15
+ * @param asset the address of the limited asset
16
+ * @returns the limit state
17
+ */
18
+ export declare function getLimitsState(broker: Broker, exchangeId: string, asset: Address): Promise<TradingLimitsState>;
19
+ /**
20
+ * Returns a human-friendly representation of the limits for the given exchange and asset
21
+ * @param broker an instance of the broker
22
+ * @param exchangeId the id of the exchange
23
+ * @param asset the address of the asset with the limit
24
+ * @returns a list of TradingLimit objects
25
+ */
26
+ export declare function getLimits(broker: Broker, exchangeId: string, asset: Address): Promise<TradingLimit[]>;
27
+ /**
28
+ * Returns the limit id for the given exchange and asset
29
+ * @param exchangeId the id of the exchange
30
+ * @param asset the address of the asset with the limit
31
+ * @returns the limit id
32
+ */
33
+ export declare function getLimitId(exchangeId: string, asset: Address): string;
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.getLimitId = exports.getLimits = exports.getLimitsState = exports.getLimitsConfig = void 0;
13
+ const assert_1 = require("assert");
14
+ const ethers_1 = require("ethers");
15
+ /**
16
+ * Returns the limit configuration in the broker for the given exchange and asset
17
+ * @param broker an instance of the broker
18
+ * @param exchangeId the id of the exchange
19
+ * @param asset the address of the limited asset
20
+ * @returns the limit configuration
21
+ */
22
+ function getLimitsConfig(broker, exchangeId, asset) {
23
+ return __awaiter(this, void 0, void 0, function* () {
24
+ const limitId = getLimitId(exchangeId, asset);
25
+ const cfg = yield broker.tradingLimitsConfig(limitId);
26
+ return {
27
+ timestep0: cfg['timestep0'],
28
+ timestep1: cfg['timestep1'],
29
+ limit0: cfg['limit0'],
30
+ limit1: cfg['limit1'],
31
+ limitGlobal: cfg['limitGlobal'],
32
+ flags: cfg['flags'],
33
+ };
34
+ });
35
+ }
36
+ exports.getLimitsConfig = getLimitsConfig;
37
+ /**
38
+ * Returns the limit state in the broker for the given exchange and asset
39
+ * @param broker an instance of the broker
40
+ * @param exchangeId the id of the exchange
41
+ * @param asset the address of the limited asset
42
+ * @returns the limit state
43
+ */
44
+ function getLimitsState(broker, exchangeId, asset) {
45
+ return __awaiter(this, void 0, void 0, function* () {
46
+ const limitId = getLimitId(exchangeId, asset);
47
+ const [cfg, state] = yield Promise.all([
48
+ getLimitsConfig(broker, exchangeId, asset),
49
+ broker.tradingLimitsState(limitId),
50
+ ]);
51
+ const isL0Enabled = cfg.timestep0 > 0;
52
+ const isL1Enabled = cfg.timestep1 > 0;
53
+ const nowEpoch = Math.floor(Date.now() / 1000);
54
+ const isL0Outdated = isL0Enabled && nowEpoch > state['lastUpdated0'] + cfg.timestep0;
55
+ const isL1Outdated = isL1Enabled && nowEpoch > state['lastUpdated1'] + cfg.timestep1;
56
+ return {
57
+ lastUpdated0: isL0Outdated ? nowEpoch : state['lastUpdated0'],
58
+ lastUpdated1: isL1Outdated ? nowEpoch : state['lastUpdated1'],
59
+ netflow0: isL0Outdated ? 0 : state['netflow0'],
60
+ netflow1: isL1Outdated ? 0 : state['netflow1'],
61
+ netflowGlobal: state['netflowGlobal'],
62
+ };
63
+ });
64
+ }
65
+ exports.getLimitsState = getLimitsState;
66
+ /**
67
+ * Returns a human-friendly representation of the limits for the given exchange and asset
68
+ * @param broker an instance of the broker
69
+ * @param exchangeId the id of the exchange
70
+ * @param asset the address of the asset with the limit
71
+ * @returns a list of TradingLimit objects
72
+ */
73
+ function getLimits(broker, exchangeId, asset) {
74
+ return __awaiter(this, void 0, void 0, function* () {
75
+ const [cfg, state] = yield Promise.all([
76
+ getLimitsConfig(broker, exchangeId, asset),
77
+ getLimitsState(broker, exchangeId, asset),
78
+ ]);
79
+ const limits = [];
80
+ if (cfg.limit0 > 0) {
81
+ limits.push({
82
+ asset: asset,
83
+ maxIn: cfg.limit0 - state.netflow0,
84
+ maxOut: cfg.limit0 + state.netflow0,
85
+ until: state.lastUpdated0 + cfg.timestep0,
86
+ });
87
+ }
88
+ if (cfg.limit1 > 0) {
89
+ limits.push({
90
+ asset: asset,
91
+ maxIn: cfg.limit1 - state.netflow1,
92
+ maxOut: cfg.limit1 + state.netflow1,
93
+ until: state.lastUpdated1 + cfg.timestep1,
94
+ });
95
+ }
96
+ if (cfg.limitGlobal > 0) {
97
+ const timestampIn2030 = 1893456000; // a far away timestamp
98
+ limits.push({
99
+ asset: asset,
100
+ maxIn: cfg.limitGlobal - state.netflowGlobal,
101
+ maxOut: cfg.limitGlobal + state.netflowGlobal,
102
+ until: timestampIn2030,
103
+ });
104
+ }
105
+ return limits;
106
+ });
107
+ }
108
+ exports.getLimits = getLimits;
109
+ /**
110
+ * Returns the limit id for the given exchange and asset
111
+ * @param exchangeId the id of the exchange
112
+ * @param asset the address of the asset with the limit
113
+ * @returns the limit id
114
+ */
115
+ function getLimitId(exchangeId, asset) {
116
+ const assetBytes32 = ethers_1.utils.zeroPad(asset, 32);
117
+ const exchangeIdBytes = ethers_1.utils.arrayify(exchangeId);
118
+ const assetBytes = ethers_1.utils.arrayify(assetBytes32);
119
+ (0, assert_1.strict)(exchangeIdBytes.length === assetBytes.length, 'exchangeId and asset0 must be the same length');
120
+ return ethers_1.utils.hexlify(exchangeIdBytes.map((b, i) => b ^ assetBytes[i]));
121
+ }
122
+ exports.getLimitId = getLimitId;
@@ -1,6 +1,6 @@
1
+ import { Address, TradingLimit, TradingLimitsConfig, TradingLimitsState } from './types';
1
2
  import { IBroker } from '@mento-protocol/mento-core-ts';
2
- import { BigNumber, BigNumberish, providers, Signer } from 'ethers';
3
- import { Address } from './types';
3
+ import { BigNumber, BigNumberish, Signer, providers } from 'ethers';
4
4
  export interface Exchange {
5
5
  providerAddr: Address;
6
6
  id: string;
@@ -109,9 +109,44 @@ export declare class Mento {
109
109
  getExchangesForProvider(exchangeProviderAddr: Address): Promise<Exchange[]>;
110
110
  /**
111
111
  * Returns the Mento exchange (if any) for a given pair of tokens
112
- * @param token0 the first token
113
- * @param token1 the second token
112
+ * @param token0 the address of the first token
113
+ * @param token1 the address of the second token
114
114
  * @returns exchange
115
115
  */
116
116
  getExchangeForTokens(token0: Address, token1: Address): Promise<Exchange>;
117
+ /**
118
+ * Returns the Mento exchange for a given exchange id
119
+ * @param exchangeId the id of the exchange
120
+ * @returns the exchange with the given id
121
+ */
122
+ getExchangeById(exchangeId: string): Promise<Exchange>;
123
+ /**
124
+ * Returns whether trading is enabled in the given mode for a given exchange id
125
+ * @param exchangeId the id of the exchange
126
+ * @param mode the trading mode
127
+ * @returns true if trading is enabled in the given mode, false otherwise
128
+ */
129
+ isTradingEnabled(exchangeId: string): Promise<boolean>;
130
+ /**
131
+ * Return the trading limits for a given exchange id. Each limit is an object with the following fields:
132
+ * asset: the address of the asset with the limit
133
+ * maxIn: the maximum amount of the asset that can be sold
134
+ * maxOut: the maximum amount of the asset that can be bought
135
+ * until: the timestamp until which the limit is valid
136
+ * @param exchangeId the id of the exchange
137
+ * @returns the list of trading limits
138
+ */
139
+ getTradingLimits(exchangeId: string): Promise<TradingLimit[]>;
140
+ /**
141
+ * Returns the trading limits configuration for a given exchange id
142
+ * @param exchangeId the id of the exchange
143
+ * @returns the trading limits configuration
144
+ */
145
+ getTradingLimitConfig(exchangeId: string): Promise<TradingLimitsConfig>;
146
+ /**
147
+ * Returns the trading limits state for a given exchange id
148
+ * @param exchangeId the id of the exchange
149
+ * @returns the trading limits state
150
+ */
151
+ getTradingLimitState(exchangeId: string): Promise<TradingLimitsState>;
117
152
  }