-
Notifications
You must be signed in to change notification settings - Fork 215
/
bootstrap.js
1158 lines (1054 loc) · 37.6 KB
/
bootstrap.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @ts-check
import { allComparable } from '@agoric/same-structure';
import {
makeLoopbackProtocolHandler,
makeEchoConnectionHandler,
makeNonceMaker,
} from '@agoric/swingset-vat/src/vats/network/index.js';
import { E, Far } from '@agoric/far';
import { makeStore } from '@agoric/store';
import { installOnChain as installTreasuryOnChain } from '@agoric/treasury/bundles/install-on-chain.js';
import { installOnChain as installPegasusOnChain } from '@agoric/pegasus/bundles/install-on-chain.js';
import { makePluginManager } from '@agoric/swingset-vat/src/vats/plugin-manager.js';
import { assert, details as X } from '@agoric/assert';
import {
makeRatio,
natSafeMath,
} from '@agoric/zoe/src/contractSupport/index.js';
import { AmountMath, AssetKind } from '@agoric/ertp';
import { Nat } from '@agoric/nat';
import { makeBridgeManager } from './bridge.js';
import { makeNameHubKit } from './nameHub.js';
import {
CENTRAL_ISSUER_NAME,
demoIssuerEntries,
fromCosmosIssuerEntries,
BLD_ISSUER_ENTRY,
} from './issuers';
const { multiply, floorDivide } = natSafeMath;
const NUM_IBC_PORTS = 3;
const QUOTE_INTERVAL = 5 * 60;
const BASIS_POINTS_DENOM = 10000n;
const CENTRAL_DENOM_NAME = 'urun';
// On-chain timer device is in seconds, so scale to milliseconds.
const CHAIN_TIMER_DEVICE_SCALE = 1000;
console.debug(`loading bootstrap.js`);
// Used for coordinating on an index in comms for the provisioning service
const PROVISIONER_INDEX = 1;
function makeVattpFrom(vats) {
const { vattp, comms } = vats;
return Far('vattp', {
makeNetworkHost(allegedName, console = undefined) {
return E(vattp).makeNetworkHost(allegedName, comms, console);
},
});
}
export function buildRootObject(vatPowers, vatParameters) {
const { D } = vatPowers;
async function setupCommandDevice(httpVat, cmdDevice, roles) {
await E(httpVat).setCommandDevice(cmdDevice, roles);
D(cmdDevice).registerInboundHandler(httpVat);
}
// Make services that are provided on the real or virtual chain side
async function makeChainBundler(
vats,
bridgeManager,
timerDevice,
vatAdminSvc,
noFakeCurrencies,
) {
/** @type {ERef<ReturnType<import('./vat-bank')['buildRootObject']>>} */
const bankVat = vats.bank;
// Name these differently to distinguish their uses.
// TODO: eventually make these different facets of the bridgeManager,
// binding to srcIDs/dstIDs 'bank' and 'dibc' respectively.
const bankBridgeManager = bridgeManager;
const dibcBridgeManager = bridgeManager;
const chainTimerServiceP = E(vats.timer).createTimerService(timerDevice);
const feeIssuerConfig = {
name: CENTRAL_ISSUER_NAME,
assetKind: AssetKind.NAT,
displayInfo: { decimalPlaces: 6, assetKind: AssetKind.NAT },
initialFunds: 1_000_000_000_000_000_000n,
};
const zoeFeesConfig = {
getPublicFacetFee: 50n,
installFee: 65_000n,
startInstanceFee: 5_000_000n,
offerFee: 65_000n,
timeAuthority: chainTimerServiceP,
lowFee: 500_000n,
highFee: 5_000_000n,
shortExp: 1000n * 60n * 5n, // 5 min in milliseconds
longExp: 1000n * 60n * 60n * 24n * 1n, // 1 day in milliseconds
};
const meteringConfig = {
incrementBy: 25_000_000n,
initial: 50_000_000n,
threshold: 25_000_000n,
price: {
feeNumerator: 1n,
computronDenominator: 1n, // default is just one-to-one
},
};
// Create singleton instances.
const [
bankManager,
sharingService,
board,
chainTimerService,
{ zoeService: zoe, feeMintAccess, feeCollectionPurse },
{ priceAuthority, adminFacet: priceAuthorityAdmin },
walletManager,
] = await Promise.all([
E(bankVat).makeBankManager(bankBridgeManager),
E(vats.sharing).getSharingService(),
E(vats.board).getBoard(),
chainTimerServiceP,
/** @type {Promise<{ zoeService: ZoeServiceFeePurseRequired, feeMintAccess:
* FeeMintAccess, feeCollectionPurse: FeePurse }>} */ (E(
vats.zoe,
).buildZoe(vatAdminSvc, feeIssuerConfig, zoeFeesConfig, meteringConfig)),
E(vats.priceAuthority).makePriceAuthority(),
E(vats.walletManager).buildWalletManager(vatAdminSvc),
]);
const zoeWUnlimitedPurse = E(zoe).bindDefaultFeePurse(feeCollectionPurse);
const {
nameHub: agoricNames,
nameAdmin: agoricNamesAdmin,
} = makeNameHubKit();
const {
nameHub: namesByAddress,
nameAdmin: namesByAddressAdmin,
} = makeNameHubKit();
const {
nameHub: pegasusConnections,
nameAdmin: pegasusConnectionsAdmin,
} = makeNameHubKit();
async function installEconomy(bootstrapPaymentValue) {
// Create a mapping from all the nameHubs we create to their corresponding
// nameAdmin.
/** @type {Store<NameHub, NameAdmin>} */
const nameAdmins = makeStore('nameHub');
await Promise.all(
['brand', 'installation', 'issuer', 'instance', 'uiConfig'].map(
async nm => {
const { nameHub, nameAdmin } = makeNameHubKit();
await E(agoricNamesAdmin).update(nm, nameHub);
nameAdmins.init(nameHub, nameAdmin);
if (nm === 'uiConfig') {
// Reserve the Treasury's config until we've populated it.
nameAdmin.reserve('Treasury');
}
},
),
);
// Install the economy, giving the components access to the name admins we made.
const [treasuryInstallResults] = await Promise.all([
installTreasuryOnChain({
agoricNames,
board,
centralName: CENTRAL_ISSUER_NAME,
chainTimerService,
nameAdmins,
priceAuthority,
zoeWPurse: zoeWUnlimitedPurse,
bootstrapPaymentValue,
feeMintAccess,
}),
installPegasusOnChain({
agoricNames,
board,
nameAdmins,
namesByAddress,
zoeWPurse: zoeWUnlimitedPurse,
}),
]);
return treasuryInstallResults;
}
const demoIssuers = demoIssuerEntries(noFakeCurrencies);
// all the non=RUN issuers. RUN can't be initialized until we have the
// bootstrap payment, but we need to know pool sizes to ask for that.
const demoAndBldIssuers = [...demoIssuers, BLD_ISSUER_ENTRY];
// Calculate how much RUN we need to fund the AMM pools
function ammPoolRunDeposits(issuers) {
let ammTotal = 0n;
const ammPoolIssuers = [];
const ammPoolBalances = [];
issuers.forEach(entry => {
const [issuerName, record] = entry;
if (!record.collateralConfig) {
// skip RUN and fake issuers
return;
}
assert(record.tradesGivenCentral);
/** @type {bigint} */
// The initial trade represents the fair value of RUN for collateral.
const initialTrade = record.tradesGivenCentral[0];
// The collateralValue to be deposited is given, and we want to deposit
// the same value of RUN in the pool. For instance, We're going to
// deposit 2 * 10^13 BLD, and 10^6 build will trade for 28.9 * 10^6 RUN
const poolBalance = floorDivide(
multiply(record.collateralConfig.collateralValue, initialTrade[0]),
initialTrade[1],
);
ammTotal += poolBalance;
ammPoolIssuers.push(issuerName);
ammPoolBalances.push(poolBalance);
});
return {
ammTotal,
ammPoolBalances,
ammPoolIssuers,
};
}
const {
ammTotal: ammDepositValue,
ammPoolBalances,
ammPoolIssuers,
} = ammPoolRunDeposits(demoAndBldIssuers);
// We'll usually have something like:
// {
// type: 'AG_COSMOS_INIT',
// chainID: 'agoric',
// storagePort: 1,
// supplyCoins: [
// { denom: 'provisionpass', amount: '100' },
// { denom: 'sendpacketpass', amount: '100' },
// { denom: 'ubld', amount: '1000000000000000' },
// { denom: 'urun', amount: '50000000000' }
// ]
// vbankPort: 3,
// vibcPort: 2
// }
const { supplyCoins = [] } =
(vatParameters && vatParameters.argv && vatParameters.argv.bootMsg) || {};
const centralBootstrapSupply = supplyCoins.find(
({ denom }) => denom === CENTRAL_DENOM_NAME,
) || { amount: '0' };
// Now we can bootstrap the economy!
const bankBootstrapSupply = Nat(BigInt(centralBootstrapSupply.amount));
// Ask the treasury for enough RUN to fund both AMM and bank.
const bootstrapPaymentValue = bankBootstrapSupply + ammDepositValue;
// NOTE: no use of the voteCreator. We'll need it to initiate votes on
// changing Treasury parameters.
const { treasuryCreator, _voteCreator, ammFacets } = await installEconomy(
bootstrapPaymentValue,
);
const [
centralIssuer,
centralBrand,
ammInstance,
pegasusInstance,
] = await Promise.all([
E(agoricNames).lookup('issuer', CENTRAL_ISSUER_NAME),
E(agoricNames).lookup('brand', CENTRAL_ISSUER_NAME),
E(agoricNames).lookup('instance', 'amm'),
E(agoricNames).lookup('instance', 'Pegasus'),
]);
// Start the reward distributor.
const epochTimerService = chainTimerService;
const distributorParams = {
epochInterval: 60n * 60n, // 1 hour
};
const feeCollectorDepositFacet = await E(bankManager)
.getFeeCollectorDepositFacet(CENTRAL_DENOM_NAME, {
issuer: centralIssuer,
brand: centralBrand,
})
.catch(e => {
console.log('Cannot create fee collector', e);
return undefined;
});
if (feeCollectorDepositFacet) {
// Only distribute fees if there is a collector.
E(vats.distributeFees)
.buildDistributor(
E(vats.distributeFees).makeFeeCollector(zoeWUnlimitedPurse, [
treasuryCreator,
ammFacets.creatorFacet,
]),
feeCollectorDepositFacet,
epochTimerService,
harden(distributorParams),
)
.catch(e => console.error('Error distributing fees', e));
}
/**
* @type {Store<Brand, Payment>} A store containing payments that weren't
* used by the bank and can be used for other purposes.
*/
const unusedBankPayments = makeStore('brand');
/* Prime the bank vat with our bootstrap payment. */
const centralBootstrapPayment = await E(
treasuryCreator,
).getBootstrapPayment(AmountMath.make(centralBrand, bootstrapPaymentValue));
const [ammBootstrapPayment, bankBootstrapPayment] = await E(
centralIssuer,
).split(
centralBootstrapPayment,
AmountMath.make(centralBrand, ammDepositValue),
);
// If there's no bankBridgeManager, we'll find other uses for these funds.
if (!bankBridgeManager) {
unusedBankPayments.init(centralBrand, bankBootstrapPayment);
}
/** @type {Array<[string, import('./issuers').IssuerInitializationRecord]>} */
const rawIssuerEntries = [
...fromCosmosIssuerEntries({
issuer: centralIssuer,
brand: centralBrand,
bankDenom: CENTRAL_DENOM_NAME,
bankPayment: bankBootstrapPayment,
}),
// We still create demo currencies, but not obviously fake ones unless
// $FAKE_CURRENCIES is given.
...demoIssuers,
];
const issuerEntries = await Promise.all(
rawIssuerEntries.map(async entry => {
const [issuerName, record] = entry;
if (record.issuer !== undefined) {
return entry;
}
/** @type {Issuer} */
const issuer = await E(vats.mints).makeMintAndIssuer(
issuerName,
...(record.issuerArgs || []),
);
const brand = await E(issuer).getBrand();
const newRecord = harden({ ...record, brand, issuer });
/** @type {[string, typeof newRecord]} */
const newEntry = [issuerName, newRecord];
return newEntry;
}),
);
// Add bank assets.
await Promise.all(
issuerEntries.map(async entry => {
const [issuerName, record] = entry;
const { bankDenom, bankPurse, brand, issuer, bankPayment } = record;
if (!bankDenom || !bankPurse) {
return undefined;
}
assert(brand);
assert(issuer);
const makeMintKit = async () => {
// We need to obtain the mint in order to mint the tokens when they
// come from the bank.
// FIXME: Be more careful with the mint.
const mint = await E(vats.mints).getMint(issuerName);
return harden({ brand, issuer, mint });
};
let kitP;
if (bankBridgeManager && bankPayment) {
// The bank needs the payment to back its existing bridge peg.
kitP = harden({ brand, issuer, payment: bankPayment });
} else if (unusedBankPayments.has(brand)) {
// No need to back the currency.
kitP = harden({ brand, issuer });
} else {
kitP = makeMintKit();
}
const kit = await kitP;
return E(bankManager).addAsset(bankDenom, issuerName, bankPurse, kit);
}),
);
async function addAllCollateral() {
async function splitAllCentralPayments() {
const ammPoolAmounts = ammPoolBalances.map(b =>
AmountMath.make(centralBrand, b),
);
const allPayments = await E(centralIssuer).splitMany(
ammBootstrapPayment,
ammPoolAmounts,
);
const issuerMap = {};
for (let i = 0; i < ammPoolBalances.length; i += 1) {
const issuerName = ammPoolIssuers[i];
issuerMap[issuerName] = {
payment: allPayments[i],
amount: ammPoolAmounts[i],
};
}
return issuerMap;
}
const issuerMap = await splitAllCentralPayments();
return Promise.all(
issuerEntries.map(async entry => {
const [issuerName, record] = entry;
const config = record.collateralConfig;
if (!config) {
return undefined;
}
assert(record.tradesGivenCentral);
const initialPrice = record.tradesGivenCentral[0];
assert(initialPrice);
const initialPriceNumerator = /** @type {bigint} */ (initialPrice[0]);
const rates = {
initialPrice: makeRatio(
initialPriceNumerator,
centralBrand,
/** @type {bigint} */ (initialPrice[1]),
record.brand,
),
initialMargin: makeRatio(config.initialMarginPercent, centralBrand),
liquidationMargin: makeRatio(
config.liquidationMarginPercent,
centralBrand,
),
interestRate: makeRatio(
config.interestRateBasis,
centralBrand,
BASIS_POINTS_DENOM,
),
loanFee: makeRatio(
config.loanFeeBasis,
centralBrand,
BASIS_POINTS_DENOM,
),
};
const collateralPayments = E(vats.mints).mintInitialPayments(
[issuerName],
[config.collateralValue],
);
const secondaryPayment = E.get(collateralPayments)[0];
assert(record.issuer, `No issuer for ${issuerName}`);
const liquidityIssuer = E(ammFacets.ammPublicFacet).addPool(
record.issuer,
config.keyword,
);
const [secondaryAmount, liquidityBrand] = await Promise.all([
E(record.issuer).getAmountOf(secondaryPayment),
E(liquidityIssuer).getBrand(),
]);
const centralAmount = issuerMap[issuerName].amount;
const proposal = harden({
want: { Liquidity: AmountMath.makeEmpty(liquidityBrand) },
give: { Secondary: secondaryAmount, Central: centralAmount },
});
E(zoeWUnlimitedPurse).offer(
E(ammFacets.ammPublicFacet).makeAddLiquidityInvitation(),
proposal,
harden({
Secondary: secondaryPayment,
Central: issuerMap[issuerName].payment,
}),
);
return E(treasuryCreator).addVaultType(
record.issuer,
config.keyword,
rates,
);
}),
);
}
/**
* @param {ERef<Issuer>} issuerIn
* @param {ERef<Issuer>} issuerOut
* @param {ERef<Brand>} brandIn
* @param {ERef<Brand>} brandOut
* @param {Array<[bigint | number, bigint | number]>} tradeList
*/
const makeFakePriceAuthority = (
issuerIn,
issuerOut,
brandIn,
brandOut,
tradeList,
) =>
E(vats.priceAuthority).makeFakePriceAuthority({
issuerIn,
issuerOut,
actualBrandIn: brandIn,
actualBrandOut: brandOut,
tradeList,
timer: chainTimerService,
quoteInterval: QUOTE_INTERVAL,
});
const [ammPublicFacet, pegasus] = await Promise.all(
[ammInstance, pegasusInstance].map(instance =>
E(zoeWUnlimitedPurse).getPublicFacet(instance),
),
);
await addAllCollateral();
const brandsWithPriceAuthorities = await E(
ammPublicFacet,
).getAllPoolBrands();
await Promise.all(
issuerEntries.map(async entry => {
// Create priceAuthority pairs for centralIssuer based on the
// AMM or FakePriceAuthority.
const [issuerName, record] = entry;
console.debug(`Creating ${issuerName}-${CENTRAL_ISSUER_NAME}`);
const { tradesGivenCentral, issuer } = record;
assert(issuer);
const brand = await E(issuer).getBrand();
let toCentral;
let fromCentral;
if (brandsWithPriceAuthorities.includes(brand)) {
({ toCentral, fromCentral } = await E(ammPublicFacet)
.getPriceAuthorities(brand)
.catch(_e => {
// console.warn('could not get AMM priceAuthorities', _e);
return {};
}));
}
if (!fromCentral && tradesGivenCentral) {
// We have no amm from-central price authority, make one from trades.
if (issuerName !== CENTRAL_ISSUER_NAME) {
console.log(
`Making fake price authority for ${CENTRAL_ISSUER_NAME}-${issuerName}`,
);
}
fromCentral = makeFakePriceAuthority(
centralIssuer,
issuer,
centralBrand,
brand,
tradesGivenCentral,
);
}
if (!toCentral && centralIssuer !== issuer && tradesGivenCentral) {
// We have no amm to-central price authority, make one from trades.
console.log(
`Making fake price authority for ${issuerName}-${CENTRAL_ISSUER_NAME}`,
);
/** @type {Array<[bigint | number, bigint | number]>} */
const tradesGivenOther = tradesGivenCentral.map(
([valueCentral, valueOther]) => [valueOther, valueCentral],
);
toCentral = makeFakePriceAuthority(
issuer,
centralIssuer,
brand,
centralBrand,
tradesGivenOther,
);
}
// Register the price pairs.
await Promise.all(
[
[fromCentral, centralBrand, brand],
[toCentral, brand, centralBrand],
].map(async ([pa, fromBrand, toBrand]) => {
const paPresence = await pa;
if (!paPresence) {
return;
}
await E(priceAuthorityAdmin).registerPriceAuthority(
paPresence,
fromBrand,
toBrand,
);
}),
);
}),
);
// This needs to happen after creating all the services.
// eslint-disable-next-line no-use-before-define
await registerNetworkProtocols(
vats,
dibcBridgeManager,
pegasus,
pegasusConnectionsAdmin,
);
/** @type {ERef<Protocol>} */
const network = vats.network;
return Far('chainBundler', {
async createUserBundle(_nickname, address, powerFlags = []) {
// Bind to some fresh ports (unspecified name) on the IBC implementation
// and provide them for the user to have.
const ibcport = [];
for (let i = 0; i < NUM_IBC_PORTS; i += 1) {
// eslint-disable-next-line no-await-in-loop
const port = await E(network).bind('/ibc-port/');
ibcport.push(port);
}
/** @type {{ issuerName: string, purseName: string, issuer: Issuer,
* brand: Brand, payment: Payment, payToBank: boolean }[]} */
const userPaymentRecords = [];
await Promise.all(
issuerEntries.map(async entry => {
const [issuerName, record] = entry;
if (!record.defaultPurses) {
return;
}
const { issuer, brand, bankPurse } = record;
assert(issuer);
assert(brand);
await Promise.all(
record.defaultPurses.map(async ([purseName, value]) => {
// Only pay to the bank if we don't have an actual bridge to the
// underlying chain (from which we'll get the assets).
let payToBank = false;
if (purseName === bankPurse) {
if (bankBridgeManager) {
// Don't mint or pay if we have a separate bank layer.
// We'll obtain the assets from the bank layer.
return;
}
payToBank = true;
}
const splitUnusedBankPayment = async () => {
if (!payToBank || !unusedBankPayments.has(brand)) {
return undefined;
}
// We have an unusedPayment, so we can split off a payment.
const amount = AmountMath.make(brand, Nat(value));
// TODO: what happens if unusedBankPayment doesn't have enough
// remaining?
const [fragment, remaining] = await E(issuer).split(
unusedBankPayments.get(brand),
amount,
);
unusedBankPayments.set(brand, remaining);
return fragment;
};
const getPayment = async () => {
const unused = await splitUnusedBankPayment();
if (unused) {
return unused;
}
const [minted] = await E(vats.mints).mintInitialPayments(
[issuerName],
[value],
);
return minted;
};
const payment = await getPayment();
userPaymentRecords.push({
issuerName,
issuer,
brand,
purseName,
payment,
payToBank,
});
}),
);
}),
);
const bank = await E(bankManager).getBankForAddress(address);
// Separate out the purse-creating payments from the bank payments.
const faucetPaymentInfo = [];
await Promise.all(
userPaymentRecords.map(async precord => {
const {
payToBank,
issuer,
issuerName,
payment,
brand,
purseName,
} = precord;
if (!payToBank) {
// Just a faucet payment to be claimed by a wallet.
faucetPaymentInfo.push({
issuer,
issuerPetname: issuerName,
payment,
brand,
pursePetname: purseName,
});
return;
}
// Deposit the payment in the bank now.
assert(brand);
const purse = E(bank).getPurse(brand);
await E(purse).deposit(payment);
}),
);
const userFeePurse = await E(zoe).makeFeePurse();
const zoeWUserFeePurse = await E(zoe).bindDefaultFeePurse(userFeePurse);
const faucet = Far('faucet', {
// A method to reap the spoils of our on-chain provisioning.
async tapFaucet() {
return faucetPaymentInfo;
},
getFeePurse() {
return userFeePurse;
},
});
// Create a name hub for this address.
const {
nameHub: myAddressNameHub,
nameAdmin: rawMyAddressNameAdmin,
} = makeNameHubKit();
// Register it with the namesByAddress hub.
namesByAddressAdmin.update(address, myAddressNameHub);
/** @type {MyAddressNameAdmin} */
const myAddressNameAdmin = Far('myAddressNameAdmin', {
...rawMyAddressNameAdmin,
getMyAddress() {
return address;
},
});
const makeChainWallet = () =>
E(walletManager).makeWallet({
bank,
feePurse: userFeePurse,
agoricNames,
namesByAddress,
myAddressNameAdmin,
zoe: zoeWUserFeePurse,
board,
timerDevice,
timerDeviceScale: CHAIN_TIMER_DEVICE_SCALE,
});
const additionalPowers = {};
const powerFlagConfig = [
['agoricNamesAdmin', agoricNamesAdmin],
['bankManager', bankManager],
['chainWallet', () => makeChainWallet()],
['pegasusConnections', pegasusConnections],
['priceAuthorityAdmin', priceAuthorityAdmin],
['treasuryCreator', treasuryCreator],
['vattp', () => makeVattpFrom(vats)],
];
await Promise.all(
powerFlagConfig.map(async ([flag, value]) => {
if (
!powerFlags ||
(!powerFlags.includes(`agoric.${flag}`) &&
!powerFlags.includes('agoric.ALL_THE_POWERS'))
) {
return;
}
const powerP = typeof value === 'function' ? value() : value;
additionalPowers[flag] = await powerP;
}),
);
const bundle = harden({
...additionalPowers,
agoricNames,
bank,
chainTimerService,
sharingService,
faucet,
ibcport,
myAddressNameAdmin,
namesByAddress,
priceAuthority,
board,
zoe: zoeWUserFeePurse,
});
return bundle;
},
});
}
async function registerNetworkProtocols(
vats,
dibcBridgeManager,
pegasus,
pegasusConnectionsAdmin,
) {
/** @type {ERef<Protocol>} */
const network = vats.network;
const ps = [];
// Every vat has a loopback device.
ps.push(
E(vats.network).registerProtocolHandler(
['/local'],
makeLoopbackProtocolHandler(),
),
);
if (dibcBridgeManager) {
// We have access to the bridge, and therefore IBC.
const callbacks = Far('callbacks', {
downcall(method, obj) {
return dibcBridgeManager.toBridge('dibc', {
...obj,
type: 'IBC_METHOD',
method,
});
},
});
const ibcHandler = await E(vats.ibc).createInstance(callbacks);
dibcBridgeManager.register('dibc', ibcHandler);
ps.push(
E(vats.network).registerProtocolHandler(
['/ibc-port', '/ibc-hop'],
ibcHandler,
),
);
} else {
const loHandler = makeLoopbackProtocolHandler(
makeNonceMaker('ibc-channel/channel-'),
);
ps.push(
E(vats.network).registerProtocolHandler(['/ibc-port'], loHandler),
);
}
await Promise.all(ps);
// Add an echo listener on our ibc-port network (whether real or virtual).
const echoPort = await E(network).bind('/ibc-port/echo');
E(echoPort).addListener(
Far('listener', {
async onAccept(_port, _localAddr, _remoteAddr, _listenHandler) {
return harden(makeEchoConnectionHandler());
},
async onListen(port, _listenHandler) {
console.debug(`listening on echo port: ${port}`);
},
}),
);
if (pegasus) {
// Add the Pegasus transfer port.
const port = await E(network).bind('/ibc-port/transfer');
E(port).addListener(
Far('listener', {
async onAccept(_port, _localAddr, _remoteAddr, _listenHandler) {
const chandlerP = E(pegasus).makePegConnectionHandler();
const proxyMethod = name => (...args) =>
E(chandlerP)[name](...args);
const onOpen = proxyMethod('onOpen');
const onClose = proxyMethod('onClose');
let localAddr;
return Far('pegasusConnectionHandler', {
onOpen(c, actualLocalAddr, ...args) {
localAddr = actualLocalAddr;
if (pegasusConnectionsAdmin) {
pegasusConnectionsAdmin.update(localAddr, c);
}
return onOpen(c, ...args);
},
onReceive: proxyMethod('onReceive'),
onClose(c, ...args) {
try {
return onClose(c, ...args);
} finally {
if (pegasusConnectionsAdmin) {
pegasusConnectionsAdmin.delete(localAddr, c);
}
}
},
});
},
async onListen(p, _listenHandler) {
console.debug(`Listening on Pegasus transfer port: ${p}`);
},
}),
);
}
if (dibcBridgeManager) {
// Register a provisioning handler over the bridge.
const handler = Far('provisioningHandler', {
async fromBridge(_srcID, obj) {
switch (obj.type) {
case 'PLEASE_PROVISION': {
const { nickname, address, powerFlags } = obj;
return E(vats.provisioning)
.pleaseProvision(nickname, address, powerFlags)
.catch(e =>
console.error(
`Error provisioning ${nickname} ${address}:`,
e,
),
);
}
default:
assert.fail(X`Unrecognized request ${obj.type}`);
}
},
});
dibcBridgeManager.register('provision', handler);
}
}
// objects that live in the client's solo vat. Some services should only
// be in the DApp environment (or only in end-user), but we're not yet
// making a distinction, so the user also gets them.
async function createLocalBundle(vats, devices, vatAdminSvc) {
// This will eventually be a vat spawning service. Only needed by dev
// environments.
const spawner = E(vats.spawner).buildSpawner(vatAdminSvc);
const localTimerService = E(vats.timer).createTimerService(devices.timer);
// Needed for DApps, maybe for user clients.
const scratch = E(vats.uploads).getUploads();
// Only create the plugin manager if the device exists.
let plugin;
if (devices.plugin) {
plugin = makePluginManager(devices.plugin, vatPowers);
}
// This will allow dApp developers to register in their api/deploy.js
const httpRegCallback = Far('httpRegCallback', {
doneLoading(subsystems) {
return E(vats.http).doneLoading(subsystems);
},
send(obj, connectionHandles) {
return E(vats.http).send(obj, connectionHandles);
},
registerURLHandler(handler, path) {
return E(vats.http).registerURLHandler(handler, path);
},
registerAPIHandler(handler) {
return E(vats.http).registerURLHandler(handler, '/api');
},
async registerWallet(wallet, privateWallet, privateWalletBridge) {
await Promise.all([
E(vats.http).registerURLHandler(privateWallet, '/private/wallet'),
E(vats.http).registerURLHandler(
privateWalletBridge,
'/private/wallet-bridge',
),
E(vats.http).setWallet(wallet),
]);
},
});
return allComparable(
harden({
...(plugin ? { plugin } : {}),
scratch,
spawner,
localTimerService,
network: vats.network,
http: httpRegCallback,
vattp: makeVattpFrom(vats),
}),
);
}
return Far('root', {
async bootstrap(vats, devices) {
const bridgeManager =