@streamflow/stream 5.4.0 → 5.6.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/README.md CHANGED
@@ -426,12 +426,11 @@ try {
426
426
 
427
427
  ## Handling errors
428
428
 
429
- Protocol raises custom errors on:
430
-
431
- - validation errors
432
- - state missmatch errors (such as canceling a stream that is complete/already canceled)
433
-
434
- Errors are returned per blockchain specification format.
429
+ `GenericStreamClient` wraps all errors when making on-chain calls with `ContractError` error class:
430
+ - this class inherits original traceback
431
+ - error may optionally contain `contractErrorCode` property that can be further mapped to a specific **Contract** error
432
+ - for `createMultiple` method errors are wrapped individually for every recipient address
433
+ - please check documentation for common enums `ContractErrorCode` and `SolanaContractErrorCode` to see short description for each error
435
434
 
436
435
  A public map of protocol errors is available [here](https://streamflow.notion.site/Streamflow-protocol-docs-0accad86d5c44e5db84fd4fb49b8ff54).
437
436
 
@@ -39,6 +39,7 @@ export default class AptosStreamClient extends BaseStreamClient {
39
39
  * Attempts updating the stream auto withdrawal params and amount per period
40
40
  */
41
41
  update(updateData: IUpdateData, { senderWallet, tokenId }: ITransactionAptosExt): Promise<ITransactionResult>;
42
+ extractErrorCode(err: Error): string | null;
42
43
  /**
43
44
  * Returns StreamClient protocol program ID.
44
45
  */
@@ -84,6 +84,7 @@ var types_1 = require("../common/types");
84
84
  var constants_1 = require("./constants");
85
85
  var types_2 = require("./types");
86
86
  var wallet_1 = require("./wallet");
87
+ var utils_1 = require("./utils");
87
88
  var AptosStreamClient = /** @class */ (function (_super) {
88
89
  __extends(AptosStreamClient, _super);
89
90
  function AptosStreamClient(clusterUrl, cluster, maxGas, programId) {
@@ -332,6 +333,10 @@ var AptosStreamClient = /** @class */ (function (_super) {
332
333
  });
333
334
  });
334
335
  };
336
+ AptosStreamClient.prototype.extractErrorCode = function (err) {
337
+ var _a;
338
+ return (0, utils_1.extractAptosErrorCode)((_a = err.toString()) !== null && _a !== void 0 ? _a : "Unknown error!");
339
+ };
335
340
  /**
336
341
  * Returns StreamClient protocol program ID.
337
342
  */
@@ -348,7 +353,6 @@ var AptosStreamClient = /** @class */ (function (_super) {
348
353
  var acc = new aptos_1.AptosAccount(); // Generate random address as seeds for deriving "escrow" account
349
354
  var seeds = acc.address();
350
355
  var metadataId = aptos_1.AptosAccount.getResourceAccountAddress(wallet.address, seeds.toUint8Array());
351
- console.log(seeds);
352
356
  return [
353
357
  metadataId.toString(),
354
358
  {
@@ -1,2 +1,8 @@
1
1
  import { ICluster } from "../common/types";
2
2
  export declare const APTOS_PROGRAM_IDS: Record<ICluster, string>;
3
+ export declare const APTOS_ERROR_MATCH_REGEX: RegExp;
4
+ export declare const APTOS_MODULE_ERROR_MAP: {
5
+ [key: string]: {
6
+ [key: number]: string;
7
+ };
8
+ };
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  var _a;
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.APTOS_PROGRAM_IDS = void 0;
4
+ exports.APTOS_MODULE_ERROR_MAP = exports.APTOS_ERROR_MATCH_REGEX = exports.APTOS_PROGRAM_IDS = void 0;
5
5
  var types_1 = require("../common/types");
6
6
  exports.APTOS_PROGRAM_IDS = (_a = {},
7
7
  _a[types_1.ICluster.Mainnet] = "0x9009d93d52576bf9ac6dc6cf10b870610bcb316342fef6eff80662fbbfce51b0",
@@ -10,3 +10,19 @@ exports.APTOS_PROGRAM_IDS = (_a = {},
10
10
  _a[types_1.ICluster.Testnet] = "0xc6737de143d91b2f99a7e490d4f8348fdfa3bdd1eb8737a27d0455f8a3625688",
11
11
  _a[types_1.ICluster.Local] = "0x9009d93d52576bf9ac6dc6cf10b870610bcb316342fef6eff80662fbbfce51b0",
12
12
  _a);
13
+ exports.APTOS_ERROR_MATCH_REGEX = /Move abort in [a-z0-9]+::([^:]+): ([A-Z_]+)/;
14
+ exports.APTOS_MODULE_ERROR_MAP = {
15
+ protocol: {
16
+ 1: types_1.ContractErrorCode.ECONTRACT_NOT_INIT,
17
+ 2: types_1.ContractErrorCode.EBAD_AMOUNT,
18
+ 3: types_1.ContractErrorCode.ENO_PERMISSIONS,
19
+ 4: types_1.ContractErrorCode.EBADINPUT,
20
+ 5: types_1.ContractErrorCode.ECLOSED,
21
+ 6: types_1.ContractErrorCode.EBAD_INPUT_AMOUNT_PER_PERIOD,
22
+ 8: types_1.ContractErrorCode.EBAD_INPUT_UPDATE_RATE,
23
+ 9: types_1.ContractErrorCode.EBAD_INPUT_CLIFF_AMOUNT,
24
+ 10: types_1.ContractErrorCode.EBAD_INPUT_PERIOD,
25
+ 11: types_1.ContractErrorCode.EBAD_INPUT_START,
26
+ 12: types_1.ContractErrorCode.ENO_RECIPIENT_COIN_ADDRESS,
27
+ },
28
+ };
@@ -0,0 +1 @@
1
+ export declare function extractAptosErrorCode(errorText: string): string | null;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.extractAptosErrorCode = void 0;
4
+ var constants_1 = require("./constants");
5
+ function extractAptosErrorCode(errorText) {
6
+ var match = constants_1.APTOS_ERROR_MATCH_REGEX.exec(errorText);
7
+ if (!match) {
8
+ return null;
9
+ }
10
+ return match[2];
11
+ }
12
+ exports.extractAptosErrorCode = extractAptosErrorCode;
@@ -51,29 +51,35 @@ var AptosWalletWrapper = /** @class */ (function () {
51
51
  }
52
52
  AptosWalletWrapper.prototype.signAndSubmitTransaction = function (input) {
53
53
  return __awaiter(this, void 0, void 0, function () {
54
- var builder, rawTxn, signedTx, tx;
54
+ var builder, rawTxn, res, signedTx, tx;
55
55
  return __generator(this, function (_a) {
56
56
  switch (_a.label) {
57
57
  case 0:
58
- if (!(this.wallet instanceof aptos_1.AptosAccount)) return [3 /*break*/, 5];
58
+ if (!(this.wallet instanceof aptos_1.AptosAccount)) return [3 /*break*/, 6];
59
59
  builder = new aptos_1.TransactionBuilderRemoteABI(this.client, {
60
60
  sender: this.address,
61
61
  });
62
62
  return [4 /*yield*/, builder.build(input.function, input.type_arguments, input.arguments)];
63
63
  case 1:
64
64
  rawTxn = _a.sent();
65
- return [4 /*yield*/, this.client.signTransaction(this.wallet, rawTxn)];
65
+ return [4 /*yield*/, this.client.simulateTransaction(this.wallet, rawTxn)];
66
66
  case 2:
67
+ res = _a.sent();
68
+ if (!res[0].success) {
69
+ throw new Error("Transaction Simulation failed: ".concat(JSON.stringify(res)));
70
+ }
71
+ return [4 /*yield*/, this.client.signTransaction(this.wallet, rawTxn)];
72
+ case 3:
67
73
  signedTx = _a.sent();
68
74
  return [4 /*yield*/, this.client.submitSignedBCSTransaction(signedTx)];
69
- case 3:
75
+ case 4:
70
76
  tx = _a.sent();
71
77
  return [4 /*yield*/, this.client.waitForTransaction(tx.hash)];
72
- case 4:
78
+ case 5:
73
79
  _a.sent();
74
80
  return [2 /*return*/, tx.hash];
75
- case 5: return [4 /*yield*/, this.wallet.signAndSubmitTransaction(input)];
76
- case 6: return [2 /*return*/, (_a.sent()).hash];
81
+ case 6: return [4 /*yield*/, this.wallet.signAndSubmitTransaction(input)];
82
+ case 7: return [2 /*return*/, (_a.sent()).hash];
77
83
  }
78
84
  });
79
85
  });
@@ -9,4 +9,5 @@ export declare abstract class BaseStreamClient {
9
9
  protected abstract getOne(getOneData: IGetOneData, chainSpecificParams: any): Promise<Stream>;
10
10
  protected abstract get(getAllData: IGetAllData, chainSpecificParams: any): Promise<[string, Stream][]>;
11
11
  protected abstract update(updateData: IUpdateData, chainSpecificParams: any): Promise<ITransactionResult>;
12
+ extractErrorCode(err: Error): string | null;
12
13
  }
@@ -4,6 +4,10 @@ exports.BaseStreamClient = void 0;
4
4
  var BaseStreamClient = /** @class */ (function () {
5
5
  function BaseStreamClient() {
6
6
  }
7
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
8
+ BaseStreamClient.prototype.extractErrorCode = function (err) {
9
+ return null;
10
+ };
7
11
  return BaseStreamClient;
8
12
  }());
9
13
  exports.BaseStreamClient = BaseStreamClient;
@@ -33,12 +33,22 @@ export interface SuiStreamClientOptions {
33
33
  cluster?: ICluster;
34
34
  ids?: ISuiIdParameters;
35
35
  }
36
+ /** Type referencing options for specific Chain Client */
36
37
  declare type StreamClientOptions<T extends IChain> = T extends IChain.Solana ? SolanaStreamClientOptions : T extends IChain.Aptos ? AptosStreamClientOptions : T extends IChain.Sui ? SuiStreamClientOptions : EvmStreamClientOptions;
38
+ /** Type referencing Chain Client implementation */
37
39
  declare type StreamClientType<T extends IChain> = T extends IChain.Solana ? SolanaStreamClient : T extends IChain.Aptos ? AptosStreamClient : T extends IChain.Sui ? SuiStreamClient : EvmStreamClient;
40
+ /** Type referencing additional parameters used by a Chain Client */
38
41
  declare type ChainSpecificParams<T, SolanaExt, AptosExt, SuiExt> = T extends SolanaStreamClient ? SolanaExt : T extends AptosStreamClient ? AptosExt : T extends SuiStreamClient ? SuiExt : undefined;
42
+ /** Type referencing additional parameters used on Create by a Chain Client */
39
43
  declare type CreateSpecificParams<T extends IChain> = ChainSpecificParams<StreamClientType<T>, ICreateStreamSolanaExt, ICreateStreamAptosExt, ICreateStreamSuiExt>;
44
+ /** Type referencing additional parameters used on Topup by a Chain Client */
40
45
  declare type TopupSpecificParams<T extends IChain> = ChainSpecificParams<StreamClientType<T>, ITopUpStreamSolanaExt, ITransactionAptosExt, ITransactionSuiExt>;
46
+ /** Type referencing additional parameters used on other interactions by a Chain Client */
41
47
  declare type InteractSpecificParams<T extends IChain> = ChainSpecificParams<StreamClientType<T>, IInteractStreamSolanaExt, ITransactionAptosExt, ITransactionSuiExt>;
48
+ /** Generic Stream Client implementation that wrap Chain Client methods and enriches error messages if possible
49
+ * @property {StreamClientType} - Chain Client implementation
50
+ * @property {chain} - Chain
51
+ */
42
52
  export default class GenericStreamClient<T extends IChain> extends BaseStreamClient {
43
53
  nativeStreamClient: StreamClientType<T>;
44
54
  chain: IChain;
@@ -17,10 +17,15 @@ var __extends = (this && this.__extends) || (function () {
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  var BaseStreamClient_1 = require("./BaseStreamClient");
19
19
  var types_1 = require("./types");
20
+ var utils_1 = require("./utils");
20
21
  var aptos_1 = require("../aptos");
21
22
  var evm_1 = require("../evm");
22
23
  var solana_1 = require("../solana");
23
24
  var sui_1 = require("../sui");
25
+ /** Generic Stream Client implementation that wrap Chain Client methods and enriches error messages if possible
26
+ * @property {StreamClientType} - Chain Client implementation
27
+ * @property {chain} - Chain
28
+ */
24
29
  var GenericStreamClient = /** @class */ (function (_super) {
25
30
  __extends(GenericStreamClient, _super);
26
31
  function GenericStreamClient(options) {
@@ -47,37 +52,43 @@ var GenericStreamClient = /** @class */ (function (_super) {
47
52
  * Creates a new stream/vesting contract.
48
53
  */
49
54
  GenericStreamClient.prototype.create = function (streamData, chainSpecificParams) {
50
- return this.nativeStreamClient.create(streamData, chainSpecificParams);
55
+ var _this = this;
56
+ return (0, utils_1.handleContractError)(function () { return _this.nativeStreamClient.create(streamData, chainSpecificParams); }, this.nativeStreamClient.extractErrorCode);
51
57
  };
52
58
  /**
53
59
  * Creates multiple stream/vesting contracts.
54
60
  */
55
61
  GenericStreamClient.prototype.createMultiple = function (multipleStreamData, chainSpecificParams) {
56
- return this.nativeStreamClient.createMultiple(multipleStreamData, chainSpecificParams);
62
+ var _this = this;
63
+ return (0, utils_1.handleContractError)(function () { return _this.nativeStreamClient.createMultiple(multipleStreamData, chainSpecificParams); }, this.nativeStreamClient.extractErrorCode);
57
64
  };
58
65
  /**
59
66
  * Attempts withdrawing from the specified stream.
60
67
  */
61
68
  GenericStreamClient.prototype.withdraw = function (withdrawData, chainSpecificParams) {
62
- return this.nativeStreamClient.withdraw(withdrawData, chainSpecificParams);
69
+ var _this = this;
70
+ return (0, utils_1.handleContractError)(function () { return _this.nativeStreamClient.withdraw(withdrawData, chainSpecificParams); }, this.nativeStreamClient.extractErrorCode);
63
71
  };
64
72
  /**
65
73
  * Attempts canceling the specified stream.
66
74
  */
67
75
  GenericStreamClient.prototype.cancel = function (cancelData, chainSpecificParams) {
68
- return this.nativeStreamClient.cancel(cancelData, chainSpecificParams);
76
+ var _this = this;
77
+ return (0, utils_1.handleContractError)(function () { return _this.nativeStreamClient.cancel(cancelData, chainSpecificParams); }, this.nativeStreamClient.extractErrorCode);
69
78
  };
70
79
  /**
71
80
  * Attempts changing the stream/vesting contract's recipient (effectively transferring the stream/vesting contract).
72
81
  */
73
82
  GenericStreamClient.prototype.transfer = function (transferData, chainSpecificParams) {
74
- return this.nativeStreamClient.transfer(transferData, chainSpecificParams);
83
+ var _this = this;
84
+ return (0, utils_1.handleContractError)(function () { return _this.nativeStreamClient.transfer(transferData, chainSpecificParams); }, this.nativeStreamClient.extractErrorCode);
75
85
  };
76
86
  /**
77
87
  * Tops up stream account with specified amount.
78
88
  */
79
89
  GenericStreamClient.prototype.topup = function (topupData, chainSpecificParams) {
80
- return this.nativeStreamClient.topup(topupData, chainSpecificParams);
90
+ var _this = this;
91
+ return (0, utils_1.handleContractError)(function () { return _this.nativeStreamClient.topup(topupData, chainSpecificParams); }, this.nativeStreamClient.extractErrorCode);
81
92
  };
82
93
  /**
83
94
  * Fetch stream data by its id (address).
@@ -95,7 +106,8 @@ var GenericStreamClient = /** @class */ (function (_super) {
95
106
  * Attempts updating the stream auto withdrawal params and amount per period
96
107
  */
97
108
  GenericStreamClient.prototype.update = function (updateData, chainSpecificParams) {
98
- return this.nativeStreamClient.update(updateData, chainSpecificParams);
109
+ var _this = this;
110
+ return (0, utils_1.handleContractError)(function () { return _this.nativeStreamClient.update(updateData, chainSpecificParams); }, this.nativeStreamClient.extractErrorCode);
99
111
  };
100
112
  return GenericStreamClient;
101
113
  }(BaseStreamClient_1.BaseStreamClient));
@@ -60,6 +60,7 @@ export interface IGetAllData {
60
60
  export interface ICreateMultiError {
61
61
  recipient: string;
62
62
  error: string;
63
+ contractErrorCode?: string;
63
64
  }
64
65
  declare type MetadataId = string;
65
66
  export interface ITransactionResult {
@@ -100,6 +101,96 @@ export declare enum IChain {
100
101
  Polygon = "Polygon",
101
102
  Sui = "Sui"
102
103
  }
104
+ /**
105
+ * Error codes raised by all protocols except for Solana
106
+ */
107
+ export declare enum ContractErrorCode {
108
+ /** Contract does not exist */
109
+ ECONTRACT_NOT_INIT = "ECONTRACT_NOT_INIT",
110
+ /** Invalid total amount */
111
+ EBAD_AMOUNT = "EBAD_AMOUNT",
112
+ /** No permissions to perform an operation */
113
+ ENO_PERMISSIONS = "ENO_PERMISSIONS",
114
+ /** Invalid input parameters on create/update */
115
+ EBADINPUT = "EBADINPUT",
116
+ /** Contract is already ended */
117
+ ECLOSED = "ECLOSED",
118
+ /** Invalid amount per period input */
119
+ EBAD_INPUT_AMOUNT_PER_PERIOD = "EBAD_INPUT_AMOUNT_PER_PERIOD",
120
+ /** Pause feature is not supported */
121
+ EBAD_INPUT_PAUSABLE = "EBAD_INPUT_PAUSABLE",
122
+ /** Not used currently */
123
+ EBAD_INPUT_UPDATE_RATE = "EBAD_INPUT_UPDATE_RATE",
124
+ /** Invalid cliff amount input */
125
+ EBAD_INPUT_CLIFF_AMOUNT = "EBAD_INPUT_CLIFF_AMOUNT",
126
+ /** Invalid period input */
127
+ EBAD_INPUT_PERIOD = "EBAD_INPUT_PERIOD",
128
+ /** Invalid start time of the contract */
129
+ EBAD_INPUT_START = "EBAD_INPUT_START",
130
+ /** EVM: token allowance is not enough to create a Contract */
131
+ EBAD_INSUFFICIENT_TOKEN_ALLOWANCE = "EBAD_INSUFFICIENT_TOKEN_ALLOWANCE",
132
+ /** EVM: not enough coins were passed for withdrawal fees */
133
+ EBAD_INSUFFICIENT_WITHDRAWAL_FEES = "EBAD_INSUFFICIENT_WITHDRAWAL_FEES",
134
+ /** Sui: Insufficient amount of tokens passed */
135
+ EBAD_INSUFFICIENT_AMOUNT = "EBAD_INSUFFICIENT_AMOUNT",
136
+ /** Contract is already paused */
137
+ EPAUSED = "EPAUSED",
138
+ /** Contract is not paused */
139
+ ENOTPAUSED = "ENOTPAUSED",
140
+ /** Aptos: user opt out from direct coin transfers feature and has not coin wallet registered */
141
+ ENO_RECIPIENT_COIN_ADDRESS = "ENO_RECIPIENT_COIN_ADDRESS"
142
+ }
143
+ /**
144
+ * Error codes raised by Solana protocol specifically
145
+ */
146
+ export declare enum SolanaContractErrorCode {
147
+ /** Accounts not writable */
148
+ AccountsNotWritable = "AccountsNotWritable",
149
+ /** Invalid Metadata */
150
+ InvalidMetadata = "InvalidMetadata",
151
+ /** Invalid metadata account */
152
+ InvalidMetadataAccount = "InvalidMetadataAccount",
153
+ /** Provided accounts don't match the ones in contract */
154
+ MetadataAccountMismatch = "MetadataAccountMismatch",
155
+ /** Invalid escrow account */
156
+ InvalidEscrowAccount = "InvalidEscrowAccount",
157
+ /** Provided account(s) is/are not valid associated token accounts */
158
+ NotAssociated = "NotAssociated",
159
+ /** Sender mint does not match accounts mint */
160
+ MintMismatch = "MintMismatch",
161
+ /** Recipient not transferable for account */
162
+ TransferNotAllowed = "TransferNotAllowed",
163
+ /** Contract closed */
164
+ ContractClosed = "ContractClosed",
165
+ /** Invalid Streamflow Treasury accounts supplied */
166
+ InvalidTreasury = "InvalidTreasury",
167
+ /** Given timestamps are invalid */
168
+ InvalidTimestamps = "InvalidTimestamps",
169
+ /** Invalid deposit configuration */
170
+ InvalidDepositConfiguration = "InvalidDepositConfiguration",
171
+ /** Amount cannot be zero */
172
+ AmountIsZero = "AmountIsZero",
173
+ /** Amount requested is larger than available */
174
+ AmountMoreThanAvailable = "AmountMoreThanAvailable",
175
+ /** Amount currently available is zero */
176
+ AmountAvailableIsZero = "AmountAvailableIsZero",
177
+ /** Arithmetic error */
178
+ ArithmeticError = "ArithmeticError",
179
+ /** Metadata account data must be 1104 bytes long */
180
+ InvalidMetadataSize = "InvalidMetadataSize",
181
+ /** Metadata state account must be initialized */
182
+ UninitializedMetadata = "UninitializedMetadata",
183
+ /** Authority does not have permission for this action */
184
+ Unauthorized = "Unauthorized",
185
+ /** Contract is not transferable to the original recipient */
186
+ SelfTransfer = "SelfTransfer",
187
+ /** Contract is already paused */
188
+ AlreadyPaused = "AlreadyPaused",
189
+ /** Contract is not paused */
190
+ NotPaused = "NotPaused",
191
+ /** Meta account is not rent exempt */
192
+ MetadataNotRentExempt = "MetadataNotRentExempt"
193
+ }
103
194
  export interface Stream {
104
195
  magic: number;
105
196
  version: number;
@@ -146,4 +237,16 @@ export interface Stream {
146
237
  type: StreamType;
147
238
  unlocked(currentTimestamp: number): BN;
148
239
  }
240
+ /**
241
+ * Error wrapper for calls made to the contract on chain
242
+ */
243
+ export declare class ContractError extends Error {
244
+ contractErrorCode: string | null;
245
+ /**
246
+ * Constructs the Error Wrapper
247
+ * @param error Original error raised probably by the chain SDK
248
+ * @param code extracted code from the error if managed to parse it
249
+ */
250
+ constructor(error: Error, code?: string | null);
251
+ }
149
252
  export {};
@@ -1,6 +1,21 @@
1
1
  "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
2
17
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.IChain = exports.StreamType = exports.StreamDirection = exports.ICluster = void 0;
18
+ exports.ContractError = exports.SolanaContractErrorCode = exports.ContractErrorCode = exports.IChain = exports.StreamType = exports.StreamDirection = exports.ICluster = void 0;
4
19
  // Utility types
5
20
  var ICluster;
6
21
  (function (ICluster) {
@@ -31,3 +46,120 @@ var IChain;
31
46
  IChain["Polygon"] = "Polygon";
32
47
  IChain["Sui"] = "Sui";
33
48
  })(IChain = exports.IChain || (exports.IChain = {}));
49
+ /**
50
+ * Error codes raised by all protocols except for Solana
51
+ */
52
+ var ContractErrorCode;
53
+ (function (ContractErrorCode) {
54
+ /** Contract does not exist */
55
+ ContractErrorCode["ECONTRACT_NOT_INIT"] = "ECONTRACT_NOT_INIT";
56
+ /** Invalid total amount */
57
+ ContractErrorCode["EBAD_AMOUNT"] = "EBAD_AMOUNT";
58
+ /** No permissions to perform an operation */
59
+ ContractErrorCode["ENO_PERMISSIONS"] = "ENO_PERMISSIONS";
60
+ /** Invalid input parameters on create/update */
61
+ ContractErrorCode["EBADINPUT"] = "EBADINPUT";
62
+ /** Contract is already ended */
63
+ ContractErrorCode["ECLOSED"] = "ECLOSED";
64
+ /** Invalid amount per period input */
65
+ ContractErrorCode["EBAD_INPUT_AMOUNT_PER_PERIOD"] = "EBAD_INPUT_AMOUNT_PER_PERIOD";
66
+ /** Pause feature is not supported */
67
+ ContractErrorCode["EBAD_INPUT_PAUSABLE"] = "EBAD_INPUT_PAUSABLE";
68
+ /** Not used currently */
69
+ ContractErrorCode["EBAD_INPUT_UPDATE_RATE"] = "EBAD_INPUT_UPDATE_RATE";
70
+ /** Invalid cliff amount input */
71
+ ContractErrorCode["EBAD_INPUT_CLIFF_AMOUNT"] = "EBAD_INPUT_CLIFF_AMOUNT";
72
+ /** Invalid period input */
73
+ ContractErrorCode["EBAD_INPUT_PERIOD"] = "EBAD_INPUT_PERIOD";
74
+ /** Invalid start time of the contract */
75
+ ContractErrorCode["EBAD_INPUT_START"] = "EBAD_INPUT_START";
76
+ /** EVM: token allowance is not enough to create a Contract */
77
+ ContractErrorCode["EBAD_INSUFFICIENT_TOKEN_ALLOWANCE"] = "EBAD_INSUFFICIENT_TOKEN_ALLOWANCE";
78
+ /** EVM: not enough coins were passed for withdrawal fees */
79
+ ContractErrorCode["EBAD_INSUFFICIENT_WITHDRAWAL_FEES"] = "EBAD_INSUFFICIENT_WITHDRAWAL_FEES";
80
+ /** Sui: Insufficient amount of tokens passed */
81
+ ContractErrorCode["EBAD_INSUFFICIENT_AMOUNT"] = "EBAD_INSUFFICIENT_AMOUNT";
82
+ /** Contract is already paused */
83
+ ContractErrorCode["EPAUSED"] = "EPAUSED";
84
+ /** Contract is not paused */
85
+ ContractErrorCode["ENOTPAUSED"] = "ENOTPAUSED";
86
+ /** Aptos: user opt out from direct coin transfers feature and has not coin wallet registered */
87
+ ContractErrorCode["ENO_RECIPIENT_COIN_ADDRESS"] = "ENO_RECIPIENT_COIN_ADDRESS";
88
+ })(ContractErrorCode = exports.ContractErrorCode || (exports.ContractErrorCode = {}));
89
+ /**
90
+ * Error codes raised by Solana protocol specifically
91
+ */
92
+ var SolanaContractErrorCode;
93
+ (function (SolanaContractErrorCode) {
94
+ /** Accounts not writable */
95
+ SolanaContractErrorCode["AccountsNotWritable"] = "AccountsNotWritable";
96
+ /** Invalid Metadata */
97
+ SolanaContractErrorCode["InvalidMetadata"] = "InvalidMetadata";
98
+ /** Invalid metadata account */
99
+ SolanaContractErrorCode["InvalidMetadataAccount"] = "InvalidMetadataAccount";
100
+ /** Provided accounts don't match the ones in contract */
101
+ SolanaContractErrorCode["MetadataAccountMismatch"] = "MetadataAccountMismatch";
102
+ /** Invalid escrow account */
103
+ SolanaContractErrorCode["InvalidEscrowAccount"] = "InvalidEscrowAccount";
104
+ /** Provided account(s) is/are not valid associated token accounts */
105
+ SolanaContractErrorCode["NotAssociated"] = "NotAssociated";
106
+ /** Sender mint does not match accounts mint */
107
+ SolanaContractErrorCode["MintMismatch"] = "MintMismatch";
108
+ /** Recipient not transferable for account */
109
+ SolanaContractErrorCode["TransferNotAllowed"] = "TransferNotAllowed";
110
+ /** Contract closed */
111
+ SolanaContractErrorCode["ContractClosed"] = "ContractClosed";
112
+ /** Invalid Streamflow Treasury accounts supplied */
113
+ SolanaContractErrorCode["InvalidTreasury"] = "InvalidTreasury";
114
+ /** Given timestamps are invalid */
115
+ SolanaContractErrorCode["InvalidTimestamps"] = "InvalidTimestamps";
116
+ /** Invalid deposit configuration */
117
+ SolanaContractErrorCode["InvalidDepositConfiguration"] = "InvalidDepositConfiguration";
118
+ /** Amount cannot be zero */
119
+ SolanaContractErrorCode["AmountIsZero"] = "AmountIsZero";
120
+ /** Amount requested is larger than available */
121
+ SolanaContractErrorCode["AmountMoreThanAvailable"] = "AmountMoreThanAvailable";
122
+ /** Amount currently available is zero */
123
+ SolanaContractErrorCode["AmountAvailableIsZero"] = "AmountAvailableIsZero";
124
+ /** Arithmetic error */
125
+ SolanaContractErrorCode["ArithmeticError"] = "ArithmeticError";
126
+ /** Metadata account data must be 1104 bytes long */
127
+ SolanaContractErrorCode["InvalidMetadataSize"] = "InvalidMetadataSize";
128
+ /** Metadata state account must be initialized */
129
+ SolanaContractErrorCode["UninitializedMetadata"] = "UninitializedMetadata";
130
+ /** Authority does not have permission for this action */
131
+ SolanaContractErrorCode["Unauthorized"] = "Unauthorized";
132
+ /** Contract is not transferable to the original recipient */
133
+ SolanaContractErrorCode["SelfTransfer"] = "SelfTransfer";
134
+ /** Contract is already paused */
135
+ SolanaContractErrorCode["AlreadyPaused"] = "AlreadyPaused";
136
+ /** Contract is not paused */
137
+ SolanaContractErrorCode["NotPaused"] = "NotPaused";
138
+ /** Meta account is not rent exempt */
139
+ SolanaContractErrorCode["MetadataNotRentExempt"] = "MetadataNotRentExempt";
140
+ })(SolanaContractErrorCode = exports.SolanaContractErrorCode || (exports.SolanaContractErrorCode = {}));
141
+ /**
142
+ * Error wrapper for calls made to the contract on chain
143
+ */
144
+ var ContractError = /** @class */ (function (_super) {
145
+ __extends(ContractError, _super);
146
+ /**
147
+ * Constructs the Error Wrapper
148
+ * @param error Original error raised probably by the chain SDK
149
+ * @param code extracted code from the error if managed to parse it
150
+ */
151
+ function ContractError(error, code) {
152
+ var _this = _super.call(this, error.message) || this;
153
+ _this.name = "ContractError"; // Set the name property
154
+ _this.contractErrorCode = code !== null && code !== void 0 ? code : null;
155
+ // Copy properties from the original error
156
+ Object.getOwnPropertyNames(error).forEach(function (key) {
157
+ _this[key] = error[key];
158
+ });
159
+ // If you want to capture the stack trace:
160
+ _this.stack = error.stack;
161
+ return _this;
162
+ }
163
+ return ContractError;
164
+ }(Error));
165
+ exports.ContractError = ContractError;
@@ -13,3 +13,10 @@ export declare const getBN: (value: number, decimals: number) => BN;
13
13
  * @param {number} decimals - Number of decimals the token has.
14
14
  */
15
15
  export declare const getNumberFromBN: (value: BN, decimals: number) => number;
16
+ /**
17
+ * Used to make on chain calls to the contract and wrap raised errors if any
18
+ * @param func function that interacts with the contract
19
+ * @param callback callback that may be used to extract error code
20
+ * @returns {T}
21
+ */
22
+ export declare function handleContractError<T>(func: () => Promise<T>, callback?: (err: Error) => string | null): Promise<T>;
@@ -1,10 +1,47 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (_) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
2
38
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
39
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
40
  };
5
41
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getNumberFromBN = exports.getBN = void 0;
42
+ exports.handleContractError = exports.getNumberFromBN = exports.getBN = void 0;
7
43
  var bn_js_1 = __importDefault(require("bn.js"));
44
+ var types_1 = require("./types");
8
45
  /**
9
46
  * Used for conversion of token amounts to their Big Number representation.
10
47
  * Get Big Number representation in the smallest units from the same value in the highest units.
@@ -32,3 +69,33 @@ var getNumberFromBN = function (value, decimals) {
32
69
  : value.toNumber() / Math.pow(10, decimals);
33
70
  };
34
71
  exports.getNumberFromBN = getNumberFromBN;
72
+ /**
73
+ * Used to make on chain calls to the contract and wrap raised errors if any
74
+ * @param func function that interacts with the contract
75
+ * @param callback callback that may be used to extract error code
76
+ * @returns {T}
77
+ */
78
+ function handleContractError(func, callback) {
79
+ return __awaiter(this, void 0, void 0, function () {
80
+ var err_1;
81
+ return __generator(this, function (_a) {
82
+ switch (_a.label) {
83
+ case 0:
84
+ _a.trys.push([0, 2, , 3]);
85
+ return [4 /*yield*/, func()];
86
+ case 1: return [2 /*return*/, _a.sent()];
87
+ case 2:
88
+ err_1 = _a.sent();
89
+ if (err_1 instanceof Error) {
90
+ if (callback) {
91
+ throw new types_1.ContractError(err_1, callback(err_1));
92
+ }
93
+ throw new types_1.ContractError(err_1);
94
+ }
95
+ throw err_1;
96
+ case 3: return [2 /*return*/];
97
+ }
98
+ });
99
+ });
100
+ }
101
+ exports.handleContractError = handleContractError;
@@ -18,6 +18,7 @@ export default class EvmStreamClient extends BaseStreamClient {
18
18
  update(updateData: IUpdateData): Promise<ITransactionResult>;
19
19
  getOne({ id }: IGetOneData): Promise<Stream>;
20
20
  get({ address, direction, }: IGetAllData): Promise<[string, Stream][]>;
21
+ extractErrorCode(err: Error): string | null;
21
22
  /**
22
23
  * Returns StreamClient protocol program ID.
23
24
  */