-
Notifications
You must be signed in to change notification settings - Fork 64
/
base.ts
944 lines (891 loc) · 38.9 KB
/
base.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
import BN from 'bn.js';
import Web3 from 'web3';
import { Signer } from 'ethers';
import { AbiItem } from 'web3-utils';
import { Contract, ContractOptions } from 'web3-eth-contract';
import ERC677ABI from '../../contracts/abi/erc-677';
import GnosisSafeABI from '../../contracts/abi/gnosis-safe';
import PrepaidCardManagerABI from '../../contracts/abi/v0.9.0/prepaid-card-manager';
import DAIOracleABI from '../../contracts/abi/v0.9.0/chainlink-feed-adapter';
import { getAddress, getOracle } from '../../contracts/addresses';
import { ZERO_ADDRESS } from '../constants';
import { getSDK } from '../version-resolver';
import { ERC20ABI } from '../../index';
import {
EventABI,
getParamsFromEvent,
GnosisExecTx,
gasEstimate,
executeTransaction,
SendPayload,
getSendPayload,
executeSend,
getNextNonceFromEstimate,
executeSendWithRateLock,
Operation,
} from '../utils/safe-utils';
import { isTransactionHash, TransactionOptions, waitForTransactionConsistency } from '../utils/general-utils';
import { Signature, signSafeTxAsBytes, signPrepaidCardSendTx, signSafeTx } from '../utils/signing-utils';
import { PrepaidCardSafe } from '../safes';
import type { SuccessfulTransactionReceipt } from '../utils/successful-transaction-receipt';
import { itemSetEventABI } from '../prepaid-card-market/base';
import { TransactionReceipt } from 'web3-core';
const { fromWei } = Web3.utils;
const POLL_INTERVAL = 500;
const TIMEOUT = 1000 * 60 * 5;
// We don't enforce a maximum payment amount on chain, but generally we want to
// stay below the AML limit of $10,000 USD.
export const MAXIMUM_PAYMENT_AMOUNT = 10000 * 100;
export const MAX_PREPAID_CARD_AMOUNT = 10;
/**
* The `PrepaidCard` API is used to create and interact with prepaid cards within the layer 2 network in which the Card Protocol runs. The `PrepaidCard` API can be obtained from `getSDK()` with a `Web3` instance that is configured to operate on a layer 2 network (like Gnosis Chain or Sokol).
* @example
* ```ts
* import { getSDK } from "@cardstack/cardpay-sdk";
* let web3 = new Web3(myProvider); // Layer 2 web3 instance
* let prepaidCard = await getSDK('PrepaidCard', web3);
* ```
* @group Cardpay
* @category Main
*/
export default class PrepaidCard {
private prepaidCardManager: Contract | undefined;
constructor(protected layer2Web3: Web3, private layer2Signer?: Signer) {}
/**
* This call will return the price in terms of the specified token of how much it costs to have a face value in the specified units of SPEND (**§**). This takes into account both the exchange rate of the specified token as well as gas fees that are deducted from the face value when creating a prepaid card. Note though, that the face value of the prepaid card in SPEND will drift based on the exchange rate of the underlying token used to create the prepaid card. (However, this drift should be very slight since we are using *stable* coins to purchase prepaid cards (emphasis on "stable"). Since the units of SPEND are very small relative to wei (**§** 1 === $0.01 USD), the face value input is a number type. This API returns the amount of tokens required to achieve a particular face value as a string in native units of the specified token (e.g. `wei`).
* @example
* ```ts
* // You must send 'amountInDai' to the prepaidCardManager contract
* // to achieve a prepaid card with §5000 face value
* let amountInDAI = await prepaidCard.priceForFaceValue(daiCpxdAddress, 5000);
* ```
* @remarks Note that if you are creating multiple cards or splitting cards, use this API to ensure the amount to provision for each prepaid card you want to create in order to achieve teh desired face values for each of the prepaid cards created.
*/
async priceForFaceValue(tokenAddress: string, spendFaceValue: number): Promise<string> {
return await (await this.getPrepaidCardMgr()).methods
.priceForFaceValue(tokenAddress, String(spendFaceValue))
.call();
}
/**
* This call will return the gas fee in terms of the specified token for the creation of a prepaid card. All prepaid cards will be seeded with some `CARD.CPXD` in order to pay our gnosis safe relayer for gas. In order to offset these costs, a small fee will be charged when creating or splitting a prepaid card. The gas fee that is charged is returned as a string value in native units of the specified token (e.g. `wei`). This is the same fee that is accounted for in the `PrepaidCard.priceForFaceValue` API.
* @example
* ```ts
* let gasFeeInDai = await prepaidCard.gasFee(daiCpxdAddress);
* ```
*/
async gasFee(tokenAddress: string): Promise<string> {
return await (await this.getPrepaidCardMgr()).methods.gasFee(tokenAddress).call();
}
async issuingToken(prepaidCardAddress: string): Promise<string> {
return (await (await this.getPrepaidCardMgr()).methods.cardDetails(prepaidCardAddress).call()).issueToken;
}
async customizationDID(prepaidCardAddress: string): Promise<string> {
return (await (await this.getPrepaidCardMgr()).methods.cardDetails(prepaidCardAddress).call()).customizationDID;
}
/**
* This call will return a promise for the most current face value of a prepaid card.
* @example
* ```ts
* let faceValue = await prepaidCard.faceValue(prepaidCardAddress);
* ```
*/
async faceValue(prepaidCardAddress: string): Promise<number> {
let faceValue = await (await this.getPrepaidCardMgr()).methods.faceValue(prepaidCardAddress).call();
return parseInt(faceValue.toString());
}
/**
* This call will return a promise for a boolean indicating if the prepaid card can be split.
* @example
* ```ts
*let canSplit = await prepaidCard.canSplit(prepaidCardAddress);
* ```
*/
async canSplit(prepaidCard: string): Promise<boolean> {
let prepaidCardMgr = await this.getPrepaidCardMgr();
let owner = await prepaidCardMgr.methods.getPrepaidCardOwner(prepaidCard).call();
let issuer = await prepaidCardMgr.methods.getPrepaidCardIssuer(prepaidCard).call();
return owner === issuer && owner !== ZERO_ADDRESS;
}
/**
* This call will return a promise for a boolean indicating if the prepaid card can be transferred.
* @example
* ```ts
* let canTransfer = await prepaidCard.canTransfer(prepaidCardAddress);
* ```
*/
async canTransfer(prepaidCard: string): Promise<boolean> {
let prepaidCardMgr = await this.getPrepaidCardMgr();
let owner = await prepaidCardMgr.methods.getPrepaidCardOwner(prepaidCard).call();
let issuer = await prepaidCardMgr.methods.getPrepaidCardIssuer(prepaidCard).call();
let hasBeenUsed = await prepaidCardMgr.methods.hasBeenUsed(prepaidCard).call();
return !hasBeenUsed && owner === issuer && owner !== ZERO_ADDRESS;
}
/**
* This call will return the prepaid card payment limits in units of SPEND (we return a number types since it is safe to represent SPEND as a number in javascript).
* @returns a promise object containing min and max number
* @example
* ```ts
* let { min, max } = await prepaidCard.getPaymentLimits();
* ```
* @remarks since the limits are in units of SPEND, it is totally safe to represent as
* a number vs a string
*/
async getPaymentLimits(): Promise<{ min: number; max: number }> {
let prepaidCardMgr = await this.getPrepaidCardMgr();
let min = await prepaidCardMgr.methods.MINIMUM_MERCHANT_PAYMENT().call();
return { min: parseInt(min.toString()), max: MAXIMUM_PAYMENT_AMOUNT };
}
/**
* This call will pay a merchant from a prepaid card.
* @param merchantSafe The safe address of the merchant that will be receiving payment
* @param prepaidCardAddress The prepaid card address to use to pay the merchant
* @param spendAmount The amount of **§** SPEND to pay the merchant.
* @param txnOptions You can optionally provide a TransactionOptions argument, to obtain the nonce or transaction hash of the operation before the creation process is complete
* @param contractOptions You can optionally provide an object that specifies the "from" address. The gas price and gas limit will be calculated by the card protocol and are not configurable.
* @returns a promise for a web3 transaction receipt.
* @example
* ```ts
* let { min, max } = await prepaidCard.getPaymentLimits();
* ```
* @remarks since the limits are in units of SPEND, it is totally safe to represent as
* a number vs a string
*/
async payMerchant(txnHash: string): Promise<SuccessfulTransactionReceipt>;
async payMerchant(
merchantSafe: string,
prepaidCardAddress: string,
spendAmount: number,
txnOptions?: TransactionOptions,
contractOptions?: ContractOptions
): Promise<SuccessfulTransactionReceipt>;
async payMerchant(
merchantSafeOrTxnHash: string,
prepaidCardAddress?: string,
spendAmount?: number,
txnOptions?: TransactionOptions,
contractOptions?: ContractOptions
): Promise<SuccessfulTransactionReceipt> {
if (isTransactionHash(merchantSafeOrTxnHash)) {
let txnHash = merchantSafeOrTxnHash;
return await waitForTransactionConsistency(this.layer2Web3, txnHash);
}
if (!prepaidCardAddress) {
throw new Error('prepaidCardAddress is required');
}
if (!spendAmount) {
throw new Error('spendAmount is required');
}
let merchantSafe = merchantSafeOrTxnHash;
let { nonce, onNonce, onTxnHash } = txnOptions ?? {};
if (spendAmount < 50) {
// this is hard coded in the PrepaidCardManager contract
throw new Error(`The amount to pay merchant §${spendAmount} SPEND is below the minimum allowable amount`);
}
let from = contractOptions?.from ?? (await this.layer2Web3.eth.getAccounts())[0];
await this.convertFromSpendForPrepaidCard(
prepaidCardAddress,
spendAmount,
(issuingToken, balanceAmount, requiredTokenAmount, symbol) =>
new Error(
`Prepaid card does not have enough balance to pay merchant. The issuing token ${issuingToken} balance of prepaid card ${prepaidCardAddress} is ${fromWei(
balanceAmount
)} ${symbol}, payment amount in issuing token is ${fromWei(requiredTokenAmount)} ${symbol}`
)
);
let gnosisResult = await executeSendWithRateLock(this.layer2Web3, prepaidCardAddress, async (rateLock) => {
let payload = await this.getPayMerchantPayload(prepaidCardAddress, merchantSafe, spendAmount, rateLock);
if (nonce == null) {
nonce = getNextNonceFromEstimate(payload);
if (typeof onNonce === 'function') {
onNonce(nonce);
}
}
return await this.executePayMerchant(
prepaidCardAddress,
merchantSafe,
spendAmount,
rateLock,
payload,
await signPrepaidCardSendTx(this.layer2Web3, prepaidCardAddress, payload, nonce, from, this.layer2Signer),
nonce
);
});
if (!gnosisResult) {
throw new Error(
`Unable to obtain a gnosis transaction result for merchant payment from prepaid card ${prepaidCardAddress} to merchant safe ${merchantSafe} for ${spendAmount} SPEND`
);
}
let txnHash = gnosisResult.ethereumTx.txHash;
if (typeof onTxnHash === 'function') {
await onTxnHash(txnHash);
}
return await waitForTransactionConsistency(this.layer2Web3, txnHash, prepaidCardAddress, nonce!);
}
/**
* This call will transfer a prepaid card from an issuer to a customer. Note that currently, once a prepaid card has been transferred to a customer (and EOA that did not create the prepaid card), then it becomes no longer transferrable. Additionally, if a prepaid card was used to fund a prepaid card split, the funding prepaid card also becomes non-transferrable, as it is considered the issuer's own personal prepaid card at that point.
* @param prepaidCardAddress The address of the prepaid card to be transferred
* @param newOwner The address of the new prepaid card owner
* @param txnOptions You can optionally provide a TransactionOptions argument, to obtain the nonce or transaction hash of the operation before the creation process is complete
* @param contractOptions You can optionally provide an object that specifies the "from" address. The gas price and gas limit will be calculated by the card protocol and are not configurable.
* @returns a promise for a web3 transaction receipt.
* @example
* ```ts
* let result = await prepaidCard.transfer(prepaidCardAddress, newOwner);
* ```
*/
async transfer(txnHash: string): Promise<SuccessfulTransactionReceipt>;
async transfer(
prepaidCardAddress: string,
newOwner: string,
txnOptions?: TransactionOptions,
contractOptions?: ContractOptions
): Promise<SuccessfulTransactionReceipt>;
async transfer(
prepaidCardAddressOrTxnHash: string,
newOwner?: string,
txnOptions?: TransactionOptions,
contractOptions?: ContractOptions
): Promise<SuccessfulTransactionReceipt> {
if (isTransactionHash(prepaidCardAddressOrTxnHash)) {
let txnHash = prepaidCardAddressOrTxnHash;
return await waitForTransactionConsistency(this.layer2Web3, txnHash);
}
let prepaidCardAddress = prepaidCardAddressOrTxnHash;
if (!newOwner) {
throw new Error('newOwner is required');
}
let { nonce, onNonce, onTxnHash } = txnOptions ?? {};
if (!(await this.canTransfer(prepaidCardAddress))) {
throw new Error(`The prepaid card ${prepaidCardAddress} is not allowed to be transferred`);
}
let from = contractOptions?.from ?? (await this.layer2Web3.eth.getAccounts())[0];
let prepaidCardMgr = await this.getPrepaidCardMgr();
let transferData = await prepaidCardMgr.methods.getTransferCardData(prepaidCardAddress, newOwner).call();
// the quirk here is that we are signing this txn in advance so we need to
// optimistically advance the nonce by 2 to account for the fact that we are
// executing the "send" action before this one (which advances the nonce by 1).
let transferNonce: BN;
if (nonce != null) {
// a passed in nonce represents the next nonce to use, so we add 1 to it
// to get the nonce we'd want to use for the transfer execTransaction
transferNonce = nonce.add(new BN(1));
} else {
let prepaidCard = new this.layer2Web3.eth.Contract(GnosisSafeABI as AbiItem[], prepaidCardAddress);
let currentNonce = new BN(await prepaidCard.methods.nonce().call());
transferNonce = currentNonce.add(new BN('1'));
}
let [previousOwnerSignature] = await signSafeTxAsBytes(
this.layer2Web3,
prepaidCardAddress,
0,
transferData,
Operation.CALL,
'0',
'0',
'0',
await this.issuingToken(prepaidCardAddress),
ZERO_ADDRESS,
transferNonce,
from,
prepaidCardAddress,
this.layer2Signer
);
let gnosisResult = await executeSendWithRateLock(this.layer2Web3, prepaidCardAddress, async (rateLock) => {
let payload = await this.getTransferPayload(prepaidCardAddress, newOwner, previousOwnerSignature, rateLock);
if (nonce == null) {
nonce = getNextNonceFromEstimate(payload);
if (typeof onNonce === 'function') {
onNonce(nonce);
}
}
return await this.executeTransfer(
prepaidCardAddress,
newOwner,
previousOwnerSignature,
rateLock,
payload,
await signPrepaidCardSendTx(this.layer2Web3, prepaidCardAddress, payload, nonce, from, this.layer2Signer),
nonce
);
});
if (!gnosisResult) {
throw new Error(
`Unable to obtain a gnosis transaction result for prepaid card transfer of prepaid card ${prepaidCardAddress} to new owner ${newOwner}`
);
}
let txnHash = gnosisResult.ethereumTx.txHash;
if (typeof onTxnHash === 'function') {
await onTxnHash(txnHash);
}
return await waitForTransactionConsistency(this.layer2Web3, txnHash, prepaidCardAddress, transferNonce);
}
/**
* This call will use a prepaid card as the source of funds when creating more prepaid cards, in effect "splitting" the prepaid card being used to fund the transaction. Prepaid cards created from the split command are automatically placed in the PrepaidCardInventory. (Note that the prepaid card that is used to fund the creation of more prepaid cards may not be transferred and is considered the issuer's own personal prepaid card.) The creation mechanisms for prepaid cards created via a `PrepaidCard.split` are identical to `PrepaidCard.create` in terms of the total cost and gas charges.
* @param prepaidCardAddress The address of the prepaid card that you are using to fund the creation of more prepaid cards
* @param faceValues An array of face values in units of **§** SPEND as numbers. Note there is a maximum of 15 prepaid cards that can be created in a single transaction and a minimum face value of **§100** is enforced for each card.
* @param marketAddress The address of the prepaid card market to create the prepaid card within. Set to `undefined` to place the newly created prepaid cards in the default market (Cardstack issuer via Wyre). Note that all split cards must go into a market.
* @param customizationDID A DID string that represents the customization for the prepaid card. The customization for a prepaid card can be retrieved using a DID resolver with this DID. If there is no customization an `undefined` value can be specified here.
* @param txnOption You can optionally provide a TransactionOptions argument, to obtain the nonce or transaction hash of the operation before the creation process is complete
* @param contractOptions You can optionally provide an object that specifies the "from" address. The gas price and gas limit will be calculated by the card protocol and are not configurable.
* @example
* ```ts
*let result = await prepaidCard.split(
* prepaidCardAddress,
* [5000, 4000], // split into 2 cards: §5000 SPEND face value and §4000 SPEND face value
* undefined,
* "did:cardstack:56d6fc54-d399-443b-8778-d7e4512d3a49"
*);
*```
*/
async split(
txnHash: string
): Promise<{ prepaidCards: PrepaidCardSafe[]; sku: string; txReceipt: SuccessfulTransactionReceipt }>;
async split(
prepaidCardAddress: string,
faceValues: number[],
marketAddress: string | undefined,
customizationDID: string | undefined,
txnOptions?: TransactionOptions,
contractOptions?: ContractOptions
): Promise<{ prepaidCards: PrepaidCardSafe[]; sku: string; txReceipt: SuccessfulTransactionReceipt }>;
async split(
prepaidCardAddressOrTxnHash: string,
faceValues?: number[],
marketAddress?: string | undefined,
customizationDID?: string | undefined,
txnOptions?: TransactionOptions,
contractOptions?: ContractOptions
): Promise<{ prepaidCards: PrepaidCardSafe[]; sku: string; txReceipt: SuccessfulTransactionReceipt }> {
if (isTransactionHash(prepaidCardAddressOrTxnHash)) {
let txnHash = prepaidCardAddressOrTxnHash;
let txReceipt = await waitForTransactionConsistency(this.layer2Web3, txnHash);
return {
txReceipt,
prepaidCards: await this.resolvePrepaidCards(await this.getPrepaidCardsFromTxn(txnHash)),
sku: await this.getSkuFromTxnReceipt(txReceipt),
};
}
let prepaidCardAddress = prepaidCardAddressOrTxnHash;
if (!faceValues) {
throw new Error(`faceValues must be provided`);
}
if (faceValues.length > MAX_PREPAID_CARD_AMOUNT) {
throw new Error(`Cannot create more than ${MAX_PREPAID_CARD_AMOUNT} at a time`);
}
if (!(await this.canSplit(prepaidCardAddress))) {
throw new Error(`The prepaid card ${prepaidCardAddress} is not allowed to be split`);
}
let from = contractOptions?.from ?? (await this.layer2Web3.eth.getAccounts())[0];
let layerTwoOracle = await getSDK('LayerTwoOracle', this.layer2Web3);
let issuingToken = await this.issuingToken(prepaidCardAddress);
let amountCache = new Map<number, string>();
let amounts: BN[] = [];
let totalWeiAmount = new BN('0');
for (let faceValue of faceValues) {
let weiAmount = amountCache.get(faceValue);
if (weiAmount == null) {
weiAmount = await this.priceForFaceValue(issuingToken, faceValue);
amountCache.set(faceValue, weiAmount);
}
let weiAmountBN = new BN(weiAmount);
totalWeiAmount = totalWeiAmount.add(weiAmountBN);
amounts.push(weiAmountBN);
}
let totalAmountInSpend = await layerTwoOracle.convertToSpend(issuingToken, totalWeiAmount.toString());
// add 1 SPEND to account for rounding errors, unconsumed tokens are
// refunded back to the prepaid card
totalAmountInSpend++;
await this.convertFromSpendForPrepaidCard(
prepaidCardAddress,
totalAmountInSpend,
(issuingToken, balanceAmount, requiredTokenAmount, symbol) =>
new Error(
`Prepaid card does not have enough balance to perform requested split. The issuing token ${issuingToken} balance of prepaid card ${prepaidCardAddress} is ${fromWei(
balanceAmount
)} ${symbol}, the total amount necessary for the split in issuing token is ${fromWei(
requiredTokenAmount
)} ${symbol}`
)
);
let { nonce, onNonce, onTxnHash } = txnOptions ?? {};
let gnosisResult = await executeSendWithRateLock(this.layer2Web3, prepaidCardAddress, async (rateLock) => {
let payload = await this.getSplitPayload(
prepaidCardAddress,
totalAmountInSpend,
amounts,
faceValues,
rateLock,
customizationDID,
marketAddress
);
if (nonce == null) {
nonce = getNextNonceFromEstimate(payload);
if (typeof onNonce === 'function') {
onNonce(nonce);
}
}
return await this.executeSplit(
prepaidCardAddress,
totalAmountInSpend,
amounts,
faceValues,
rateLock,
payload,
await signPrepaidCardSendTx(this.layer2Web3, prepaidCardAddress, payload, nonce, from, this.layer2Signer),
nonce,
customizationDID
);
});
if (!gnosisResult) {
throw new Error(`Unable to split prepaid card ${prepaidCardAddress} into face values: ${faceValues.join(', ')}`);
}
if (typeof onTxnHash === 'function') {
await onTxnHash(gnosisResult.ethereumTx.txHash);
}
let prepaidCardAddresses = await this.getPrepaidCardsFromTxn(gnosisResult.ethereumTx.txHash);
let txReceipt = await waitForTransactionConsistency(
this.layer2Web3,
gnosisResult.ethereumTx.txHash,
prepaidCardAddress,
nonce!
);
return {
txReceipt,
prepaidCards: await this.resolvePrepaidCards(prepaidCardAddresses),
sku: await this.getSkuFromTxnReceipt(txReceipt),
};
}
/**
* This call will create a new prepaid card from a gnosis safe, specifically a gnosis safe that holds tokens that were bridged to the layer 2 network from teh `TokenBridge` api. From this call you can create 1 or more prepaid cards from the `*.CPXD` layer 2 tokens (in the Gnosis Chain network, for example). When a token is bridged to a layer 2 network like Gnosis Chain, it will obtain a `*.CPXD` suffix, indicating that it can participate in the Card Protocol on Gnosis Chain. The face value for the prepaid card does not include the amount of tokens consumed by the gas to create the card as well as fees to create a prepaid card. (Note that the XD in CPXD originally comes from "XDai" the former name of Gnosis Chain.)
*
* ```
*total cost in *.CPXD = (Face value in § * token exchange rate) + fees + gas
*```
*
* Note that gas is charged in the `*.CPXD` token which will be deducted from your safe. You can use the `PrepaidCard.costForFaceValue` method to determine what the final cost for a card with a particular face value in units of **§** will be in the token of your choosing. You can use this amount to create the desired face value for your prepaid card.
* @param
* @param safeAddress The address of the safe that you are using to pay for the prepaid card
*@param tokenAddress The contract address of the token that you wish to use to pay for the prepaid card. Note that the face value of the prepaid card will fluctuate based on the exchange rate of this token and the **§** unit.
* @parma faceValues An array of face values in units of **§** SPEND as numbers. Note there is a maximum of 15 prepaid cards that can be created in a single transaction and a minimum face value of **§100** is enforced for each card.
* @param marketAddress The address of the prepaid card market to create the prepaid card within. Set to `undefined` to not place to newly created prepaid card in the market
* @param customizationDID A DID string that represents the customization for the prepaid card. The customization for a prepaid card can be retrieved using a DID resolver with this DID. If there is no customization an `undefined` value can be specified here.
* @param txnOptions You can optionally provide a TransactionOptions argument, to obtain the nonce or transaction hash of the operation before the creation process is complete
* @param contractOptions You can optionally provide an object that specifies the "from" address. The gas price and gas limit will be calculated by the card protocol and are not configurable
* @param force force a prepaid card to be created when DAI Oracle is not snapped to USD rate
* @example
* ```ts
* let daicpxd = await getAddress('daiCpxd', web3);
*let result = await prepaidCard.create(
* safeAddress,
* daicpxd,
* [5000], // §5000 SPEND face value
* undefined,
* "did:cardstack:56d6fc54-d399-443b-8778-d7e4512d3a49"
*);
*```
*/
async create(txnHash: string): Promise<{ prepaidCards: PrepaidCardSafe[]; txnReceipt: SuccessfulTransactionReceipt }>;
async create(
safeAddress: string,
tokenAddress: string,
faceValues: number[],
marketAddress: string | undefined,
customizationDID: string | undefined,
txnOptions?: TransactionOptions,
contractOptions?: ContractOptions,
force?: boolean // force a prepaid card to be created when DAI Oracle is not snapped to USD rate
): Promise<{ prepaidCards: PrepaidCardSafe[]; txnReceipt: SuccessfulTransactionReceipt }>;
async create(
safeAddressOrTxnHash: string,
tokenAddress?: string,
faceValues?: number[],
marketAddress?: string | undefined,
customizationDID?: string | undefined,
txnOptions?: TransactionOptions,
contractOptions?: ContractOptions,
force?: boolean // force a prepaid card to be created when DAI Oracle is not snapped to USD rate
): Promise<{ prepaidCards: PrepaidCardSafe[]; txnReceipt: SuccessfulTransactionReceipt }> {
if (isTransactionHash(safeAddressOrTxnHash)) {
let txnHash = safeAddressOrTxnHash;
return {
prepaidCards: await this.resolvePrepaidCards(await this.getPrepaidCardsFromTxn(txnHash)),
txnReceipt: await waitForTransactionConsistency(this.layer2Web3, txnHash),
};
}
let safeAddress = safeAddressOrTxnHash;
if (!tokenAddress) {
throw new Error('tokenAddress must be provided');
}
if (!faceValues) {
throw new Error('faceValues must be provided');
}
if (faceValues.length > MAX_PREPAID_CARD_AMOUNT) {
throw new Error(`Cannot create more than ${MAX_PREPAID_CARD_AMOUNT} at a time`);
}
let prepaidCardMgr = await this.getPrepaidCardMgr();
let minimumFaceValue = parseInt(await prepaidCardMgr.methods.minimumFaceValue().call());
if (!faceValues.every((faceValue) => faceValue >= minimumFaceValue)) {
throw new Error(`faceValue must be greater than or equal to ${minimumFaceValue}`);
}
let daiOracleAddress = await getOracle('DAI.CPXD', this.layer2Web3);
let daiOracle = new this.layer2Web3.eth.Contract(DAIOracleABI as AbiItem[], daiOracleAddress);
if (!(await daiOracle.methods.isSnappedToUSD().call()) && !force) {
throw new Error(
`Cannot create prepaid card without DAI Oracle being snapped to USD rate. Please use force=true to override`
);
}
let from = contractOptions?.from ?? (await this.layer2Web3.eth.getAccounts())[0];
let amountCache = new Map<number, string>();
let amounts: BN[] = [];
let totalWeiAmount = new BN('0');
for (let faceValue of faceValues) {
let weiAmount = amountCache.get(faceValue);
if (weiAmount == null) {
weiAmount = await this.priceForFaceValue(tokenAddress, faceValue);
amountCache.set(faceValue, weiAmount);
}
let weiAmountBN = new BN(weiAmount);
totalWeiAmount = totalWeiAmount.add(weiAmountBN);
amounts.push(weiAmountBN);
}
let token = new this.layer2Web3.eth.Contract(ERC20ABI as AbiItem[], tokenAddress);
let symbol = await token.methods.symbol().call();
let balance = new BN(await token.methods.balanceOf(safeAddress).call());
if (balance.lt(totalWeiAmount)) {
throw new Error(
`Safe does not have enough balance to make prepaid card(s). The issuing token ${tokenAddress} balance of the safe ${safeAddress} is ${fromWei(
balance
)}, the total amount necessary to create prepaid cards is ${fromWei(
totalWeiAmount
)} ${symbol} + a small amount for gas`
);
}
let payload = await this.getCreateCardPayload(
from,
tokenAddress,
amounts,
faceValues,
customizationDID,
marketAddress
);
let estimate = await gasEstimate(
this.layer2Web3,
safeAddress,
tokenAddress,
'0',
payload,
Operation.CALL,
tokenAddress
);
let gasCost = new BN(estimate.safeTxGas).add(new BN(estimate.baseGas)).mul(new BN(estimate.gasPrice));
if (balance.lt(totalWeiAmount.add(gasCost))) {
throw new Error(
`Safe does not have enough balance to make prepaid card(s). The issuing token ${tokenAddress} balance of the safe ${safeAddress} is ${fromWei(
balance
)}, the total amount necessary to create prepaid cards is ${fromWei(
totalWeiAmount
)} ${symbol}, the gas cost is ${fromWei(gasCost)} ${symbol}`
);
}
let { nonce, onNonce, onTxnHash } = txnOptions ?? {};
if (nonce == null) {
nonce = getNextNonceFromEstimate(estimate);
if (typeof onNonce === 'function') {
onNonce(nonce);
}
}
let gnosisTxn = await executeTransaction(
this.layer2Web3,
safeAddress,
tokenAddress,
payload,
Operation.CALL,
estimate,
nonce,
await signSafeTx(
this.layer2Web3,
safeAddress,
tokenAddress,
payload,
Operation.CALL,
estimate,
nonce,
from,
this.layer2Signer
)
);
if (typeof onTxnHash === 'function') {
await onTxnHash(gnosisTxn.ethereumTx.txHash);
}
let prepaidCardAddresses = await this.getPrepaidCardsFromTxn(gnosisTxn.ethereumTx.txHash);
return {
prepaidCards: await this.resolvePrepaidCards(prepaidCardAddresses),
txnReceipt: await waitForTransactionConsistency(this.layer2Web3, gnosisTxn.ethereumTx.txHash, safeAddress, nonce),
};
}
async convertFromSpendForPrepaidCard(
prepaidCardAddress: string,
minimumSpendBalance: number,
onError: (issuingToken: string, balanceAmount: string, requiredTokenAmount: string, symbol: string) => Error
): Promise<string> {
let issuingToken = await this.issuingToken(prepaidCardAddress);
let layerTwoOracle = await getSDK('LayerTwoOracle', this.layer2Web3);
let weiAmount = await layerTwoOracle.convertFromSpend(issuingToken, minimumSpendBalance);
let token = new this.layer2Web3.eth.Contract(ERC20ABI as AbiItem[], issuingToken);
let symbol = await token.methods.symbol().call();
let prepaidCardBalance = new BN(await token.methods.balanceOf(prepaidCardAddress).call());
if (prepaidCardBalance.lt(new BN(weiAmount))) {
onError(issuingToken, prepaidCardBalance.toString(), weiAmount, symbol);
}
return weiAmount;
}
async resolvePrepaidCards(prepaidCardAddresses: string[]): Promise<PrepaidCardSafe[]> {
let safes = await getSDK('Safes', this.layer2Web3);
let prepaidCards: PrepaidCardSafe[] | undefined;
let startTime = Date.now();
do {
if (prepaidCards) {
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL));
} else {
prepaidCards = [];
}
for (let prepaidCardAddress of prepaidCardAddresses) {
if (prepaidCards.find((p) => p.address === prepaidCardAddress)) {
continue;
}
let prepaidCard = (await safes.viewSafe(prepaidCardAddress)).safe;
if (prepaidCard?.type === 'prepaid-card') {
prepaidCards.push(prepaidCard);
}
}
} while (prepaidCards.length < prepaidCardAddresses.length && Date.now() - startTime < TIMEOUT);
if (prepaidCards.length < prepaidCardAddresses.length) {
throw new Error(`Timeout while waiting for the prepaid cards to be created.`);
}
return prepaidCards;
}
async getPrepaidCardOwner(prepaidCard: string): Promise<string> {
let prepaidCardMgr = await this.getPrepaidCardMgr();
return prepaidCardMgr.methods.getPrepaidCardOwner(prepaidCard).call();
}
async getPrepaidCardMgr() {
if (this.prepaidCardManager) {
return this.prepaidCardManager;
}
this.prepaidCardManager = new this.layer2Web3.eth.Contract(
PrepaidCardManagerABI as AbiItem[],
await getAddress('prepaidCardManager', this.layer2Web3)
);
return this.prepaidCardManager;
}
protected async getCreateCardPayload(
owner: string,
tokenAddress: string,
issuingTokenAmounts: BN[],
spendAmounts: number[],
customizationDID = '',
marketAddress = ZERO_ADDRESS
): Promise<string> {
let prepaidCardManagerAddress = await getAddress('prepaidCardManager', this.layer2Web3);
let token = new this.layer2Web3.eth.Contract(ERC677ABI as AbiItem[], tokenAddress);
let sum = new BN(0);
for (let amount of issuingTokenAmounts) {
sum = sum.add(amount);
}
return token.methods
.transferAndCall(
prepaidCardManagerAddress,
sum,
this.layer2Web3.eth.abi.encodeParameters(
['address', 'uint256[]', 'uint256[]', 'string', 'address', 'address', 'address'],
[
owner,
issuingTokenAmounts,
spendAmounts.map((i) => i.toString()),
customizationDID,
marketAddress,
ZERO_ADDRESS,
ZERO_ADDRESS,
]
)
)
.encodeABI();
}
async getPrepaidCardsFromTxn(txnHash: string): Promise<string[]> {
let prepaidCardMgrAddress = await getAddress('prepaidCardManager', this.layer2Web3);
let txnReceipt = await waitForTransactionConsistency(this.layer2Web3, txnHash);
return getParamsFromEvent(this.layer2Web3, txnReceipt, this.createPrepaidCardEventABI(), prepaidCardMgrAddress).map(
(createCardLog) => createCardLog.card
);
}
// allow TransactionReceipt as argument
// eslint-disable-next-line @typescript-eslint/ban-types
private async getSkuFromTxnReceipt(txnReceipt: TransactionReceipt): Promise<string> {
// this assumes the default prepaid card market address, once we have
// multiple prepaid card markets we should refactor this
let marketAddress = await getAddress('prepaidCardMarket', this.layer2Web3);
let [event] = getParamsFromEvent(this.layer2Web3, txnReceipt, itemSetEventABI(this.layer2Web3), marketAddress);
return event.sku;
}
private async getPayMerchantPayload(
prepaidCardAddress: string,
merchantSafe: string,
spendAmount: number,
rate: string
): Promise<SendPayload> {
return getSendPayload(
this.layer2Web3,
prepaidCardAddress,
spendAmount,
rate,
'payMerchant',
this.layer2Web3.eth.abi.encodeParameters(['address'], [merchantSafe])
);
}
private async getSplitPayload(
prepaidCardAddress: string,
totalSpendAmount: number,
issuingTokenAmounts: BN[],
spendAmounts: number[],
rate: string,
customizationDID = '',
marketAddress = ZERO_ADDRESS
): Promise<SendPayload> {
return getSendPayload(
this.layer2Web3,
prepaidCardAddress,
totalSpendAmount,
rate,
'split',
this.layer2Web3.eth.abi.encodeParameters(
['uint256[]', 'uint256[]', 'string', 'address'],
[issuingTokenAmounts, spendAmounts, customizationDID, marketAddress]
)
);
}
private async getTransferPayload(
prepaidCardAddress: string,
newOwner: string,
previousOwnerSignature: string,
rate: string
): Promise<SendPayload> {
return getSendPayload(
this.layer2Web3,
prepaidCardAddress,
0,
rate,
'transfer',
this.layer2Web3.eth.abi.encodeParameters(['address', 'bytes'], [newOwner, previousOwnerSignature])
);
}
private async executePayMerchant(
prepaidCardAddress: string,
merchantSafe: string,
spendAmount: number,
rate: string,
payload: SendPayload,
signatures: Signature[],
nonce: BN
): Promise<GnosisExecTx> {
return await executeSend(
this.layer2Web3,
prepaidCardAddress,
spendAmount,
rate,
payload,
'payMerchant',
this.layer2Web3.eth.abi.encodeParameters(['address'], [merchantSafe]),
signatures,
nonce
);
}
private async executeSplit(
prepaidCardAddress: string,
totalSpendAmount: number,
issuingTokenAmounts: BN[],
spendAmounts: number[],
rate: string,
payload: SendPayload,
signatures: Signature[],
nonce: BN,
customizationDID = '',
marketAddress = ZERO_ADDRESS
): Promise<GnosisExecTx> {
return await executeSend(
this.layer2Web3,
prepaidCardAddress,
totalSpendAmount,
rate,
payload,
'split',
this.layer2Web3.eth.abi.encodeParameters(
['uint256[]', 'uint256[]', 'string', 'address'],
[issuingTokenAmounts, spendAmounts, customizationDID, marketAddress]
),
signatures,
nonce
);
}
private async executeTransfer(
prepaidCardAddress: string,
newOwner: string,
previousOwnerSignature: string,
rate: string,
payload: SendPayload,
signatures: Signature[],
nonce: BN
): Promise<GnosisExecTx> {
return await executeSend(
this.layer2Web3,
prepaidCardAddress,
0,
rate,
payload,
'transfer',
this.layer2Web3.eth.abi.encodeParameters(['address', 'bytes'], [newOwner, previousOwnerSignature]),
signatures,
nonce
);
}
private createPrepaidCardEventABI(): EventABI {
return {
topic: this.layer2Web3.eth.abi.encodeEventSignature(
'CreatePrepaidCard(address,address,address,address,uint256,uint256,uint256,string)'
),
abis: [
{
type: 'address',
name: 'supplier',
},
{
type: 'address',
name: 'card',
},
{
type: 'address',
name: 'token',
},
{
type: 'address',
name: 'createdFromDepot',
},
{
type: 'uint256',
name: 'issuingTokenAmount',
},
{
type: 'uint256',
name: 'spendAmount',
},
{
type: 'uint256',
name: 'gasFeeCollected',
},
{
type: 'string',
name: 'customizationDID',
},
],
};
}
}