This repository has been archived by the owner on Jun 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathauctionItems.js
247 lines (204 loc) · 7.29 KB
/
auctionItems.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
238
239
240
241
242
243
244
245
246
247
// @ts-check
import { assert, details as X } from '@agoric/assert';
import { Far } from '@endo/far';
import { E } from '@endo/eventual-send';
import { AmountMath } from '@agoric/ertp';
import { makeNotifierKit } from '@agoric/notifier';
import {
assertIssuerKeywords,
defaultAcceptanceMsg,
assertNatAssetKind,
offerTo,
} from '@agoric/zoe/src/contractSupport/index.js';
import '@agoric/zoe/exported.js';
/**
* Auction a list of NFT items which identified by `string`, with timeAuthority, minBidPerItem,
* needs {Money, Items}
* Allow you to `withdraw` anytime.
*
* @typedef {{
* instance: Instance,
* makeBidInvitation: Function,
* getSessionDetails: Function,
* completedP: Promise,
* sellerSeatP: Promise<UserSeat>
* }} AuctionSession
* @type {ContractStartFn}
*/
const start = (zcf) => {
const {
minimalBid,
issuers,
brands,
timeAuthority,
winnerPriceOption,
bidDuration = 300n, // 5 mins in chain timer 1s resolution
auctionInstallation,
} = zcf.getTerms();
assertIssuerKeywords(zcf, harden(['Items', 'Money']));
const moneyBrand = brands.Money;
const itemBrand = brands.Items;
assertNatAssetKind(zcf, moneyBrand);
/** @type Record<string, AuctionSession> */
const sellerSessions = {};
let availableItems = AmountMath.make(itemBrand, harden([]));
const zoeService = zcf.getZoeService();
const { zcfSeat: sellerSeat } = zcf.makeEmptySeatKit();
const { notifier: availableItemsNotifier, updater: availableItemsUpdater } =
makeNotifierKit();
const sell = (seat) => {
sellerSeat.incrementBy(seat.decrementBy(seat.getCurrentAllocation()));
zcf.reallocate(sellerSeat, seat);
seat.exit();
// update current amount
const addedAmount = sellerSeat.getAmountAllocated('Items', itemBrand);
// XXX the sell method can be call multiple times,
// so available items should be added to, not updated
availableItems = AmountMath.add(availableItems, addedAmount);
availableItemsUpdater.updateState(availableItems);
return defaultAcceptanceMsg;
};
// The seller can selectively withdraw any items and/or any amount of money by specifying amounts in their
// `want`. If no `want` is specified, then all of the `sellerSeat`'s allocation is withdrawn.
const withdraw = (seat) => {
const { want } = seat.getProposal();
const amount =
want && (want.Items || want.Money)
? want
: sellerSeat.getCurrentAllocation();
seat.incrementBy(sellerSeat.decrementBy(harden(amount)));
zcf.reallocate(sellerSeat, seat);
seat.exit();
return 'Withdraw success';
};
const getAvailableItems = () => {
// XXX we can not get the allocated amount, because it may ignore the auctioning items
assert(sellerSeat && !sellerSeat.hasExited(), X`no items are for sale`);
return availableItems;
};
const getAvailableItemsNotifier = () => availableItemsNotifier;
const startAuctioningItem = async (itemKey) => {
const itemAmount = AmountMath.make(itemBrand, harden([itemKey]));
const availableAmount = sellerSeat.getAmountAllocated('Items', itemBrand);
assert(
AmountMath.isGTE(availableAmount, itemAmount),
X`Item ${itemKey} is no longer available`,
);
const issuerKeywordRecord = harden({
Asset: issuers.Items,
Ask: issuers.Money,
});
const terms = harden({
winnerPriceOption,
timeAuthority,
bidDuration,
});
const { creatorInvitation, instance } = await E(zoeService).startInstance(
auctionInstallation,
issuerKeywordRecord,
terms,
);
const shouldBeInvitationMsg = `The auctionContract instance should return a creatorInvitation`;
assert(creatorInvitation, shouldBeInvitationMsg);
const proposal = harden({
give: { Asset: itemAmount },
want: { Ask: minimalBid },
exit: { waived: null },
});
const { userSeatPromise: sellerSeatP, deposited } = await offerTo(
zcf,
creatorInvitation,
harden({
Items: 'Asset',
Money: 'Ask',
}),
proposal,
sellerSeat,
sellerSeat,
);
const completedP = deposited.then(async () => {
// get after match allocation
// TODO Stop using getCurrentAllocationJig.
// See https://github.com/Agoric/agoric-sdk/issues/5833
const sellerAllocation = await E(sellerSeatP).getFinalAllocation();
// check Asset amount after the auction session
const isAssetItemSold = AmountMath.isEmpty(sellerAllocation.Asset);
if (isAssetItemSold) {
// item was sold, update available items by substracting sold amount
// XXX we can not get the allocated amount, because it is prone to
// race-condition when multiple auctions are completed consecutively
availableItems = AmountMath.subtract(availableItems, itemAmount);
availableItemsUpdater.updateState(availableItems);
}
// unset the session, this handles the case auction session was failed
// then item should be available for a new session
delete sellerSessions[itemKey];
});
const auctionObj = await E(sellerSeatP).getOfferResult();
return {
sellerSeatP,
instance,
completedP,
makeBidInvitation: () => E(auctionObj).makeBidInvitation(),
getSessionDetails: () => E(auctionObj).getSessionDetails(),
};
};
const getOrCreateAuctionSession = async (itemKey) => {
assert.typeof(itemKey, 'string');
if (!sellerSessions[itemKey]) {
sellerSessions[itemKey] = await startAuctioningItem(itemKey);
}
return sellerSessions[itemKey];
};
const makeBidInvitationForKey = async (itemKey) => {
const session = await getOrCreateAuctionSession(itemKey);
return session.makeBidInvitation();
};
const getSessionDetailsForKey = async (itemKey) => {
assert.typeof(itemKey, 'string');
const session = sellerSessions[itemKey];
if (!session) {
// session is not started, try to return general data,
// The trade-off here is we have to fake the session data,
// and it there may be mismatch between our version and the inner one
const itemAmount = AmountMath.make(itemBrand, harden([itemKey]));
return harden({
auctionedAssets: itemAmount,
minimumBid: minimalBid,
winnerPriceOption,
closesAfter: null,
bidDuration,
timeAuthority,
bids: [],
});
}
return session.getSessionDetails();
};
const getCompletedPromiseForKey = (itemKey) => {
const session = sellerSessions[itemKey];
return session && session.completedP;
};
const makeWithdrawInvitation = async () => {
return zcf.makeInvitation(withdraw, 'withdraw');
};
const publicFacet = Far('AuctionItemsPublicFacet', {
getAvailableItems,
getAvailableItemsNotifier,
getItemsIssuer: () => issuers.Items,
makeBidInvitationForKey,
getCompletedPromiseForKey,
getSessionDetailsForKey,
});
const creatorFacet = Far('AuctionItemsCreatorFacet', {
makeBidInvitationForKey,
getAvailableItems: publicFacet.getAvailableItems,
getItemsIssuer: publicFacet.getItemsIssuer,
makeWithdrawInvitation,
getCompletedPromiseForKey,
getSessionDetailsForKey,
});
const creatorInvitation = zcf.makeInvitation(sell, 'seller');
return harden({ creatorFacet, creatorInvitation, publicFacet });
};
harden(start);
export { start };