-
Notifications
You must be signed in to change notification settings - Fork 208
/
addPool.js
237 lines (205 loc) · 7.67 KB
/
addPool.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
// @ts-check
import { E } from '@endo/eventual-send';
import { AmountMath, AssetKind } from '@agoric/ertp';
import { assertProposalShape } from '@agoric/zoe/src/contractSupport/index.js';
import { makePromiseKit } from '@endo/promise-kit';
import { definePoolKind } from './pool.js';
const { details: X } = assert;
const DISPLAY_INFO = harden({ decimalPlaces: 6 });
/**
* @param {ZCF} zcf
* @param {(Brand) => boolean} isInSecondaries
* @param {WeakStore<Brand,ZCFMint>} brandToLiquidityMint
* @param {WeakStore<Brand,ERef<Issuer>>} brandToLiquidityIssuer
* @param {() => (secondaryBrand: Brand) => Promise<void>} getAddIssuerToReserve
*/
export const makeAddIssuer = (
zcf,
isInSecondaries,
brandToLiquidityMint,
brandToLiquidityIssuer,
getAddIssuerToReserve,
) => {
/**
* Add a new issuer. If we previously received a request for the same issuer,
* we'll return the issuer or a promise for it.
*
* @param {Issuer} secondaryIssuer
* @param {string} keyword
*/
const addIssuer = async (secondaryIssuer, keyword) => {
const [secondaryAssetKind, secondaryBrand] = await Promise.all([
E(secondaryIssuer).getAssetKind(),
E(secondaryIssuer).getBrand(),
]);
// AWAIT ///////////////
assert(
secondaryAssetKind === AssetKind.NAT,
X`${keyword} asset not fungible (must use NAT math)`,
);
if (brandToLiquidityIssuer.has(secondaryBrand)) {
return brandToLiquidityIssuer.get(secondaryBrand);
}
assert(
!isInSecondaries(secondaryBrand),
X`issuer ${secondaryIssuer} already has a pool`,
);
if (brandToLiquidityMint.has(secondaryBrand)) {
const { issuer } = brandToLiquidityMint
.get(secondaryBrand)
.getIssuerRecord();
return issuer;
}
/** @type {import('@endo/promise-kit').PromiseKit<Issuer<'nat'>>} */
const liquidityPromiseKit = makePromiseKit();
brandToLiquidityIssuer.init(secondaryBrand, liquidityPromiseKit.promise);
const liquidityKeyword = `${keyword}Liquidity`;
zcf.assertUniqueKeyword(liquidityKeyword);
return E.when(
Promise.all([
zcf.saveIssuer(secondaryIssuer, keyword),
zcf.makeZCFMint(liquidityKeyword, AssetKind.NAT, DISPLAY_INFO),
]),
)
.then(([issuer, mint]) => {
console.log(
X`Saved issuer ${secondaryIssuer} to keyword ${keyword} and got back ${issuer}`,
);
// this ensures that getSecondaryIssuer(thisIssuer) will return even
// before the pool is created
brandToLiquidityMint.init(secondaryBrand, mint);
const { issuer: liquidityIssuer } = mint.getIssuerRecord();
liquidityPromiseKit.resolve(liquidityIssuer);
// we only need entries in this table until brandToLiquidityIssuer knows
// the issuer and the promise is resolved.
brandToLiquidityIssuer.delete(secondaryBrand);
// defer lookup until necessary. more aligned with governed
// param we expect this to be eventually.
const addIssuerToReserve = getAddIssuerToReserve();
// tell the reserve about this brand, which it will validate by
// calling back to AMM for the issuer
return addIssuerToReserve(secondaryBrand).then(() => liquidityIssuer);
})
.catch(e => {
console.error(
X`Failure Saving issuer ${secondaryIssuer}. Not added to Reserve`,
);
liquidityPromiseKit.reject(e);
brandToLiquidityIssuer.delete(secondaryBrand);
brandToLiquidityMint.delete(secondaryBrand);
throw e;
});
};
return addIssuer;
};
/**
* @param {ZCF<import('./multipoolMarketMaker.js').AMMTerms>} zcf
* @param {(brand: Brand, pool: PoolFacets) => void} initPool add new pool to store
* @param {Brand} centralBrand
* @param {ERef<Timer>} timer
* @param {IssuerKit} quoteIssuerKit
* @param {import('./multipoolMarketMaker.js').AMMParamGetters} params retrieve governed params
* @param {ZCFSeat} protocolSeat seat that holds collected fees
* @param {WeakStore<Brand,ZCFMint>} brandToLiquidityMint
* @param {(secondaryBrand: Brand, reserveLiquidityTokenSeat: ZCFSeat, liquidityKeyword: Keyword) => Promise<void>} onOfferHandled
* @param {ERef<StorageNode>} [storageNode]
* @param {ERef<Marshaller>} [marshaller]
*/
export const makeAddPoolInvitation = (
zcf,
initPool,
centralBrand,
timer,
quoteIssuerKit,
params,
protocolSeat,
brandToLiquidityMint,
onOfferHandled,
storageNode,
marshaller,
) => {
const makePool = definePoolKind(
zcf,
centralBrand,
timer,
quoteIssuerKit,
params,
protocolSeat,
storageNode,
marshaller,
);
/** @type {(Brand) => Promise<{poolFacets: PoolFacets, liquidityZcfMint: ZCFMint}>} */
const addPool = async secondaryBrand => {
const liquidityZcfMint = brandToLiquidityMint.get(secondaryBrand);
const { zcfSeat: poolSeat } = zcf.makeEmptySeatKit();
/** @type {PoolFacets} */
const poolFacets = makePool(liquidityZcfMint, poolSeat, secondaryBrand);
initPool(secondaryBrand, poolFacets);
return { liquidityZcfMint, poolFacets };
};
/** @param {ZCFSeat} seat */
const handleAddPoolOffer = async seat => {
assertProposalShape(seat, {
give: { Central: null, Secondary: null },
});
const {
give: { Central: centralAmount, Secondary: secondaryAmount },
want: proposalWant,
} = seat.getProposal();
const secondaryBrand = secondaryAmount.brand;
const { brand: liquidityBrand, issuer } = brandToLiquidityMint
.get(secondaryBrand)
.getIssuerRecord();
const minPoolLiquidity = params.getMinInitialPoolLiquidity();
if (proposalWant.Liquidity) {
const { Liquidity: wantLiquidityAmount } = proposalWant;
const centralAboveMinimum =
// @ts-expect-error central is NAT
centralAmount.value - minPoolLiquidity.value;
// when providing initial liquidity, the liquidity tokens issued will be
// equal to the central provided. Here, the reserve gets the minimum
const funderLiquidityAmount = AmountMath.make(
liquidityBrand,
centralAboveMinimum,
);
assert(
AmountMath.isGTE(funderLiquidityAmount, wantLiquidityAmount),
X`Requested too many liquidity tokens (${wantLiquidityAmount}, max: ${funderLiquidityAmount}`,
);
}
assert(
AmountMath.isGTE(centralAmount, minPoolLiquidity),
X`The minimum initial liquidity is ${minPoolLiquidity}, rejecting ${centralAmount}`,
);
const minLiqAmount = AmountMath.make(
liquidityBrand,
minPoolLiquidity.value,
);
// @ts-expect-error find might return undefined
const [liquidityKeyword] = Object.entries(zcf.getTerms().issuers).find(
([_, i]) => i === issuer,
);
assert(liquidityKeyword, 'liquidity brand required');
// COMMIT POINT /////////////////////
const {
poolFacets: { pool, helper },
} = await addPool(secondaryBrand);
// in addLiquidityInternal, funder provides centralAmount & secondaryAmount,
// and receives liquidity tokens equal to centralAmount. Afterward, we'll
// transfer minPoolLiquidity in tokens from the funder to the reserve.
helper.addLiquidityInternal(seat, secondaryAmount, centralAmount);
seat.decrementBy({ Liquidity: minLiqAmount });
const { zcfSeat: reserveLiquidityTokenSeat } = zcf.makeEmptySeatKit();
reserveLiquidityTokenSeat.incrementBy({ [liquidityKeyword]: minLiqAmount });
zcf.reallocate(reserveLiquidityTokenSeat, seat);
seat.exit();
pool.updateState();
await onOfferHandled(
secondaryBrand,
reserveLiquidityTokenSeat,
liquidityKeyword,
);
return 'Added liquidity.';
};
return () => zcf.makeInvitation(handleAddPoolOffer, 'Add Pool and Liquidity');
};