@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,30 @@
1
+ import { APTOS_ERROR_MATCH_REGEX } from "./constants.js";
2
+ export function extractAptosErrorCode(errorText) {
3
+ const match = APTOS_ERROR_MATCH_REGEX.exec(errorText);
4
+ if (!match) {
5
+ return null;
6
+ }
7
+ return match[2];
8
+ }
9
+ function isAddressSpecial(address) {
10
+ if (address.length === 3) {
11
+ return true;
12
+ }
13
+ return false;
14
+ }
15
+ /**
16
+ * Aptos has inconsistencies in how it returns addresses.
17
+ * This method normalizes them to be 64+2(0x...) characters long, or leaves it as SPECIAL ADDRESS (0x0 - 0xf inclusive)
18
+ * Per this: https://github.com/aptos-labs/aptos-ts-sdk/blob/main/src/core/accountAddress.ts#L115
19
+ * */
20
+ export function normalizeAptosAddress(address) {
21
+ if (isAddressSpecial(address)) {
22
+ return address;
23
+ }
24
+ const length = address.length;
25
+ if (length === 66 || length < 3) {
26
+ return address;
27
+ }
28
+ const missingZeros = 66 - length;
29
+ return address.slice(0, 2) + "0".repeat(missingZeros) + address.slice(2);
30
+ }
@@ -0,0 +1,33 @@
1
+ import { AptosAccount, TransactionBuilderRemoteABI } from "aptos";
2
+ export class AptosWalletWrapper {
3
+ wallet;
4
+ address;
5
+ client;
6
+ constructor(wallet, client) {
7
+ this.client = client;
8
+ this.wallet = wallet;
9
+ if (wallet instanceof AptosAccount) {
10
+ this.address = wallet.address();
11
+ }
12
+ else {
13
+ this.address = wallet.account.address;
14
+ }
15
+ }
16
+ async signAndSubmitTransaction(input) {
17
+ if (this.wallet instanceof AptosAccount) {
18
+ const builder = new TransactionBuilderRemoteABI(this.client, {
19
+ sender: this.address,
20
+ });
21
+ const rawTxn = await builder.build(input.function, input.type_arguments, input.arguments);
22
+ const res = await this.client.simulateTransaction(this.wallet, rawTxn);
23
+ if (!res[0].success) {
24
+ throw new Error(`Transaction Simulation failed: ${JSON.stringify(res)}`);
25
+ }
26
+ const signedTx = await this.client.signTransaction(this.wallet, rawTxn);
27
+ const tx = await this.client.submitSignedBCSTransaction(signedTx);
28
+ await this.client.waitForTransaction(tx.hash);
29
+ return tx.hash;
30
+ }
31
+ return (await this.wallet.signAndSubmitTransaction(input)).hash;
32
+ }
33
+ }
@@ -1,4 +1,4 @@
1
- import { ICreateStreamData, ICreateMultipleStreamData, IFees, IWithdrawData, ICancelData, ITransferData, ITopUpData, IGetFeesData, IGetOneData, IUpdateData, ITransactionResult, IMultiTransactionResult, ICreateResult, IGetAllData, Stream } from "./types";
1
+ import { ICancelData, ICreateMultipleStreamData, ICreateResult, ICreateStreamData, IFees, IGetAllData, IGetFeesData, IGetOneData, IMultiTransactionResult, ITopUpData, ITransactionResult, ITransferData, IUpdateData, IWithdrawData, Stream } from "./types.js";
2
2
  export declare abstract class BaseStreamClient {
3
3
  abstract create(streamData: ICreateStreamData, chainSpecificParams: any): Promise<ICreateResult>;
4
4
  abstract createMultiple(multipleStreamData: ICreateMultipleStreamData, chainSpecificParams: any): Promise<IMultiTransactionResult>;
@@ -0,0 +1,19 @@
1
+ export class BaseStreamClient {
2
+ /**
3
+ * Returns total fee percent, streamflow fees + partner fees
4
+ * @param getFeesData structure with address for which we need to derive fee, either sender or partner usually
5
+ * @param chainSpecificParams additional parameters required by chain client
6
+ * @returns fee as floating number, so if fee is 0.99%, it will return 0.99
7
+ */
8
+ async getTotalFee(getFeesData, chainSpecificParams) {
9
+ const fees = await this.getFees(getFeesData, chainSpecificParams);
10
+ if (fees) {
11
+ return fees.partnerFee + fees.streamflowFee;
12
+ }
13
+ return this.getDefaultStreamflowFee(chainSpecificParams);
14
+ }
15
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
16
+ extractErrorCode(err) {
17
+ return null;
18
+ }
19
+ }
@@ -1,12 +1,12 @@
1
1
  import { Commitment, ConnectionConfig } from "@solana/web3.js";
2
2
  import { Signer } from "ethers";
3
3
  import PQueue from "p-queue";
4
- import { BaseStreamClient } from "./BaseStreamClient";
5
- import { ICancelData, IChain, ICluster, ICreateMultipleStreamData, ICreateStreamData, IGetOneData, ITopUpData, ITransferData, IUpdateData, IWithdrawData, ITransactionResult, IMultiTransactionResult, ICreateResult, IGetAllData, Stream, IFees, IGetFeesData } from "./types";
6
- import { AptosStreamClient, ICreateStreamAptosExt, ITransactionAptosExt } from "../aptos";
7
- import { EvmStreamClient } from "../evm";
8
- import { SolanaStreamClient, ICreateStreamSolanaExt, IInteractStreamSolanaExt, ITopUpStreamSolanaExt } from "../solana";
9
- import { ICreateStreamSuiExt, ITransactionSuiExt, ISuiIdParameters, SuiStreamClient } from "../sui";
4
+ import { BaseStreamClient } from "./BaseStreamClient.js";
5
+ import { ICancelData, IChain, ICluster, ICreateMultipleStreamData, ICreateStreamData, IGetOneData, ITopUpData, ITransferData, IUpdateData, IWithdrawData, ITransactionResult, IMultiTransactionResult, ICreateResult, IGetAllData, Stream, IFees, IGetFeesData } from "./types.js";
6
+ import { AptosStreamClient, ICreateStreamAptosExt, ITransactionAptosExt } from "../aptos/index.js";
7
+ import { EvmStreamClient } from "../evm/index.js";
8
+ import { SolanaStreamClient, ICreateStreamSolanaExt, IInteractStreamSolanaExt, ITopUpStreamSolanaExt } from "../solana/index.js";
9
+ import { ICreateStreamSuiExt, ITransactionSuiExt, ISuiIdParameters, SuiStreamClient } from "../sui/index.js";
10
10
  export interface SolanaStreamClientOptions {
11
11
  chain: IChain.Solana;
12
12
  clusterUrl: string;
@@ -0,0 +1,101 @@
1
+ import { BaseStreamClient } from "./BaseStreamClient.js";
2
+ import { IChain, } from "./types.js";
3
+ import { handleContractError } from "./utils.js";
4
+ import { AptosStreamClient } from "../aptos/index.js";
5
+ import { EvmStreamClient } from "../evm/index.js";
6
+ import { SolanaStreamClient, } from "../solana/index.js";
7
+ import { SuiStreamClient } from "../sui/index.js";
8
+ import { WITHDRAW_AVAILABLE_AMOUNT } from "./constants.js";
9
+ /** Generic Stream Client implementation that wrap Chain Client methods and enriches error messages if possible
10
+ * @property {StreamClientType} - Chain Client implementation
11
+ * @property {chain} - Chain
12
+ */
13
+ export default class GenericStreamClient extends BaseStreamClient {
14
+ nativeStreamClient;
15
+ chain;
16
+ constructor(options) {
17
+ super();
18
+ this.chain = options.chain;
19
+ switch (options.chain) {
20
+ case IChain.Solana:
21
+ this.nativeStreamClient = new SolanaStreamClient(options.clusterUrl, options.cluster, options.commitment, options.programId, options.sendRate, options.sendThrottler);
22
+ break;
23
+ case IChain.Aptos:
24
+ this.nativeStreamClient = new AptosStreamClient(options.clusterUrl, options.cluster, options.maxGas, options.programId);
25
+ break;
26
+ case IChain.BNB:
27
+ case IChain.Ethereum:
28
+ case IChain.Polygon:
29
+ this.nativeStreamClient = new EvmStreamClient(options.clusterUrl, options.chain, options.signer, options.cluster, options.programId);
30
+ break;
31
+ case IChain.Sui:
32
+ this.nativeStreamClient = new SuiStreamClient(options.clusterUrl, options.cluster, options.ids);
33
+ }
34
+ }
35
+ /**
36
+ * Creates a new stream/vesting contract.
37
+ */
38
+ create(streamData, chainSpecificParams) {
39
+ return handleContractError(() => this.nativeStreamClient.create(streamData, chainSpecificParams), this.nativeStreamClient.extractErrorCode);
40
+ }
41
+ /**
42
+ * Creates multiple stream/vesting contracts.
43
+ */
44
+ createMultiple(multipleStreamData, chainSpecificParams) {
45
+ return handleContractError(() => this.nativeStreamClient.createMultiple(multipleStreamData, chainSpecificParams), this.nativeStreamClient.extractErrorCode);
46
+ }
47
+ /**
48
+ * Attempts withdrawing from the specified stream.
49
+ */
50
+ withdraw({ id, amount = WITHDRAW_AVAILABLE_AMOUNT }, chainSpecificParams) {
51
+ return 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 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 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 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 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
+ }
@@ -0,0 +1,3 @@
1
+ import BigNumber from "bignumber.js";
2
+ export declare const BASE_FEE = 1009900;
3
+ export declare const WITHDRAW_AVAILABLE_AMOUNT: BigNumber;
@@ -0,0 +1,3 @@
1
+ import BigNumber from "bignumber.js";
2
+ export const BASE_FEE = 1009900; // Buffer to include usual fees when calculating stream amount
3
+ export const WITHDRAW_AVAILABLE_AMOUNT = BigNumber("18446744073709551615"); // Magical number to withdraw all available amount from a Contract
@@ -1,28 +1,28 @@
1
- import BN from "bn.js";
2
- import { StreamType } from "./types";
1
+ import BigNumber from "bignumber.js";
2
+ import { StreamType } from "./types.js";
3
3
  interface ICalculateUnlockedAmount {
4
- depositedAmount: BN;
4
+ depositedAmount: BigNumber;
5
5
  cliff: number;
6
- cliffAmount: BN;
6
+ cliffAmount: BigNumber;
7
7
  end: number;
8
8
  currentTimestamp: number;
9
9
  lastRateChangeTime: number;
10
10
  period: number;
11
- amountPerPeriod: BN;
12
- fundsUnlockedAtLastRateChange: BN;
11
+ amountPerPeriod: BigNumber;
12
+ fundsUnlockedAtLastRateChange: BigNumber;
13
13
  }
14
- export declare const calculateUnlockedAmount: ({ depositedAmount, cliff, cliffAmount, end, currentTimestamp, lastRateChangeTime, period, amountPerPeriod, fundsUnlockedAtLastRateChange, }: ICalculateUnlockedAmount) => BN;
14
+ export declare const calculateUnlockedAmount: ({ depositedAmount, cliff, cliffAmount, end, currentTimestamp, lastRateChangeTime, period, amountPerPeriod, fundsUnlockedAtLastRateChange, }: ICalculateUnlockedAmount) => BigNumber;
15
15
  export declare const isCliffCloseToDepositedAmount: (streamData: {
16
- depositedAmount: BN;
17
- cliffAmount: BN;
16
+ depositedAmount: BigNumber;
17
+ cliffAmount: BigNumber;
18
18
  }) => boolean;
19
19
  export declare const isPayment: (streamData: {
20
20
  canTopup: boolean;
21
21
  }) => boolean;
22
22
  export declare const isVesting: (streamData: {
23
23
  canTopup: boolean;
24
- depositedAmount: BN;
25
- cliffAmount: BN;
24
+ depositedAmount: BigNumber;
25
+ cliffAmount: BigNumber;
26
26
  }) => boolean;
27
27
  export declare const isTokenLock: (streamData: {
28
28
  canTopup: boolean;
@@ -31,8 +31,8 @@ export declare const isTokenLock: (streamData: {
31
31
  cancelableByRecipient: boolean;
32
32
  transferableBySender: boolean;
33
33
  transferableByRecipient: boolean;
34
- depositedAmount: BN;
35
- cliffAmount: BN;
34
+ depositedAmount: BigNumber;
35
+ cliffAmount: BigNumber;
36
36
  }) => boolean;
37
37
  export declare const buildStreamType: (streamData: {
38
38
  canTopup: boolean;
@@ -41,7 +41,7 @@ export declare const buildStreamType: (streamData: {
41
41
  cancelableByRecipient: boolean;
42
42
  transferableBySender: boolean;
43
43
  transferableByRecipient: boolean;
44
- depositedAmount: BN;
45
- cliffAmount: BN;
44
+ depositedAmount: BigNumber;
45
+ cliffAmount: BigNumber;
46
46
  }) => StreamType;
47
47
  export {};
@@ -0,0 +1,42 @@
1
+ import BigNumber from "bignumber.js";
2
+ import { StreamType } from "./types.js";
3
+ export const calculateUnlockedAmount = ({ depositedAmount, cliff, cliffAmount, end, currentTimestamp, lastRateChangeTime, period, amountPerPeriod, fundsUnlockedAtLastRateChange, }) => {
4
+ const deposited = depositedAmount;
5
+ if (currentTimestamp < cliff)
6
+ return BigNumber(0);
7
+ if (currentTimestamp > end)
8
+ return deposited;
9
+ const savedUnlockedFunds = lastRateChangeTime === 0 ? cliffAmount : fundsUnlockedAtLastRateChange;
10
+ const savedUnlockedFundsTime = lastRateChangeTime === 0 ? cliff : lastRateChangeTime;
11
+ const streamed = BigNumber(Math.floor((currentTimestamp - savedUnlockedFundsTime) / period))
12
+ .times(amountPerPeriod)
13
+ .plus(savedUnlockedFunds);
14
+ return streamed.lt(deposited) ? streamed : deposited;
15
+ };
16
+ export const isCliffCloseToDepositedAmount = (streamData) => {
17
+ return streamData.cliffAmount.gte(streamData.depositedAmount.minus(BigNumber(1)));
18
+ };
19
+ export const isPayment = (streamData) => {
20
+ return streamData.canTopup;
21
+ };
22
+ export const isVesting = (streamData) => {
23
+ return !streamData.canTopup && !isCliffCloseToDepositedAmount(streamData);
24
+ };
25
+ export const isTokenLock = (streamData) => {
26
+ return (!streamData.canTopup &&
27
+ !streamData.automaticWithdrawal &&
28
+ !streamData.cancelableBySender &&
29
+ !streamData.cancelableByRecipient &&
30
+ !streamData.transferableBySender &&
31
+ !streamData.transferableByRecipient &&
32
+ isCliffCloseToDepositedAmount(streamData));
33
+ };
34
+ export const buildStreamType = (streamData) => {
35
+ if (isVesting(streamData)) {
36
+ return StreamType.Vesting;
37
+ }
38
+ if (isTokenLock(streamData)) {
39
+ return StreamType.Lock;
40
+ }
41
+ return StreamType.Payment;
42
+ };
@@ -1,13 +1,13 @@
1
1
  import { TransactionInstruction } from "@solana/web3.js";
2
2
  import { Types } from "aptos";
3
- import BN from "bn.js";
3
+ import BigNumber from "bignumber.js";
4
4
  export { IChain, ICluster, ContractError } from "@streamflow/common";
5
5
  export interface IRecipient {
6
6
  recipient: string;
7
- amount: BN;
7
+ amount: BigNumber;
8
8
  name: string;
9
- cliffAmount: BN;
10
- amountPerPeriod: BN;
9
+ cliffAmount: BigNumber;
10
+ amountPerPeriod: BigNumber;
11
11
  }
12
12
  export interface IStreamConfig {
13
13
  period: number;
@@ -33,19 +33,19 @@ export interface IInteractData {
33
33
  id: string;
34
34
  }
35
35
  export interface IWithdrawData extends IInteractData {
36
- amount?: BN;
36
+ amount?: BigNumber;
37
37
  }
38
38
  export interface IUpdateData extends IInteractData {
39
39
  enableAutomaticWithdrawal?: boolean;
40
- withdrawFrequency?: BN;
41
- amountPerPeriod?: BN;
40
+ withdrawFrequency?: BigNumber;
41
+ amountPerPeriod?: BigNumber;
42
42
  }
43
43
  export type ICancelData = IInteractData;
44
44
  export interface ITransferData extends IInteractData {
45
45
  newRecipient: string;
46
46
  }
47
47
  export interface ITopUpData extends IInteractData {
48
- amount: BN;
48
+ amount: BigNumber;
49
49
  }
50
50
  export type IGetOneData = IInteractData;
51
51
  export interface IGetFeesData {
@@ -184,7 +184,7 @@ export interface Stream {
184
184
  magic: number;
185
185
  version: number;
186
186
  createdAt: number;
187
- withdrawnAmount: BN;
187
+ withdrawnAmount: BigNumber;
188
188
  canceledAt: number;
189
189
  end: number;
190
190
  lastWithdrawnAt: number;
@@ -196,20 +196,20 @@ export interface Stream {
196
196
  escrowTokens: string;
197
197
  streamflowTreasury: string;
198
198
  streamflowTreasuryTokens: string;
199
- streamflowFeeTotal: BN;
200
- streamflowFeeWithdrawn: BN;
199
+ streamflowFeeTotal: BigNumber;
200
+ streamflowFeeWithdrawn: BigNumber;
201
201
  streamflowFeePercent: number;
202
- partnerFeeTotal: BN;
203
- partnerFeeWithdrawn: BN;
202
+ partnerFeeTotal: BigNumber;
203
+ partnerFeeWithdrawn: BigNumber;
204
204
  partnerFeePercent: number;
205
205
  partner: string;
206
206
  partnerTokens: string;
207
207
  start: number;
208
- depositedAmount: BN;
208
+ depositedAmount: BigNumber;
209
209
  period: number;
210
- amountPerPeriod: BN;
210
+ amountPerPeriod: BigNumber;
211
211
  cliff: number;
212
- cliffAmount: BN;
212
+ cliffAmount: BigNumber;
213
213
  cancelableBySender: boolean;
214
214
  cancelableByRecipient: boolean;
215
215
  automaticWithdrawal: boolean;
@@ -220,10 +220,10 @@ export interface Stream {
220
220
  withdrawalFrequency: number;
221
221
  closed: boolean;
222
222
  currentPauseStart: number;
223
- pauseCumulative: BN;
223
+ pauseCumulative: BigNumber;
224
224
  lastRateChangeTime: number;
225
- fundsUnlockedAtLastRateChange: BN;
225
+ fundsUnlockedAtLastRateChange: BigNumber;
226
226
  type: StreamType;
227
- unlocked(currentTimestamp: number): BN;
227
+ unlocked(currentTimestamp: number): BigNumber;
228
228
  remaining(decimals: number): number;
229
229
  }
@@ -0,0 +1,106 @@
1
+ export { IChain, ICluster, ContractError } from "@streamflow/common";
2
+ export var StreamDirection;
3
+ (function (StreamDirection) {
4
+ StreamDirection["Outgoing"] = "outgoing";
5
+ StreamDirection["Incoming"] = "incoming";
6
+ StreamDirection["All"] = "all";
7
+ })(StreamDirection || (StreamDirection = {}));
8
+ export var StreamType;
9
+ (function (StreamType) {
10
+ StreamType["All"] = "all";
11
+ StreamType["Payment"] = "payment";
12
+ StreamType["Vesting"] = "vesting";
13
+ StreamType["Lock"] = "lock";
14
+ })(StreamType || (StreamType = {}));
15
+ /**
16
+ * Error codes raised by all protocols except for Solana
17
+ */
18
+ export var ContractErrorCode;
19
+ (function (ContractErrorCode) {
20
+ /** Contract does not exist */
21
+ ContractErrorCode["ECONTRACT_NOT_INIT"] = "ECONTRACT_NOT_INIT";
22
+ /** Invalid total amount */
23
+ ContractErrorCode["EBAD_AMOUNT"] = "EBAD_AMOUNT";
24
+ /** No permissions to perform an operation */
25
+ ContractErrorCode["ENO_PERMISSIONS"] = "ENO_PERMISSIONS";
26
+ /** Invalid input parameters on create/update */
27
+ ContractErrorCode["EBADINPUT"] = "EBADINPUT";
28
+ /** Contract is already ended */
29
+ ContractErrorCode["ECLOSED"] = "ECLOSED";
30
+ /** Invalid amount per period input */
31
+ ContractErrorCode["EBAD_INPUT_AMOUNT_PER_PERIOD"] = "EBAD_INPUT_AMOUNT_PER_PERIOD";
32
+ /** Pause feature is not supported */
33
+ ContractErrorCode["EBAD_INPUT_PAUSABLE"] = "EBAD_INPUT_PAUSABLE";
34
+ /** Not used currently */
35
+ ContractErrorCode["EBAD_INPUT_UPDATE_RATE"] = "EBAD_INPUT_UPDATE_RATE";
36
+ /** Invalid cliff amount input */
37
+ ContractErrorCode["EBAD_INPUT_CLIFF_AMOUNT"] = "EBAD_INPUT_CLIFF_AMOUNT";
38
+ /** Invalid period input */
39
+ ContractErrorCode["EBAD_INPUT_PERIOD"] = "EBAD_INPUT_PERIOD";
40
+ /** Invalid start time of the contract */
41
+ ContractErrorCode["EBAD_INPUT_START"] = "EBAD_INPUT_START";
42
+ /** EVM: token allowance is not enough to create a Contract */
43
+ ContractErrorCode["EBAD_INSUFFICIENT_TOKEN_ALLOWANCE"] = "EBAD_INSUFFICIENT_TOKEN_ALLOWANCE";
44
+ /** EVM: not enough coins were passed for withdrawal fees */
45
+ ContractErrorCode["EBAD_INSUFFICIENT_WITHDRAWAL_FEES"] = "EBAD_INSUFFICIENT_WITHDRAWAL_FEES";
46
+ /** Sui: Insufficient amount of tokens passed */
47
+ ContractErrorCode["EBAD_INSUFFICIENT_AMOUNT"] = "EBAD_INSUFFICIENT_AMOUNT";
48
+ /** Contract is already paused */
49
+ ContractErrorCode["EPAUSED"] = "EPAUSED";
50
+ /** Contract is not paused */
51
+ ContractErrorCode["ENOTPAUSED"] = "ENOTPAUSED";
52
+ /** Aptos: user opt out from direct coin transfers feature and has not coin wallet registered */
53
+ ContractErrorCode["ENO_RECIPIENT_COIN_ADDRESS"] = "ENO_RECIPIENT_COIN_ADDRESS";
54
+ })(ContractErrorCode || (ContractErrorCode = {}));
55
+ /**
56
+ * Error codes raised by Solana protocol specifically
57
+ */
58
+ export var SolanaContractErrorCode;
59
+ (function (SolanaContractErrorCode) {
60
+ /** Accounts not writable */
61
+ SolanaContractErrorCode["AccountsNotWritable"] = "AccountsNotWritable";
62
+ /** Invalid Metadata */
63
+ SolanaContractErrorCode["InvalidMetadata"] = "InvalidMetadata";
64
+ /** Invalid metadata account */
65
+ SolanaContractErrorCode["InvalidMetadataAccount"] = "InvalidMetadataAccount";
66
+ /** Provided accounts don't match the ones in contract */
67
+ SolanaContractErrorCode["MetadataAccountMismatch"] = "MetadataAccountMismatch";
68
+ /** Invalid escrow account */
69
+ SolanaContractErrorCode["InvalidEscrowAccount"] = "InvalidEscrowAccount";
70
+ /** Provided account(s) is/are not valid associated token accounts */
71
+ SolanaContractErrorCode["NotAssociated"] = "NotAssociated";
72
+ /** Sender mint does not match accounts mint */
73
+ SolanaContractErrorCode["MintMismatch"] = "MintMismatch";
74
+ /** Recipient not transferable for account */
75
+ SolanaContractErrorCode["TransferNotAllowed"] = "TransferNotAllowed";
76
+ /** Contract closed */
77
+ SolanaContractErrorCode["ContractClosed"] = "ContractClosed";
78
+ /** Invalid Streamflow Treasury accounts supplied */
79
+ SolanaContractErrorCode["InvalidTreasury"] = "InvalidTreasury";
80
+ /** Given timestamps are invalid */
81
+ SolanaContractErrorCode["InvalidTimestamps"] = "InvalidTimestamps";
82
+ /** Invalid deposit configuration */
83
+ SolanaContractErrorCode["InvalidDepositConfiguration"] = "InvalidDepositConfiguration";
84
+ /** Amount cannot be zero */
85
+ SolanaContractErrorCode["AmountIsZero"] = "AmountIsZero";
86
+ /** Amount requested is larger than available */
87
+ SolanaContractErrorCode["AmountMoreThanAvailable"] = "AmountMoreThanAvailable";
88
+ /** Amount currently available is zero */
89
+ SolanaContractErrorCode["AmountAvailableIsZero"] = "AmountAvailableIsZero";
90
+ /** Arithmetic error */
91
+ SolanaContractErrorCode["ArithmeticError"] = "ArithmeticError";
92
+ /** Metadata account data must be 1104 bytes long */
93
+ SolanaContractErrorCode["InvalidMetadataSize"] = "InvalidMetadataSize";
94
+ /** Metadata state account must be initialized */
95
+ SolanaContractErrorCode["UninitializedMetadata"] = "UninitializedMetadata";
96
+ /** Authority does not have permission for this action */
97
+ SolanaContractErrorCode["Unauthorized"] = "Unauthorized";
98
+ /** Contract is not transferable to the original recipient */
99
+ SolanaContractErrorCode["SelfTransfer"] = "SelfTransfer";
100
+ /** Contract is already paused */
101
+ SolanaContractErrorCode["AlreadyPaused"] = "AlreadyPaused";
102
+ /** Contract is not paused */
103
+ SolanaContractErrorCode["NotPaused"] = "NotPaused";
104
+ /** Meta account is not rent exempt */
105
+ SolanaContractErrorCode["MetadataNotRentExempt"] = "MetadataNotRentExempt";
106
+ })(SolanaContractErrorCode || (SolanaContractErrorCode = {}));
@@ -1,28 +1,28 @@
1
- import BN from "bn.js";
1
+ import BigNumber from "bignumber.js";
2
2
  /**
3
- * Used for conversion of token amounts to their Big Number representation.
4
- * Get Big Number representation in the smallest units from the same value in the highest units.
5
- * @param {number} value - Number of tokens you want to convert to its BN representation.
3
+ * Used for token amounts conversion from their Big Number representation to number.
4
+ * Get value in the highest units from BigNumber representation of the same value in the smallest units.
5
+ * @param {BigNumber} value - Big Number representation of value in the smallest units.
6
6
  * @param {number} decimals - Number of decimals the token has.
7
7
  */
8
- export declare const getBN: (value: number, decimals: number) => BN;
8
+ export declare const getNumberFromBigNumber: (bigNum: BigNumber, decimals: number) => number;
9
9
  /**
10
- * Used for token amounts conversion from their Big Number representation to number.
11
- * Get value in the highest units from BN representation of the same value in the smallest units.
12
- * @param {BN} value - Big Number representation of value in the smallest units.
10
+ * Used for conversion of token amounts to their Big Number representation.
11
+ * Get Big Number representation in the smallest units from the same value in the highest units.
12
+ * @param {number} value - Number of tokens you want to convert to its BigNumber representation.
13
13
  * @param {number} decimals - Number of decimals the token has.
14
14
  */
15
- export declare const getNumberFromBN: (value: BN, decimals: number) => number;
15
+ export declare const getScaledBigNumber: (value: number | string | BigNumber, decimals: number) => BigNumber;
16
16
  /**
17
17
  * Calculate total amount of a Contract including all fees.
18
- * - first we convert fee floating to a BN with up to 4 decimals precision
18
+ * - first we convert fee floating to a BigNumber with up to 4 decimals precision
19
19
  * - then we reverse the fee with `FEE_MULTIPLIER` to safely multiply it by depositedAmount
20
20
  * to receive a total number and not percentage of depositedAmount
21
21
  * @param depositedAmount deposited raw tokens
22
22
  * @param totalFee sum of all fees in percentage as floating number, e.g. 0.99% should be supplied as 0.99
23
23
  * @returns total tokens amount that Contract will retrieve from the Sender
24
24
  */
25
- export declare const calculateTotalAmountToDeposit: (depositedAmount: BN, totalFee: number) => BN;
25
+ export declare const calculateTotalAmountToDeposit: (depositedAmount: BigNumber, totalFee: number) => BigNumber;
26
26
  /**
27
27
  * Used to make on chain calls to the contract and wrap raised errors if any
28
28
  * @param func function that interacts with the contract
@@ -30,4 +30,3 @@ export declare const calculateTotalAmountToDeposit: (depositedAmount: BN, totalF
30
30
  * @returns {T}
31
31
  */
32
32
  export declare function handleContractError<T>(func: () => Promise<T>, callback?: (err: Error) => string | null): Promise<T>;
33
- export { normalizeAptosAddress } from "../aptos/utils";
@@ -0,0 +1,56 @@
1
+ import BigNumber from "bignumber.js";
2
+ import { ContractError } from "./types.js";
3
+ const FEE_PRECISION = 4;
4
+ const FEE_NORMALIZER = 10 ** FEE_PRECISION;
5
+ const FEE_MULTIPLIER = BigNumber(10 ** 6);
6
+ /**
7
+ * Used for token amounts conversion from their Big Number representation to number.
8
+ * Get value in the highest units from BigNumber representation of the same value in the smallest units.
9
+ * @param {BigNumber} value - Big Number representation of value in the smallest units.
10
+ * @param {number} decimals - Number of decimals the token has.
11
+ */
12
+ export const getNumberFromBigNumber = (bigNum, decimals) => {
13
+ return bigNum.div(BigNumber(10).pow(decimals)).toNumber();
14
+ };
15
+ /**
16
+ * Used for conversion of token amounts to their Big Number representation.
17
+ * Get Big Number representation in the smallest units from the same value in the highest units.
18
+ * @param {number} value - Number of tokens you want to convert to its BigNumber representation.
19
+ * @param {number} decimals - Number of decimals the token has.
20
+ */
21
+ export const getScaledBigNumber = (value, decimals) => {
22
+ return new BigNumber(value).times(new BigNumber(10).pow(decimals));
23
+ };
24
+ /**
25
+ * Calculate total amount of a Contract including all fees.
26
+ * - first we convert fee floating to a BigNumber with up to 4 decimals precision
27
+ * - then we reverse the fee with `FEE_MULTIPLIER` to safely multiply it by depositedAmount
28
+ * to receive a total number and not percentage of depositedAmount
29
+ * @param depositedAmount deposited raw tokens
30
+ * @param totalFee sum of all fees in percentage as floating number, e.g. 0.99% should be supplied as 0.99
31
+ * @returns total tokens amount that Contract will retrieve from the Sender
32
+ */
33
+ export const calculateTotalAmountToDeposit = (depositedAmount, totalFee) => {
34
+ const totalFeeNormalized = BigNumber(totalFee).times(FEE_NORMALIZER);
35
+ return depositedAmount.times(totalFeeNormalized.plus(FEE_MULTIPLIER)).div(FEE_MULTIPLIER);
36
+ };
37
+ /**
38
+ * Used to make on chain calls to the contract and wrap raised errors if any
39
+ * @param func function that interacts with the contract
40
+ * @param callback callback that may be used to extract error code
41
+ * @returns {T}
42
+ */
43
+ export async function handleContractError(func, callback) {
44
+ try {
45
+ return await func();
46
+ }
47
+ catch (err) {
48
+ if (err instanceof Error) {
49
+ if (callback) {
50
+ throw new ContractError(err, callback(err));
51
+ }
52
+ throw new ContractError(err);
53
+ }
54
+ throw err;
55
+ }
56
+ }
@@ -1,7 +1,7 @@
1
1
  import { ethers } from "ethers";
2
- import BN from "bn.js";
3
- import { BaseStreamClient } from "../common/BaseStreamClient";
4
- import { ICancelData, IChain, ICluster, ICreateMultipleStreamData, ICreateResult, ICreateStreamData, IGetFeesData, IGetAllData, IGetOneData, IFees, IMultiTransactionResult, ITopUpData, ITransactionResult, ITransferData, IUpdateData, IWithdrawData, Stream } from "../common/types";
2
+ import BigNumber from "bignumber.js";
3
+ import { BaseStreamClient } from "../common/BaseStreamClient.js";
4
+ import { ICancelData, IChain, ICluster, ICreateMultipleStreamData, ICreateResult, ICreateStreamData, IGetFeesData, IGetAllData, IGetOneData, IFees, IMultiTransactionResult, ITopUpData, ITransactionResult, ITransferData, IUpdateData, IWithdrawData, Stream } from "../common/types.js";
5
5
  export default class EvmStreamClient extends BaseStreamClient {
6
6
  private programId;
7
7
  private provider;
@@ -25,7 +25,7 @@ export default class EvmStreamClient extends BaseStreamClient {
25
25
  * Returns StreamClient protocol program ID.
26
26
  */
27
27
  getProgramId(): string;
28
- approveTokens(tokenId: string, amount: BN): Promise<void>;
28
+ approveTokens(tokenId: string, amount: BigNumber): Promise<void>;
29
29
  private generateMultiPayloads;
30
30
  private getFeeParams;
31
31
  private formatMetadataId;