@streamflow/stream 6.5.0 → 7.0.0-alpha.10

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.
Files changed (137) hide show
  1. package/README.md +17 -22
  2. package/dist/cjs/__tests__/aptos/streamClient.spec.js +111 -0
  3. package/dist/cjs/__tests__/common/GenericStreamClient.spec.js +45 -0
  4. package/dist/cjs/aptos/StreamClient.js +226 -0
  5. package/dist/cjs/aptos/constants.js +27 -0
  6. package/dist/{aptos → cjs/aptos}/index.js +6 -6
  7. package/dist/cjs/aptos/types.js +69 -0
  8. package/dist/{aptos → cjs/aptos}/utils.js +4 -4
  9. package/dist/cjs/aptos/wallet.js +34 -0
  10. package/dist/cjs/common/BaseStreamClient.js +23 -0
  11. package/dist/cjs/common/GenericStreamClient.js +102 -0
  12. package/dist/{common → cjs/common}/constants.js +2 -2
  13. package/dist/{common → cjs/common}/contractUtils.js +19 -20
  14. package/dist/cjs/common/utils.js +66 -0
  15. package/dist/cjs/evm/StreamClient.js +238 -0
  16. package/dist/cjs/evm/constants.js +38 -0
  17. package/dist/{evm → cjs/evm}/index.js +8 -8
  18. package/dist/{evm → cjs/evm}/types.js +26 -35
  19. package/dist/{evm → cjs/evm}/utils.js +2 -2
  20. package/dist/{index.js → cjs/index.js} +10 -10
  21. package/dist/cjs/solana/StreamClient.js +737 -0
  22. package/dist/{solana → cjs/solana}/constants.js +33 -33
  23. package/dist/cjs/solana/index.js +39 -0
  24. package/dist/{solana → cjs/solana}/instructions.js +83 -83
  25. package/dist/{solana → cjs/solana}/layout.js +8 -9
  26. package/dist/{solana → cjs/solana}/types.js +16 -26
  27. package/dist/cjs/solana/utils.js +134 -0
  28. package/dist/cjs/sui/StreamClient.js +402 -0
  29. package/dist/cjs/sui/constants.js +42 -0
  30. package/dist/{sui → cjs/sui}/index.js +5 -5
  31. package/dist/cjs/sui/types.js +68 -0
  32. package/dist/{sui → cjs/sui}/utils.js +7 -7
  33. package/dist/cjs/sui/wallet.js +40 -0
  34. package/dist/esm/__tests__/aptos/streamClient.spec.js +106 -0
  35. package/dist/esm/__tests__/common/GenericStreamClient.spec.js +40 -0
  36. package/dist/{aptos → esm/aptos}/StreamClient.d.ts +3 -3
  37. package/dist/esm/aptos/StreamClient.js +226 -0
  38. package/dist/{aptos → esm/aptos}/constants.d.ts +1 -1
  39. package/dist/esm/aptos/constants.js +24 -0
  40. package/dist/esm/aptos/index.d.ts +4 -0
  41. package/dist/esm/aptos/index.js +4 -0
  42. package/dist/{aptos → esm/aptos}/types.d.ts +13 -13
  43. package/dist/esm/aptos/types.js +105 -0
  44. package/dist/esm/aptos/utils.js +30 -0
  45. package/dist/esm/aptos/wallet.js +33 -0
  46. package/dist/{common → esm/common}/BaseStreamClient.d.ts +1 -1
  47. package/dist/esm/common/BaseStreamClient.js +19 -0
  48. package/dist/{common → esm/common}/GenericStreamClient.d.ts +6 -6
  49. package/dist/esm/common/GenericStreamClient.js +101 -0
  50. package/dist/esm/common/constants.d.ts +3 -0
  51. package/dist/esm/common/constants.js +3 -0
  52. package/dist/{common → esm/common}/contractUtils.d.ts +15 -15
  53. package/dist/esm/common/contractUtils.js +42 -0
  54. package/dist/{common → esm/common}/types.d.ts +19 -19
  55. package/dist/esm/common/types.js +106 -0
  56. package/dist/{common → esm/common}/utils.d.ts +11 -12
  57. package/dist/esm/common/utils.js +56 -0
  58. package/dist/{evm → esm/evm}/StreamClient.d.ts +4 -4
  59. package/dist/esm/evm/StreamClient.js +237 -0
  60. package/dist/esm/evm/abi.js +1255 -0
  61. package/dist/{evm → esm/evm}/constants.d.ts +1 -1
  62. package/dist/esm/evm/constants.js +35 -0
  63. package/dist/esm/evm/ercAbi.js +222 -0
  64. package/dist/esm/evm/index.d.ts +5 -0
  65. package/dist/esm/evm/index.js +5 -0
  66. package/dist/{evm → esm/evm}/types.d.ts +38 -38
  67. package/dist/esm/evm/types.js +102 -0
  68. package/dist/esm/evm/utils.js +8 -0
  69. package/dist/esm/index.d.ts +9 -0
  70. package/dist/esm/index.js +9 -0
  71. package/dist/{solana → esm/solana}/StreamClient.d.ts +4 -4
  72. package/dist/esm/solana/StreamClient.js +711 -0
  73. package/dist/{solana → esm/solana}/constants.d.ts +3 -1
  74. package/dist/esm/solana/constants.js +62 -0
  75. package/dist/esm/solana/index.d.ts +6 -0
  76. package/dist/esm/solana/index.js +6 -0
  77. package/dist/esm/solana/instructionTypes.js +1 -0
  78. package/dist/{solana → esm/solana}/instructions.d.ts +18 -18
  79. package/dist/esm/solana/instructions.js +257 -0
  80. package/dist/{solana → esm/solana}/layout.d.ts +2 -1
  81. package/dist/esm/solana/layout.js +155 -0
  82. package/dist/esm/solana/timelockIDL.js +420 -0
  83. package/dist/{solana → esm/solana}/types.d.ts +38 -37
  84. package/dist/esm/solana/types.js +101 -0
  85. package/dist/{solana → esm/solana}/utils.d.ts +4 -1
  86. package/dist/esm/solana/utils.js +123 -0
  87. package/dist/{sui → esm/sui}/StreamClient.d.ts +3 -3
  88. package/dist/esm/sui/StreamClient.js +403 -0
  89. package/dist/{sui → esm/sui}/constants.d.ts +1 -1
  90. package/dist/esm/sui/constants.js +39 -0
  91. package/dist/esm/sui/index.d.ts +4 -0
  92. package/dist/esm/sui/index.js +4 -0
  93. package/dist/{sui → esm/sui}/types.d.ts +13 -13
  94. package/dist/esm/sui/types.js +104 -0
  95. package/dist/{sui → esm/sui}/utils.d.ts +1 -1
  96. package/dist/esm/sui/utils.js +23 -0
  97. package/dist/{sui → esm/sui}/wallet.d.ts +1 -1
  98. package/dist/esm/sui/wallet.js +38 -0
  99. package/package.json +37 -35
  100. package/dist/__tests__/aptos/streamClient.spec.js +0 -161
  101. package/dist/__tests__/common/GenericStreamClient.spec.js +0 -44
  102. package/dist/aptos/StreamClient.js +0 -431
  103. package/dist/aptos/constants.js +0 -28
  104. package/dist/aptos/index.d.ts +0 -4
  105. package/dist/aptos/types.js +0 -77
  106. package/dist/aptos/wallet.js +0 -89
  107. package/dist/common/BaseStreamClient.js +0 -71
  108. package/dist/common/GenericStreamClient.js +0 -128
  109. package/dist/common/constants.d.ts +0 -3
  110. package/dist/common/utils.js +0 -118
  111. package/dist/evm/StreamClient.js +0 -496
  112. package/dist/evm/constants.js +0 -39
  113. package/dist/evm/index.d.ts +0 -5
  114. package/dist/index.d.ts +0 -9
  115. package/dist/solana/StreamClient.js +0 -1253
  116. package/dist/solana/index.d.ts +0 -7
  117. package/dist/solana/index.js +0 -43
  118. package/dist/solana/utils.js +0 -211
  119. package/dist/sui/StreamClient.js +0 -648
  120. package/dist/sui/constants.js +0 -43
  121. package/dist/sui/index.d.ts +0 -4
  122. package/dist/sui/types.js +0 -102
  123. package/dist/sui/wallet.js +0 -90
  124. /package/dist/{common → cjs/common}/types.js +0 -0
  125. /package/dist/{evm → cjs/evm}/abi.js +0 -0
  126. /package/dist/{evm → cjs/evm}/ercAbi.js +0 -0
  127. /package/dist/{solana → cjs/solana}/instructionTypes.js +0 -0
  128. /package/dist/{solana → cjs/solana}/timelockIDL.js +0 -0
  129. /package/dist/{__tests__ → esm/__tests__}/aptos/streamClient.spec.d.ts +0 -0
  130. /package/dist/{__tests__ → esm/__tests__}/common/GenericStreamClient.spec.d.ts +0 -0
  131. /package/dist/{aptos → esm/aptos}/utils.d.ts +0 -0
  132. /package/dist/{aptos → esm/aptos}/wallet.d.ts +0 -0
  133. /package/dist/{evm → esm/evm}/abi.d.ts +0 -0
  134. /package/dist/{evm → esm/evm}/ercAbi.d.ts +0 -0
  135. /package/dist/{evm → esm/evm}/utils.d.ts +0 -0
  136. /package/dist/{solana → esm/solana}/instructionTypes.d.ts +0 -0
  137. /package/dist/{solana → esm/solana}/timelockIDL.d.ts +0 -0
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BaseStreamClient = void 0;
4
+ class BaseStreamClient {
5
+ /**
6
+ * Returns total fee percent, streamflow fees + partner fees
7
+ * @param getFeesData structure with address for which we need to derive fee, either sender or partner usually
8
+ * @param chainSpecificParams additional parameters required by chain client
9
+ * @returns fee as floating number, so if fee is 0.99%, it will return 0.99
10
+ */
11
+ async getTotalFee(getFeesData, chainSpecificParams) {
12
+ const fees = await this.getFees(getFeesData, chainSpecificParams);
13
+ if (fees) {
14
+ return fees.partnerFee + fees.streamflowFee;
15
+ }
16
+ return this.getDefaultStreamflowFee(chainSpecificParams);
17
+ }
18
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
19
+ extractErrorCode(err) {
20
+ return null;
21
+ }
22
+ }
23
+ exports.BaseStreamClient = BaseStreamClient;
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const BaseStreamClient_js_1 = require("./BaseStreamClient.js");
4
+ const types_js_1 = require("./types.js");
5
+ const utils_js_1 = require("./utils.js");
6
+ const index_js_1 = require("../aptos/index.js");
7
+ const index_js_2 = require("../evm/index.js");
8
+ const index_js_3 = require("../solana/index.js");
9
+ const index_js_4 = require("../sui/index.js");
10
+ const constants_js_1 = require("./constants.js");
11
+ /** Generic Stream Client implementation that wrap Chain Client methods and enriches error messages if possible
12
+ * @property {StreamClientType} - Chain Client implementation
13
+ * @property {chain} - Chain
14
+ */
15
+ class GenericStreamClient extends BaseStreamClient_js_1.BaseStreamClient {
16
+ constructor(options) {
17
+ super();
18
+ this.chain = options.chain;
19
+ switch (options.chain) {
20
+ case types_js_1.IChain.Solana:
21
+ this.nativeStreamClient = new index_js_3.SolanaStreamClient(options.clusterUrl, options.cluster, options.commitment, options.programId, options.sendRate, options.sendThrottler);
22
+ break;
23
+ case types_js_1.IChain.Aptos:
24
+ this.nativeStreamClient = new index_js_1.AptosStreamClient(options.clusterUrl, options.cluster, options.maxGas, options.programId);
25
+ break;
26
+ case types_js_1.IChain.BNB:
27
+ case types_js_1.IChain.Ethereum:
28
+ case types_js_1.IChain.Polygon:
29
+ this.nativeStreamClient = new index_js_2.EvmStreamClient(options.clusterUrl, options.chain, options.signer, options.cluster, options.programId);
30
+ break;
31
+ case types_js_1.IChain.Sui:
32
+ this.nativeStreamClient = new index_js_4.SuiStreamClient(options.clusterUrl, options.cluster, options.ids);
33
+ }
34
+ }
35
+ /**
36
+ * Creates a new stream/vesting contract.
37
+ */
38
+ create(streamData, chainSpecificParams) {
39
+ return (0, utils_js_1.handleContractError)(() => this.nativeStreamClient.create(streamData, chainSpecificParams), this.nativeStreamClient.extractErrorCode);
40
+ }
41
+ /**
42
+ * Creates multiple stream/vesting contracts.
43
+ */
44
+ createMultiple(multipleStreamData, chainSpecificParams) {
45
+ return (0, utils_js_1.handleContractError)(() => this.nativeStreamClient.createMultiple(multipleStreamData, chainSpecificParams), this.nativeStreamClient.extractErrorCode);
46
+ }
47
+ /**
48
+ * Attempts withdrawing from the specified stream.
49
+ */
50
+ withdraw({ id, amount = constants_js_1.WITHDRAW_AVAILABLE_AMOUNT }, chainSpecificParams) {
51
+ return (0, utils_js_1.handleContractError)(() => this.nativeStreamClient.withdraw({ id, amount }, chainSpecificParams), this.nativeStreamClient.extractErrorCode);
52
+ }
53
+ /**
54
+ * Attempts canceling the specified stream.
55
+ */
56
+ cancel(cancelData, chainSpecificParams) {
57
+ return (0, utils_js_1.handleContractError)(() => this.nativeStreamClient.cancel(cancelData, chainSpecificParams), this.nativeStreamClient.extractErrorCode);
58
+ }
59
+ /**
60
+ * Attempts changing the stream/vesting contract's recipient (effectively transferring the stream/vesting contract).
61
+ */
62
+ transfer(transferData, chainSpecificParams) {
63
+ return (0, utils_js_1.handleContractError)(() => this.nativeStreamClient.transfer(transferData, chainSpecificParams), this.nativeStreamClient.extractErrorCode);
64
+ }
65
+ /**
66
+ * Tops up stream account with specified amount.
67
+ */
68
+ topup(topupData, chainSpecificParams) {
69
+ return (0, utils_js_1.handleContractError)(() => this.nativeStreamClient.topup(topupData, chainSpecificParams), this.nativeStreamClient.extractErrorCode);
70
+ }
71
+ /**
72
+ * Fetch stream data by its id (address).
73
+ */
74
+ getOne(getOneData) {
75
+ return this.nativeStreamClient.getOne(getOneData);
76
+ }
77
+ /**
78
+ * Fetch streams by sender or recipient address.
79
+ */
80
+ get(getAllData) {
81
+ return this.nativeStreamClient.get(getAllData);
82
+ }
83
+ /**
84
+ * Attempts updating the stream auto withdrawal params and amount per period
85
+ */
86
+ update(updateData, chainSpecificParams) {
87
+ return (0, utils_js_1.handleContractError)(() => this.nativeStreamClient.update(updateData, chainSpecificParams), this.nativeStreamClient.extractErrorCode);
88
+ }
89
+ /**
90
+ * Returns streamflow and partner fees for the specific wallet in %
91
+ */
92
+ getFees(getFeesData) {
93
+ return this.nativeStreamClient.getFees(getFeesData);
94
+ }
95
+ /**
96
+ * Returns default Streamflow Fee in %
97
+ */
98
+ getDefaultStreamflowFee() {
99
+ return this.nativeStreamClient.getDefaultStreamflowFee();
100
+ }
101
+ }
102
+ exports.default = GenericStreamClient;
@@ -4,6 +4,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.WITHDRAW_AVAILABLE_AMOUNT = exports.BASE_FEE = void 0;
7
- var bn_js_1 = __importDefault(require("bn.js"));
7
+ const bignumber_js_1 = __importDefault(require("bignumber.js"));
8
8
  exports.BASE_FEE = 1009900; // Buffer to include usual fees when calculating stream amount
