@zebec-network/exchange-card-sdk 1.9.0-dev.6 → 1.9.0-dev.8

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,37 +1,10 @@
1
+ import { type TransactionOptions } from "@provablehq/aleo-types";
1
2
  import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
2
3
  import { AleoNetworkClient as TestnetAleoNetworkClient } from "@provablehq/sdk/testnet.js";
3
4
  import { ZebecCardAPIService } from "../helpers/apiHelpers";
4
- /**
5
- * Transaction creation options
6
- */
7
- interface TransactionOptions {
8
- /**
9
- * The program to execute
10
- */
11
- program: string;
12
- /**
13
- * The function to call
14
- */
15
- function: string;
16
- /**
17
- * The function inputs
18
- */
19
- inputs: string[];
20
- /**
21
- * The transaction fee to pay
22
- */
23
- fee?: number;
24
- /**
25
- * Record indices to use
26
- */
27
- recordIndices?: number[];
28
- /**
29
- * Whether the fee is private
30
- */
31
- privateFee?: boolean;
32
- }
33
5
  export interface AleoWallet {
34
6
  address: string;
7
+ decrypt: (cipherText: string) => Promise<string>;
35
8
  requestRecords: (program: string, includePlaintext?: boolean | undefined) => Promise<unknown[]>;
36
9
  executeTransaction: (options: TransactionOptions) => Promise<{
37
10
  transactionId: string;
@@ -39,18 +12,41 @@ export interface AleoWallet {
39
12
  }
40
13
  export type AleoTransferCreditParams = {
41
14
  amount: number | string;
42
- transferType?: "public" | "private" | "privateToPublic" | "publicToPrivate";
15
+ transferType?: "public" | "private";
43
16
  fee?: number;
44
17
  privateFee?: boolean;
45
18
  };
46
- export type AleoTransferTokenParams = {
47
- tokenProgramId: string;
48
- tokenSymbol: string;
19
+ export type AleoTransferStableCoinParams = {
20
+ programId: "usad_stablecoin.aleo" | "usdcx_stablecoin.aleo";
49
21
  amount: number | string;
50
- transferType?: "public" | "private" | "privateToPublic" | "publicToPrivate";
22
+ transferType?: "public" | "private";
51
23
  fee?: number;
52
24
  privateFee?: boolean;
53
25
  };
26
+ export declare const NETWORK_CONFIG: {
27
+ mainnet: {
28
+ explorer: string;
29
+ stablecoins: {
30
+ usad: string;
31
+ usdcx: string;
32
+ };
33
+ freezeListApi: {
34
+ usad: string;
35
+ usdcx: string;
36
+ };
37
+ };
38
+ testnet: {
39
+ explorer: string;
40
+ stablecoins: {
41
+ usad: string;
42
+ usdcx: string;
43
+ };
44
+ freezeListApi: {
45
+ usad: string;
46
+ usdcx: string;
47
+ };
48
+ };
49
+ };
54
50
  export declare class AleoService {
55
51
  readonly wallet: AleoWallet;
56
52
  readonly sandbox: boolean;
@@ -68,16 +64,27 @@ export declare class AleoService {
68
64
  address: string;
69
65
  tag?: string;
70
66
  }>;
67
+ /**
68
+ * Fetch unspent records for a program, decrypt them, and return the one
69
+ * with the highest non-zero balance as a single-line plaintext string.
70
+ */
71
+ private _getRecord;
72
+ /**
73
+ * Build a Sealance Merkle exclusion proof proving the sender is NOT on the
74
+ * program's freeze list. Required for compliant stablecoin transfers.
75
+ */
76
+ private _getComplianceProof;
71
77
  /**
72
78
  * Transfer native Aleo credits to the specified recipient.
73
79
  */
74
- transferCredits(params: AleoTransferCreditParams): Promise<{
80
+ transferCredit(params: AleoTransferCreditParams): Promise<{
75
81
  transactionId: string;
76
82
  }>;
77
- transferTokens(params: AleoTransferTokenParams): Promise<{
83
+ transferStableCoin(params: AleoTransferStableCoinParams): Promise<{
78
84
  transactionId: string;
79
85
  }>;
80
- getBalance(walletAddress: string): Promise<string>;
81
- getTokenBalance(walletAddress: string, tokenProgramId: string, tokenSymbol: string): Promise<string>;
86
+ getPublicBalance(): Promise<string>;
87
+ getPublicTokenBalance(tokenProgramId: string, tokenSymbol: string): Promise<string>;
88
+ getPrivateBalance(): Promise<string>;
89
+ getPrivateTokenBalance(tokenProgramId: string, tokenSymbol: string): Promise<string>;
82
90
  }
83
- export {};
@@ -1,8 +1,33 @@
1
- import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
2
- import { AleoNetworkClient as TestnetAleoNetworkClient } from "@provablehq/sdk/testnet.js";
1
+ import { Network } from "@provablehq/aleo-types";
2
+ import { AleoNetworkClient, SealanceMerkleTree } from "@provablehq/sdk/mainnet.js";
3
+ import { AleoNetworkClient as TestnetAleoNetworkClient, SealanceMerkleTree as TestnetSealanceMerkleTree, } from "@provablehq/sdk/testnet.js";
3
4
  import { ALEO_NETWORK_CLIENT_URL } from "../constants";
4
5
  import { ZebecCardAPIService } from "../helpers/apiHelpers";
5
- import { creditsToMicrocredits, getTokenBySymbol, microcreditsToCredits, } from "../utils";
6
+ import { fromMicroUnits, getTokenBySymbol, toMicroUnits } from "../utils";
7
+ export const NETWORK_CONFIG = {
8
+ [Network.MAINNET]: {
9
+ explorer: "https://explorer.provable.com/transaction",
10
+ stablecoins: {
11
+ usad: "usad_stablecoin.aleo",
12
+ usdcx: "usdcx_stablecoin.aleo",
13
+ },
14
+ freezeListApi: {
15
+ usad: "https://api.explorer.provable.com/v2/mainnet/programs/usad_freezelist.aleo/compliance/freeze-list",
16
+ usdcx: "https://api.explorer.provable.com/v2/mainnet/programs/usdcx_freezelist.aleo/compliance/freeze-list",
17
+ },
18
+ },
19
+ [Network.TESTNET]: {
20
+ explorer: "https://explorer.provable.com/testnet/transaction",
21
+ stablecoins: {
22
+ usad: "test_usad_stablecoin.aleo",
23
+ usdcx: "test_usdcx_stablecoin.aleo",
24
+ },
25
+ freezeListApi: {
26
+ usad: "https://api.explorer.provable.com/v2/testnet/programs/test_usad_freezelist.aleo/compliance/freeze-list",
27
+ usdcx: "https://api.explorer.provable.com/v2/testnet/programs/test_usdcx_freezelist.aleo/compliance/freeze-list",
28
+ },
29
+ },
30
+ };
6
31
  export class AleoService {
7
32
  wallet;
8
33
  sandbox;
@@ -25,93 +50,143 @@ export class AleoService {
25
50
  const data = await this.apiService.fetchVault(symbol);
26
51
  return data;
27
52
  }
53
+ /**
54
+ * Fetch unspent records for a program, decrypt them, and return the one
55
+ * with the highest non-zero balance as a single-line plaintext string.
56
+ */
57
+ async _getRecord(program, includePlaintext = false) {
58
+ const records = await this.wallet.requestRecords(program, includePlaintext);
59
+ console.debug("Fetched records:", records);
60
+ const unspent = records?.filter((r) => typeof r === "object" && r !== null && "spent" in r && !r.spent);
61
+ if (!unspent?.length) {
62
+ throw new Error(`No unspent ${program} records found`);
63
+ }
64
+ // Decrypt all unspent records in parallel (fast with AutoDecrypt permission)
65
+ const decrypted = await Promise.all(unspent.map(async (rec) => {
66
+ if (typeof rec !== "object" ||
67
+ rec === null ||
68
+ !("recordCiphertext" in rec) ||
69
+ typeof rec.recordCiphertext !== "string") {
70
+ throw new Error("Invalid record format");
71
+ }
72
+ console.debug("Decrypting record:", rec);
73
+ const plaintext = await this.wallet.decrypt(rec.recordCiphertext);
74
+ console.debug("Decrypted plaintext:", plaintext);
75
+ return plaintext.replace(/\s+/g, " ").trim();
76
+ }));
77
+ // Find records with non-zero balance, sorted highest-first
78
+ const withBalance = decrypted
79
+ .map((line) => {
80
+ const match = line.match(/microcredits:\s*(\d+)u64/) || line.match(/amount:\s*(\d+)u\d+/);
81
+ return { line, balance: match ? BigInt(match[1]) : 0n };
82
+ })
83
+ .filter((r) => r.balance > 0n)
84
+ .sort((a, b) => (b.balance > a.balance ? 1 : -1));
85
+ if (!withBalance.length) {
86
+ throw new Error(`No ${program} records with balance found`);
87
+ }
88
+ return withBalance[0].line;
89
+ }
90
+ /**
91
+ * Build a Sealance Merkle exclusion proof proving the sender is NOT on the
92
+ * program's freeze list. Required for compliant stablecoin transfers.
93
+ */
94
+ async _getComplianceProof(stablecoinKey, senderAddress, network) {
95
+ if (network === Network.CANARY) {
96
+ throw new Error("Compliance proof generation is not supported on canary network");
97
+ }
98
+ const sealance = this.sandbox ? new TestnetSealanceMerkleTree() : new SealanceMerkleTree();
99
+ const url = NETWORK_CONFIG[network].freezeListApi[stablecoinKey];
100
+ const res = await fetch(url);
101
+ const freezeList = await res.json();
102
+ const tree = sealance.convertTreeToBigInt(freezeList);
103
+ const [leftIdx, rightIdx] = sealance.getLeafIndices(tree, senderAddress);
104
+ const leftProof = sealance.getSiblingPath(tree, leftIdx, 16);
105
+ const rightProof = sealance.getSiblingPath(tree, rightIdx, 16);
106
+ return sealance.formatMerkleProof([leftProof, rightProof]);
107
+ }
28
108
  /**
29
109
  * Transfer native Aleo credits to the specified recipient.
30
110
  */
31
- async transferCredits(params) {
111
+ async transferCredit(params) {
32
112
  const { amount } = params;
33
113
  const transferType = params.transferType || "public";
34
114
  const privateFee = params?.privateFee || false;
115
+ const fee = toMicroUnits(params.fee || 0.1, 6);
35
116
  const vault = await this.fetchVault("ALEO");
36
117
  const recipient = vault.address;
37
118
  console.log("recipient:", recipient);
38
- const amountInMiroCredits = creditsToMicrocredits(amount);
39
- const programName = "credits.aleo";
40
- const functionName = transferType === "public"
41
- ? "transfer_public"
42
- : transferType === "private"
43
- ? "transfer_private"
44
- : transferType === "privateToPublic"
45
- ? "transfer_private_to_public"
46
- : "transfer_public_to_private";
119
+ const amountInMicroCredits = toMicroUnits(amount, 6, "u64");
120
+ const PROGRAM_NAME = "credits.aleo";
121
+ const functionName = transferType === "public" ? "transfer_public" : "transfer_private";
122
+ let inputs;
123
+ switch (functionName) {
124
+ case "transfer_public":
125
+ inputs = [recipient, `${amountInMicroCredits}u64`];
126
+ break;
127
+ case "transfer_private": {
128
+ const record = await this._getRecord(PROGRAM_NAME);
129
+ inputs = [record, recipient, amountInMicroCredits];
130
+ break;
131
+ }
132
+ default:
133
+ throw new Error("Invalid or Unsupported transfer type");
134
+ }
135
+ if (functionName !== "transfer_public") {
136
+ throw new Error("Only public transfers are currently supported for credits. Private and cross-type transfers require additional implementation.");
137
+ }
47
138
  const result = await this.wallet.executeTransaction({
48
- program: programName,
139
+ program: PROGRAM_NAME,
49
140
  function: functionName,
50
- inputs: [recipient, `${amountInMiroCredits}u64`],
51
- fee: Number(creditsToMicrocredits(params.fee || 0.1)),
141
+ inputs,
142
+ fee: Number(fee),
52
143
  privateFee,
53
144
  });
54
145
  return result;
55
146
  }
56
- async transferTokens(params) {
57
- const { tokenSymbol, amount } = params;
58
- const tokenMetadata = await getTokenBySymbol(tokenSymbol, this.sandbox ? "testnet" : "mainnet");
59
- if (!("decimals" in tokenMetadata)) {
60
- throw new Error(`Token metadata for ${tokenSymbol} does not include decimals.`);
61
- }
62
- const tokenDecimals = tokenMetadata.decimals;
63
- if (!("token_id" in tokenMetadata)) {
64
- throw new Error(`Token metadata for ${tokenSymbol} does not include token_id.`);
65
- }
66
- const tokenId = tokenMetadata.token_id;
67
- if (!("token_id_datatype" in tokenMetadata)) {
68
- throw new Error(`Token metadata for ${tokenSymbol} does not include token_id_datatype.`);
69
- }
70
- const tokenIdDatatype = tokenMetadata.token_id_datatype;
147
+ async transferStableCoin(params) {
148
+ const { amount } = params;
71
149
  const transferType = params.transferType || "public";
72
150
  const privateFee = params?.privateFee || false;
151
+ const fee = toMicroUnits(params.fee || 0.1, 6);
152
+ const programId = this.sandbox ? `test_${params.programId}` : params.programId;
153
+ const tokenSymbol = params.programId === "usad_stablecoin.aleo" ? "USAD" : "USDCX";
154
+ const functionName = transferType === "public" ? "transfer_public" : "transfer_private";
73
155
  const vault = await this.fetchVault(tokenSymbol);
74
156
  const recipient = vault.address;
75
- const amountInMicroTokens = creditsToMicrocredits(amount, tokenDecimals);
76
- const programName = "token_registry.aleo";
77
- const functionName = transferType === "public"
78
- ? "transfer_public"
79
- : transferType === "private"
80
- ? "transfer_private"
81
- : transferType === "privateToPublic"
82
- ? "transfer_private_to_public"
83
- : "transfer_public_to_private";
157
+ const amountInMicroUnits = toMicroUnits(amount, 6, "u128");
158
+ let inputs;
159
+ switch (functionName) {
160
+ case "transfer_public":
161
+ inputs = [recipient, amountInMicroUnits];
162
+ break;
163
+ case "transfer_private": {
164
+ // For private transfer, we need to find a record with sufficient balance
165
+ const [record, complianceProof] = await Promise.all([
166
+ this._getRecord(programId),
167
+ this._getComplianceProof(tokenSymbol.toLowerCase(), this.wallet.address, this.sandbox ? Network.TESTNET : Network.MAINNET),
168
+ ]);
169
+ inputs = [recipient, amountInMicroUnits, record, complianceProof];
170
+ break;
171
+ }
172
+ default:
173
+ throw new Error("Invalid or Unsupported transfer type");
174
+ }
84
175
  const result = await this.wallet.executeTransaction({
85
- fee: Number(creditsToMicrocredits(params.fee || 0.1)),
176
+ fee: Number(fee),
86
177
  privateFee,
87
- program: programName,
178
+ program: programId,
88
179
  function: functionName,
89
- inputs: [`${tokenId}${tokenIdDatatype}`, recipient, `${amountInMicroTokens}u128`],
180
+ inputs,
90
181
  });
91
182
  return result;
92
183
  }
93
- async getBalance(walletAddress) {
94
- const programId = "credits.aleo";
95
- const mappingName = "account";
96
- const balance = await this.networkClient.getProgramMappingValue(programId, mappingName, walletAddress);
97
- if (balance) {
98
- // regex to extract the number part and convert it to a string with 6 decimal places
99
- const regex = /(\d+)u64/;
100
- const match = balance.match(regex);
101
- if (match) {
102
- const amount = match[1];
103
- const formattedAmount = microcreditsToCredits(amount);
104
- return formattedAmount;
105
- }
106
- else {
107
- throw new Error(`Invalid balance format: ${balance}`);
108
- }
109
- }
110
- else {
111
- return "0";
112
- }
184
+ async getPublicBalance() {
185
+ const balance = await this.networkClient.getPublicBalance(this.wallet.address);
186
+ const formattedAmount = fromMicroUnits(balance);
187
+ return formattedAmount;
113
188
  }
114
- async getTokenBalance(walletAddress, tokenProgramId, tokenSymbol) {
189
+ async getPublicTokenBalance(tokenProgramId, tokenSymbol) {
115
190
  const tokenMetadata = await getTokenBySymbol(tokenSymbol, this.sandbox ? "testnet" : "mainnet");
116
191
  if (!("decimals" in tokenMetadata)) {
117
192
  throw new Error(`Token metadata for ${tokenSymbol} does not include decimals.`);
@@ -125,13 +200,13 @@ export class AleoService {
125
200
  if (!balanceMappingName) {
126
201
  throw new Error("No public balance mapping found (no 'balances' or 'account').");
127
202
  }
128
- const balance = await this.networkClient.getProgramMappingValue(tokenProgramId, balanceMappingName, walletAddress);
203
+ const balance = await this.networkClient.getProgramMappingValue(tokenProgramId, balanceMappingName, this.wallet.address);
129
204
  if (balance) {
130
- const regex = /(\d+)u128/;
205
+ const regex = /(\d+)u\d+/;
131
206
  const match = balance.match(regex);
132
207
  if (match) {
133
208
  const amount = match[1];
134
- const formattedAmount = microcreditsToCredits(amount, tokenMetadata.decimals);
209
+ const formattedAmount = fromMicroUnits(amount, tokenMetadata.decimals);
135
210
  return formattedAmount;
136
211
  }
137
212
  else {
@@ -142,4 +217,64 @@ export class AleoService {
142
217
  return "0";
143
218
  }
144
219
  }
220
+ async getPrivateBalance() {
221
+ const programId = "credits.aleo";
222
+ const records = await this.wallet.requestRecords(programId, false);
223
+ if (!records) {
224
+ throw new Error(`No records found for program ${programId}`);
225
+ }
226
+ // console.log("Fetched Records:", records);
227
+ const unspent = records.filter((r) => r && typeof r === "object" && "spent" in r && !r.spent);
228
+ if (!unspent || !unspent.length) {
229
+ throw new Error(`No unspent ${programId} records found`);
230
+ }
231
+ const decrypted = await Promise.all(unspent.map(async (rec) => {
232
+ if (!rec ||
233
+ typeof rec !== "object" ||
234
+ !("recordCiphertext" in rec) ||
235
+ typeof rec.recordCiphertext !== "string") {
236
+ throw new Error(`Invalid record format: ${JSON.stringify(rec)}`);
237
+ }
238
+ const plaintext = await this.wallet.decrypt(rec.recordCiphertext);
239
+ return plaintext.replace(/\s+/g, " ").trim();
240
+ }));
241
+ const balance = decrypted
242
+ .map((line) => {
243
+ const match = line.match(/microcredits:\s*(\d+)u64/);
244
+ return match ? BigInt(match[1]) : 0n;
245
+ })
246
+ .reduce((acc, val) => acc + val, 0n);
247
+ return fromMicroUnits(balance, 6);
248
+ }
249
+ async getPrivateTokenBalance(tokenProgramId, tokenSymbol) {
250
+ const records = await this.wallet.requestRecords(tokenProgramId, false);
251
+ if (!records) {
252
+ throw new Error(`No records found for program ${tokenProgramId}`);
253
+ }
254
+ const unspent = records.filter((r) => r && typeof r === "object" && "spent" in r && !r.spent);
255
+ if (!unspent || !unspent.length) {
256
+ throw new Error(`No unspent ${tokenProgramId} records found`);
257
+ }
258
+ const decrypted = await Promise.all(unspent.map(async (rec) => {
259
+ if (!rec ||
260
+ typeof rec !== "object" ||
261
+ !("recordCiphertext" in rec) ||
262
+ typeof rec.recordCiphertext !== "string") {
263
+ throw new Error(`Invalid record format: ${JSON.stringify(rec)}`);
264
+ }
265
+ const plaintext = await this.wallet.decrypt(rec.recordCiphertext);
266
+ return plaintext.replace(/\s+/g, " ").trim();
267
+ }));
268
+ const balance = decrypted
269
+ .map((line) => {
270
+ const match = line.match(/amount:\s*(\d+)u\d+/);
271
+ return match ? BigInt(match[1]) : 0n;
272
+ })
273
+ .reduce((acc, val) => acc + val, 0n);
274
+ const tokenMetadata = await getTokenBySymbol(tokenSymbol, this.sandbox ? "testnet" : "mainnet");
275
+ if (!("decimals" in tokenMetadata)) {
276
+ throw new Error(`Token metadata for ${tokenSymbol} does not include decimals.`);
277
+ }
278
+ return fromMicroUnits(balance, tokenMetadata.decimals);
279
+ }
145
280
  }
@@ -0,0 +1,31 @@
1
+ import { type AuthTokenProvider, LedgerController, TokenStandardController, ValidatorController, type WalletSDK } from "@canton-network/wallet-sdk";
2
+ export interface CantonWallet {
3
+ partyId: string;
4
+ executeTransaction: (command: unknown, disclosedContractId: unknown[]) => Promise<string>;
5
+ }
6
+ export interface CantonConfig {
7
+ ledgerApiUrl: string;
8
+ validatorAppApiUrl: string;
9
+ }
10
+ export declare function createLedgerFactory(ledgerApiUrl: string): (userId: string, authTokenProvider: AuthTokenProvider, isAdmin: boolean) => LedgerController;
11
+ export declare function createValidatorFactory(validatorAppApiUrl: string): (userId: string, authTokenProvider: AuthTokenProvider) => ValidatorController;
12
+ export declare function createTokenStandardFactory(ledgerApiUrl: string, validatorAppApiUrl: string): (userId: string, authTokenProvider: AuthTokenProvider, isAdmin: boolean) => TokenStandardController;
13
+ export declare class CantonService {
14
+ readonly wallet: CantonWallet;
15
+ readonly cantonConfig: CantonConfig;
16
+ readonly cantonWalletSdk: WalletSDK;
17
+ private apiService;
18
+ constructor(wallet: CantonWallet, cantonConfig: CantonConfig, sdkOptions?: {
19
+ sandbox?: boolean;
20
+ });
21
+ connect(): Promise<void>;
22
+ fetchVault(symbol?: string): Promise<{
23
+ address: string;
24
+ tag?: string;
25
+ }>;
26
+ transferNative(params: {
27
+ amount: number | string;
28
+ instrumentId: string;
29
+ instrumentAdmin: string;
30
+ }): Promise<string>;
31
+ }
@@ -0,0 +1,57 @@
1
+ import { LedgerController, localNetStaticConfig, TokenStandardController, ValidatorController, WalletSDKImpl, } from "@canton-network/wallet-sdk";
2
+ import { ZebecCardAPIService } from "../helpers/apiHelpers";
3
+ export function createLedgerFactory(ledgerApiUrl) {
4
+ return (userId, authTokenProvider, isAdmin) => {
5
+ return new LedgerController(userId, new URL(ledgerApiUrl), undefined, isAdmin, authTokenProvider);
6
+ };
7
+ }
8
+ export function createValidatorFactory(validatorAppApiUrl) {
9
+ return (userId, authTokenProvider) => {
10
+ return new ValidatorController(userId, new URL(validatorAppApiUrl), authTokenProvider);
11
+ };
12
+ }
13
+ export function createTokenStandardFactory(ledgerApiUrl, validatorAppApiUrl) {
14
+ return (userId, authTokenProvider, isAdmin) => {
15
+ return new TokenStandardController(userId, new URL(ledgerApiUrl), new URL(validatorAppApiUrl), undefined, authTokenProvider, isAdmin);
16
+ };
17
+ }
18
+ export class CantonService {
19
+ wallet;
20
+ cantonConfig;
21
+ cantonWalletSdk;
22
+ apiService;
23
+ constructor(wallet, cantonConfig, sdkOptions) {
24
+ this.wallet = wallet;
25
+ this.cantonConfig = cantonConfig;
26
+ this.apiService = new ZebecCardAPIService(sdkOptions?.sandbox || false);
27
+ this.cantonWalletSdk = new WalletSDKImpl().configure({
28
+ logger: console,
29
+ ledgerFactory: createLedgerFactory(cantonConfig.ledgerApiUrl),
30
+ validatorFactory: createValidatorFactory(cantonConfig.validatorAppApiUrl),
31
+ tokenStandardFactory: createTokenStandardFactory(cantonConfig.ledgerApiUrl, cantonConfig.validatorAppApiUrl),
32
+ });
33
+ }
34
+ async connect() {
35
+ await this.cantonWalletSdk.connect();
36
+ }
37
+ async fetchVault(symbol = "CANTON") {
38
+ const data = await this.apiService.fetchVault(symbol);
39
+ return data;
40
+ }
41
+ // methods for transfering natve assets
42
+ async transferNative(params) {
43
+ const vault = await this.fetchVault("CANTON");
44
+ const sender = this.wallet.partyId;
45
+ const receiver = vault.address;
46
+ const memo = vault.tag;
47
+ // implement transfer logic here
48
+ this.cantonWalletSdk.tokenStandard?.setTransferFactoryRegistryUrl(localNetStaticConfig.LOCALNET_REGISTRY_API_URL);
49
+ const [transferCommand, disclosedContracts] =
50
+ // biome-ignore lint/style/noNonNullAssertion: we can be sure that tokenStandard is defined here since we set its factory in the SDK constructor
51
+ await this.cantonWalletSdk.tokenStandard.createTransfer(sender, receiver, params.amount.toString(), {
52
+ instrumentId: params.instrumentId,
53
+ instrumentAdmin: params.instrumentAdmin,
54
+ }, [], memo);
55
+ return this.wallet.executeTransaction(transferCommand, disclosedContracts);
56
+ }
57
+ }
@@ -1,6 +1,7 @@
1
1
  export * from "./aleoService";
2
2
  export * from "./algorandService";
3
3
  export * from "./bobaService";
4
+ export * from "./cantonService";
4
5
  export * from "./nearService";
5
6
  export * from "./octaService";
6
7
  export * from "./quaiService";
@@ -1,6 +1,7 @@
1
1
  export * from "./aleoService";
2
2
  export * from "./algorandService";
3
3
  export * from "./bobaService";
4
+ export * from "./cantonService";
4
5
  export * from "./nearService";
5
6
  export * from "./octaService";
6
7
  export * from "./quaiService";
package/dist/utils.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type algosdk from "algosdk";
2
+ import { BigNumber } from "bignumber.js";
2
3
  /**
3
4
  * Convert ALGO to microAlgos
4
5
  * @param algos Amount in ALGO
@@ -35,11 +36,11 @@ export declare function getAssetDecimals(client: algosdk.Algodv2, assetId: numbe
35
36
  /**
36
37
  * Convert credits to microcredits
37
38
  */
38
- export declare function creditsToMicrocredits(credits: BigNumber.Value, decimals?: number): string;
39
+ export declare function toMicroUnits(credits: BigNumber.Value, decimals?: number, typeSuffix?: string): string;
39
40
  /**
40
41
  * Convert microcredits to credits
41
42
  */
42
- export declare function microcreditsToCredits(microcredits: BigNumber.Value, decimals?: number): string;
43
+ export declare function fromMicroUnits(microcredits: BigNumber.Value, decimals?: number): string;
43
44
  export type TokenMetadata = {
44
45
  token_id: string;
45
46
  token_id_datatype: string | null;
package/dist/utils.js CHANGED
@@ -61,13 +61,13 @@ export async function getAssetDecimals(client, assetId) {
61
61
  /**
62
62
  * Convert credits to microcredits
63
63
  */
64
- export function creditsToMicrocredits(credits, decimals = 6) {
65
- return BigNumber(credits).times(BigNumber(10).pow(decimals)).toFixed(0);
64
+ export function toMicroUnits(credits, decimals = 6, typeSuffix) {
65
+ return `${BigNumber(credits).times(BigNumber(10).pow(decimals)).toFixed(0)}${typeSuffix || ""}`;
66
66
  }
67
67
  /**
68
68
  * Convert microcredits to credits
69
69
  */
70
- export function microcreditsToCredits(microcredits, decimals = 6) {
70
+ export function fromMicroUnits(microcredits, decimals = 6) {
71
71
  return BigNumber(microcredits).div(BigNumber(10).pow(decimals)).toFixed();
72
72
  }
73
73
  export async function getTokenBySymbol(tokenSymbol, network = "mainnet") {
package/package.json CHANGED
@@ -1,17 +1,18 @@
1
1
  {
2
2
  "author": "Zebec Network | Ashish Sapkota",
3
3
  "dependencies": {
4
+ "@canton-network/wallet-sdk": "^0.21.1",
4
5
  "@near-js/crypto": "^2.5.1",
5
6
  "@near-js/providers": "^2.5.1",
6
7
  "@near-js/transactions": "^2.5.1",
7
8
  "@near-js/types": "^2.5.1",
8
9
  "@near-js/utils": "^2.5.1",
10
+ "@provablehq/aleo-types": "^0.3.0-alpha.3",
9
11
  "@provablehq/sdk": "^0.9.15",
10
12
  "@stellar/stellar-sdk": "^14.4.3",
11
13
  "algosdk": "^3.4.0",
12
14
  "axios": "^1.11.0",
13
- "bignumber.js": "^9.3.1",
14
- "bitcoinjs-lib": "^6.1.7",
15
+ "bignumber.js": "^10.0.2",
15
16
  "ethers": "^6.15.0",
16
17
  "quais": "^1.0.0-alpha.52",
17
18
  "xrpl": "^4.4.1"
@@ -19,9 +20,11 @@
19
20
  "description": "An sdk for purchasing silver card in zebec",
20
21
  "devDependencies": {
21
22
  "@algorandfoundation/algokit-utils": "^9.1.2",
23
+ "@canton-network/dapp-sdk": "^0.21.2",
22
24
  "@near-js/accounts": "^2.5.1",
23
25
  "@near-js/keystores": "^2.5.1",
24
26
  "@near-js/signers": "^2.5.1",
27
+ "@near-js/tokens": "^2.5.1",
25
28
  "@typechain/ethers-v6": "^0.5.1",
26
29
  "@types/mocha": "^10.0.10",
27
30
  "@types/node": "^24.3.1",
@@ -62,5 +65,5 @@
62
65
  },
63
66
  "type": "module",
64
67
  "types": "dist/index.d.ts",
65
- "version": "1.9.0-dev.6"
68
+ "version": "1.9.0-dev.8"
66
69
  }
@@ -1,48 +0,0 @@
1
- import * as bitcoin from "bitcoinjs-lib";
2
- interface BitcoinWallet {
3
- address: string;
4
- signTransaction: (psbt: bitcoin.Psbt) => Promise<bitcoin.Psbt>;
5
- broadcastTransaction: (tx: string) => Promise<string>;
6
- }
7
- export declare class BitcoinService {
8
- readonly wallet: BitcoinWallet;
9
- private apiService;
10
- private network;
11
- private apiEndpoint;
12
- constructor(wallet: BitcoinWallet, sdkOptions?: {
13
- sandbox?: boolean;
14
- apiKey?: string;
15
- });
16
- /**
17
- * Fetches the Bitcoin vault address.
18
- *
19
- * @returns {Promise<{ address: string }>} A promise that resolves to the vault address.
20
- */
21
- fetchVault(): Promise<{
22
- address: string;
23
- tag?: string;
24
- }>;
25
- getUTXOs(): Promise<Array<{
26
- txid: string;
27
- vout: number;
28
- value: number;
29
- rawTx: Buffer;
30
- }>>;
31
- private getBalance;
32
- /**
33
- * Transfers Bitcoin to the vault address.
34
- *
35
- * @param {string} amount - The amount of BTC to transfer in BTC units
36
- * @param {number} feeRate - Fee rate in satoshis per byte
37
- * @returns {Promise<string>} - A promise that resolves to the transaction hash
38
- * @throws {Error} If there is not enough balance or if the transaction fails.
39
- */
40
- transferBTC(amount: string, feeRate?: number): Promise<string>;
41
- /**
42
- * Gets the balance of the Bitcoin wallet.
43
- *
44
- * @returns {Promise<string>} - A promise that resolves to the wallet balance in BTC
45
- */
46
- getWalletBalance(): Promise<string>;
47
- }
48
- export {};
@@ -1,146 +0,0 @@
1
- import axios from "axios";
2
- import * as bitcoin from "bitcoinjs-lib";
3
- import { BITCOIN_ENDPOINTS } from "../constants";
4
- import { ZebecCardAPIService } from "../helpers/apiHelpers";
5
- export class BitcoinService {
6
- wallet;
7
- apiService;
8
- network;
9
- apiEndpoint;
10
- constructor(wallet, sdkOptions) {
11
- this.wallet = wallet;
12
- const sandbox = sdkOptions?.sandbox ?? false;
13
- this.apiService = new ZebecCardAPIService(sandbox);
14
- this.network = sandbox ? bitcoin.networks.testnet : bitcoin.networks.bitcoin;
15
- this.apiEndpoint = sandbox ? BITCOIN_ENDPOINTS.Sandbox : BITCOIN_ENDPOINTS.Production;
16
- }
17
- /**
18
- * Fetches the Bitcoin vault address.
19
- *
20
- * @returns {Promise<{ address: string }>} A promise that resolves to the vault address.
21
- */
22
- async fetchVault() {
23
- const data = await this.apiService.fetchVault("BTC");
24
- return data;
25
- }
26
- async getUTXOs() {
27
- const response = await axios.get(`${this.apiEndpoint}/address/${this.wallet.address}/utxo`);
28
- console.log("utxos:", response.data);
29
- return Promise.all(response.data.map(async (utxo) => {
30
- const rawTx = await axios.get(`${this.apiEndpoint}/tx/${utxo.txid}/hex`);
31
- console.log("txHex:", rawTx.data);
32
- if (!rawTx.data) {
33
- throw new Error("Transaction not found");
34
- }
35
- // const scriptPubKey = txResponse.data.vout[utxo.vout].scriptpubkey;
36
- return {
37
- txid: utxo.txid,
38
- vout: utxo.vout,
39
- value: utxo.value,
40
- rawTx: Buffer.from(rawTx.data, "hex"),
41
- };
42
- }));
43
- }
44
- async getBalance() {
45
- const response = await axios.get(`${this.apiEndpoint}/address/${this.wallet.address}/utxo`);
46
- const utxos = response.data;
47
- return utxos.reduce((sum, utxo) => sum + utxo.value, 0);
48
- }
49
- /**
50
- * Transfers Bitcoin to the vault address.
51
- *
52
- * @param {string} amount - The amount of BTC to transfer in BTC units
53
- * @param {number} feeRate - Fee rate in satoshis per byte
54
- * @returns {Promise<string>} - A promise that resolves to the transaction hash
55
- * @throws {Error} If there is not enough balance or if the transaction fails.
56
- */
57
- async transferBTC(amount, feeRate = 10) {
58
- // Convert BTC to satoshis
59
- const satoshisToSend = Math.floor(Number(amount) * 100_000_000);
60
- // Fetch deposit address
61
- const vault = await this.fetchVault();
62
- console.log({ vault });
63
- let retries = 0;
64
- const maxRetries = 5;
65
- let delay = 1000;
66
- const psbt = new bitcoin.Psbt({ network: this.network });
67
- const utxos = await this.getUTXOs();
68
- let inputAmount = 0;
69
- for (const utxo of utxos) {
70
- const transaction = bitcoin.Transaction.fromBuffer(utxo.rawTx);
71
- const script = transaction.outs[utxo.vout].script;
72
- const value = transaction.outs[utxo.vout].value;
73
- inputAmount += value;
74
- psbt.addInput({
75
- hash: utxo.txid,
76
- index: utxo.vout,
77
- // nonWitnessUtxo: utxo.rawTx,
78
- witnessUtxo: {
79
- script: script,
80
- value: value,
81
- },
82
- });
83
- if (inputAmount >= satoshisToSend)
84
- break;
85
- }
86
- if (inputAmount < satoshisToSend) {
87
- throw new Error("Insufficient UTXO amount");
88
- }
89
- // Add output for payment
90
- psbt.addOutput({
91
- // address: vault.address,
92
- address: "tb1q6h8w53xzj74n28kg8qq3d78xxgrch8zd2km97d",
93
- value: satoshisToSend,
94
- });
95
- // Add change output if necessary
96
- const estimatedFee = Math.ceil(psbt.toBuffer().length * feeRate);
97
- // Check wallet balance
98
- const balance = utxos.reduce((sum, utxo) => sum + utxo.value, 0);
99
- if (balance < satoshisToSend + estimatedFee) {
100
- throw new Error("Insufficient balance");
101
- }
102
- const changeAmount = inputAmount - satoshisToSend - estimatedFee;
103
- if (changeAmount > 0) {
104
- psbt.addOutput({
105
- address: this.wallet.address,
106
- value: changeAmount,
107
- });
108
- }
109
- console.log("psbt:", JSON.stringify(psbt));
110
- // Sign transaction
111
- const signedPsbt = await this.wallet.signTransaction(psbt);
112
- const tx = signedPsbt.finalizeAllInputs().extractTransaction();
113
- while (retries < maxRetries) {
114
- try {
115
- // Broadcast transaction
116
- return this.wallet.broadcastTransaction(tx.toHex());
117
- }
118
- catch (error) {
119
- console.debug("error: ", error);
120
- if (retries >= maxRetries) {
121
- throw error;
122
- }
123
- retries += 1;
124
- console.debug(`Retrying in ${delay / 1000} seconds...`);
125
- await new Promise((resolve) => setTimeout(resolve, delay));
126
- delay *= 2; // Exponential backoff
127
- }
128
- }
129
- throw new Error("Max retries reached");
130
- }
131
- /**
132
- * Gets the balance of the Bitcoin wallet.
133
- *
134
- * @returns {Promise<string>} - A promise that resolves to the wallet balance in BTC
135
- */
136
- async getWalletBalance() {
137
- try {
138
- const balanceSats = await this.getBalance();
139
- return (balanceSats / 100_000_000).toString();
140
- }
141
- catch (error) {
142
- console.debug("Error fetching BTC balance:", error);
143
- return "0";
144
- }
145
- }
146
- }