@flashbacktech/flashbackclient 0.1.28 → 0.1.31

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.
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ /**
3
+ * TypeScript models for FlashOnStellar V2 contract
4
+ * These models correspond to the Rust contract types
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.ErrorCode = exports.DataKey = exports.DealStatus = exports.BucketStatus = void 0;
8
+ var BucketStatus;
9
+ (function (BucketStatus) {
10
+ BucketStatus["Active"] = "Active";
11
+ BucketStatus["Inactive"] = "Inactive";
12
+ BucketStatus["Deleted"] = "Deleted";
13
+ })(BucketStatus || (exports.BucketStatus = BucketStatus = {}));
14
+ var DealStatus;
15
+ (function (DealStatus) {
16
+ DealStatus["Pending"] = "Pending";
17
+ DealStatus["Accepted"] = "Accepted";
18
+ DealStatus["Funded"] = "Funded";
19
+ DealStatus["Completed"] = "Completed";
20
+ DealStatus["Cancelled"] = "Cancelled";
21
+ DealStatus["BreachedConsumer"] = "BreachedConsumer";
22
+ DealStatus["BreachedProvider"] = "BreachedProvider";
23
+ })(DealStatus || (exports.DealStatus = DealStatus = {}));
24
+ var DataKey;
25
+ (function (DataKey) {
26
+ DataKey["Owner"] = "Owner";
27
+ DataKey["StableAssetAddress"] = "StableAssetAddress";
28
+ DataKey["Provider"] = "Provider";
29
+ DataKey["ProviderCount"] = "ProviderCount";
30
+ DataKey["ProviderMap"] = "ProviderMap";
31
+ DataKey["Consumer"] = "Consumer";
32
+ DataKey["ConsumerCount"] = "ConsumerCount";
33
+ DataKey["ConsumerMap"] = "ConsumerMap";
34
+ DataKey["Bucket"] = "Bucket";
35
+ DataKey["BucketCount"] = "BucketCount";
36
+ DataKey["BucketMap"] = "BucketMap";
37
+ DataKey["Deal"] = "Deal";
38
+ DataKey["DealCount"] = "DealCount";
39
+ DataKey["DealMap"] = "DealMap";
40
+ DataKey["ActiveDealMap"] = "ActiveDealMap";
41
+ })(DataKey || (exports.DataKey = DataKey = {}));
42
+ var ErrorCode;
43
+ (function (ErrorCode) {
44
+ ErrorCode["ConsumerAlreadyExists"] = "ConsumerAlreadyExists";
45
+ ErrorCode["ProviderAlreadyExists"] = "ProviderAlreadyExists";
46
+ ErrorCode["BucketAlreadyExists"] = "BucketAlreadyExists";
47
+ ErrorCode["BucketLocked"] = "BucketLocked";
48
+ // Add more error codes as needed
49
+ })(ErrorCode || (exports.ErrorCode = ErrorCode = {}));
@@ -0,0 +1,72 @@
1
+ import { ClientContext } from './client';
2
+ import { Provider } from './models';
3
+ /**
4
+ * Provider operations client for FlashOnStellar V2
5
+ * Implements all provider-related contract methods
6
+ */
7
+ export declare class ProviderOps {
8
+ private context;
9
+ constructor(context: ClientContext);
10
+ /**
11
+ * Registers a new provider in the system
12
+ * @param provider_id - Address of the provider to register
13
+ * @param description - Description of the provider
14
+ * @returns Promise resolving to the registration result
15
+ */
16
+ registerProvider(provider_id: string, description: string): Promise<boolean>;
17
+ /**
18
+ * Updates an existing provider's information
19
+ * @param provider_id - Address of the provider to update
20
+ * @param description - New description for the provider
21
+ * @returns Promise resolving to the update result
22
+ */
23
+ updateProvider(provider_id: string, description: string): Promise<boolean>;
24
+ /**
25
+ * Deletes a provider from the system
26
+ * @param provider_id - Address of the provider to delete
27
+ * @returns Promise resolving to the deletion result
28
+ */
29
+ deleteProvider(provider_id: string): Promise<boolean>;
30
+ /**
31
+ * Retrieves provider information
32
+ * @param provider_id - Address of the provider to retrieve
33
+ * @returns Promise resolving to Provider object or null if not found
34
+ */
35
+ getProvider(provider_id: string): Promise<Provider | null>;
36
+ /**
37
+ * Gets the total count of providers in the system
38
+ * @returns Promise resolving to the total number of providers
39
+ */
40
+ getProviderCount(): Promise<number>;
41
+ /**
42
+ * Retrieves a paginated list of providers
43
+ * @param skip - Number of items to skip for pagination
44
+ * @param take - Number of items to take per page
45
+ * @returns Promise resolving to a map of provider addresses to Provider objects
46
+ */
47
+ getProviders(skip?: number, take?: number): Promise<Map<string, Provider>>;
48
+ /**
49
+ * Gets all buckets associated with a provider
50
+ * @param provider_id - Address of the provider
51
+ * @returns Promise resolving to an array of bucket IDs
52
+ */
53
+ getProviderBuckets(provider_id: string): Promise<string[]>;
54
+ /**
55
+ * Gets all deals associated with a provider
56
+ * @param provider_id - Address of the provider
57
+ * @returns Promise resolving to an array of deal IDs
58
+ */
59
+ getProviderDeals(provider_id: string): Promise<string[]>;
60
+ /**
61
+ * Gets all active deals associated with a provider
62
+ * @param provider_id - Address of the provider
63
+ * @returns Promise resolving to an array of active deal IDs
64
+ */
65
+ getProviderActiveDeals(provider_id: string): Promise<string[]>;
66
+ /**
67
+ * Gets the total number of units (buckets) owned by a provider
68
+ * @param provider_id - Address of the provider
69
+ * @returns Promise resolving to the total number of units
70
+ */
71
+ getProviderUnitsCount(provider_id: string): Promise<number>;
72
+ }
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ProviderOps = void 0;
4
+ const transaction_1 = require("./transaction");
5
+ /**
6
+ * Provider operations client for FlashOnStellar V2
7
+ * Implements all provider-related contract methods
8
+ */
9
+ class ProviderOps {
10
+ constructor(context) {
11
+ this.context = context;
12
+ }
13
+ /**
14
+ * Registers a new provider in the system
15
+ * @param provider_id - Address of the provider to register
16
+ * @param description - Description of the provider
17
+ * @returns Promise resolving to the registration result
18
+ */
19
+ async registerProvider(provider_id, description) {
20
+ return (0, transaction_1.callContractMethod)(this.context, provider_id, {
21
+ method: 'register_provider',
22
+ args: [
23
+ { value: provider_id, type: 'address' },
24
+ { value: description, type: 'string' }
25
+ ]
26
+ });
27
+ }
28
+ /**
29
+ * Updates an existing provider's information
30
+ * @param provider_id - Address of the provider to update
31
+ * @param description - New description for the provider
32
+ * @returns Promise resolving to the update result
33
+ */
34
+ async updateProvider(provider_id, description) {
35
+ return (0, transaction_1.callContractMethod)(this.context, provider_id, {
36
+ method: 'update_provider',
37
+ args: [
38
+ { value: provider_id, type: 'address' },
39
+ { value: description, type: 'string' }
40
+ ]
41
+ });
42
+ }
43
+ /**
44
+ * Deletes a provider from the system
45
+ * @param provider_id - Address of the provider to delete
46
+ * @returns Promise resolving to the deletion result
47
+ */
48
+ async deleteProvider(provider_id) {
49
+ return (0, transaction_1.callContractMethod)(this.context, provider_id, {
50
+ method: 'delete_provider',
51
+ args: [
52
+ { value: provider_id, type: 'address' }
53
+ ]
54
+ });
55
+ }
56
+ /**
57
+ * Retrieves provider information
58
+ * @param provider_id - Address of the provider to retrieve
59
+ * @returns Promise resolving to Provider object or null if not found
60
+ */
61
+ async getProvider(provider_id) {
62
+ const result = await (0, transaction_1.callContractMethod)(this.context, provider_id, {
63
+ method: 'get_provider',
64
+ args: [
65
+ { value: provider_id, type: 'address' }
66
+ ]
67
+ });
68
+ if (result && typeof result === 'object') {
69
+ return result;
70
+ }
71
+ return null;
72
+ }
73
+ /**
74
+ * Gets the total count of providers in the system
75
+ * @returns Promise resolving to the total number of providers
76
+ */
77
+ async getProviderCount() {
78
+ const result = await (0, transaction_1.callContractMethod)(this.context, '', {
79
+ method: 'get_provider_count',
80
+ args: []
81
+ });
82
+ if (typeof result === 'number') {
83
+ return result;
84
+ }
85
+ return 0;
86
+ }
87
+ /**
88
+ * Retrieves a paginated list of providers
89
+ * @param skip - Number of items to skip for pagination
90
+ * @param take - Number of items to take per page
91
+ * @returns Promise resolving to a map of provider addresses to Provider objects
92
+ */
93
+ async getProviders(skip = 0, take = 10) {
94
+ const result = await (0, transaction_1.callContractMethod)(this.context, '', {
95
+ method: 'get_providers',
96
+ args: [
97
+ { value: skip, type: 'u32' },
98
+ { value: take, type: 'u32' }
99
+ ]
100
+ });
101
+ if (result && typeof result === 'object') {
102
+ // Convert the result to a Map<string, Provider>
103
+ const providerMap = new Map();
104
+ // Note: The actual conversion depends on how the contract returns the data
105
+ // This is a placeholder implementation
106
+ return providerMap;
107
+ }
108
+ return new Map();
109
+ }
110
+ /**
111
+ * Gets all buckets associated with a provider
112
+ * @param provider_id - Address of the provider
113
+ * @returns Promise resolving to an array of bucket IDs
114
+ */
115
+ async getProviderBuckets(provider_id) {
116
+ const provider = await this.getProvider(provider_id);
117
+ if (!provider) {
118
+ return [];
119
+ }
120
+ // Extract bucket IDs from the provider's buckets map
121
+ const bucketIds = [];
122
+ provider.buckets.forEach((_, bucketId) => {
123
+ bucketIds.push(bucketId);
124
+ });
125
+ return bucketIds;
126
+ }
127
+ /**
128
+ * Gets all deals associated with a provider
129
+ * @param provider_id - Address of the provider
130
+ * @returns Promise resolving to an array of deal IDs
131
+ */
132
+ async getProviderDeals(provider_id) {
133
+ const provider = await this.getProvider(provider_id);
134
+ if (!provider) {
135
+ return [];
136
+ }
137
+ // Extract deal IDs from the provider's deals map
138
+ const dealIds = [];
139
+ provider.deals.forEach((_, dealId) => {
140
+ dealIds.push(dealId);
141
+ });
142
+ return dealIds;
143
+ }
144
+ /**
145
+ * Gets all active deals associated with a provider
146
+ * @param provider_id - Address of the provider
147
+ * @returns Promise resolving to an array of active deal IDs
148
+ */
149
+ async getProviderActiveDeals(provider_id) {
150
+ const provider = await this.getProvider(provider_id);
151
+ if (!provider) {
152
+ return [];
153
+ }
154
+ // Extract active deal IDs from the provider's active_deals map
155
+ const activeDealIds = [];
156
+ provider.active_deals.forEach((_, dealId) => {
157
+ activeDealIds.push(dealId);
158
+ });
159
+ return activeDealIds;
160
+ }
161
+ /**
162
+ * Gets the total number of units (buckets) owned by a provider
163
+ * @param provider_id - Address of the provider
164
+ * @returns Promise resolving to the total number of units
165
+ */
166
+ async getProviderUnitsCount(provider_id) {
167
+ const provider = await this.getProvider(provider_id);
168
+ if (!provider) {
169
+ return 0;
170
+ }
171
+ return provider.units_count;
172
+ }
173
+ }
174
+ exports.ProviderOps = ProviderOps;
@@ -0,0 +1,36 @@
1
+ import { Transaction, Memo, MemoType, Operation, FeeBumpTransaction } from '@stellar/stellar-sdk';
2
+ interface ClientContext {
3
+ network: StellarNetwork;
4
+ signTransaction?: (xdrToSign: string) => Promise<string>;
5
+ contractAddress: string;
6
+ }
7
+ interface StellarNetwork {
8
+ network: string;
9
+ networkPassphrase: string;
10
+ }
11
+ declare const getNetwork: (network: string) => StellarNetwork;
12
+ declare const getPublicKeyFromPrivateKey: (privateKey: string) => string;
13
+ interface ContractMethodCall {
14
+ method: string;
15
+ args?: Array<{
16
+ value: number | string | bigint | boolean | null | undefined;
17
+ type: 'u32' | 'i32' | 'u64' | 'i64' | 'u128' | 'i128' | 'string' | 'symbol' | 'address' | 'bool';
18
+ }>;
19
+ }
20
+ interface ContractMethodResponse {
21
+ isSuccess: boolean;
22
+ isReadOnly: boolean;
23
+ result: string | unknown;
24
+ }
25
+ declare const prepareTransaction: (context: ClientContext, address: string, contractCall: ContractMethodCall) => Promise<ContractMethodResponse>;
26
+ declare const signTransaction: (context: ClientContext, xdrToSign: string, privateKey: string) => Promise<Transaction<Memo<MemoType>, Operation[]> | FeeBumpTransaction>;
27
+ declare const sendTransaction: (context: ClientContext, signedTransactionXDR: string) => Promise<any>;
28
+ /**
29
+ * Calls a contract method and handles the transaction flow
30
+ * @param context - Client context
31
+ * @param address - Address to use for the transaction
32
+ * @param contractCall - Contract method call details
33
+ * @returns Promise resolving to the method result
34
+ */
35
+ declare const callContractMethod: (context: ClientContext, address: string, contractCall: ContractMethodCall) => Promise<any>;
36
+ export { prepareTransaction, sendTransaction, signTransaction, callContractMethod, getNetwork, StellarNetwork, getPublicKeyFromPrivateKey, };
@@ -0,0 +1,168 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getPublicKeyFromPrivateKey = exports.getNetwork = exports.callContractMethod = exports.signTransaction = exports.sendTransaction = exports.prepareTransaction = void 0;
4
+ const timing_js_1 = require("../utils/timing.js");
5
+ // Polyfill for BigInt JSON serialization
6
+ BigInt.prototype.toJSON = function () {
7
+ return this.toString();
8
+ };
9
+ const stellar_sdk_1 = require("@stellar/stellar-sdk");
10
+ const stellar_sdk_2 = require("@stellar/stellar-sdk");
11
+ const getNetwork = (network) => {
12
+ let networkPassphrase = '';
13
+ switch (network) {
14
+ case 'TESTNET':
15
+ networkPassphrase = 'Test SDF Network ; September 2015';
16
+ break;
17
+ case 'PUBLIC':
18
+ networkPassphrase = 'Public Global Stellar Network ; September 2015';
19
+ break;
20
+ }
21
+ return { network, networkPassphrase };
22
+ };
23
+ exports.getNetwork = getNetwork;
24
+ const getPublicKeyFromPrivateKey = (privateKey) => {
25
+ const keypair = stellar_sdk_1.Keypair.fromSecret(privateKey);
26
+ return keypair.publicKey();
27
+ };
28
+ exports.getPublicKeyFromPrivateKey = getPublicKeyFromPrivateKey;
29
+ const getServer = (network) => {
30
+ let serverUrl = '';
31
+ switch (network.network) {
32
+ case 'TESTNET':
33
+ serverUrl = 'https://soroban-testnet.stellar.org:443';
34
+ break;
35
+ case 'PUBLIC':
36
+ serverUrl = 'https://rpc.stellar.org:443';
37
+ break;
38
+ }
39
+ const server = new stellar_sdk_2.rpc.Server(serverUrl);
40
+ return server;
41
+ };
42
+ const TIMEOUT_TRANSACTION = 60;
43
+ const prepareTransaction = async (context, address, contractCall) => {
44
+ const contractAddress = context.contractAddress;
45
+ const contract = new stellar_sdk_1.Contract(contractAddress);
46
+ const server = getServer(context.network);
47
+ const sourceAccount = await server.getAccount(address);
48
+ const response = {
49
+ isSuccess: false,
50
+ isReadOnly: false,
51
+ result: '',
52
+ };
53
+ // Convert raw values to ScVal
54
+ const convertedArgs = contractCall.args?.map((arg) => (0, stellar_sdk_1.nativeToScVal)(arg.value, { type: arg.type })) || [];
55
+ const builtTransaction = new stellar_sdk_1.TransactionBuilder(sourceAccount, {
56
+ fee: stellar_sdk_1.BASE_FEE,
57
+ networkPassphrase: context.network.networkPassphrase,
58
+ })
59
+ .addOperation(contract.call(contractCall.method, ...convertedArgs))
60
+ .setTimeout(TIMEOUT_TRANSACTION)
61
+ .build();
62
+ const sim = await server.simulateTransaction(builtTransaction);
63
+ if (stellar_sdk_2.rpc.Api.isSimulationSuccess(sim)) {
64
+ response.isSuccess = true;
65
+ //console.log('Simulation success:', JSON.stringify(sim));
66
+ const result = sim.result && sim.result.retval ? (0, stellar_sdk_1.scValToNative)(sim.result.retval) : undefined;
67
+ const footprint = sim.transactionData.getFootprint();
68
+ const isReadOnly = footprint.readOnly().length > 0 && footprint.readWrite().length === 0;
69
+ if (isReadOnly) {
70
+ response.isReadOnly = true;
71
+ response.result = result;
72
+ return response;
73
+ }
74
+ // For write operations, continue with the normal flow of returning the XDR
75
+ const preparedTransaction = await server.prepareTransaction(builtTransaction);
76
+ response.result = preparedTransaction.toXDR();
77
+ return response;
78
+ }
79
+ else {
80
+ if (stellar_sdk_2.rpc.Api.isSimulationError(sim)) {
81
+ throw new Error(`Tansaction simulation error: ${JSON.stringify(sim.error)}`);
82
+ }
83
+ throw new Error('Transaction simulation failed');
84
+ }
85
+ };
86
+ exports.prepareTransaction = prepareTransaction;
87
+ const signTransaction = async (context, xdrToSign, privateKey) => {
88
+ const preparedTransaction = stellar_sdk_1.TransactionBuilder.fromXDR(xdrToSign, context.network.networkPassphrase);
89
+ const sourceKeypair = stellar_sdk_1.Keypair.fromSecret(privateKey);
90
+ preparedTransaction.sign(sourceKeypair);
91
+ return preparedTransaction;
92
+ };
93
+ exports.signTransaction = signTransaction;
94
+ const sendTransaction = async (context, signedTransactionXDR) => {
95
+ const server = getServer(context.network);
96
+ const signedTransaction = stellar_sdk_1.TransactionBuilder.fromXDR(signedTransactionXDR, context.network.networkPassphrase);
97
+ // Submit the transaction to the Stellar-RPC server. The RPC server will
98
+ // then submit the transaction into the network for us. Then we will have to
99
+ // wait, polling `getTransaction` until the transaction completes.
100
+ try {
101
+ const sendResponse = await server.sendTransaction(signedTransaction);
102
+ if (sendResponse.status === 'PENDING') {
103
+ let getResponse = await server.getTransaction(sendResponse.hash);
104
+ // Poll `getTransaction` until the status is not "NOT_FOUND"
105
+ while (getResponse.status === 'NOT_FOUND') {
106
+ // See if the transaction is complete
107
+ getResponse = await server.getTransaction(sendResponse.hash);
108
+ // Wait one second
109
+ await (0, timing_js_1.sleep)(1000);
110
+ }
111
+ //console.log(`getTransaction response: ${JSON.stringify(getResponse)}`);
112
+ if (getResponse.status === 'SUCCESS') {
113
+ // Make sure the transaction's resultMetaXDR is not empty
114
+ if (!getResponse.resultMetaXdr) {
115
+ throw new Error('Empty resultMetaXDR in getTransaction response');
116
+ }
117
+ // Find the return value from the contract and return it
118
+ const transactionMeta = getResponse.resultMetaXdr;
119
+ const returnValue = transactionMeta.v3().sorobanMeta()?.returnValue();
120
+ if (returnValue) {
121
+ return (0, stellar_sdk_1.scValToNative)(returnValue);
122
+ }
123
+ }
124
+ else {
125
+ throw new Error(`Transaction failed: ${getResponse.resultXdr}`);
126
+ }
127
+ }
128
+ else {
129
+ throw new Error(sendResponse.errorResult?.toString() || 'Unknown error');
130
+ }
131
+ }
132
+ catch (err) {
133
+ // Catch and report any errors we've thrown
134
+ throw new Error(`Transaction sending error: ${JSON.stringify(err)}`);
135
+ }
136
+ };
137
+ exports.sendTransaction = sendTransaction;
138
+ /**
139
+ * Calls a contract method and handles the transaction flow
140
+ * @param context - Client context
141
+ * @param address - Address to use for the transaction
142
+ * @param contractCall - Contract method call details
143
+ * @returns Promise resolving to the method result
144
+ */
145
+ const callContractMethod = async (context, address, contractCall) => {
146
+ try {
147
+ // Prepare the transaction
148
+ const preparedResponse = await prepareTransaction(context, address, contractCall);
149
+ if (preparedResponse.isReadOnly) {
150
+ // For read-only operations, return the result directly
151
+ return preparedResponse.result;
152
+ }
153
+ // For write operations, we need to sign and send the transaction
154
+ if (!context.signTransaction) {
155
+ throw new Error('Sign transaction callback required for write operations');
156
+ }
157
+ // Sign the transaction
158
+ const signedXDR = await context.signTransaction(preparedResponse.result);
159
+ // Send the signed transaction
160
+ const result = await sendTransaction(context, signedXDR);
161
+ return result;
162
+ }
163
+ catch (error) {
164
+ console.error('Error calling contract method:', error);
165
+ throw error;
166
+ }
167
+ };
168
+ exports.callContractMethod = callContractMethod;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flashbacktech/flashbackclient",
3
- "version": "0.1.28",
3
+ "version": "0.1.31",
4
4
  "type": "commonjs",
5
5
  "publishConfig": {
6
6
  "access": "public"