9
- exports.WITHDRAW_AVAILABLE_AMOUNT = new bn_js_1.default("18446744073709551615"); // Magical number to withdraw all available amount from a Contract
9
+ exports.WITHDRAW_AVAILABLE_AMOUNT = (0, bignumber_js_1.default)("18446744073709551615"); // Magical number to withdraw all available amount from a Contract
@@ -4,36 +4,35 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.buildStreamType = exports.isTokenLock = exports.isVesting = exports.isPayment = exports.isCliffCloseToDepositedAmount = exports.calculateUnlockedAmount = void 0;
7
- var bn_js_1 = __importDefault(require("bn.js"));
8
- var types_1 = require("./types");
9
- var calculateUnlockedAmount = function (_a) {
10
- var depositedAmount = _a.depositedAmount, cliff = _a.cliff, cliffAmount = _a.cliffAmount, end = _a.end, currentTimestamp = _a.currentTimestamp, lastRateChangeTime = _a.lastRateChangeTime, period = _a.period, amountPerPeriod = _a.amountPerPeriod, fundsUnlockedAtLastRateChange = _a.fundsUnlockedAtLastRateChange;
11
- var deposited = depositedAmount;
7
+ const bignumber_js_1 = __importDefault(require("bignumber.js"));
8
+ const types_js_1 = require("./types.js");
9
+ const calculateUnlockedAmount = ({ depositedAmount, cliff, cliffAmount, end, currentTimestamp, lastRateChangeTime, period, amountPerPeriod, fundsUnlockedAtLastRateChange, }) => {
10
+ const deposited = depositedAmount;
12
11
  if (currentTimestamp < cliff)
13
- return new bn_js_1.default(0);
12
+ return (0, bignumber_js_1.default)(0);
14
13
  if (currentTimestamp > end)
15
14
  return deposited;
16
- var savedUnlockedFunds = lastRateChangeTime === 0 ? cliffAmount : fundsUnlockedAtLastRateChange;
17
- var savedUnlockedFundsTime = lastRateChangeTime === 0 ? cliff : lastRateChangeTime;
18
- var streamed = new bn_js_1.default(Math.floor((currentTimestamp - savedUnlockedFundsTime) / period))
19
- .mul(amountPerPeriod)
20
- .add(savedUnlockedFunds);
15
+ const savedUnlockedFunds = lastRateChangeTime === 0 ? cliffAmount : fundsUnlockedAtLastRateChange;
16
+ const savedUnlockedFundsTime = lastRateChangeTime === 0 ? cliff : lastRateChangeTime;
17
+ const streamed = (0, bignumber_js_1.default)(Math.floor((currentTimestamp - savedUnlockedFundsTime) / period))
18
+ .times(amountPerPeriod)
19
+ .plus(savedUnlockedFunds);
21
20
  return streamed.lt(deposited) ? streamed : deposited;
22
21
  };
23
22
  exports.calculateUnlockedAmount = calculateUnlockedAmount;
24
- var isCliffCloseToDepositedAmount = function (streamData) {
25
- return streamData.cliffAmount.gte(streamData.depositedAmount.sub(new bn_js_1.default("1")));
23
+ const isCliffCloseToDepositedAmount = (streamData) => {
24
+ return streamData.cliffAmount.gte(streamData.depositedAmount.minus((0, bignumber_js_1.default)(1)));
26
25
  };
27
26
  exports.isCliffCloseToDepositedAmount = isCliffCloseToDepositedAmount;
28
- var isPayment = function (streamData) {
27
+ const isPayment = (streamData) => {
29
28
  return streamData.canTopup;
30
29
  };
31
30
  exports.isPayment = isPayment;
32
- var isVesting = function (streamData) {
31
+ const isVesting = (streamData) => {
33
32
  return !streamData.canTopup && !(0, exports.isCliffCloseToDepositedAmount)(streamData);
34
33
  };
35
34
  exports.isVesting = isVesting;
36
- var isTokenLock = function (streamData) {
35
+ const isTokenLock = (streamData) => {
37
36
  return (!streamData.canTopup &&
38
37
  !streamData.automaticWithdrawal &&
39
38
  !streamData.cancelableBySender &&
@@ -43,13 +42,13 @@ var isTokenLock = function (streamData) {
43
42
  (0, exports.isCliffCloseToDepositedAmount)(streamData));
44
43
  };
45
44
  exports.isTokenLock = isTokenLock;
46
- var buildStreamType = function (streamData) {
45
+ const buildStreamType = (streamData) => {
47
46
  if ((0, exports.isVesting)(streamData)) {
48
- return types_1.StreamType.Vesting;
47
+ return types_js_1.StreamType.Vesting;
49
48
  }
50
49
  if ((0, exports.isTokenLock)(streamData)) {
51
- return types_1.StreamType.Lock;
50
+ return types_js_1.StreamType.Lock;
52
51
  }
53
- return types_1.StreamType.Payment;
52
+ return types_js_1.StreamType.Payment;
54
53
  };
55
54
  exports.buildStreamType = buildStreamType;
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.handleContractError = exports.calculateTotalAmountToDeposit = exports.getScaledBigNumber = exports.getNumberFromBigNumber = void 0;
7
+ const bignumber_js_1 = __importDefault(require("bignumber.js"));
8
+ const types_js_1 = require("./types.js");
9
+ const FEE_PRECISION = 4;
10
+ const FEE_NORMALIZER = 10 ** FEE_PRECISION;
11
+ const FEE_MULTIPLIER = (0, bignumber_js_1.default)(10 ** 6);
12
+ /**
13
+ * Used for token amounts conversion from their Big Number representation to number.
14
+ * Get value in the highest units from BigNumber representation of the same value in the smallest units.
15
+ * @param {BigNumber} value - Big Number representation of value in the smallest units.
16
+ * @param {number} decimals - Number of decimals the token has.
17
+ */
18
+ const getNumberFromBigNumber = (bigNum, decimals) => {
19
+ return bigNum.div((0, bignumber_js_1.default)(10).pow(decimals)).toNumber();
20
+ };
21
+ exports.getNumberFromBigNumber = getNumberFromBigNumber;
22
+ /**
23
+ * Used for conversion of token amounts to their Big Number representation.
24
+ * Get Big Number representation in the smallest units from the same value in the highest units.
25
+ * @param {number} value - Number of tokens you want to convert to its BigNumber representation.
26
+ * @param {number} decimals - Number of decimals the token has.
27
+ */
28
+ const getScaledBigNumber = (value, decimals) => {
29
+ return new bignumber_js_1.default(value).times(new bignumber_js_1.default(10).pow(decimals));
30
+ };
31
+ exports.getScaledBigNumber = getScaledBigNumber;
32
+ /**
33
+ * Calculate total amount of a Contract including all fees.
34
+ * - first we convert fee floating to a BigNumber with up to 4 decimals precision
35
+ * - then we reverse the fee with `FEE_MULTIPLIER` to safely multiply it by depositedAmount
36
+ * to receive a total number and not percentage of depositedAmount
37
+ * @param depositedAmount deposited raw tokens
38
+ * @param totalFee sum of all fees in percentage as floating number, e.g. 0.99% should be supplied as 0.99
39
+ * @returns total tokens amount that Contract will retrieve from the Sender
40
+ */
41
+ const calculateTotalAmountToDeposit = (depositedAmount, totalFee) => {
42
+ const totalFeeNormalized = (0, bignumber_js_1.default)(totalFee).times(FEE_NORMALIZER);
43
+ return depositedAmount.times(totalFeeNormalized.plus(FEE_MULTIPLIER)).div(FEE_MULTIPLIER);
44
+ };
45
+ exports.calculateTotalAmountToDeposit = calculateTotalAmountToDeposit;
46
+ /**
47
+ * Used to make on chain calls to the contract and wrap raised errors if any
48
+ * @param func function that interacts with the contract
49
+ * @param callback callback that may be used to extract error code
50
+ * @returns {T}
51
+ */
52
+ async function handleContractError(func, callback) {
53
+ try {
54
+ return await func();
55
+ }
56
+ catch (err) {
57
+ if (err instanceof Error) {
58
+ if (callback) {
59
+ throw new types_js_1.ContractError(err, callback(err));
60
+ }
61
+ throw new types_js_1.ContractError(err);
62
+ }
63
+ throw err;
64
+ }
65
+ }
66
+ exports.handleContractError = handleContractError;
@@ -0,0 +1,238 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const ethers_1 = require("ethers");
7
+ const bignumber_js_1 = __importDefault(require("bignumber.js"));
8
+ const ethereum_checksum_address_1 = require("ethereum-checksum-address");
9
+ const BaseStreamClient_js_1 = require("../common/BaseStreamClient.js");
10
+ const types_js_1 = require("../common/types.js");
11
+ const constants_js_1 = require("./constants.js");
12
+ const abi_js_1 = __importDefault(require("./abi.js"));
13
+ const ercAbi_js_1 = __importDefault(require("./ercAbi.js"));
14
+ const constants_js_2 = require("../common/constants.js");
15
+ const types_js_2 = require("./types.js");
16
+ const utils_js_1 = require("./utils.js");
17
+ class EvmStreamClient extends BaseStreamClient_js_1.BaseStreamClient {
18
+ constructor(clusterUrl, chain, signer, cluster = types_js_1.ICluster.Mainnet, programId) {
19
+ super();
20
+ if (chain !== types_js_1.IChain.Ethereum && chain !== types_js_1.IChain.BNB && chain !== types_js_1.IChain.Polygon) {
21
+ throw new Error("Wrong chain. Supported chains are Ethereum , BNB and Polygon!");
22
+ }
23
+ if (programId) {
24
+ this.programId = programId;
25
+ }
26
+ else {
27
+ switch (chain) {
28
+ case types_js_1.IChain.Ethereum:
29
+ this.programId = constants_js_1.ETHEREUM_PROGRAM_IDS[cluster];
30
+ break;
31
+ case types_js_1.IChain.BNB:
32
+ this.programId = constants_js_1.BNB_PROGRAM_IDS[cluster];
33
+ break;
34
+ case types_js_1.IChain.Polygon:
35
+ this.programId = constants_js_1.POLYGON_PROGRAM_IDS[cluster];
36
+ break;
37
+ }
38
+ }
39
+ this.provider = new ethers_1.ethers.providers.JsonRpcProvider(clusterUrl);
40
+ this.signer = signer;
41
+ const baseContract = new ethers_1.ethers.Contract(this.programId, abi_js_1.default);
42
+ this.readContract = baseContract.connect(this.provider);
43
+ this.writeContract = baseContract.connect(this.signer);
44
+ }
45
+ async create(streamData) {
46
+ const multiParams = {
47
+ ...streamData,
48
+ recipients: [streamData],
49
+ };
50
+ const fees = await this.readContract.getWithdrawalFees(...this.getFeeParams(multiParams));
51
+ const args = (await this.generateMultiPayloads(multiParams))[0];
52
+ const sum = streamData.amount.times((0, bignumber_js_1.default)(constants_js_2.BASE_FEE)).div((0, bignumber_js_1.default)(1000000));
53
+ await this.approveTokens(streamData.tokenId, sum);
54
+ const result = await this.writeContract.create(...args, {
55
+ value: fees.value,
56
+ });
57
+ const confirmedTx = await result.wait();
58
+ const metadataId = this.formatMetadataId(confirmedTx.events.find((item) => item.event === "ContractCreated").args[0]);
59
+ return {
60
+ ixs: [],
61
+ txId: result.hash,
62
+ metadataId,
63
+ };
64
+ }
65
+ async createMultiple(multipleStreamData) {
66
+ const fees = await this.readContract.getWithdrawalFees(...this.getFeeParams(multipleStreamData));
67
+ const args = await this.generateMultiPayloads(multipleStreamData);
68
+ const sum = multipleStreamData.recipients
69
+ .reduce((acc, v) => acc.plus(v.amount), (0, bignumber_js_1.default)(0))
70
+ .times((0, bignumber_js_1.default)(constants_js_2.BASE_FEE))
71
+ .div((0, bignumber_js_1.default)(1000000));
72
+ await this.approveTokens(multipleStreamData.tokenId, sum);
73
+ const creationPromises = args.map((item) => this.writeContract.create(...item, { value: fees.value }));
74
+ const signatures = [];
75
+ const results = await Promise.all(creationPromises);
76
+ const confirmations = await Promise.allSettled(results.map((result) => result.wait()));
77
+ const successes = confirmations
78
+ .filter((el) => el.status === "fulfilled")
79
+ .map((el) => el.value);
80
+ signatures.push(...successes.map((el) => el.hash));
81
+ const metadatas = confirmations.map((result) => result.status === "fulfilled"
82
+ ? this.formatMetadataId(result.value.events.find((item) => item.event === "ContractCreated").args[0])
83
+ : null);
84
+ const metadataToRecipient = metadatas.reduce((acc, value, index) => {
85
+ if (value) {
86
+ acc[value] = multipleStreamData.recipients[index];
87
+ }
88
+ return acc;
89
+ }, {});
90
+ const failures = confirmations
91
+ .filter((el) => el.status === "rejected")
92
+ .map((el) => el.reason);
93
+ return {
94
+ txs: signatures,
95
+ metadatas: metadatas.filter(Boolean),
96
+ metadataToRecipient,
97
+ errors: failures,
98
+ };
99
+ }
100
+ async withdraw({ id, amount = constants_js_2.WITHDRAW_AVAILABLE_AMOUNT }) {
101
+ const result = await this.writeContract.withdraw(id, amount.toString());
102
+ return {
103
+ ixs: [],
104
+ txId: result.hash,
105
+ };
106
+ }
107
+ async cancel(cancelData) {
108
+ const result = await this.writeContract.cancel(cancelData.id);
109
+ return {
110
+ ixs: [],
111
+ txId: result.hash,
112
+ };
113
+ }
114
+ async transfer(transferData) {
115
+ const result = await this.writeContract.transfer(transferData.id, transferData.newRecipient);
116
+ return {
117
+ ixs: [],
118
+ txId: result.hash,
119
+ };
120
+ }
121
+ async topup(topupData) {
122
+ const fees = await this.readContract.getTopUpWithdrawalFees(topupData.id, topupData.amount.toString());
123
+ const sum = topupData.amount.times((0, bignumber_js_1.default)(constants_js_2.BASE_FEE)).div((0, bignumber_js_1.default)(1000000));
124
+ const stream = await this.getOne({ id: topupData.id });
125
+ await this.approveTokens(stream.mint, sum);
126
+ const result = await this.writeContract.topUp(topupData.id, topupData.amount.toString(), {
127
+ value: fees.value,
128
+ });
129
+ return {
130
+ ixs: [],
131
+ txId: result.hash,
132
+ };
133
+ }
134
+ async update(updateData) {
135
+ const result = await this.writeContract.update(updateData.id, updateData.enableAutomaticWithdrawal ? [true] : [], updateData.withdrawFrequency ? [updateData.withdrawFrequency.toString()] : [], updateData.amountPerPeriod ? [updateData.amountPerPeriod.toString()] : []);
136
+ return {
137
+ ixs: [],
138
+ txId: result.hash,
139
+ };
140
+ }
141
+ async getOne({ id }) {
142
+ const result = await this.readContract.getById(id);
143
+ return new types_js_2.EvmContract(result);
144
+ }
145
+ async get({ address,
146
+ // type = StreamType.All,
147
+ direction = types_js_1.StreamDirection.All, }) {
148
+ const addresses = [];
149
+ if (direction === types_js_1.StreamDirection.All || direction === types_js_1.StreamDirection.Outgoing) {
150
+ const senderAddresses = await this.readContract.getBySender(address);
151
+ addresses.push(...senderAddresses);
152
+ }
153
+ if (direction === types_js_1.StreamDirection.All || direction === types_js_1.StreamDirection.Incoming) {
154
+ const recipientAddresses = await this.readContract.getByRecipient(address);
155
+ addresses.push(...recipientAddresses);
156
+ }
157
+ const uniqueAddresses = [...new Set(addresses)];
158
+ const results = await this.readContract.getMultiple(uniqueAddresses);
159
+ return results.map((result, index) => [uniqueAddresses[index], new types_js_2.EvmContract(result)]);
160
+ }
161
+ extractErrorCode(err) {
162
+ return (0, utils_js_1.extractEvmErrorCode)(err.toString() ?? "Unknown error!");
163
+ }
164
+ async getFees({ address }) {
165
+ const fees = await this.readContract.getFees(address);
166
+ if (!fees.exists) {
167
+ return null;
168
+ }
169
+ return {
170
+ streamflowFee: fees.streamflow_fee.toNumber() / 100,
171
+ partnerFee: fees.partner_fee.toNumber() / 100,
172
+ };
173
+ }
174
+ async getDefaultStreamflowFee() {
175
+ const fee = await this.readContract.getStreamflowFees();
176
+ return fee.toNumber() / 100;
177
+ }
178
+ /**
179
+ * Returns StreamClient protocol program ID.
180
+ */
181
+ getProgramId() {
182
+ return this.programId;
183
+ }
184
+ async approveTokens(tokenId, amount) {
185
+ const tokenContract = new ethers_1.ethers.Contract(tokenId, ercAbi_js_1.default, this.signer);
186
+ const address = await this.signer.getAddress();
187
+ const allowance = await tokenContract.allowance(address, this.programId);
188
+ if ((0, bignumber_js_1.default)(allowance.toString()).gte(amount)) {
189
+ return;
190
+ }
191
+ const approvalTx = await tokenContract.approve(this.programId, amount.toString());
192
+ await approvalTx.wait();
193
+ }
194
+ // Utility function to prepare transaction payloads for multiple recipients.
195
+ async generateMultiPayloads(multipleStreamData) {
196
+ const sender = await this.signer.getAddress();
197
+ return multipleStreamData.recipients.map((recipient) => {
198
+ return [
199
+ multipleStreamData.tokenId,
200
+ recipient.amount.toString(),
201
+ multipleStreamData.period,
202
+ recipient.amountPerPeriod.toString(),
203
+ multipleStreamData.start,
204
+ recipient.cliffAmount.toString(),
205
+ [
206
+ multipleStreamData.cancelableBySender,
207
+ multipleStreamData.cancelableByRecipient,
208
+ multipleStreamData.transferableBySender,
209
+ multipleStreamData.transferableByRecipient,
210
+ multipleStreamData.canTopup,
211
+ multipleStreamData.canPause || false,
212
+ multipleStreamData.canUpdateRate || false,
213
+ multipleStreamData.automaticWithdrawal || false,
214
+ multipleStreamData.withdrawalFrequency || 0,
215
+ recipient.name,
216
+ ],
217
+ recipient.recipient,
218
+ multipleStreamData.partner || sender,
219
+ ];
220
+ });
221
+ }
222
+ getFeeParams(multipleStreamData) {
223
+ return [
224
+ multipleStreamData.recipients[0].amount.toString(),
225
+ multipleStreamData.period,
226
+ multipleStreamData.recipients[0].amountPerPeriod.toString(),
227
+ multipleStreamData.start,
228
+ multipleStreamData.recipients[0].cliffAmount.toString(),
229
+ multipleStreamData.automaticWithdrawal || false,
230
+ multipleStreamData.withdrawalFrequency || 0,
231
+ ];
232
+ }
233
+ formatMetadataId(id) {
234
+ // 40 chars is ethereum address size
235
+ return (0, ethereum_checksum_address_1.toChecksumAddress)(`0x${id.slice(-40)}`);
236
+ }
237
+ }
238
+ exports.default = EvmStreamClient;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EVM_ERROR_MAP = exports.EVM_ERROR_MATCH_REGEX = exports.POLYGON_PROGRAM_IDS = exports.BNB_PROGRAM_IDS = exports.ETHEREUM_PROGRAM_IDS = void 0;
4
+ const types_js_1 = require("../common/types.js");
5
+ exports.ETHEREUM_PROGRAM_IDS = {
6
+ [types_js_1.ICluster.Mainnet]: "0x94d4646Bd307Bf91CB1893BC64d976BF9E60D9B2",
7
+ [types_js_1.ICluster.Devnet]: "0x5Db7a43D20De64E3a3BC765334a477026FD13E7d",
8
+ [types_js_1.ICluster.Testnet]: "0x5Db7a43D20De64E3a3BC765334a477026FD13E7d",
9
+ [types_js_1.ICluster.Local]: "0x5Db7a43D20De64E3a3BC765334a477026FD13E7d",
10
+ };
11
+ exports.BNB_PROGRAM_IDS = {
12
+ [types_js_1.ICluster.Mainnet]: "0x94d4646Bd307Bf91CB1893BC64d976BF9E60D9B2",
13
+ [types_js_1.ICluster.Devnet]: "0x5Db7a43D20De64E3a3BC765334a477026FD13E7d",
14
+ [types_js_1.ICluster.Testnet]: "0x5Db7a43D20De64E3a3BC765334a477026FD13E7d",
15
+ [types_js_1.ICluster.Local]: "0x5Db7a43D20De64E3a3BC765334a477026FD13E7d",
16
+ };
17
+ exports.POLYGON_PROGRAM_IDS = {
18
+ [types_js_1.ICluster.Mainnet]: "0x94d4646Bd307Bf91CB1893BC64d976BF9E60D9B2",
19
+ [types_js_1.ICluster.Devnet]: "0x5Db7a43D20De64E3a3BC765334a477026FD13E7d",
20
+ [types_js_1.ICluster.Testnet]: "0x5Db7a43D20De64E3a3BC765334a477026FD13E7d",
21
+ [types_js_1.ICluster.Local]: "0x5Db7a43D20De64E3a3BC765334a477026FD13E7d",
22
+ };
23
+ exports.EVM_ERROR_MATCH_REGEX = /execution reverted: ([A-Z_]+)/;
24
+ exports.EVM_ERROR_MAP = {
25
+ ECONTRACT_NOT_INIT: types_js_1.ContractErrorCode.ECONTRACT_NOT_INIT,
26
+ EBAD_AMOUNT: types_js_1.ContractErrorCode.EBAD_AMOUNT,
27
+ ENO_PERMISSIONS: types_js_1.ContractErrorCode.ENO_PERMISSIONS,
28
+ EBADINPUT: types_js_1.ContractErrorCode.EBADINPUT,
29
+ ECLOSED: types_js_1.ContractErrorCode.ECLOSED,
30
+ EBAD_INPUT_AMOUNT_PER_PERIOD: types_js_1.ContractErrorCode.EBAD_INPUT_AMOUNT_PER_PERIOD,
31
+ EBAD_INPUT_PAUSABLE: types_js_1.ContractErrorCode.EBAD_INPUT_PAUSABLE,
32
+ EBAD_INPUT_UPDATE_RATE: types_js_1.ContractErrorCode.EBAD_INPUT_UPDATE_RATE,
33
+ EBAD_INPUT_CLIFF_AMOUNT: types_js_1.ContractErrorCode.EBAD_INPUT_CLIFF_AMOUNT,
34
+ EBAD_INPUT_PERIOD: types_js_1.ContractErrorCode.EBAD_INPUT_PERIOD,
35
+ EBAD_INPUT_START: types_js_1.ContractErrorCode.EBAD_INPUT_START,
36
+ EBAD_INSUFFICIENT_TOKEN_ALLOWANCE: types_js_1.ContractErrorCode.EBAD_INSUFFICIENT_TOKEN_ALLOWANCE,
37
+ EBAD_INSUFFICIENT_WITHDRAWAL_FEES: types_js_1.ContractErrorCode.EBAD_INSUFFICIENT_WITHDRAWAL_FEES,
38
+ };
@@ -30,11 +30,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
30
30
  };
31
31
  Object.defineProperty(exports, "__esModule", { value: true });
32
32
  exports.ercAbi = exports.constants = exports.EvmStreamClient = exports.default = void 0;
33
- var StreamClient_1 = require("./StreamClient");
34
- Object.defineProperty(exports, "default", { enumerable: true, get: function () { return __importDefault(StreamClient_1).default; } });
35
- Object.defineProperty(exports, "EvmStreamClient", { enumerable: true, get: function () { return __importDefault(StreamClient_1).default; } });
36
- __exportStar(require("./utils"), exports);
37
- __exportStar(require("./types"), exports);
38
- exports.constants = __importStar(require("./constants"));
39
- var ercAbi_1 = require("./ercAbi");
40
- Object.defineProperty(exports, "ercAbi", { enumerable: true, get: function () { return __importDefault(ercAbi_1).default; } });
33
+ var StreamClient_js_1 = require("./StreamClient.js");
34
+ Object.defineProperty(exports, "default", { enumerable: true, get: function () { return __importDefault(StreamClient_js_1).default; } });
35
+ Object.defineProperty(exports, "EvmStreamClient", { enumerable: true, get: function () { return __importDefault(StreamClient_js_1).default; } });
36
+ __exportStar(require("./utils.js"), exports);
37
+ __exportStar(require("./types.js"), exports);
38
+ exports.constants = __importStar(require("./constants.js"));
39
+ var ercAbi_js_1 = require("./ercAbi.js");
40
+ Object.defineProperty(exports, "ercAbi", { enumerable: true, get: function () { return __importDefault(ercAbi_js_1).default; } });