@zebec-network/exchange-card-sdk 1.1.10-beta.1 → 1.1.10-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,2 @@
1
1
  export * from "./stellarService";
2
- export * from "./TaoService";
3
- export * from "./TonService";
4
- export * from "./XdbService";
5
2
  export * from "./xrplService";
@@ -15,9 +15,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  // export * from "./bitcoinService";
18
- // export * from "./EvmService";
19
18
  __exportStar(require("./stellarService"), exports);
20
- __exportStar(require("./TaoService"), exports);
21
- __exportStar(require("./TonService"), exports);
22
- __exportStar(require("./XdbService"), exports);
23
19
  __exportStar(require("./xrplService"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zebec-network/exchange-card-sdk",
3
- "version": "1.1.10-beta.1",
3
+ "version": "1.1.10-beta.2",
4
4
  "description": "An sdk for purchasing silver card in zebec",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -1,37 +0,0 @@
1
- import { AxiosResponse } from "axios";
2
- import { ethers } from "ethers";
3
- import { ERC20, ZebecCard } from "../artifacts";
4
- import { SupportedChain } from "../chains";
5
- import { APIConfig } from "../helpers/apiHelpers";
6
- import { Quote, Recipient } from "../types";
7
- export declare class ZebecCardService {
8
- readonly signer: ethers.Signer;
9
- readonly zebecCard: ZebecCard;
10
- readonly usdcToken: ERC20;
11
- readonly chainId: SupportedChain;
12
- private readonly apiService;
13
- constructor(signer: ethers.Signer, chainId: number, apiConfig: APIConfig, sdkOptions?: {
14
- sandbox?: boolean;
15
- });
16
- /**
17
- * Fetches a quote for the given amount.
18
- *
19
- * @param {string | number} amount - The amount for which to fetch the quote.
20
- * @returns {Promise<Quote>} A promise that resolves to a Quote object.
21
- */
22
- fetchQuote(): Promise<Quote>;
23
- /**
24
- * Transfer specified amount from user's vault balance to card vault with some fee amount for card purchase.
25
- * @param params
26
- * @returns
27
- */
28
- purchaseCard(params: {
29
- amount: number;
30
- recipient: Recipient;
31
- quote: Quote;
32
- }): Promise<[
33
- ethers.ContractTransactionResponse,
34
- ethers.ContractTransactionResponse,
35
- AxiosResponse
36
- ]>;
37
- }
@@ -1,134 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ZebecCardService = void 0;
4
- const axios_1 = require("axios");
5
- const ethers_1 = require("ethers");
6
- const artifacts_1 = require("../artifacts");
7
- const chains_1 = require("../chains");
8
- const constants_1 = require("../constants");
9
- const errors_1 = require("../errors");
10
- const apiHelpers_1 = require("../helpers/apiHelpers");
11
- const types_1 = require("../types");
12
- const utils_1 = require("../utils");
13
- class ZebecCardService {
14
- signer;
15
- zebecCard;
16
- usdcToken;
17
- chainId;
18
- apiService;
19
- constructor(signer, chainId, apiConfig, sdkOptions) {
20
- this.signer = signer;
21
- const sandbox = sdkOptions?.sandbox ? sdkOptions.sandbox : false;
22
- this.chainId = (0, chains_1.parseSupportedChain)(chainId);
23
- const isTesnetChainId = chains_1.TESTNET_CHAINIDS.includes(this.chainId);
24
- if ((sandbox && !isTesnetChainId) || (!sandbox && isTesnetChainId)) {
25
- throw new Error("Only testnet chains are allowed in sandbox environment");
26
- }
27
- this.apiService = new apiHelpers_1.ZebecCardAPIService(apiConfig, sandbox);
28
- const zebecCardAddress = constants_1.ZEBEC_CARD_ADDRESS[this.chainId];
29
- const usdcAddress = constants_1.USDC_ADDRESS[this.chainId];
30
- this.zebecCard = artifacts_1.ZebecCard__factory.connect(zebecCardAddress, signer);
31
- this.usdcToken = artifacts_1.ERC20__factory.connect(usdcAddress, signer);
32
- }
33
- /**
34
- * Fetches a quote for the given amount.
35
- *
36
- * @param {string | number} amount - The amount for which to fetch the quote.
37
- * @returns {Promise<Quote>} A promise that resolves to a Quote object.
38
- */
39
- async fetchQuote() {
40
- const res = await this.apiService.fetchQuote("USDC");
41
- return res;
42
- }
43
- /**
44
- * Transfer specified amount from user's vault balance to card vault with some fee amount for card purchase.
45
- * @param params
46
- * @returns
47
- */
48
- async purchaseCard(params) {
49
- // Check card service status
50
- await this.apiService.ping();
51
- const decimals = await this.usdcToken.decimals();
52
- const totalAmount = (0, utils_1.formatAmount)(params.amount + constants_1.PLATFORM_FEE, Number(decimals));
53
- const parsedAmount = ethers_1.ethers.parseUnits(totalAmount.toString(), decimals);
54
- if (!(0, utils_1.isEmailValid)(params.recipient.emailAddress)) {
55
- throw new errors_1.InvalidEmailError(params.recipient.emailAddress);
56
- }
57
- const usdcBalance = await this.usdcToken.balanceOf(this.signer);
58
- console.debug("Usdc Balance:", usdcBalance);
59
- if (parsedAmount > usdcBalance) {
60
- throw new errors_1.NotEnoughBalanceError(ethers_1.ethers.formatUnits(usdcBalance, decimals), params.amount.toString());
61
- }
62
- let cardConfig = await this.zebecCard.cardConfig();
63
- const minRange = cardConfig.minCardAmount;
64
- const maxRange = cardConfig.maxCardAmount;
65
- if (parsedAmount < minRange || parsedAmount > maxRange) {
66
- throw new errors_1.CardPurchaseAmountOutOfRangeError(ethers_1.ethers.formatUnits(minRange, decimals), ethers_1.ethers.formatUnits(maxRange, decimals));
67
- }
68
- const cardPurchaseInfo = await this.zebecCard.cardPurchases(this.signer);
69
- const lastCardPurchaseDate = new Date(Number(cardPurchaseInfo.unixInRecord * 1000n));
70
- const today = new Date();
71
- let cardPurchaseOfDay = 0n;
72
- if ((0, utils_1.areDatesOfSameDay)(today, lastCardPurchaseDate)) {
73
- cardPurchaseOfDay = cardPurchaseInfo.totalCardBoughtPerDay + parsedAmount;
74
- }
75
- else {
76
- cardPurchaseOfDay = parsedAmount;
77
- }
78
- if (cardPurchaseOfDay > cardConfig.dailyCardBuyLimit) {
79
- throw new errors_1.DailyCardPurchaseLimitExceedError(ethers_1.ethers.formatUnits(cardConfig.dailyCardBuyLimit, decimals), ethers_1.ethers.formatUnits(cardPurchaseInfo.totalCardBoughtPerDay, decimals));
80
- }
81
- const allowance = await this.usdcToken.allowance(this.signer, this.zebecCard);
82
- console.debug("Allowance:", allowance);
83
- if (allowance < parsedAmount) {
84
- console.debug("===== Approving token =====");
85
- const approveResponse = await this.usdcToken.approve(this.zebecCard, parsedAmount);
86
- const approveReceipt = await approveResponse.wait();
87
- console.debug("Approve hash: %s \n", approveReceipt?.hash);
88
- }
89
- console.debug("===== Depositing USDC =====");
90
- const depositResponse = await this.zebecCard.depositUsdc(parsedAmount);
91
- const depositReceipt = await depositResponse.wait();
92
- console.debug("Deposit hash: %s \n", depositReceipt?.hash);
93
- cardConfig = await this.zebecCard.cardConfig();
94
- const purchaseCounter = Number((cardConfig.counter + 1n).toString());
95
- const cardTypeId = "103253238082";
96
- const emailHash = await (0, utils_1.hashSHA256)(params.recipient.emailAddress);
97
- console.debug("===== Purchasing Card =====");
98
- const buyCardResponse = await this.zebecCard.buyCard(parsedAmount, cardTypeId, emailHash);
99
- const buyCardReceipt = await buyCardResponse.wait();
100
- console.debug("Purchase hash: %s \n", buyCardReceipt?.hash);
101
- const usdAmount = types_1.Money.USD(params.amount);
102
- const buyer = await this.signer.getAddress();
103
- const receipt = new types_1.Receipt(params.quote, new types_1.Deposit("USDC", Number(totalAmount), "", buyer, buyCardResponse.hash, "", this.chainId, purchaseCounter));
104
- const payload = new types_1.OrderCardRequest(usdAmount, params.recipient, receipt);
105
- let retries = 0;
106
- let delay = 1000; // Initial delay in milliseconds (1 second)
107
- const maxRetries = 5; // Max retry default
108
- while (retries < maxRetries) {
109
- try {
110
- const response = await this.apiService.purchaseCard(payload);
111
- console.debug("API response: %o \n", response.data);
112
- return [depositResponse, buyCardResponse, response];
113
- }
114
- catch (error) {
115
- if (error instanceof axios_1.AxiosError) {
116
- console.debug("error", error.response?.data);
117
- console.debug("error", error.message);
118
- }
119
- else {
120
- console.debug("error", error);
121
- }
122
- if (retries >= maxRetries) {
123
- throw error;
124
- }
125
- retries += 1;
126
- console.debug(`Retrying in ${delay / 1000} seconds...`);
127
- await new Promise((resolve) => setTimeout(resolve, delay));
128
- delay *= 2; // Exponential backoff
129
- }
130
- }
131
- throw new Error("Max retries reached");
132
- }
133
- }
134
- exports.ZebecCardService = ZebecCardService;
@@ -1,49 +0,0 @@
1
- import { KeyringPair } from "@polkadot/keyring/types";
2
- import { Signer } from "@polkadot/types/types";
3
- import { APIConfig } from "../helpers/apiHelpers";
4
- import { Quote } from "../types";
5
- export declare class ZebecCardTAOService {
6
- readonly signer: Signer | KeyringPair;
7
- private apiService;
8
- private taoRPC;
9
- /**
10
- * Constructs an instance of the service.
11
- *
12
- * @param {Signer} signer - The signer which can be either a PolkadotJs Signer or a KeyringPair.
13
- * @param {APIConfig} apiConfig - The configuration object for the API.
14
- * @param sdkOptions - Optional configuration for the SDK.
15
- */
16
- constructor(signer: Signer | KeyringPair, apiConfig: APIConfig, sdkOptions?: {
17
- sandbox?: boolean;
18
- });
19
- /**
20
- * Fetches a quote for the given amount.
21
- *
22
- * @param {string | number} amount - The amount for which to fetch the quote.
23
- * @returns {Promise<Quote>} A promise that resolves to a Quote object.
24
- */
25
- fetchQuote(): Promise<Quote>;
26
- /**
27
- * Fetches the TAO Vault address.
28
- *
29
- * @returns {Promise<string>} A promise that resolves to the TAO Vault address.
30
- */
31
- fetchTAOVault(): Promise<string>;
32
- /**
33
- * Executes TAO token transfer for card purchase.
34
- *
35
- * @param params - The parameters required for token transfer.
36
- * @param params.walletAddress - The wallet address from which TAO tokens will be transferred.
37
- * @param params.amount - The amount of TAO tokens to transfer.
38
- * @param params.depositAddress - The destination address to receive tokens.
39
- * @returns A promise that resolves to an object containing transaction and block hashes.
40
- * @throws {Error} If there is not enough balance or if the transaction fails.
41
- */
42
- transferTAO(params: {
43
- walletAddress: string;
44
- amount: number;
45
- }): Promise<{
46
- txHash: string;
47
- blockHash: string;
48
- }>;
49
- }
@@ -1,105 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ZebecCardTAOService = void 0;
4
- const api_1 = require("@polkadot/api");
5
- const constants_1 = require("../constants");
6
- const apiHelpers_1 = require("../helpers/apiHelpers");
7
- class ZebecCardTAOService {
8
- signer;
9
- apiService;
10
- taoRPC;
11
- /**
12
- * Constructs an instance of the service.
13
- *
14
- * @param {Signer} signer - The signer which can be either a PolkadotJs Signer or a KeyringPair.
15
- * @param {APIConfig} apiConfig - The configuration object for the API.
16
- * @param sdkOptions - Optional configuration for the SDK.
17
- */
18
- constructor(signer, apiConfig, sdkOptions) {
19
- this.signer = signer;
20
- const sandbox = sdkOptions?.sandbox ? sdkOptions.sandbox : false;
21
- this.apiService = new apiHelpers_1.ZebecCardAPIService(apiConfig, sandbox);
22
- this.taoRPC = sandbox ? constants_1.TAO_RPC_URL.Sandbox : constants_1.TAO_RPC_URL.Production;
23
- }
24
- /**
25
- * Fetches a quote for the given amount.
26
- *
27
- * @param {string | number} amount - The amount for which to fetch the quote.
28
- * @returns {Promise<Quote>} A promise that resolves to a Quote object.
29
- */
30
- async fetchQuote() {
31
- const res = await this.apiService.fetchQuote("TAO");
32
- return res;
33
- }
34
- /**
35
- * Fetches the TAO Vault address.
36
- *
37
- * @returns {Promise<string>} A promise that resolves to the TAO Vault address.
38
- */
39
- async fetchTAOVault() {
40
- const data = await this.apiService.fetchVault("TAO");
41
- return data.address;
42
- }
43
- /**
44
- * Executes TAO token transfer for card purchase.
45
- *
46
- * @param params - The parameters required for token transfer.
47
- * @param params.walletAddress - The wallet address from which TAO tokens will be transferred.
48
- * @param params.amount - The amount of TAO tokens to transfer.
49
- * @param params.depositAddress - The destination address to receive tokens.
50
- * @returns A promise that resolves to an object containing transaction and block hashes.
51
- * @throws {Error} If there is not enough balance or if the transaction fails.
52
- */
53
- async transferTAO(params) {
54
- // Connect to TAO network
55
- const provider = new api_1.WsProvider(this.taoRPC);
56
- const api = await api_1.ApiPromise.create({ provider });
57
- try {
58
- // Calculate total amount with proper decimal places
59
- const totalAmount = Math.floor(params.amount * 10 ** 9);
60
- // Check wallet balance
61
- const balance = await api?.query.system.account(params.walletAddress);
62
- const freeBalance = balance.data.free.toNumber();
63
- if (freeBalance < totalAmount) {
64
- throw new Error("Not enough balance");
65
- }
66
- // Create and submit transaction
67
- let resolveOut;
68
- let rejectOut;
69
- const promise = new Promise((resolve, reject) => {
70
- resolveOut = resolve;
71
- rejectOut = reject;
72
- });
73
- let blockHash = "";
74
- let txHash = "";
75
- const depositAddress = await this.fetchTAOVault();
76
- const tx = api.tx.balances.transferKeepAlive(depositAddress, totalAmount);
77
- const unsub = await tx.signAndSend("address" in this.signer ? this.signer : params.walletAddress, {
78
- signer: "address" in this.signer ? undefined : this.signer,
79
- }, ({ events = [], isInBlock, isFinalized, isError, status, txHash: _txHash }) => {
80
- console.debug("Transaction status:", status.type);
81
- if (isInBlock || isFinalized) {
82
- console.debug("Included at block hash", status.asInBlock.toHex());
83
- blockHash = status.asInBlock.toHex();
84
- txHash = _txHash.toHex();
85
- const isSuccess = events.every(({ event }) => !api.events.system.ExtrinsicFailed.is(event));
86
- if (isSuccess) {
87
- unsub();
88
- resolveOut();
89
- }
90
- }
91
- else if (isError) {
92
- unsub();
93
- rejectOut(new Error("Transaction failed"));
94
- }
95
- });
96
- await promise;
97
- return { txHash, blockHash };
98
- }
99
- finally {
100
- // Ensure API is disconnected
101
- await api.disconnect().catch(() => { });
102
- }
103
- }
104
- }
105
- exports.ZebecCardTAOService = ZebecCardTAOService;
@@ -1,57 +0,0 @@
1
- import { APIConfig } from "../helpers/apiHelpers";
2
- import { ITonConnect } from "@tonconnect/sdk";
3
- import { Quote } from "../types";
4
- export declare class ZebecCardTONService {
5
- readonly signer: ITonConnect;
6
- private apiService;
7
- private tonRPC;
8
- private tonweb;
9
- private sandbox;
10
- /**
11
- * Constructs an instance of the service.
12
- *
13
- * @param {Signer} signer - The signer which can be either a PolkadotJs Signer or a KeyringPair.
14
- * @param {APIConfig} apiConfig - The configuration object for the API.
15
- * @param sdkOptions - Optional configuration for the SDK.
16
- */
17
- constructor(signer: ITonConnect, apiConfig: APIConfig, sdkOptions?: {
18
- sandbox?: boolean;
19
- apiKey?: string;
20
- });
21
- /**
22
- * Fetches a quote for the given amount.
23
- *
24
- * @param {string | number} amount - The amount for which to fetch the quote.
25
- * @returns {Promise<Quote>} A promise that resolves to a Quote object.
26
- */
27
- fetchQuote(): Promise<Quote>;
28
- /**
29
- * Fetches the TAO Vault address.
30
- *
31
- * @returns {Promise<string>} A promise that resolves to the TAO Vault address.
32
- */
33
- fetchVault(): Promise<{
34
- address: string;
35
- tag?: string;
36
- }>;
37
- /**
38
- * Purchases a card by transferring TAO tokens.
39
- *
40
- * @param params - The parameters required to purchase a card.
41
- * @param params.walletAddress - The wallet address from which TAO tokens will be transferred.
42
- * @param params.amount - The amount of TAO tokens to transfer.
43
- * @returns A promise that resolves to transaction hash.
44
- * @throws {Error} If there is not enough balance or if the transaction fails.
45
- */
46
- transferTon(params: {
47
- walletAddress: string;
48
- amount: number;
49
- }): Promise<string>;
50
- /**
51
- * Retrieves the balance of the specified wallet.
52
- *
53
- * @param {string} wallet - The address of the wallet to get the balance for. If the address starts with "0:", it will be converted to a full address format.
54
- * @returns {Promise<string>} - A promise that resolves to the balance of the wallet.
55
- */
56
- getWalletBalance(wallet: string): Promise<string>;
57
- }
@@ -1,137 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.ZebecCardTONService = void 0;
7
- const constants_1 = require("../constants");
8
- const apiHelpers_1 = require("../helpers/apiHelpers");
9
- const tonweb_1 = __importDefault(require("tonweb"));
10
- async function formatPayload(message) {
11
- const cell = new tonweb_1.default.boc.Cell();
12
- cell.bits.writeUint(0, 32);
13
- cell.bits.writeString(message);
14
- const boc = await cell.toBoc();
15
- return Buffer.from(boc).toString("base64");
16
- }
17
- async function bocToHash(boc) {
18
- const cell = tonweb_1.default.boc.Cell.fromBoc(Buffer.from(boc, "base64").toString("hex"));
19
- return Buffer.from(await cell[0].hash()).toString("hex");
20
- }
21
- class ZebecCardTONService {
22
- signer;
23
- apiService;
24
- tonRPC;
25
- tonweb;
26
- sandbox;
27
- /**
28
- * Constructs an instance of the service.
29
- *
30
- * @param {Signer} signer - The signer which can be either a PolkadotJs Signer or a KeyringPair.
31
- * @param {APIConfig} apiConfig - The configuration object for the API.
32
- * @param sdkOptions - Optional configuration for the SDK.
33
- */
34
- constructor(signer, apiConfig, sdkOptions) {
35
- this.signer = signer;
36
- const sandbox = sdkOptions?.sandbox ? sdkOptions.sandbox : false;
37
- this.apiService = new apiHelpers_1.ZebecCardAPIService(apiConfig, sandbox);
38
- this.tonRPC = sandbox ? constants_1.TON_RPC_URL.Sandbox : constants_1.TON_RPC_URL.Production;
39
- this.tonweb = new tonweb_1.default(new tonweb_1.default.HttpProvider(this.tonRPC, {
40
- apiKey: sdkOptions?.apiKey ?? "2191825d6718d115f3caffa8f69de292dd55de3b8c62a61421e7887148a60d6c",
41
- }));
42
- this.sandbox = sandbox;
43
- }
44
- /**
45
- * Fetches a quote for the given amount.
46
- *
47
- * @param {string | number} amount - The amount for which to fetch the quote.
48
- * @returns {Promise<Quote>} A promise that resolves to a Quote object.
49
- */
50
- async fetchQuote() {
51
- const res = await this.apiService.fetchQuote("TON");
52
- return res;
53
- }
54
- /**
55
- * Fetches the TAO Vault address.
56
- *
57
- * @returns {Promise<string>} A promise that resolves to the TAO Vault address.
58
- */
59
- async fetchVault() {
60
- const data = await this.apiService.fetchVault("TON");
61
- return data;
62
- }
63
- /**
64
- * Purchases a card by transferring TAO tokens.
65
- *
66
- * @param params - The parameters required to purchase a card.
67
- * @param params.walletAddress - The wallet address from which TAO tokens will be transferred.
68
- * @param params.amount - The amount of TAO tokens to transfer.
69
- * @returns A promise that resolves to transaction hash.
70
- * @throws {Error} If there is not enough balance or if the transaction fails.
71
- */
72
- async transferTon(params) {
73
- if (!this.signer.account?.walletStateInit ||
74
- !this.signer.account?.publicKey ||
75
- !this.signer.account?.address) {
76
- throw new Error("Invalid wallet account");
77
- }
78
- // Fetch deposit address
79
- const { address: depositAddress, tag } = await this.fetchVault();
80
- const walletAddress = new tonweb_1.default.utils.Address(this.signer.account.address).toString(true, true, false, this.sandbox);
81
- // Calculate fees and total amount
82
- const platform_fee = (params.amount * constants_1.PLATFORM_FEE) / 10000;
83
- const totalAmount = Math.floor((params.amount + platform_fee) * 10 ** 9);
84
- // Check Wallet balance
85
- const balance = await this.tonweb.getBalance(walletAddress);
86
- if (Number(balance) < totalAmount) {
87
- throw new Error("Insufficient balance");
88
- }
89
- // Prepare transaction
90
- const transaction = {
91
- validUntil: Math.floor(Date.now() / 1000) + 60, // 60 sec
92
- messages: [
93
- {
94
- address: depositAddress,
95
- amount: totalAmount.toString(),
96
- payload: await formatPayload(tag || ""),
97
- },
98
- ],
99
- };
100
- // Sign and submit transaction
101
- const result = await this.signer.sendTransaction(transaction);
102
- const txHash = await bocToHash(result.boc);
103
- let retries = 0;
104
- const maxRetries = 5;
105
- let delay = 1000;
106
- while (retries < maxRetries) {
107
- try {
108
- return txHash;
109
- }
110
- catch (error) {
111
- console.debug("error: ", error);
112
- if (retries >= maxRetries) {
113
- throw error;
114
- }
115
- retries += 1;
116
- console.debug(`Retrying in ${delay / 1000} seconds...`);
117
- await new Promise((resolve) => setTimeout(resolve, delay));
118
- delay *= 2; // Exponential backoff
119
- }
120
- }
121
- throw new Error("Max retries reached");
122
- }
123
- /**
124
- * Retrieves the balance of the specified wallet.
125
- *
126
- * @param {string} wallet - The address of the wallet to get the balance for. If the address starts with "0:", it will be converted to a full address format.
127
- * @returns {Promise<string>} - A promise that resolves to the balance of the wallet.
128
- */
129
- async getWalletBalance(wallet) {
130
- let walletAddress = wallet;
131
- if (wallet.startsWith("0:")) {
132
- walletAddress = new tonweb_1.default.utils.Address(wallet).toString(true, true, false, this.sandbox);
133
- }
134
- return this.tonweb.utils.fromNano(await this.tonweb.getBalance(walletAddress));
135
- }
136
- }
137
- exports.ZebecCardTONService = ZebecCardTONService;
@@ -1,52 +0,0 @@
1
- import { StellarWalletsKit } from "@creit.tech/stellar-wallets-kit";
2
- import { APIConfig } from "../helpers/apiHelpers";
3
- import { Quote } from "../types";
4
- export declare class XDBService {
5
- readonly kit: StellarWalletsKit;
6
- private apiService;
7
- private server;
8
- private sandbox;
9
- /**
10
- * Constructs an instance of the service.
11
- *
12
- * @param {DigitalBitsSdk.Keypair} signer - The signer keypair for the DigitalBits wallet.
13
- * @param {APIConfig} apiConfig - The configuration object for the API.
14
- * @param sdkOptions - Optional configuration for the SDK.
15
- */
16
- constructor(kit: StellarWalletsKit, apiConfig: APIConfig, sdkOptions?: {
17
- sandbox?: boolean;
18
- apiKey?: string;
19
- });
20
- /**
21
- * Fetches a quote for the given amount.
22
- *
23
- * @param {string | number} amount - The amount for which to fetch the quote.
24
- * @returns {Promise<Quote>} A promise that resolves to a Quote object.
25
- */
26
- fetchQuote(): Promise<Quote>;
27
- /**
28
- * Fetches the Vault address.
29
- *
30
- * @returns {Promise<string>} A promise that resolves to the Vault address.
31
- */
32
- fetchVault(): Promise<{
33
- address: string;
34
- tag?: string;
35
- }>;
36
- /**
37
- * Purchases a card by transferring XDB tokens.
38
- *
39
- * @param params - The parameters required to purchase a card.
40
- * @returns A promise that resolves to an array containing the transaction details and the API response.
41
- * @throws {InvalidEmailError} If the recipient's email address is invalid.
42
- * @throws {Error} If the quote is invalid or expired, if there is not enough balance, or if the transaction fails.
43
- */
44
- transferXDB(amount: string): Promise<string>;
45
- /**
46
- * Retrieves the balance of the specified wallet.
47
- *
48
- * @param {string} wallet - The public key of the wallet to get the balance for.
49
- * @returns {Promise<string>} - A promise that resolves to the balance of the wallet.
50
- */
51
- getWalletBalance(wallet: string): Promise<string>;
52
- }
@@ -1,118 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.XDBService = void 0;
4
- const stellar_sdk_1 = require("@stellar/stellar-sdk");
5
- const constants_1 = require("../constants");
6
- const apiHelpers_1 = require("../helpers/apiHelpers");
7
- class XDBService {
8
- kit;
9
- apiService;
10
- server;
11
- sandbox;
12
- /**
13
- * Constructs an instance of the service.
14
- *
15
- * @param {DigitalBitsSdk.Keypair} signer - The signer keypair for the DigitalBits wallet.
16
- * @param {APIConfig} apiConfig - The configuration object for the API.
17
- * @param sdkOptions - Optional configuration for the SDK.
18
- */
19
- constructor(kit, apiConfig, sdkOptions) {
20
- this.kit = kit;
21
- const sandbox = sdkOptions?.sandbox ? sdkOptions.sandbox : false;
22
- this.apiService = new apiHelpers_1.ZebecCardAPIService(apiConfig, sandbox);
23
- this.server = new stellar_sdk_1.Horizon.Server(sandbox ? constants_1.DIGITALBITS_RPC_URL.Sandbox : constants_1.DIGITALBITS_RPC_URL.Production);
24
- this.sandbox = sandbox;
25
- }
26
- /**
27
- * Fetches a quote for the given amount.
28
- *
29
- * @param {string | number} amount - The amount for which to fetch the quote.
30
- * @returns {Promise<Quote>} A promise that resolves to a Quote object.
31
- */
32
- async fetchQuote() {
33
- const res = await this.apiService.fetchQuote("XDB");
34
- return res;
35
- }
36
- /**
37
- * Fetches the Vault address.
38
- *
39
- * @returns {Promise<string>} A promise that resolves to the Vault address.
40
- */
41
- async fetchVault() {
42
- const data = await this.apiService.fetchVault("XDB");
43
- return data;
44
- }
45
- /**
46
- * Purchases a card by transferring XDB tokens.
47
- *
48
- * @param params - The parameters required to purchase a card.
49
- * @returns A promise that resolves to an array containing the transaction details and the API response.
50
- * @throws {InvalidEmailError} If the recipient's email address is invalid.
51
- * @throws {Error} If the quote is invalid or expired, if there is not enough balance, or if the transaction fails.
52
- */
53
- async transferXDB(amount) {
54
- // Fetch deposit address
55
- const vault = await this.fetchVault();
56
- const accountAddress = await this.kit.getAddress();
57
- // Prepare transaction
58
- const account = await this.server.loadAccount(accountAddress.address);
59
- const fee = await this.server.fetchBaseFee();
60
- const memo = stellar_sdk_1.Memo.id(vault.tag?.toString() || "");
61
- // Check Wallet balance
62
- const balance = await this.getWalletBalance(accountAddress.address);
63
- if (Number(balance) < Number(amount)) {
64
- throw new Error("Insufficient balance");
65
- }
66
- // Build and submit transaction
67
- const transaction = new stellar_sdk_1.TransactionBuilder(account, {
68
- fee: fee.toString(),
69
- networkPassphrase: this.sandbox ? constants_1.XDB_PASSPHRASE.Sandbox : constants_1.XDB_PASSPHRASE.Production,
70
- })
71
- .addOperation(stellar_sdk_1.Operation.payment({
72
- destination: vault.address,
73
- asset: stellar_sdk_1.Asset.native(),
74
- amount,
75
- }))
76
- .addMemo(memo)
77
- .setTimeout(stellar_sdk_1.TimeoutInfinite)
78
- .build();
79
- // Sign the transaction
80
- const { signedTxXdr } = await this.kit.signTransaction(transaction.toXDR());
81
- const tx = stellar_sdk_1.TransactionBuilder.fromXDR(signedTxXdr, this.sandbox ? constants_1.XDB_PASSPHRASE.Sandbox : constants_1.XDB_PASSPHRASE.Production);
82
- let retries = 0;
83
- const maxRetries = 5;
84
- let delay = 1000;
85
- while (retries < maxRetries) {
86
- try {
87
- const transactionResult = await this.server.submitTransaction(tx, {
88
- skipMemoRequiredCheck: false,
89
- });
90
- const txHash = transactionResult.hash;
91
- return txHash;
92
- }
93
- catch (error) {
94
- console.debug("error: ", error);
95
- if (retries >= maxRetries) {
96
- throw error;
97
- }
98
- retries += 1;
99
- console.debug(`Retrying in ${delay / 1000} seconds...`);
100
- await new Promise((resolve) => setTimeout(resolve, delay));
101
- delay *= 2; // Exponential backoff
102
- }
103
- }
104
- throw new Error("Max retries reached");
105
- }
106
- /**
107
- * Retrieves the balance of the specified wallet.
108
- *
109
- * @param {string} wallet - The public key of the wallet to get the balance for.
110
- * @returns {Promise<string>} - A promise that resolves to the balance of the wallet.
111
- */
112
- async getWalletBalance(wallet) {
113
- const account = await this.server.loadAccount(wallet);
114
- const nativeBalance = account.balances.find((balance) => balance.asset_type === "native");
115
- return nativeBalance ? nativeBalance.balance : "0";
116
- }
117
- }
118
- exports.XDBService = XDBService;