-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgondi.ts
1037 lines (933 loc) · 30.7 KB
/
gondi.ts
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
import {
Account,
Address,
createPublicClient,
createTransport,
Hash,
Hex,
TypedDataDefinition,
} from 'viem';
import { Api, Props as ApiProps } from '@/api';
import { Auction, zeroAddress, zeroHash, zeroHex } from '@/blockchain';
import { Contracts, GondiPublicClient, Wallet } from '@/contracts';
import {
MarketplaceEnum,
OffersSortField,
Ordering,
SellAndRepayOrder,
SingleNftSignedOfferInput,
TokenStandardType,
} from '@/generated/graphql';
import * as model from '@/model';
import { NftStandard } from '@/model';
import {
generateFakeRenegotiationInput,
isLoanVersion,
loanToMslLoan,
LoanToMslLoanType,
renegotiationToMslRenegotiation,
} from '@/utils/loan';
import { min } from '@/utils/number';
import { FULFILLED, REJECTED } from '@/utils/promises';
import { areSameAddress } from '@/utils/string';
import { OptionalNullable } from '@/utils/types';
export class Gondi {
contracts: Contracts;
wallet: Wallet;
account: Account;
bcClient: GondiPublicClient;
api: Api;
defaults: { Msl: Address; UserVault: Address };
constructor({ wallet, apiClient }: GondiProps) {
this.wallet = wallet;
this.account = wallet.account;
this.bcClient = createPublicClient({
chain: wallet.chain,
transport: () => createTransport(wallet.transport),
});
this.contracts = new Contracts(this.bcClient, wallet);
this.defaults = {
Msl: this.contracts.MultiSourceLoanV6.address,
UserVault: this.contracts.UserVaultV6.address,
};
this.api = new Api({ wallet, apiClient });
}
async makeSingleNftOffer(offer: model.SingleNftOfferInput) {
return await this._makeSingleNftOffer(offer);
}
/** @internal */
_makeSingleNftOffer(
offer: model.SingleNftOfferInput,
mslContractAddress: Address,
skipSave: true,
): Promise<SingleNftSignedOfferInput>;
/** @internal */
_makeSingleNftOffer(
offer: model.SingleNftOfferInput,
mslContractAddress?: Address,
skipSave?: false,
): ReturnType<Api['saveSingleNftOffer']>;
/** @internal */
async _makeSingleNftOffer(
offer: model.SingleNftOfferInput,
mslContractAddress?: Address,
skipSave?: boolean,
) {
const contract = this.contracts.Msl(mslContractAddress ?? this.defaults.Msl);
const contractAddress = contract.address;
const offerInput = {
...offer,
lenderAddress: offer.lenderAddress ? offer.lenderAddress : this.account.address,
signerAddress: this.account.address,
borrowerAddress: offer.borrowerAddress ?? zeroAddress,
requiresLiquidation: !!offer.requiresLiquidation,
contractAddress,
offerValidators: [], // This is ignored by the API but it was required in the mutation
};
const response = await this.api.generateSingleNftOfferHash({ offerInput });
const { offerHash, offerId, validators, lenderAddress, signerAddress, borrowerAddress } =
response.offer;
const collateralAddress = response.offer.nft.collection?.contractData?.contractAddress;
if (collateralAddress === undefined) throw new Error('Invalid nft');
const structToSign = {
...offerInput,
lender: lenderAddress ?? offerInput.lenderAddress,
signer: signerAddress ?? offerInput.signerAddress,
borrower: borrowerAddress ?? offerInput.borrowerAddress,
nftCollateralTokenId: response.offer.nft.tokenId,
nftCollateralAddress: collateralAddress,
validators,
offerId,
};
const signature = await contract.signOffer({ structToSign });
const signedOffer: SingleNftSignedOfferInput = {
...offerInput,
offerValidators: validators.map((validator) => ({
arguments: validator.arguments,
validator: validator.validator,
})),
offerHash: offerHash ?? zeroHash,
offerId,
signature,
};
if (skipSave) return signedOffer;
return await this.api.saveSingleNftOffer(signedOffer);
}
async makeCollectionOffer(offer: model.CollectionOfferInput) {
return await this._makeCollectionOffer(offer);
}
/** @internal */
async _makeCollectionOffer(offer: model.CollectionOfferInput, mslContractAddress?: Address) {
const contract = this.contracts.Msl(mslContractAddress ?? this.defaults.Msl);
const contractAddress = contract.address;
const offerInput = {
...offer,
lenderAddress: offer.lenderAddress ? offer.lenderAddress : this.account.address,
signerAddress: this.account.address,
borrowerAddress: offer.borrowerAddress ?? zeroAddress,
requiresLiquidation: !!offer.requiresLiquidation,
contractAddress,
offerValidators: [
// This is ignored by the API but it was required in the mutation
{
validator: zeroAddress,
arguments: zeroHex,
},
],
};
const response = await this.api.generateCollectionOfferHash({ offerInput });
const collateralAddress = response.offer.collection.contractData?.contractAddress;
if (collateralAddress === undefined) throw new Error('Invalid collection');
const { offerHash, offerId, validators, lenderAddress, signerAddress, borrowerAddress } =
response.offer;
const structToSign = {
...offerInput,
lender: lenderAddress ?? offerInput.lenderAddress,
signer: signerAddress ?? offerInput.signerAddress,
borrower: borrowerAddress ?? offerInput.borrowerAddress,
nftCollateralTokenId: 0n,
nftCollateralAddress: collateralAddress,
validators,
offerId,
};
const signature = await contract.signOffer({ structToSign });
const signedOffer = {
...offerInput,
offerValidators: validators.map((validator) => ({
arguments: validator.arguments,
validator: validator.validator,
})),
offerHash: offerHash ?? zeroHash,
offerId,
signature,
};
return await this.api.saveCollectionOffer(signedOffer);
}
async makeOrder(sellAndRepayOrderInput: Parameters<Api['publishSellAndRepayOrder']>[0]) {
let response = await this.api.publishSellAndRepayOrder(sellAndRepayOrderInput);
while (response.__typename === 'SignatureRequest') {
const key = response.key as 'signature' | 'repaymentSignature';
sellAndRepayOrderInput[key] = await this.wallet.signTypedData(
response.typedData as TypedDataDefinition,
);
response = await this.api.publishSellAndRepayOrder(sellAndRepayOrderInput);
}
if (response.__typename !== 'SellAndRepayOrder') throw new Error('This should never happen');
return { ...response, ...sellAndRepayOrderInput };
}
async cancelOrder(order: Pick<SellAndRepayOrder, 'cancelCalldata' | 'marketPlaceAddress'>) {
return this.contracts
.GenericContract(order.marketPlaceAddress)
.sendTransactionData(order.cancelCalldata);
}
async cancelOffer({ id, contractAddress }: { id: bigint; contractAddress: Address }) {
return this.contracts.Msl(contractAddress).cancelOffer({
id,
});
}
async cancelAllOffers({ minId, contractAddress }: { minId: bigint; contractAddress: Address }) {
return this.contracts.Msl(contractAddress).cancelAllOffers({
minId,
});
}
async hideOffer({ id, contractAddress }: { id: bigint; contractAddress: Address }) {
return this.api.hideOffer({ contract: contractAddress, id: id.toString() });
}
async unhideOffer({ id, contractAddress }: { id: bigint; contractAddress: Address }) {
return this.api.unhideOffer({
contract: contractAddress,
id: id.toString(),
});
}
async makeRefinanceOffer({ renegotiation, contractAddress, ...props }: MakeRefinanceOfferProps) {
const { isV4, isV5 } = isLoanVersion(contractAddress, this.wallet.chain.id);
if (props.skipSignature && props.withFallbackOffer) {
throw new Error('skipSignature and withFallbackOffer cannot be true at the same time');
}
if (props.withFallbackOffer && (isV4 || isV5)) {
throw new Error('Unsupported contract address for withFallbackOffer argument');
}
const renegotiationInput = {
lenderAddress: this.account.address,
signerAddress: this.account.address,
...renegotiation,
targetPrincipal: renegotiation.targetPrincipal ?? [],
trancheIndex: renegotiation.trancheIndex ?? [],
};
const response = await this.api.generateRenegotiationOfferHash({
renegotiationInput,
});
const { renegotiationId, offerHash, loanId, lenderAddress, signerAddress } = response.offer;
if (props.skipSignature) {
return {
...renegotiationInput,
offerHash: offerHash ?? zeroHash,
signature: zeroHash,
renegotiationId,
};
}
const structToSign = {
...renegotiationInput,
fee: renegotiationInput.feeAmount,
lender: lenderAddress ?? renegotiationInput.lenderAddress,
signer: signerAddress ?? renegotiationInput.signerAddress ?? zeroAddress,
strictImprovement: false,
loanId,
renegotiationId,
};
const contract = this.contracts.Msl(contractAddress);
const signature = await contract.signRenegotiationOffer({ structToSign });
const renegotiationOffer = {
...renegotiationInput,
signature,
offerHash: offerHash ?? zeroHash,
renegotiationId,
};
if (props.withFallbackOffer) {
const {
aprBps,
duration,
expirationTime,
principalAmount,
feeAmount: fee,
} = renegotiationInput;
const offerInput: model.SingleNftOfferInput = {
nftId: props.nftId,
principalAddress: props.principalAddress,
principalAmount,
aprBps,
duration,
expirationTime,
fee,
maxSeniorRepayment: 0n,
capacity: 0n,
};
const fallbackOffer = await this._makeSingleNftOffer(offerInput, contractAddress, true);
return await this.api.saveRefinanceOffer(renegotiationOffer, fallbackOffer);
}
return await this.api.saveRefinanceOffer(renegotiationOffer);
}
async cancelRefinanceOffer({ id, contractAddress }: { id: bigint; contractAddress: Address }) {
return this.contracts.Msl(contractAddress).cancelRefinanceOffer({
id,
});
}
async hideRenegotiationOffer({ id, contractAddress }: { id: bigint; contractAddress: Address }) {
return this.api.hideRenegotiationOffer({
id: id.toString(),
contractAddress,
});
}
async unhideRenegotiationOffer({
id,
contractAddress,
}: {
id: bigint;
contractAddress: Address;
}) {
return this.api.unhideRenegotiationOffer({
id: id.toString(),
contractAddress,
});
}
async hideOrder({ id }: { id: number }) {
return this.api.hideOrder({ id });
}
async showOrder({ id }: { id: number }) {
return this.api.showOrder({ id });
}
async cancelAllRenegotiations({
minId,
contractAddress,
}: {
minId: bigint;
contractAddress: Address;
}) {
return this.contracts.Msl(contractAddress).cancelAllRenegotiations({
minId,
});
}
offerExecutionFromOffers(
offers: OfferFromExecutionOffer[],
amounts?: bigint[],
): EmitLoanArgs['offerExecution'] {
return offers.map((offer, idx) => {
const { signature, lenderAddress, borrowerAddress, offerHash } = offer;
if (!(signature && lenderAddress && borrowerAddress && offerHash))
throw new Error('Misisng required field for offer');
return {
offer: {
...offer,
offerHash,
lenderAddress,
lender: lenderAddress,
borrowerAddress,
borrower: borrowerAddress,
signature,
maxSeniorRepayment: offer.maxSeniorRepayment ?? 0n,
},
amount: amounts?.[idx] ?? offer.principalAmount,
lenderOfferSignature: signature,
};
});
}
async emitLoan(args: EmitLoanArgs) {
const contractAddress = args.offerExecution[0].offer.contractAddress;
return this.contracts.Msl(contractAddress).emitLoan(args);
}
async refinanceFromOffers({
loan,
loanId,
executionData,
}: {
loan: LoanToMslLoanType;
loanId: bigint;
executionData: EmitLoanArgs;
}) {
return this.contracts.Msl(loan.contractAddress).refinanceFromOffers({
loan: loanToMslLoan(loan),
loanId,
executionData,
});
}
async repayLoan({
loan,
loanId,
nftReceiver,
}: {
loan: LoanToMslLoanType;
loanId: bigint;
nftReceiver?: Address;
}) {
return this.contracts.Msl(loan.contractAddress).repayLoan({
loan: loanToMslLoan(loan),
nftReceiver,
loanId,
});
}
async offers({
limit = 20,
cursor,
sortBy = { field: OffersSortField.CreatedDate, order: Ordering.Desc },
filterBy = {},
}: model.ListOffersProps) {
const { status, nft, collection, borrower, ...fields } = filterBy;
return await this.api.listOffers({
first: limit,
after: cursor,
sortBy,
statuses: status,
nfts: nft ? [nft] : [],
collections: collection ? [collection] : [],
borrowerAddress: borrower,
...fields,
});
}
async loans({ limit = 20, cursor, ...rest }: model.ListLoansProps) {
return await this.api.listLoans({
first: limit,
after: cursor,
...rest,
});
}
async list({ nft }: { nft: number }) {
return await this.api.listNft({ nftId: nft });
}
async unlist({ nft }: { nft: number }) {
return await this.api.unlistNft({ nftId: nft });
}
async listings({
collections,
user,
marketPlaces = [MarketplaceEnum.Gondi],
limit = 20,
cursor,
}: model.ListListingsProps) {
return await this.api.listListings({
collections,
userFilter: user,
marketplaceNames: marketPlaces,
after: cursor,
first: limit,
});
}
async nftId(
props: (
| { slug: string; contractAddress?: never }
| { slug?: never; contractAddress: Address }
) & { tokenId: bigint },
) {
let result;
if (props.slug) result = await this.api.nftIdBySlugTokenId(props);
if (props.contractAddress) result = await this.api.nftIdByContractAddressAndTokenId(props);
if (!result?.nft) {
throw new Error(`invalid nft ${props}`);
}
return Number(result.nft.id);
}
async collections(props: {
statsCurrency?: Address;
standards?: TokenStandardType[];
collections?: number[];
cursor?: string;
}) {
const { statsCurrency: currency = zeroAddress, collections, standards, cursor } = props;
const {
collections: { edges, pageInfo },
} = await this.api.collections({ currency, collections, standards, after: cursor });
return { collections: edges.map((edge) => edge.node), pageInfo };
}
async collectionId(props: { slug: string; contractAddress?: never }): Promise<number>;
async collectionId(props: { slug?: never; contractAddress: Address }): Promise<number[]>;
async collectionId(
props:
| {
slug: string;
contractAddress?: never;
}
| {
slug?: never;
contractAddress: Address;
},
) {
let result;
if (props.slug) {
result = await this.api.collectionIdBySlug(props);
if (!result?.collection) {
throw new Error(`invalid collection ${props}`);
}
return Number(result.collection.id);
}
if (props.contractAddress) {
result = await this.api.collectionsIdByContractAddress(props);
if (!result?.collections) {
throw new Error(`invalid collection ${props}`);
}
return result.collections.map((collection) => Number(collection.id));
}
}
async ownedNfts(args: Parameters<Api['ownedNfts']>[0]) {
const result = await this.api.ownedNfts(args);
const { edges: ownedNfts, pageInfo } = result.ownedNfts;
return { ownedNfts: ownedNfts.map((edge) => edge.node), pageInfo };
}
async getRemainingLockupSeconds({ loan }: { loan: LoanToMslLoanType }) {
return this.contracts.Msl(loan.contractAddress).getRemainingLockupSeconds({
loan: loanToMslLoan(loan),
});
}
async isEndLockedUp({
loan,
}: {
loan: LoanToMslLoanType & { durationFromRenegotiationOrStart: bigint };
}) {
return this.contracts.Msl(loan.contractAddress).isEndLockedUp({
loan,
});
}
private contractToVersion(contract: Address) {
if (areSameAddress(contract, this.contracts.MultiSourceLoanV4.address)) return 'v4';
if (areSameAddress(contract, this.contracts.MultiSourceLoanV5.address)) return 'v5';
return 'v6';
}
private async generateRenegotiationId({
loanId,
loan,
}: {
loanId: string;
loan: LoanToMslLoanType;
}) {
const renegotiationInput = generateFakeRenegotiationInput({
loanId,
loan,
trancheIndex: areSameAddress(loan.contractAddress, this.contracts.MultiSourceLoanV6.address),
address: this.account.address,
});
const { offer } = await this.api.generateRenegotiationOfferHash({ renegotiationInput });
return offer.renegotiationId;
}
async refinanceBatch({
aprBpsImprovementPercentage,
refinancings,
}: {
aprBpsImprovementPercentage: number; // e.g. 0.05
refinancings: {
loan: LoanToMslLoanType & { loanReferenceId: string };
source: ReturnType<typeof loanToMslLoan>['source'][number] & { loanIndex: number };
refinancingPrincipal: bigint;
}[];
}) {
const refisByContract: {
v4: {
[tokenLoanId: string]: Parameters<
Contracts['MultiSourceLoanV4']['refinanceBatch']
>[0]['refinancings'][number] & { loanReferenceId: string };
};
v5: {
[tokenLoanId: string]: Parameters<
Contracts['MultiSourceLoanV5']['refinanceBatch']
>[0]['refinancings'][number] & { loanReferenceId: string };
};
v6: {
[tokenLoanId: string]: Parameters<
Contracts['MultiSourceLoanV6']['refinanceBatch']
>[0]['refinancings'][number] & { loanReferenceId: string };
};
} = { v4: {}, v5: {}, v6: {} };
// Group sources by contract and loanId, so that we only have one refinance per loan.
refinancings.forEach(({ loan, source, refinancingPrincipal }) => {
const tokenLoanId = `${loan.nftCollateralAddress}-${loan.nftCollateralTokenId}`;
const version = this.contractToVersion(loan.contractAddress);
const currentLoanRefinancings = refisByContract[version][tokenLoanId];
const currentSourceNewAprBps = BigInt(
Math.floor(Number(source.aprBps) * (1 - aprBpsImprovementPercentage)),
);
const newAprBps = min(currentLoanRefinancings?.newAprBps, currentSourceNewAprBps);
refisByContract[version][tokenLoanId] = {
loan: loanToMslLoan(loan),
loanReferenceId: loan.loanReferenceId,
newAprBps,
sources: [...(currentLoanRefinancings?.sources ?? []), { source, refinancingPrincipal }],
};
});
// Generate renegotiationId for each contract version and call the refinanceBatch implementations.
const versions = ['v4', 'v5', 'v6'] as const;
const results = [];
for (const version of versions) {
const refinancings = Object.values(refisByContract[version]);
if (refinancings.length > 0) {
const renegotiationId = await this.generateRenegotiationId({
loan: refinancings[0].loan,
loanId: refinancings[0].loanReferenceId,
});
try {
// TODO: improve this
const refinanceBatch =
version === 'v4'
? await this.contracts.MultiSourceLoanV4.refinanceBatch({
refinancings: Object.values(refisByContract.v4),
renegotiationId,
})
: version === 'v5'
? await this.contracts.MultiSourceLoanV5.refinanceBatch({
refinancings: Object.values(refisByContract.v5),
renegotiationId,
})
: await this.contracts.MultiSourceLoanV6.refinanceBatch({
refinancings: Object.values(refisByContract.v6),
renegotiationId,
});
results.push({ status: FULFILLED, value: refinanceBatch });
} catch (reason) {
results.push({ status: REJECTED, reason, value: refinancings });
}
}
}
return results;
}
async refinanceFullLoan({
offer,
loan,
loanId,
}: {
offer: model.RenegotiationOffer;
loan: LoanToMslLoanType;
loanId: bigint;
}) {
return this.contracts.Msl(loan.contractAddress).refinanceFullLoan({
offer: renegotiationToMslRenegotiation(offer, loanId),
loan: loanToMslLoan(loan),
signature: offer.signature,
});
}
async refinancePartialLoan({
offer,
loan,
loanId,
}: {
offer: model.RenegotiationOffer;
loan: LoanToMslLoanType;
loanId: bigint;
}) {
return this.contracts.Msl(loan.contractAddress).refinancePartialLoan({
offer: renegotiationToMslRenegotiation(offer, loanId),
loan: loanToMslLoan(loan),
});
}
async addTranche({
offer,
loan,
loanId,
}: {
offer: model.RenegotiationOffer;
loan: LoanToMslLoanType;
loanId: bigint;
}) {
return this.contracts.Msl(loan.contractAddress).addTranche({
offer: renegotiationToMslRenegotiation(offer, loanId),
loan: loanToMslLoan(loan),
signature: offer.signature,
});
}
/**
* Delegate Multicall should be used when token is used as collateral for an active loan.
* Multicall will be performed to the contract address of the first delegation.
*/
async delegateMulticall(delegations: Parameters<Gondi['delegate']>[0][]) {
const contractAddress = delegations[0].loan.contractAddress;
return this.contracts.Msl(contractAddress).delegateMulticall(
delegations.map((delegation) => ({
...delegation,
loan: loanToMslLoan(delegation.loan),
})),
);
}
/** Delegate should be used when token is used as collateral for an active loan. */
async delegate({
loan,
loanId,
to,
enable,
rights,
}: {
loan: LoanToMslLoanType;
loanId: bigint;
to: Address;
enable: boolean;
rights?: Hash;
}) {
return this.contracts.Msl(loan.contractAddress).delegate({
loan: loanToMslLoan(loan),
loanId,
to,
rights,
enable,
});
}
/** RevokeDelegate should be used when token is not being used as collateral. */
async revokeDelegate({
to,
collection,
tokenId,
contract = this.defaults.Msl,
}: {
to: Address;
collection: Address;
tokenId: bigint;
contract?: Address;
}) {
return this.contracts.Msl(contract).revokeDelegate({ to, collection, tokenId });
}
/**
* RevokeDelegationsAndEmitLoan should be used when token has been delegated without being revoked,
* and a new loan wants to be emitted, erasing the delegations provided as argument.
*/
async revokeDelegationsAndEmitLoan({
delegations,
emit,
}: {
delegations: Address[];
emit: Parameters<Gondi['emitLoan']>[0];
}) {
const contractAddress = emit.offerExecution[0].offer.contractAddress;
return this.contracts.Msl(contractAddress).revokeDelegationsAndEmitLoan({ delegations, emit });
}
async liquidateLoan({ loan, loanId }: { loan: LoanToMslLoanType; loanId: bigint }) {
return this.contracts
.Msl(loan.contractAddress)
.liquidateLoan({ loanId, loan: loanToMslLoan(loan) });
}
async placeBid({
collectionContractAddress,
tokenId,
bid,
auction,
}: {
collectionContractAddress: Address;
tokenId: bigint;
bid: bigint;
auction: Auction;
}) {
return this.contracts
.All(auction.loanAddress)
.placeBid({ collectionContractAddress, tokenId, bid, auction });
}
async settleAuction({ loan, auction }: { loan: LoanToMslLoanType; auction: Auction }) {
return this.contracts
.All(auction.loanAddress)
.settleAuction({ auction, loan: loanToMslLoan(loan) });
}
async settleAuctionWithBuyout({ loan, auction }: { loan: LoanToMslLoanType; auction: Auction }) {
return this.contracts
.All(auction.loanAddress)
.settleAuctionWithBuyout({ auction, loan: loanToMslLoan(loan) });
}
async getAuctionRemainingLockupSeconds({ auction }: { auction: Auction }) {
return this.contracts.All(auction.loanAddress).getRemainingLockupSeconds({ auction });
}
/**
* Get the owner of an ERC 721 token.
*/
async getOwner({ nftAddress, tokenId }: { nftAddress: Address; tokenId: bigint }) {
const erc721 = this.contracts.ERC721(nftAddress);
return erc721.contract.read.ownerOf([tokenId]);
}
/**
* Get the balance of an ERC 1155 token id.
*/
async balanceOf({ nftAddress, tokenId }: { nftAddress: Address; tokenId: bigint }) {
const erc1155 = this.contracts.ERC1155(nftAddress);
return erc1155.contract.read.balanceOf([this.wallet.account.address, tokenId]);
}
async isApprovedNFTForAll({
nftAddress,
standard,
to = this.defaults.Msl,
}: {
nftAddress: Address;
standard: Parameters<Contracts['Nft']>[1];
to?: Address;
}) {
const nft = this.contracts.Nft(nftAddress, standard);
return nft.contract.read.isApprovedForAll([this.account.address, to]);
}
async approveNFTForAll({
nftAddress,
standard,
to = this.defaults.Msl,
}: {
nftAddress: Address;
standard: Parameters<Contracts['Nft']>[1];
to?: Address;
}) {
const nft = this.contracts.Nft(nftAddress, standard);
const txHash = await nft.safeContractWrite.setApprovalForAll([to, true]);
return {
txHash,
waitTxInBlock: async () => {
const receipt = await this.bcClient.waitForTransactionReceipt({
hash: txHash,
});
const events = nft.parseEventLogs('ApprovalForAll', receipt.logs);
if (events.length === 0) throw new Error(`${standard} approval for all not set`);
return { ...events[0].args, ...receipt };
},
};
}
async isApprovedToken({
tokenAddress,
amount,
to = this.defaults.Msl,
}: {
tokenAddress: Address;
amount: bigint;
to?: Address;
}) {
const erc20 = this.contracts.ERC20(tokenAddress);
return (await erc20.contract.read.allowance([this.account.address, to])) >= amount;
}
async approveToken({
tokenAddress,
amount = model.MAX_NUMBER,
to = this.defaults.Msl,
}: {
tokenAddress: Address;
amount?: bigint;
to?: Address;
}) {
const erc20 = this.contracts.ERC20(tokenAddress);
const txHash = await erc20.safeContractWrite.approve([to, amount]);
return {
txHash,
waitTxInBlock: async () => {
const receipt = await this.bcClient.waitForTransactionReceipt({
hash: txHash,
});
const events = erc20.parseEventLogs('Approval', receipt.logs);
if (events.length === 0) throw new Error('ERC20 approval not set');
return { ...events[0].args, ...receipt };
},
};
}
async createUserVault({ nfts }: { nfts: CreateVaultArgs }) {
return this._createUserVault({ nfts });
}
async _createUserVault({
nfts,
userVaultAddress = this.defaults.UserVault,
}: {
nfts: CreateVaultArgs;
userVaultAddress?: Address;
}) {
return this.contracts.UserVault(userVaultAddress).createVault(nfts);
}
async depositUserVaultERC721s({
userVaultAddress = this.defaults.UserVault,
...data
}: { userVaultAddress?: Address } & DepositERC721sArgs) {
return this.contracts.UserVault(userVaultAddress).depositERC721s(data);
}
async depositUserVaultERC1155s({
userVaultAddress = this.defaults.UserVault,
...data
}: { userVaultAddress?: Address } & DepositERC1155sArgs) {
return this.contracts.UserVault(userVaultAddress).depositERC1155s(data);
}
async burnUserVaultAndWithdraw({
userVaultAddress = this.defaults.UserVault,
...data
}: { userVaultAddress?: Address } & BurnAndWithdrawArgs) {
return this.contracts.UserVault(userVaultAddress).burnAndWithdraw(data);
}
async wrapOldERC721({ collection, tokenId }: wrapOldERC721Args) {
const wrapperAddress = await this.api.getWrapperAddress(collection);
const wrapper = this.contracts.OldERC721Wrapper(wrapperAddress);
const naked = this.contracts.OldERC721(collection.contractData.contractAddress);
const stashAddress = await wrapper.contract.read.stashAddress([this.wallet.account.address]);
const currentOwner = await naked.contract.read.ownerOf([tokenId]);
if (currentOwner == this.wallet.account.address) {
const txTransfer = await naked.safeContractWrite.transfer([stashAddress, tokenId]);
await this.bcClient.waitForTransactionReceipt({ hash: txTransfer });
} else if (currentOwner != stashAddress) {
throw Error('NFT not owned');
}
return await wrapper.wrapOldERC721({ tokenId });
}
async unwrapOldERC721({ collection, tokenId }: wrapOldERC721Args) {
const wrapperAddress = await this.api.getWrapperAddress(collection);
const wrapper = this.contracts.OldERC721Wrapper(wrapperAddress);
return await wrapper.unwrap(tokenId);
}
async buyWithSellAndRepay({
repaymentCalldata,
mslContractAddress,
price,
}: {
repaymentCalldata: Hex;
mslContractAddress: Address;
price: bigint;
}) {
return await this.contracts.PurchaseBundler(mslContractAddress).executeSell({
repaymentCalldata,
price,
});
}
}
interface GondiProps {
wallet: Wallet;
apiClient?: ApiProps['apiClient'];
}
type MakeOfferType =
| Omit<Awaited<ReturnType<Gondi['makeSingleNftOffer']>>, 'nftId'>
| Omit<Awaited<ReturnType<Gondi['makeCollectionOffer']>>, 'collectionId'>;
type OfferFromExecutionOffer = OptionalNullable<
MakeOfferType,
'borrowerAddress' | 'lenderAddress' | 'offerHash' | 'signature'
>;
type MakeRefinanceOfferProps = {
renegotiation: model.RenegotiationInput;
contractAddress: Address;
} & (
| { skipSignature?: never; withFallbackOffer?: never; principalAddress?: never; nftId?: never }
| { skipSignature: true; withFallbackOffer?: never; principalAddress?: never; nftId?: never }
| { skipSignature?: never; withFallbackOffer: true; principalAddress: Address; nftId: number }
);
export type CreateVaultArgs = {
collection: Address;
tokenIds: bigint[];
amounts: bigint[];