@zebec-network/exchange-card-sdk 1.2.3 → 1.3.0

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.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,5 @@
1
1
  export * from "./artifacts";
2
- export * from "./chains";
3
2
  export * from "./constants";
4
- export * from "./errors";
5
3
  export * from "./services";
6
4
  export * from "./types";
7
5
  export * from "./utils";
package/dist/index.js CHANGED
@@ -15,9 +15,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./artifacts"), exports);
18
- __exportStar(require("./chains"), exports);
19
18
  __exportStar(require("./constants"), exports);
20
- __exportStar(require("./errors"), exports);
21
19
  __exportStar(require("./services"), exports);
22
20
  __exportStar(require("./types"), exports);
23
21
  __exportStar(require("./utils"), exports);
@@ -2,10 +2,22 @@ import algosdk from "algosdk";
2
2
  import { AlgorandClient } from "@algorandfoundation/algokit-utils";
3
3
  import { APIConfig } from "../helpers/apiHelpers";
4
4
  import { Quote } from "../types";
5
+ /**
6
+ * Configuration interface for algo transfers
7
+ * */
5
8
  export interface TransferConfig {
6
9
  amount: number | string;
7
10
  note?: string;
8
11
  }
12
+ /**
13
+ * Configuration interface for USDC transfers
14
+ * */
15
+ export interface TokenTransferConfig {
16
+ /** Asset ID for Asset (e.g. for USDC 31566704) */
17
+ assetId: number;
18
+ amount: number | string;
19
+ note?: string;
20
+ }
9
21
  export interface AlgorandWallet {
10
22
  address: string;
11
23
  signAndSendTransaction: (txn: algosdk.Transaction) => Promise<string>;
@@ -16,6 +28,7 @@ export declare class AlgorandService {
16
28
  readonly algodClient: algosdk.Algodv2;
17
29
  readonly algorandClient: AlgorandClient;
18
30
  private apiService;
31
+ private readonly network;
19
32
  constructor(wallet: AlgorandWallet, apiConfig: APIConfig, sdkOptions?: {
20
33
  sandbox?: boolean;
21
34
  });
@@ -40,12 +53,34 @@ export declare class AlgorandService {
40
53
  * @returns Transaction ID if successful
41
54
  */
42
55
  transferAlgo(config: TransferConfig): Promise<string>;
56
+ /**
57
+ * Transfer USDC (ASA token) from wallet to vault
58
+ * @param config USDC transfer configuration
59
+ * @returns Transaction ID if successful
60
+ */
61
+ transferAsset(config: TokenTransferConfig): Promise<string>;
62
+ /**
63
+ * Check if an account is opted into a specific asset
64
+ * @param address Account address
65
+ * @param assetId Asset ID to check
66
+ * @returns Whether the account is opted into the asset
67
+ */
68
+ isOptedIntoAsset(address: string, assetId: number): Promise<boolean>;
69
+ /**
70
+ * Get asset balance for a specific account in microAsset (base units)
71
+ * @param address Account address
72
+ * @param assetId Asset ID
73
+ * @returns Asset balance in base units
74
+ */
75
+ private getAssetBalanceInMicroUnit;
76
+ getAssetBalance(walletAddress: string, assetId: number): Promise<string>;
77
+ getAssetsBalance(walletAddress: string, assetIds: number[]): Promise<Map<number, string>>;
43
78
  /**
44
79
  * Get account balance in Algos
45
80
  * @param address Account address
46
81
  * @returns Balance in ALGO
47
82
  */
48
- getAccountBalance(address: string | algosdk.Address): Promise<number>;
83
+ getAccountBalance(address: string | algosdk.Address): Promise<string>;
49
84
  /**
50
85
  * Get account balance in microAlgos (for internal calculations)
51
86
  * @param address Account address
@@ -53,15 +88,3 @@ export declare class AlgorandService {
53
88
  */
54
89
  private getAccountBalanceInMicroAlgo;
55
90
  }
56
- /**
57
- * Convert ALGO to microAlgos
58
- * @param algos Amount in ALGO
59
- * @returns Amount in microAlgos
60
- */
61
- export declare function algoToMicroAlgo(algos: number | string): bigint;
62
- /**
63
- * Convert microAlgos to ALGO
64
- * @param microAlgos Amount in microAlgos
65
- * @returns Amount in ALGO
66
- */
67
- export declare function microAlgoToAlgo(microAlgos: number | bigint): number;
@@ -4,24 +4,23 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.AlgorandService = void 0;
7
- exports.algoToMicroAlgo = algoToMicroAlgo;
8
- exports.microAlgoToAlgo = microAlgoToAlgo;
9
7
  const algosdk_1 = __importDefault(require("algosdk"));
10
- const bignumber_js_1 = require("bignumber.js");
11
8
  const algokit_utils_1 = require("@algorandfoundation/algokit-utils");
12
9
  const client_manager_1 = require("@algorandfoundation/algokit-utils/types/client-manager");
13
10
  const apiHelpers_1 = require("../helpers/apiHelpers");
11
+ const utils_1 = require("../utils");
14
12
  class AlgorandService {
15
13
  wallet;
16
14
  apiConfig;
17
15
  algodClient;
18
16
  algorandClient;
19
17
  apiService;
18
+ network;
20
19
  constructor(wallet, apiConfig, sdkOptions) {
21
20
  this.wallet = wallet;
22
21
  this.apiConfig = apiConfig;
23
- const network = sdkOptions?.sandbox ? "testnet" : "mainnet";
24
- this.algodClient = client_manager_1.ClientManager.getAlgodClient(client_manager_1.ClientManager.getAlgoNodeConfig(network, "algod"));
22
+ this.network = sdkOptions?.sandbox ? "testnet" : "mainnet";
23
+ this.algodClient = client_manager_1.ClientManager.getAlgodClient(client_manager_1.ClientManager.getAlgoNodeConfig(this.network, "algod"));
25
24
  this.algorandClient = algokit_utils_1.AlgorandClient.fromClients({
26
25
  algod: this.algodClient,
27
26
  });
@@ -52,12 +51,12 @@ class AlgorandService {
52
51
  */
53
52
  async transferAlgo(config) {
54
53
  try {
55
- const parsedAmount = algoToMicroAlgo(config.amount);
54
+ const parsedAmount = (0, utils_1.parseAlgo)(config.amount);
56
55
  // Check if sender has sufficient balance
57
56
  const senderBalance = await this.getAccountBalanceInMicroAlgo(this.wallet.address);
58
- const minBalance = algoToMicroAlgo(0.1); // Minimum account balance
57
+ const minBalance = (0, utils_1.parseAlgo)(0.1); // Minimum account balance
59
58
  if (senderBalance < parsedAmount + minBalance) {
60
- throw new Error(`Insufficient balance. Need ${microAlgoToAlgo(parsedAmount + minBalance)} ALGO, have ${microAlgoToAlgo(senderBalance)} ALGO`);
59
+ throw new Error(`Insufficient balance. Need ${(0, utils_1.formatAlgo)(parsedAmount + minBalance)} ALGO, have ${(0, utils_1.formatAlgo)(senderBalance)} ALGO`);
61
60
  }
62
61
  const vault = await this.fetchVault("ALGO");
63
62
  const recipientAddress = vault.address;
@@ -84,6 +83,119 @@ class AlgorandService {
84
83
  throw error;
85
84
  }
86
85
  }
86
+ /**
87
+ * Transfer USDC (ASA token) from wallet to vault
88
+ * @param config USDC transfer configuration
89
+ * @returns Transaction ID if successful
90
+ */
91
+ async transferAsset(config) {
92
+ try {
93
+ const assetDecimals = await (0, utils_1.getAssetDecimals)(this.algodClient, config.assetId);
94
+ // const usdcConfig = USDC_ASSET_CONFIG[this.network];
95
+ const parsedAmount = (0, utils_1.parseAlgorandAsset)(config.amount, assetDecimals);
96
+ // Check if sender has sufficient USDC balance
97
+ const senderAssetBalance = await this.getAssetBalanceInMicroUnit(this.wallet.address, config.assetId);
98
+ if (senderAssetBalance < parsedAmount) {
99
+ throw new Error(`Insufficient Asset balance. Need ${(0, utils_1.formatAlgorandAsset)(parsedAmount, assetDecimals)} Asset, have ${(0, utils_1.formatAlgorandAsset)(senderAssetBalance, assetDecimals)} Asset`);
100
+ }
101
+ // Check if sender has sufficient ALGO for transaction fees
102
+ const senderAlgoBalance = await this.getAccountBalanceInMicroAlgo(this.wallet.address);
103
+ const minAlgoForFees = (0, utils_1.parseAlgo)(0.002); // Minimum ALGO for transaction fees
104
+ if (senderAlgoBalance < minAlgoForFees) {
105
+ throw new Error(`Insufficient ALGO for transaction fees. Need at least ${(0, utils_1.formatAlgo)(minAlgoForFees)} ALGO for fees`);
106
+ }
107
+ const vault = await this.fetchVault("ALGO-USDC");
108
+ const recipientAddress = vault.address;
109
+ // Validate recipient address
110
+ if (!algosdk_1.default.isValidAddress(recipientAddress)) {
111
+ throw new Error("Invalid recipient address");
112
+ }
113
+ // // Check if recipient is opted into USDC asset
114
+ const recipientOptedIn = await this.isOptedIntoAsset(recipientAddress, config.assetId);
115
+ if (!recipientOptedIn) {
116
+ throw new Error("Recipient address is not opted into USDC asset");
117
+ }
118
+ // Get suggested transaction parameters
119
+ const suggestedParams = await this.algodClient.getTransactionParams().do();
120
+ // Create asset transfer transaction
121
+ const assetTransferTxn = algosdk_1.default.makeAssetTransferTxnWithSuggestedParamsFromObject({
122
+ sender: this.wallet.address,
123
+ receiver: recipientAddress,
124
+ amount: parsedAmount,
125
+ assetIndex: config.assetId,
126
+ note: config.note ? new Uint8Array(Buffer.from(config.note)) : undefined,
127
+ suggestedParams: suggestedParams,
128
+ });
129
+ // Sign and send the transaction
130
+ const txId = await this.wallet.signAndSendTransaction(assetTransferTxn);
131
+ return txId;
132
+ }
133
+ catch (error) {
134
+ console.error("Asset transfer failed:", error);
135
+ throw error;
136
+ }
137
+ }
138
+ /**
139
+ * Check if an account is opted into a specific asset
140
+ * @param address Account address
141
+ * @param assetId Asset ID to check
142
+ * @returns Whether the account is opted into the asset
143
+ */
144
+ async isOptedIntoAsset(address, assetId) {
145
+ try {
146
+ const accountInfo = await this.algodClient.accountInformation(address).do();
147
+ return accountInfo.assets?.some((asset) => asset.assetId === BigInt(assetId)) || false;
148
+ }
149
+ catch (error) {
150
+ console.error("Error checking asset opt-in status:", error);
151
+ return false;
152
+ }
153
+ }
154
+ /**
155
+ * Get asset balance for a specific account in microAsset (base units)
156
+ * @param address Account address
157
+ * @param assetId Asset ID
158
+ * @returns Asset balance in base units
159
+ */
160
+ async getAssetBalanceInMicroUnit(walletAddress, assetId) {
161
+ try {
162
+ const accountInfo = await this.algodClient.accountInformation(walletAddress).do();
163
+ const asset = accountInfo.assets?.find((asset) => asset.assetId === BigInt(assetId));
164
+ return asset ? BigInt(asset.amount) : BigInt(0);
165
+ }
166
+ catch (error) {
167
+ console.error("Error fetching asset balance:", error);
168
+ return BigInt(0);
169
+ }
170
+ }
171
+ async getAssetBalance(walletAddress, assetId) {
172
+ const balance = await this.getAssetBalanceInMicroUnit(walletAddress, assetId);
173
+ const decimals = await (0, utils_1.getAssetDecimals)(this.algodClient, assetId);
174
+ return (0, utils_1.formatAlgorandAsset)(balance, decimals);
175
+ }
176
+ async getAssetsBalance(walletAddress, assetIds) {
177
+ const map = new Map(Array.from(assetIds.map((id) => [id, "0"])));
178
+ try {
179
+ const accountInfo = await this.algodClient.accountInformation(walletAddress).do();
180
+ const assets = accountInfo.assets;
181
+ if (!assets) {
182
+ return map;
183
+ }
184
+ await Promise.all(assetIds.map(async (id) => {
185
+ const asset = assets.find((asset) => asset.assetId === BigInt(id));
186
+ if (asset) {
187
+ const decimals = await (0, utils_1.getAssetDecimals)(this.algodClient, id);
188
+ const amount = (0, utils_1.formatAlgorandAsset)(asset.amount, decimals);
189
+ map.set(id, amount);
190
+ }
191
+ }));
192
+ return map;
193
+ }
194
+ catch (error) {
195
+ console.error("Error fetching asset balance:", error);
196
+ }
197
+ return map;
198
+ }
87
199
  /**
88
200
  * Get account balance in Algos
89
201
  * @param address Account address
@@ -91,7 +203,7 @@ class AlgorandService {
91
203
  */
92
204
  async getAccountBalance(address) {
93
205
  const amount = await this.getAccountBalanceInMicroAlgo(address);
94
- return microAlgoToAlgo(amount);
206
+ return (0, utils_1.formatAlgo)(amount);
95
207
  }
96
208
  /**
97
209
  * Get account balance in microAlgos (for internal calculations)
@@ -104,19 +216,3 @@ class AlgorandService {
104
216
  }
105
217
  }
106
218
  exports.AlgorandService = AlgorandService;
107
- /**
108
- * Convert ALGO to microAlgos
109
- * @param algos Amount in ALGO
110
- * @returns Amount in microAlgos
111
- */
112
- function algoToMicroAlgo(algos) {
113
- return BigInt((0, bignumber_js_1.BigNumber)(algos).times(1_000_000).toFixed(0));
114
- }
115
- /**
116
- * Convert microAlgos to ALGO
117
- * @param microAlgos Amount in microAlgos
118
- * @returns Amount in ALGO
119
- */
120
- function microAlgoToAlgo(microAlgos) {
121
- return (0, bignumber_js_1.BigNumber)(microAlgos).div(1_000_000).toNumber();
122
- }
@@ -33,16 +33,7 @@ export declare class StellarService {
33
33
  *
34
34
  * @returns {Promise<string>} A promise that resolves to the Vault address.
35
35
  */
36
- fetchVault(): Promise<{
37
- address: string;
38
- tag?: string;
39
- }>;
40
- /**
41
- * Fetches the Vault address.
42
- *
43
- * @returns {Promise<string>} A promise that resolves to the Vault address.
44
- */
45
- fetchUSDCVault(): Promise<{
36
+ fetchVault(symbol?: string): Promise<{
46
37
  address: string;
47
38
  tag?: string;
48
39
  }>;
@@ -38,17 +38,8 @@ class StellarService {
38
38
  *
39
39
  * @returns {Promise<string>} A promise that resolves to the Vault address.
40
40
  */
41
- async fetchVault() {
42
- const data = await this.apiService.fetchVault("XLM");
43
- return data;
44
- }
45
- /**
46
- * Fetches the Vault address.
47
- *
48
- * @returns {Promise<string>} A promise that resolves to the Vault address.
49
- */
50
- async fetchUSDCVault() {
51
- const data = await this.apiService.fetchVault("xlm-usdc");
41
+ async fetchVault(symbol = "XLM") {
42
+ const data = await this.apiService.fetchVault(symbol);
52
43
  return data;
53
44
  }
54
45
  /**
@@ -120,7 +111,7 @@ class StellarService {
120
111
  */
121
112
  async transferUSDC(amount) {
122
113
  // Fetch deposit address
123
- const vault = await this.fetchUSDCVault();
114
+ const vault = await this.fetchVault("XLM-USDC");
124
115
  // Prepare transaction
125
116
  const account = await this.server.loadAccount(this.wallet.address);
126
117
  const fee = await this.server.fetchBaseFee();
package/dist/types.d.ts CHANGED
@@ -1,59 +1,5 @@
1
- import { SupportedChain } from "./chains";
2
- export declare class OrderCardRequest {
3
- readonly amount: Money;
4
- readonly recipient: Recipient;
5
- readonly receipt: Receipt;
6
- constructor(amount: Money, recipient: Recipient, receipt: Receipt);
7
- }
8
- export declare class Quote {
1
+ export type Quote = {
9
2
  price: number;
10
3
  fluctuationPercentage: number;
11
4
  token: string;
12
- constructor(price: number, // Total token amount needed for the USD purchase
13
- fluctuationPercentage: number, // Amount of USD the user wants to purchase
14
- token: string);
15
- }
16
- export declare class Deposit {
17
- tokenName: string;
18
- tokenAmount: number;
19
- signature: string;
20
- buyerAddress: string;
21
- txHash?: string;
22
- blockHash?: string;
23
- chainId?: SupportedChain;
24
- purchaseCounter?: number;
25
- constructor(tokenName: string, tokenAmount: number, signature: string, buyerAddress: string, txHash?: string, blockHash?: string, chainId?: SupportedChain, purchaseCounter?: number);
26
- }
27
- export declare class Receipt {
28
- quote?: Quote;
29
- deposit?: Deposit;
30
- constructor(quote?: Quote, deposit?: Deposit);
31
- }
32
- export declare class Money {
33
- readonly amount: number;
34
- readonly currencyCode: string;
35
- private constructor();
36
- static create(amount: number | string, currencyCode: string): Money;
37
- static USD(amount: number | string): Money;
38
- }
39
- export declare class Recipient {
40
- readonly participantId: string;
41
- readonly firstName: string;
42
- readonly lastName: string;
43
- readonly emailAddress: string;
44
- readonly address1: string;
45
- readonly address2?: string;
46
- readonly city: string;
47
- readonly state: string;
48
- readonly postalCode: string;
49
- readonly countryCode: CountryCode;
50
- readonly language: string;
51
- readonly mobilePhone: string;
52
- private constructor();
53
- static create(participantId: string, firstName: string, lastName: string, emailAddress: string, mobilePhone: string, language: string, city: string, state: string, postalCode: string, countryCode: CountryCode, address1: string, address2?: string): Recipient;
54
- }
55
- export declare const allCountriesWithCode: {
56
- name: string;
57
- code: string;
58
- }[];
59
- export type CountryCode = "DZA" | "AGO" | "ARG" | "AUS" | "AUT" | "BEL" | "BOL" | "BRA" | "CMR" | "CAN" | "CHL" | "CRI" | "CYP" | "CZE" | "DNK" | "ECU" | "EGY" | "SLV" | "EST" | "FIN" | "FRA" | "GEO" | "DEU" | "GHA" | "GRC" | "GTM" | "HND" | "HUN" | "ISL" | "IRL" | "ITA" | "JAM" | "JPN" | "JOR" | "KEN" | "KOR" | "KWT" | "LTU" | "LUX" | "MWI" | "MYS" | "MLT" | "MEX" | "MAR" | "MOZ" | "NPL" | "NLD" | "NZL" | "NGA" | "NOR" | "OMN" | "PAK" | "PNG" | "PRY" | "PER" | "PHL" | "POL" | "PRT" | "PRI" | "QAT" | "ROU" | "SAU" | "SGP" | "SVK" | "SVN" | "ESP" | "SWE" | "TWN" | "THA" | "TTO" | "TUN" | "TUR" | "GBR" | "USA" | "URY" | "VUT" | "ZMB";
5
+ };
package/dist/types.js CHANGED
@@ -1,263 +1,2 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.allCountriesWithCode = exports.Recipient = exports.Money = exports.Receipt = exports.Deposit = exports.Quote = exports.OrderCardRequest = void 0;
4
- const errors_1 = require("./errors");
5
- const utils_1 = require("./utils");
6
- class OrderCardRequest {
7
- amount;
8
- recipient;
9
- receipt;
10
- constructor(amount, recipient, receipt) {
11
- this.amount = amount;
12
- this.receipt = receipt;
13
- this.recipient = recipient;
14
- }
15
- }
16
- exports.OrderCardRequest = OrderCardRequest;
17
- // export class Quote {
18
- // id: string; // Unique identifier for the quote
19
- // token: string; // Token symbol or name (e.g., BTC, ETH)
20
- // targetCurrency: string; // Target currency (e.g., "USD")
21
- // amountRequested: number; // Amount of USD the user wants to purchase
22
- // pricePerUnitCurrency: number; // Price of 1 USD in terms of the token
23
- // totalPrice: number; // Total token amount needed for the USD purchase
24
- // platformFee: number; // Any additional platform fee
25
- // expiresIn: number; // Validity period for the quote in seconds or ISO date
26
- // timestamp: Date; // Timestamp when the quote was generated
27
- // status: "pending" | "expired" | "accepted" | "rejected"; // Quote status
28
- // constructor(
29
- // id: string,
30
- // token: string,
31
- // targetCurrency: string,
32
- // amountRequested: number,
33
- // pricePerUnitCurrency: number,
34
- // totalPrice: number,
35
- // platformFee: number,
36
- // expiresIn: number,
37
- // timestamp: Date,
38
- // status: "pending" | "expired" | "accepted" | "rejected",
39
- // ) {
40
- // this.id = id;
41
- // this.token = token;
42
- // this.targetCurrency = targetCurrency;
43
- // this.amountRequested = amountRequested;
44
- // this.pricePerUnitCurrency = pricePerUnitCurrency;
45
- // this.totalPrice = totalPrice;
46
- // this.platformFee = platformFee;
47
- // this.expiresIn = expiresIn;
48
- // this.timestamp = timestamp;
49
- // this.status = status;
50
- // }
51
- // }
52
- class Quote {
53
- price; // Total token amount needed for the USD purchase
54
- fluctuationPercentage; // Amount of USD the user wants to purchase
55
- token; // Timestamp when the quote was generated
56
- constructor(price, // Total token amount needed for the USD purchase
57
- fluctuationPercentage, // Amount of USD the user wants to purchase
58
- token) {
59
- this.price = price;
60
- this.fluctuationPercentage = fluctuationPercentage;
61
- this.token = token;
62
- }
63
- }
64
- exports.Quote = Quote;
65
- class Deposit {
66
- tokenName;
67
- tokenAmount;
68
- signature;
69
- buyerAddress;
70
- txHash;
71
- blockHash;
72
- chainId;
73
- purchaseCounter;
74
- constructor(tokenName, tokenAmount, signature, buyerAddress, txHash, blockHash, chainId, purchaseCounter) {
75
- this.tokenName = tokenName;
76
- this.tokenAmount = tokenAmount;
77
- this.signature = signature;
78
- this.txHash = txHash;
79
- this.blockHash = blockHash;
80
- this.chainId = chainId;
81
- this.buyerAddress = buyerAddress;
82
- this.purchaseCounter = purchaseCounter;
83
- }
84
- }
85
- exports.Deposit = Deposit;
86
- class Receipt {
87
- quote;
88
- deposit;
89
- constructor(quote, deposit) {
90
- this.quote = quote;
91
- this.deposit = deposit;
92
- }
93
- }
94
- exports.Receipt = Receipt;
95
- class Money {
96
- amount;
97
- currencyCode;
98
- constructor(amount, currencyCode) {
99
- this.amount = amount;
100
- this.currencyCode = currencyCode;
101
- }
102
- // Example static method to create a Money instance from an amount and optional currency code
103
- static create(amount, currencyCode) {
104
- return new Money(Number(amount), currencyCode);
105
- }
106
- static USD(amount) {
107
- return this.create((0, utils_1.formatAmount)(amount), "USD");
108
- }
109
- }
110
- exports.Money = Money;
111
- class Recipient {
112
- participantId;
113
- firstName;
114
- lastName;
115
- emailAddress;
116
- address1;
117
- address2;
118
- city;
119
- state;
120
- postalCode;
121
- countryCode;
122
- language = "en-US";
123
- mobilePhone;
124
- constructor(participantId, firstName, lastName, emailAddress, mobilePhone, language, city, state, postalCode, countryCode, address1, address2) {
125
- this.participantId = participantId;
126
- this.firstName = firstName;
127
- this.lastName = lastName;
128
- this.address1 = address1;
129
- this.address2 = address2;
130
- this.city = city;
131
- this.state = state;
132
- this.postalCode = postalCode;
133
- this.countryCode = countryCode;
134
- this.emailAddress = emailAddress;
135
- this.language = language;
136
- this.mobilePhone = mobilePhone;
137
- }
138
- static create(participantId, firstName, lastName, emailAddress, mobilePhone, language, city, state, postalCode, countryCode, address1, address2) {
139
- if (!(0, utils_1.hasLen)(participantId, 1, 20)) {
140
- throw new errors_1.ValidationError("Participants must be of 1 to 20 characters.");
141
- }
142
- if (!(0, utils_1.isAlphaNumeric)(participantId)) {
143
- throw new errors_1.ValidationError("Participants must only contains alpha numeric characters");
144
- }
145
- if (!(0, utils_1.hasLen)(firstName, 1, 50)) {
146
- throw new errors_1.ValidationError("Firstname must be within 1 to 50 characters.");
147
- }
148
- if (!(0, utils_1.hasLen)(lastName, 1, 50)) {
149
- throw new errors_1.ValidationError("Lastname must be within 1 to 50 characters.");
150
- }
151
- if (!(0, utils_1.hasLen)(emailAddress, 1, 80)) {
152
- throw new errors_1.ValidationError("Email must be within 1 to 80 characters.");
153
- }
154
- if (!(0, utils_1.isEmailValid)(emailAddress)) {
155
- throw new errors_1.ValidationError("Email address must be a valid email.");
156
- }
157
- if (!(0, utils_1.hasLen)(language, 2, 5)) {
158
- throw new errors_1.ValidationError("Language code must be within 2 to 5 characters.");
159
- }
160
- if (!(0, utils_1.hasLen)(mobilePhone, 1, 20)) {
161
- throw new errors_1.ValidationError("Mobile phone number must be within 1 to 20 characters.");
162
- }
163
- if (!(0, utils_1.hasLen)(city, 1, 50)) {
164
- throw new errors_1.ValidationError("City must be within 1 to 50 characters.");
165
- }
166
- if (!(0, utils_1.hasLen)(state, 1, 50)) {
167
- throw new errors_1.ValidationError("State must be within 1 to 50 characters.");
168
- }
169
- if (!exports.allCountriesWithCode.find((country) => country.code === countryCode)) {
170
- throw new errors_1.ValidationError("CountryCode must be a valid supported ISO 3166-1 alpha-3 code");
171
- }
172
- if (!(0, utils_1.hasLen)(postalCode, 1, 20)) {
173
- throw new errors_1.ValidationError("Postal code must be within 1 to 20 characters.");
174
- }
175
- if (!(0, utils_1.hasLen)(address1, 1, 50)) {
176
- throw new errors_1.ValidationError("Address line 1 must be within 1 to 50 characters.");
177
- }
178
- if (address2 && !(0, utils_1.hasLen)(address2, 1, 50)) {
179
- throw new errors_1.ValidationError("Address line 2 must be within 1 to 50 characters.");
180
- }
181
- return new Recipient(participantId, firstName, lastName, emailAddress, mobilePhone, language, city, state, postalCode, countryCode, address1, address2 ?? "N/A");
182
- }
183
- }
184
- exports.Recipient = Recipient;
185
- exports.allCountriesWithCode = [
186
- { name: "Algeria", code: "DZA" },
187
- { name: "Angola", code: "AGO" },
188
- { name: "Argentina", code: "ARG" },
189
- { name: "Australia", code: "AUS" },
190
- { name: "Austria", code: "AUT" },
191
- { name: "Belgium", code: "BEL" },
192
- { name: "Bolivia (Plurinational State of)", code: "BOL" },
193
- { name: "Brazil", code: "BRA" },
194
- { name: "Cameroon", code: "CMR" },
195
- { name: "Canada", code: "CAN" },
196
- { name: "Chile", code: "CHL" },
197
- { name: "Costa Rica", code: "CRI" },
198
- { name: "Cyprus", code: "CYP" },
199
- { name: "Czechia", code: "CZE" },
200
- { name: "Denmark", code: "DNK" },
201
- { name: "Ecuador", code: "ECU" },
202
- { name: "Egypt", code: "EGY" },
203
- { name: "El Salvador", code: "SLV" },
204
- { name: "Estonia", code: "EST" },
205
- { name: "Finland", code: "FIN" },
206
- { name: "France", code: "FRA" },
207
- { name: "Georgia", code: "GEO" },
208
- { name: "Germany", code: "DEU" },
209
- { name: "Ghana", code: "GHA" },
210
- { name: "Greece", code: "GRC" },
211
- { name: "Guatemala", code: "GTM" },
212
- { name: "Honduras", code: "HND" },
213
- { name: "Hungary", code: "HUN" },
214
- { name: "Iceland", code: "ISL" },
215
- { name: "Ireland", code: "IRL" },
216
- { name: "Italy", code: "ITA" },
217
- { name: "Jamaica", code: "JAM" },
218
- { name: "Japan", code: "JPN" },
219
- { name: "Jordan", code: "JOR" },
220
- { name: "Kenya", code: "KEN" },
221
- { name: "Korea, Republic of Korea", code: "KOR" },
222
- { name: "Kuwait", code: "KWT" },
223
- { name: "Lithuania", code: "LTU" },
224
- { name: "Luxembourg", code: "LUX" },
225
- { name: "Malawi", code: "MWI" },
226
- { name: "Malaysia", code: "MYS" },
227
- { name: "Malta", code: "MLT" },
228
- { name: "Mexico", code: "MEX" },
229
- { name: "Morocco", code: "MAR" },
230
- { name: "Mozambique", code: "MOZ" },
231
- { name: "Nepal", code: "NPL" },
232
- { name: "Netherlands", code: "NLD" },
233
- { name: "New Zealand", code: "NZL" },
234
- { name: "Nigeria", code: "NGA" },
235
- { name: "Norway", code: "NOR" },
236
- { name: "Oman", code: "OMN" },
237
- { name: "Pakistan", code: "PAK" },
238
- { name: "Papua New Guinea", code: "PNG" },
239
- { name: "Paraguay", code: "PRY" },
240
- { name: "Peru", code: "PER" },
241
- { name: "Philippines", code: "PHL" },
242
- { name: "Poland", code: "POL" },
243
- { name: "Portugal", code: "PRT" },
244
- { name: "Puerto Rico", code: "PRI" },
245
- { name: "Qatar", code: "QAT" },
246
- { name: "Romania", code: "ROU" },
247
- { name: "Saudi Arabia", code: "SAU" },
248
- { name: "Singapore", code: "SGP" },
249
- { name: "Slovakia", code: "SVK" },
250
- { name: "Slovenia", code: "SVN" },
251
- { name: "Spain", code: "ESP" },
252
- { name: "Sweden", code: "SWE" },
253
- { name: "Taiwan", code: "TWN" },
254
- { name: "Thailand", code: "THA" },
255
- { name: "Trinidad and Tobago", code: "TTO" },
256
- { name: "Tunisia", code: "TUN" },
257
- { name: "Turkey", code: "TUR" },
258
- { name: "United Kingdom", code: "GBR" },
259
- { name: "United States", code: "USA" },
260
- { name: "Uruguay", code: "URY" },
261
- { name: "Vanuatu", code: "VUT" },
262
- { name: "Zambia", code: "ZMB" },
263
- ];
package/dist/utils.d.ts CHANGED
@@ -1,8 +1,35 @@
1
+ import algosdk from "algosdk";
1
2
  export declare function hashSHA256(input: string): string;
2
- export declare function isEmailValid(value: string): boolean;
3
- export declare function isAlphaNumeric(value: string): boolean;
4
- export declare function areDatesOfSameDay(date1: Date, date2: Date): boolean;
5
- export declare function hasMinLen(value: string, len: number): boolean;
6
- export declare function hasMaxLen(value: string, len: number): boolean;
7
- export declare function hasLen(value: string, min: number, max?: number): boolean;
8
- export declare function formatAmount(amount: number | string, decimalPlaces?: number): number;
3
+ /**
4
+ * Convert ALGO to microAlgos
5
+ * @param algos Amount in ALGO
6
+ * @returns Amount in microAlgos
7
+ */
8
+ export declare function parseAlgo(algos: number | string): bigint;
9
+ /**
10
+ * Convert microAlgos to ALGO
11
+ * @param microAlgos Amount in microAlgos
12
+ * @returns Amount in ALGO
13
+ */
14
+ export declare function formatAlgo(microAlgos: number | bigint): string;
15
+ /**
16
+ * Convert Amount to micro-token amount (base units)
17
+ * @param amount Amount in decimal units
18
+ * @param decimals Number of decimals for the asset
19
+ * @returns Amount in micro-token base units
20
+ */
21
+ export declare function parseAlgorandAsset(amount: number | string, decimals: number): bigint;
22
+ /**
23
+ * Convert micro-token Amount to Amount
24
+ * @param microAmount Amount in micro units
25
+ * @param decimals Number of decimals for the asset
26
+ * @returns Amount in decimal units
27
+ */
28
+ export declare function formatAlgorandAsset(microAmount: number | bigint, decimals: number): string;
29
+ /**
30
+ *
31
+ * @param client Algod Client
32
+ * @param assetId asset index of Asset
33
+ * @returns
34
+ */
35
+ export declare function getAssetDecimals(client: algosdk.Algodv2, assetId: number): Promise<number>;
package/dist/utils.js CHANGED
@@ -4,13 +4,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.hashSHA256 = hashSHA256;
7
- exports.isEmailValid = isEmailValid;
8
- exports.isAlphaNumeric = isAlphaNumeric;
9
- exports.areDatesOfSameDay = areDatesOfSameDay;
10
- exports.hasMinLen = hasMinLen;
11
- exports.hasMaxLen = hasMaxLen;
12
- exports.hasLen = hasLen;
13
- exports.formatAmount = formatAmount;
7
+ exports.parseAlgo = parseAlgo;
8
+ exports.formatAlgo = formatAlgo;
9
+ exports.parseAlgorandAsset = parseAlgorandAsset;
10
+ exports.formatAlgorandAsset = formatAlgorandAsset;
11
+ exports.getAssetDecimals = getAssetDecimals;
12
+ const bignumber_js_1 = require("bignumber.js");
14
13
  const crypto_1 = __importDefault(require("crypto"));
15
14
  function hashSHA256(input) {
16
15
  const hash = crypto_1.default.createHash("sha256");
@@ -18,31 +17,55 @@ function hashSHA256(input) {
18
17
  const hex = hash.digest("hex");
19
18
  return hex;
20
19
  }
21
- function isEmailValid(value) {
22
- return /^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,10}$/.test(value);
20
+ /**
21
+ * Convert ALGO to microAlgos
22
+ * @param algos Amount in ALGO
23
+ * @returns Amount in microAlgos
24
+ */
25
+ function parseAlgo(algos) {
26
+ return BigInt((0, bignumber_js_1.BigNumber)(algos).times(1_000_000).toFixed(0));
23
27
  }
24
- function isAlphaNumeric(value) {
25
- return /^[a-zA-Z0-9]+$/.test(value);
28
+ /**
29
+ * Convert microAlgos to ALGO
30
+ * @param microAlgos Amount in microAlgos
31
+ * @returns Amount in ALGO
32
+ */
33
+ function formatAlgo(microAlgos) {
34
+ return (0, bignumber_js_1.BigNumber)(microAlgos).div(1_000_000).toFixed();
26
35
  }
27
- function areDatesOfSameDay(date1, date2) {
28
- return (date1.getUTCDay() === date2.getUTCDay() &&
29
- date1.getUTCMonth() === date2.getUTCMonth() &&
30
- date1.getUTCFullYear() === date2.getUTCFullYear());
36
+ /**
37
+ * Convert Amount to micro-token amount (base units)
38
+ * @param amount Amount in decimal units
39
+ * @param decimals Number of decimals for the asset
40
+ * @returns Amount in micro-token base units
41
+ */
42
+ function parseAlgorandAsset(amount, decimals) {
43
+ return BigInt((0, bignumber_js_1.BigNumber)(amount).times((0, bignumber_js_1.BigNumber)(10).pow(decimals)).toFixed(0));
31
44
  }
32
- function hasMinLen(value, len) {
33
- return value.length >= len;
45
+ /**
46
+ * Convert micro-token Amount to Amount
47
+ * @param microAmount Amount in micro units
48
+ * @param decimals Number of decimals for the asset
49
+ * @returns Amount in decimal units
50
+ */
51
+ function formatAlgorandAsset(microAmount, decimals) {
52
+ return (0, bignumber_js_1.BigNumber)(microAmount).div((0, bignumber_js_1.BigNumber)(10).pow(decimals)).toFixed();
34
53
  }
35
- function hasMaxLen(value, len) {
36
- return value.length <= len;
37
- }
38
- function hasLen(value, min, max) {
39
- if (max) {
40
- return hasMinLen(value, min) && hasMaxLen(value, max);
41
- }
42
- else {
43
- return hasMinLen(value, min);
54
+ const ALGORAND_ASSET_DECIMALS_CACHE = new Map();
55
+ /**
56
+ *
57
+ * @param client Algod Client
58
+ * @param assetId asset index of Asset
59
+ * @returns
60
+ */
61
+ async function getAssetDecimals(client, assetId) {
62
+ // Check if we already have this value cached
63
+ if (ALGORAND_ASSET_DECIMALS_CACHE.has(assetId)) {
64
+ return ALGORAND_ASSET_DECIMALS_CACHE.get(assetId);
44
65
  }
45
- }
46
- function formatAmount(amount, decimalPlaces = 2) {
47
- return Number(Number(amount).toFixed(decimalPlaces));
66
+ const assetInfo = await client.getAssetByID(assetId).do();
67
+ const decimals = assetInfo.params.decimals;
68
+ // Cache the result for future use
69
+ ALGORAND_ASSET_DECIMALS_CACHE.set(assetId, decimals);
70
+ return decimals;
48
71
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zebec-network/exchange-card-sdk",
3
- "version": "1.2.3",
3
+ "version": "1.3.0",
4
4
  "description": "An sdk for purchasing silver card in zebec",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/dist/chains.d.ts DELETED
@@ -1,13 +0,0 @@
1
- /**
2
- * Supported chainIds by zebec instant card sdk.
3
- */
4
- export declare enum SupportedChain {
5
- Mainnet = 1,
6
- Sepolia = 11155111,
7
- Base = 8453,
8
- Bsc = 56,
9
- BscTestnet = 97,
10
- Polygon = 137
11
- }
12
- export declare const TESTNET_CHAINIDS: SupportedChain[];
13
- export declare function parseSupportedChain(chainId: number): SupportedChain;
package/dist/chains.js DELETED
@@ -1,42 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TESTNET_CHAINIDS = exports.SupportedChain = void 0;
4
- exports.parseSupportedChain = parseSupportedChain;
5
- const errors_1 = require("./errors");
6
- /**
7
- * Supported chainIds by zebec instant card sdk.
8
- */
9
- var SupportedChain;
10
- (function (SupportedChain) {
11
- SupportedChain[SupportedChain["Mainnet"] = 1] = "Mainnet";
12
- SupportedChain[SupportedChain["Sepolia"] = 11155111] = "Sepolia";
13
- SupportedChain[SupportedChain["Base"] = 8453] = "Base";
14
- SupportedChain[SupportedChain["Bsc"] = 56] = "Bsc";
15
- SupportedChain[SupportedChain["BscTestnet"] = 97] = "BscTestnet";
16
- SupportedChain[SupportedChain["Polygon"] = 137] = "Polygon";
17
- // Bittensor = 558,
18
- // BittensorTestnet = 559,
19
- // Ton = -239,
20
- // TonTestnet = -3,
21
- // XdbChain = -4,
22
- // Stellar = -5,
23
- })(SupportedChain || (exports.SupportedChain = SupportedChain = {}));
24
- exports.TESTNET_CHAINIDS = [SupportedChain.Sepolia, SupportedChain.BscTestnet];
25
- function parseSupportedChain(chainId) {
26
- switch (chainId) {
27
- case 1:
28
- return SupportedChain.Mainnet;
29
- case 11155111:
30
- return SupportedChain.Sepolia;
31
- case 8453:
32
- return SupportedChain.Base;
33
- case 56:
34
- return SupportedChain.Bsc;
35
- case 97:
36
- return SupportedChain.BscTestnet;
37
- case 137:
38
- return SupportedChain.Polygon;
39
- default:
40
- throw new errors_1.UnsupportedChainError(chainId);
41
- }
42
- }
package/dist/errors.d.ts DELETED
@@ -1,24 +0,0 @@
1
- export declare class UnsupportedChainError extends Error {
2
- name: string;
3
- constructor(chainId: number);
4
- }
5
- export declare class InvalidEmailError extends Error {
6
- name: string;
7
- constructor(email: string);
8
- }
9
- export declare class NotEnoughBalanceError extends Error {
10
- name: string;
11
- constructor(currentBalance: string, requiredBalance: string);
12
- }
13
- export declare class CardPurchaseAmountOutOfRangeError extends Error {
14
- name: string;
15
- constructor(minRange: string, maxRange: string);
16
- }
17
- export declare class DailyCardPurchaseLimitExceedError extends Error {
18
- name: string;
19
- constructor(dailyLimit: string, purchaseOfADay: string);
20
- }
21
- export declare class ValidationError extends Error {
22
- name: string;
23
- constructor(message: string);
24
- }
package/dist/errors.js DELETED
@@ -1,51 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ValidationError = exports.DailyCardPurchaseLimitExceedError = exports.CardPurchaseAmountOutOfRangeError = exports.NotEnoughBalanceError = exports.InvalidEmailError = exports.UnsupportedChainError = void 0;
4
- class UnsupportedChainError extends Error {
5
- name = "UnsupportedChainError";
6
- constructor(chainId) {
7
- super("Unsupported chainId: " + chainId);
8
- }
9
- }
10
- exports.UnsupportedChainError = UnsupportedChainError;
11
- class InvalidEmailError extends Error {
12
- name = "InvalidEmailError";
13
- constructor(email) {
14
- super("Invalid email: " + email);
15
- }
16
- }
17
- exports.InvalidEmailError = InvalidEmailError;
18
- class NotEnoughBalanceError extends Error {
19
- name = "NotEnoughBalanceError";
20
- constructor(currentBalance, requiredBalance) {
21
- super("Not enough balance. Current amount: " +
22
- currentBalance +
23
- " Required amount: " +
24
- requiredBalance);
25
- }
26
- }
27
- exports.NotEnoughBalanceError = NotEnoughBalanceError;
28
- class CardPurchaseAmountOutOfRangeError extends Error {
29
- name = "BuyAmountOutOfRangeError";
30
- constructor(minRange, maxRange) {
31
- super("Amount must be with range: " + minRange + " - " + maxRange);
32
- }
33
- }
34
- exports.CardPurchaseAmountOutOfRangeError = CardPurchaseAmountOutOfRangeError;
35
- class DailyCardPurchaseLimitExceedError extends Error {
36
- name = "DailyCardPurchaseLimitExceedError";
37
- constructor(dailyLimit, purchaseOfADay) {
38
- super("Requested card purchase amount exceeds daily purchase limit. Daily limit: " +
39
- dailyLimit +
40
- " Today's purchase amount: " +
41
- purchaseOfADay);
42
- }
43
- }
44
- exports.DailyCardPurchaseLimitExceedError = DailyCardPurchaseLimitExceedError;
45
- class ValidationError extends Error {
46
- name = "ValidationError";
47
- constructor(message) {
48
- super(message);
49
- }
50
- }
51
- exports.ValidationError = ValidationError;