@streamflow/stream 6.3.8 → 7.0.0-alpha.1

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 (121) hide show
  1. package/README.md +33 -1
  2. package/dist/{__tests__ → cjs/__tests__}/aptos/streamClient.spec.js +22 -21
  3. package/dist/cjs/__tests__/common/GenericStreamClient.spec.js +45 -0
  4. package/dist/{aptos → cjs/aptos}/StreamClient.js +20 -20
  5. package/dist/cjs/aptos/constants.js +28 -0
  6. package/dist/{aptos → cjs/aptos}/index.js +3 -3
  7. package/dist/{aptos → cjs/aptos}/types.js +12 -11
  8. package/dist/{aptos → cjs/aptos}/utils.js +2 -2
  9. package/dist/{common → cjs/common}/GenericStreamClient.js +19 -19
  10. package/dist/{common → cjs/common}/contractUtils.js +4 -4
  11. package/dist/{common → cjs/common}/utils.js +4 -6
  12. package/dist/{evm → cjs/evm}/StreamClient.js +29 -29
  13. package/dist/cjs/evm/constants.js +39 -0
  14. package/dist/{evm → cjs/evm}/index.js +8 -8
  15. package/dist/{evm → cjs/evm}/types.js +5 -5
  16. package/dist/{evm → cjs/evm}/utils.js +2 -2
  17. package/dist/{solana → cjs/solana}/StreamClient.js +73 -66
  18. package/dist/cjs/solana/constants.js +60 -0
  19. package/dist/cjs/solana/index.js +39 -0
  20. package/dist/{solana → cjs/solana}/instructions.js +20 -12
  21. package/dist/{solana → cjs/solana}/layout.js +8 -2
  22. package/dist/{solana → cjs/solana}/types.js +5 -5
  23. package/dist/{solana → cjs/solana}/utils.js +6 -6
  24. package/dist/{sui → cjs/sui}/StreamClient.js +25 -25
  25. package/dist/cjs/sui/constants.js +43 -0
  26. package/dist/{sui → cjs/sui}/index.js +5 -5
  27. package/dist/{sui → cjs/sui}/types.js +5 -5
  28. package/dist/{sui → cjs/sui}/utils.js +3 -3
  29. package/dist/esm/__tests__/aptos/streamClient.spec.js +106 -0
  30. package/dist/esm/__tests__/common/GenericStreamClient.spec.js +40 -0
  31. package/dist/{aptos → esm/aptos}/StreamClient.d.ts +3 -3
  32. package/dist/esm/aptos/StreamClient.js +226 -0
  33. package/dist/{aptos → esm/aptos}/constants.d.ts +1 -1
  34. package/dist/esm/aptos/constants.js +24 -0
  35. package/dist/{aptos → esm/aptos}/index.d.ts +1 -1
  36. package/dist/{sui/index.d.ts → esm/aptos/index.js} +1 -1
  37. package/dist/{aptos → esm/aptos}/types.d.ts +1 -1
  38. package/dist/esm/aptos/types.js +105 -0
  39. package/dist/esm/aptos/utils.js +30 -0
  40. package/dist/esm/aptos/wallet.js +33 -0
  41. package/dist/{common → esm/common}/BaseStreamClient.d.ts +1 -1
  42. package/dist/esm/common/BaseStreamClient.js +19 -0
  43. package/dist/{common → esm/common}/GenericStreamClient.d.ts +2 -2
  44. package/dist/esm/common/GenericStreamClient.js +101 -0
  45. package/dist/esm/common/constants.js +3 -0
  46. package/dist/{common → esm/common}/contractUtils.d.ts +1 -1
  47. package/dist/esm/common/contractUtils.js +42 -0
  48. package/dist/esm/common/types.js +106 -0
  49. package/dist/{common → esm/common}/utils.d.ts +0 -1
  50. package/dist/esm/common/utils.js +59 -0
  51. package/dist/{evm → esm/evm}/StreamClient.d.ts +2 -2
  52. package/dist/esm/evm/StreamClient.js +237 -0
  53. package/dist/esm/evm/abi.js +1255 -0
  54. package/dist/{evm → esm/evm}/constants.d.ts +1 -1
  55. package/dist/esm/evm/constants.js +35 -0
  56. package/dist/esm/evm/ercAbi.js +222 -0
  57. package/dist/esm/evm/index.d.ts +5 -0
  58. package/dist/esm/evm/index.js +5 -0
  59. package/dist/{evm → esm/evm}/types.d.ts +1 -1
  60. package/dist/esm/evm/types.js +102 -0
  61. package/dist/esm/evm/utils.js +8 -0
  62. package/dist/esm/index.js +9 -0
  63. package/dist/{solana → esm/solana}/StreamClient.d.ts +6 -6
  64. package/dist/esm/solana/StreamClient.js +695 -0
  65. package/dist/{solana → esm/solana}/constants.d.ts +2 -0
  66. package/dist/esm/solana/constants.js +56 -0
  67. package/dist/esm/solana/index.d.ts +6 -0
  68. package/dist/esm/solana/index.js +6 -0
  69. package/dist/esm/solana/instructionTypes.js +1 -0
  70. package/dist/{solana → esm/solana}/instructions.d.ts +5 -1
  71. package/dist/esm/solana/instructions.js +256 -0
  72. package/dist/{solana → esm/solana}/layout.d.ts +2 -1
  73. package/dist/esm/solana/layout.js +155 -0
  74. package/dist/esm/solana/timelockIDL.js +420 -0
  75. package/dist/{solana → esm/solana}/types.d.ts +2 -1
  76. package/dist/esm/solana/types.js +101 -0
  77. package/dist/{solana → esm/solana}/utils.d.ts +2 -1
  78. package/dist/esm/solana/utils.js +117 -0
  79. package/dist/{sui → esm/sui}/StreamClient.d.ts +3 -3
  80. package/dist/esm/sui/StreamClient.js +403 -0
  81. package/dist/{sui → esm/sui}/constants.d.ts +1 -1
  82. package/dist/esm/sui/constants.js +39 -0
  83. package/dist/esm/sui/index.d.ts +4 -0
  84. package/dist/esm/sui/index.js +4 -0
  85. package/dist/{sui → esm/sui}/types.d.ts +1 -1
  86. package/dist/esm/sui/types.js +104 -0
  87. package/dist/{sui → esm/sui}/utils.d.ts +1 -1
  88. package/dist/esm/sui/utils.js +23 -0
  89. package/dist/{sui → esm/sui}/wallet.d.ts +1 -1
  90. package/dist/esm/sui/wallet.js +38 -0
  91. package/package.json +36 -33
  92. package/dist/__tests__/common/GenericStreamClient.spec.js +0 -44
  93. package/dist/aptos/constants.js +0 -28
  94. package/dist/evm/constants.js +0 -39
  95. package/dist/evm/index.d.ts +0 -5
  96. package/dist/solana/constants.js +0 -59
  97. package/dist/solana/index.d.ts +0 -7
  98. package/dist/solana/index.js +0 -43
  99. package/dist/sui/constants.js +0 -43
  100. /package/dist/{aptos → cjs/aptos}/wallet.js +0 -0
  101. /package/dist/{common → cjs/common}/BaseStreamClient.js +0 -0
  102. /package/dist/{common → cjs/common}/constants.js +0 -0
  103. /package/dist/{common → cjs/common}/types.js +0 -0
  104. /package/dist/{evm → cjs/evm}/abi.js +0 -0
  105. /package/dist/{evm → cjs/evm}/ercAbi.js +0 -0
  106. /package/dist/{index.js → cjs/index.js} +0 -0
  107. /package/dist/{solana → cjs/solana}/instructionTypes.js +0 -0
  108. /package/dist/{solana → cjs/solana}/timelockIDL.js +0 -0
  109. /package/dist/{sui → cjs/sui}/wallet.js +0 -0
  110. /package/dist/{__tests__ → esm/__tests__}/aptos/streamClient.spec.d.ts +0 -0
  111. /package/dist/{__tests__ → esm/__tests__}/common/GenericStreamClient.spec.d.ts +0 -0
  112. /package/dist/{aptos → esm/aptos}/utils.d.ts +0 -0
  113. /package/dist/{aptos → esm/aptos}/wallet.d.ts +0 -0
  114. /package/dist/{common → esm/common}/constants.d.ts +0 -0
  115. /package/dist/{common → esm/common}/types.d.ts +0 -0
  116. /package/dist/{evm → esm/evm}/abi.d.ts +0 -0
  117. /package/dist/{evm → esm/evm}/ercAbi.d.ts +0 -0
  118. /package/dist/{evm → esm/evm}/utils.d.ts +0 -0
  119. /package/dist/{index.d.ts → esm/index.d.ts} +0 -0
  120. /package/dist/{solana → esm/solana}/instructionTypes.d.ts +0 -0
  121. /package/dist/{solana → esm/solana}/timelockIDL.d.ts +0 -0
@@ -0,0 +1,226 @@
1
+ import { AptosAccount, AptosClient } from "aptos";
2
+ import { BaseStreamClient } from "../common/BaseStreamClient.js";
3
+ import { ICluster, } from "../common/types.js";
4
+ import { APTOS_PROGRAM_IDS } from "./constants.js";
5
+ import { Contract, } from "./types.js";
6
+ import { AptosWalletWrapper } from "./wallet.js";
7
+ import { extractAptosErrorCode } from "./utils.js";
8
+ import { WITHDRAW_AVAILABLE_AMOUNT } from "../common/constants.js";
9
+ export default class AptosStreamClient extends BaseStreamClient {
10
+ programId;
11
+ maxGas;
12
+ client;
13
+ constructor(clusterUrl, cluster = ICluster.Mainnet, maxGas = "10000", programId) {
14
+ super();
15
+ this.programId = programId ? programId : APTOS_PROGRAM_IDS[cluster];
16
+ this.maxGas = maxGas;
17
+ this.client = new AptosClient(clusterUrl);
18
+ }
19
+ /**
20
+ * Creates a new stream/vesting contract.
21
+ */
22
+ async create(streamData, { senderWallet }) {
23
+ const wallet = new AptosWalletWrapper(senderWallet, this.client);
24
+ const [metadataId, payload] = this.generateMultiPayloads({
25
+ ...streamData,
26
+ recipients: [{ ...streamData }],
27
+ }, wallet)[0];
28
+ const hash = await wallet.signAndSubmitTransaction(payload);
29
+ return { ixs: [payload], txId: hash, metadataId };
30
+ }
31
+ /**
32
+ * Creates multiple stream/vesting contracts.
33
+ */
34
+ async createMultiple(multipleStreamData, { senderWallet }) {
35
+ const wallet = new AptosWalletWrapper(senderWallet, this.client);
36
+ const payloads = this.generateMultiPayloads(multipleStreamData, wallet);
37
+ const txs = [];
38
+ const metadatas = [];
39
+ const metadataToRecipient = {};
40
+ const errors = [];
41
+ for (let i = 0; i < payloads.length; i++) {
42
+ const [metadataId, payload] = payloads[i];
43
+ const recipient = multipleStreamData.recipients[i];
44
+ try {
45
+ const hash = await wallet.signAndSubmitTransaction(payload);
46
+ txs.push(hash);
47
+ }
48
+ catch (e) {
49
+ errors.push({
50
+ error: e?.toString() ?? "Unknown error!",
51
+ recipient: recipient.recipient,
52
+ });
53
+ }
54
+ finally {
55
+ metadatas.push(metadataId);
56
+ metadataToRecipient[metadataId] = recipient;
57
+ }
58
+ }
59
+ return {
60
+ txs,
61
+ metadatas,
62
+ metadataToRecipient,
63
+ errors,
64
+ };
65
+ }
66
+ /**
67
+ * Attempts withdrawing from the specified stream.
68
+ */
69
+ async withdraw({ id, amount = WITHDRAW_AVAILABLE_AMOUNT }, { senderWallet, tokenId }) {
70
+ const payload = {
71
+ type: "withdraw",
72
+ function: `${this.programId}::protocol::withdraw`,
73
+ type_arguments: [tokenId],
74
+ arguments: [id, amount.toString()],
75
+ };
76
+ const wallet = new AptosWalletWrapper(senderWallet, this.client);
77
+ const hash = await wallet.signAndSubmitTransaction(payload);
78
+ return { ixs: [payload], txId: hash };
79
+ }
80
+ /**
81
+ * Attempts canceling the specified stream.
82
+ */
83
+ async cancel(cancelData, { senderWallet, tokenId }) {
84
+ const payload = {
85
+ type: "cancel",
86
+ function: `${this.programId}::protocol::cancel`,
87
+ type_arguments: [tokenId],
88
+ arguments: [cancelData.id],
89
+ };
90
+ const wallet = new AptosWalletWrapper(senderWallet, this.client);
91
+ const hash = await wallet.signAndSubmitTransaction(payload);
92
+ return { ixs: [payload], txId: hash };
93
+ }
94
+ /**
95
+ * Attempts changing the stream/vesting contract's recipient (effectively transferring the stream/vesting contract).
96
+ */
97
+ async transfer(transferData, { senderWallet, tokenId }) {
98
+ const payload = {
99
+ type: "transfer",
100
+ function: `${this.programId}::protocol::transfer`,
101
+ type_arguments: [tokenId],
102
+ arguments: [transferData.id, transferData.newRecipient],
103
+ };
104
+ const wallet = new AptosWalletWrapper(senderWallet, this.client);
105
+ const hash = await wallet.signAndSubmitTransaction(payload);
106
+ return { ixs: [payload], txId: hash };
107
+ }
108
+ /**
109
+ * Tops up stream account with specified amount.
110
+ */
111
+ async topup(topupData, { senderWallet, tokenId }) {
112
+ const payload = {
113
+ type: "topup",
114
+ function: `${this.programId}::protocol::topup`,
115
+ type_arguments: [tokenId],
116
+ arguments: [topupData.id, topupData.amount.toString()],
117
+ };
118
+ const wallet = new AptosWalletWrapper(senderWallet, this.client);
119
+ const hash = await wallet.signAndSubmitTransaction(payload);
120
+ return { ixs: [payload], txId: hash };
121
+ }
122
+ /**
123
+ * Fetch stream data by its id (address).
124
+ */
125
+ async getOne({ id }) {
126
+ const contractResources = await this.client.getAccountResources(id);
127
+ const contract = contractResources.find((r) => r.type.includes("protocol::Contract"));
128
+ if (!contract) {
129
+ throw new Error(`Contract with id ${id} could not be found!`);
130
+ }
131
+ const tokenIdMatch = contract.type.match(/0x[0-9a-f]+::protocol::Contract<(.*)>/);
132
+ const tokenId = tokenIdMatch?.[1] ?? "";
133
+ const { data } = contract;
134
+ return new Contract(data, tokenId);
135
+ }
136
+ async get() {
137
+ throw new Error("Get all method is not supported for Aptos chain!");
138
+ }
139
+ /**
140
+ * Attempts updating the stream auto withdrawal params and amount per period
141
+ */
142
+ async update(updateData, { senderWallet, tokenId }) {
143
+ const wallet = new AptosWalletWrapper(senderWallet, this.client);
144
+ const payload = {
145
+ type: "update",
146
+ function: `${this.programId}::protocol::update`,
147
+ type_arguments: [tokenId],
148
+ arguments: [
149
+ updateData.id,
150
+ updateData.enableAutomaticWithdrawal ? [true] : [],
151
+ updateData.withdrawFrequency ? [updateData.withdrawFrequency.toString()] : [],
152
+ updateData.amountPerPeriod ? [updateData.amountPerPeriod.toString()] : [],
153
+ ],
154
+ };
155
+ const hash = await wallet.signAndSubmitTransaction(payload);
156
+ return { ixs: [payload], txId: hash };
157
+ }
158
+ async getFees({ address }) {
159
+ const resource = await this.client.getAccountResource(this.programId, `${this.programId}::fees::FeeTable`);
160
+ const data = resource.data;
161
+ const value = await this.client.getTableItem(data.values.handle, {
162
+ key_type: "address",
163
+ key: address,
164
+ value_type: "u64",
165
+ });
166
+ if (!value) {
167
+ return null;
168
+ }
169
+ return { streamflowFee: Number(value) / 100, partnerFee: 0 };
170
+ }
171
+ async getDefaultStreamflowFee() {
172
+ const resource = await this.client.getAccountResource(this.programId, `${this.programId}::admin::ConfigV2`);
173
+ return Number(resource.data.streamflow_fees) / 100;
174
+ }
175
+ extractErrorCode(err) {
176
+ return extractAptosErrorCode(err.toString() ?? "Unknown error!");
177
+ }
178
+ /**
179
+ * Returns StreamClient protocol program ID.
180
+ */
181
+ getProgramId() {
182
+ return this.programId;
183
+ }
184
+ getMaxGas() {
185
+ return { max_gas_amount: this.maxGas };
186
+ }
187
+ // Utility function to prepare transaction payloads for multiple recipients.
188
+ generateMultiPayloads(multipleStreamData, wallet) {
189
+ return multipleStreamData.recipients.map((recipient) => {
190
+ const acc = new AptosAccount(); // Generate random address as seeds for deriving "escrow" account
191
+ const seeds = acc.address();
192
+ const encoder = new TextEncoder();
193
+ // A workaround to pass a String in seeds because different wallets seem
194
+ // to serialize vector<u8> differently and String should be safer that Uin8Array
195
+ const actualSeeds = encoder.encode(seeds.hex());
196
+ const metadataId = AptosAccount.getResourceAccountAddress(wallet.address, actualSeeds);
197
+ return [
198
+ metadataId.toString(),
199
+ {
200
+ type: "create",
201
+ function: `${this.programId}::protocol::create`,
202
+ type_arguments: [multipleStreamData.tokenId],
203
+ arguments: [
204
+ seeds.hex(),
205
+ recipient.amount.toString(),
206
+ multipleStreamData.period,
207
+ recipient.amountPerPeriod.toString(),
208
+ multipleStreamData.start,
209
+ recipient.cliffAmount.toString(),
210
+ multipleStreamData.cancelableBySender,
211
+ multipleStreamData.cancelableByRecipient,
212
+ multipleStreamData.transferableBySender,
213
+ multipleStreamData.transferableByRecipient,
214
+ multipleStreamData.canTopup,
215
+ multipleStreamData.canPause || false,
216
+ multipleStreamData.canUpdateRate || false,
217
+ multipleStreamData.automaticWithdrawal || false,
218
+ multipleStreamData.withdrawalFrequency || 0,
219
+ recipient.name,
220
+ recipient.recipient,
221
+ ],
222
+ },
223
+ ];
224
+ });
225
+ }
226
+ }
@@ -1,4 +1,4 @@
1
- import { ICluster } from "../common/types";
1
+ import { ICluster } from "../common/types.js";
2
2
  export declare const APTOS_PROGRAM_IDS: Record<ICluster, string>;
3
3
  export declare const APTOS_ERROR_MATCH_REGEX: RegExp;
4
4
  export declare const APTOS_MODULE_ERROR_MAP: {
@@ -0,0 +1,24 @@
1
+ import { ContractErrorCode, ICluster } from "../common/types.js";
2
+ export const APTOS_PROGRAM_IDS = {
3
+ [ICluster.Mainnet]: "0x9009d93d52576bf9ac6dc6cf10b870610bcb316342fef6eff80662fbbfce51b0",
4
+ // TODO: Add a correct programID for Test net
5
+ [ICluster.Devnet]: "0xc6737de143d91b2f99a7e490d4f8348fdfa3bdd1eb8737a27d0455f8a3625688",
6
+ [ICluster.Testnet]: "0xc6737de143d91b2f99a7e490d4f8348fdfa3bdd1eb8737a27d0455f8a3625688",
7
+ [ICluster.Local]: "0x9009d93d52576bf9ac6dc6cf10b870610bcb316342fef6eff80662fbbfce51b0",
8
+ };
9
+ export const APTOS_ERROR_MATCH_REGEX = /Move abort in [a-z0-9]+::([^:]+): ([A-Z_]+)/;
10
+ export const APTOS_MODULE_ERROR_MAP = {
11
+ protocol: {
12
+ 1: ContractErrorCode.ECONTRACT_NOT_INIT,
13
+ 2: ContractErrorCode.EBAD_AMOUNT,
14
+ 3: ContractErrorCode.ENO_PERMISSIONS,
15
+ 4: ContractErrorCode.EBADINPUT,
16
+ 5: ContractErrorCode.ECLOSED,
17
+ 6: ContractErrorCode.EBAD_INPUT_AMOUNT_PER_PERIOD,
18
+ 8: ContractErrorCode.EBAD_INPUT_UPDATE_RATE,
19
+ 9: ContractErrorCode.EBAD_INPUT_CLIFF_AMOUNT,
20
+ 10: ContractErrorCode.EBAD_INPUT_PERIOD,
21
+ 11: ContractErrorCode.EBAD_INPUT_START,
22
+ 12: ContractErrorCode.ENO_RECIPIENT_COIN_ADDRESS,
23
+ },
24
+ };
@@ -1,4 +1,4 @@
1
- export { default, default as AptosStreamClient } from "./StreamClient";
1
+ export { default, default as AptosStreamClient } from "./StreamClient.js";
2
2
  export * from "./utils";
3
3
  export * from "./types";
4
4
  export * as constants from "./constants";
@@ -1,4 +1,4 @@
1
- export { default as SuiStreamClient } from "./StreamClient";
1
+ export { default, default as AptosStreamClient } from "./StreamClient.js";
2
2
  export * from "./utils";
3
3
  export * from "./types";
4
4
  export * as constants from "./constants";
@@ -1,7 +1,7 @@
1
1
  import { AptosAccount } from "aptos";
2
2
  import { WalletContextState } from "@manahippo/aptos-wallet-adapter";
3
3
  import BN from "bn.js";
4
- import { Stream, StreamType } from "../common/types";
4
+ import { Stream, StreamType } from "../common/types.js";
5
5
  export interface ICreateStreamAptosExt {
6
6
  senderWallet: WalletContextState | AptosAccount;
7
7
  }
@@ -0,0 +1,105 @@
1
+ import BN from "bn.js";
2
+ import { Buffer } from "buffer";
3
+ import { buildStreamType, calculateUnlockedAmount } from "../common/contractUtils.js";
4
+ import { getNumberFromBN } from "../common/utils.js";
5
+ import { normalizeAptosAddress } from "./utils.js";
6
+ export class Contract {
7
+ magic;
8
+ version;
9
+ createdAt;
10
+ withdrawnAmount;
11
+ canceledAt;
12
+ end;
13
+ lastWithdrawnAt;
14
+ sender;
15
+ senderTokens;
16
+ recipient;
17
+ recipientTokens;
18
+ mint;
19
+ escrowTokens;
20
+ streamflowTreasury;
21
+ streamflowTreasuryTokens;
22
+ streamflowFeeTotal;
23
+ streamflowFeeWithdrawn;
24
+ streamflowFeePercent;
25
+ partnerFeeTotal;
26
+ partnerFeeWithdrawn;
27
+ partnerFeePercent;
28
+ partner;
29
+ partnerTokens;
30
+ start;
31
+ depositedAmount;
32
+ period;
33
+ amountPerPeriod;
34
+ cliff;
35
+ cliffAmount;
36
+ cancelableBySender;
37
+ cancelableByRecipient;
38
+ automaticWithdrawal;
39
+ transferableBySender;
40
+ transferableByRecipient;
41
+ canTopup;
42
+ name;
43
+ withdrawalFrequency;
44
+ closed;
45
+ currentPauseStart;
46
+ pauseCumulative;
47
+ lastRateChangeTime;
48
+ fundsUnlockedAtLastRateChange;
49
+ type;
50
+ constructor(stream, tokenId) {
51
+ this.magic = 0;
52
+ this.version = 0;
53
+ this.createdAt = parseInt(stream.created);
54
+ this.withdrawnAmount = new BN(stream.withdrawn);
55
+ this.canceledAt = parseInt(stream.canceled_at);
56
+ this.end = parseInt(stream.end);
57
+ this.lastWithdrawnAt = parseInt(stream.last_withdrawn_at);
58
+ this.sender = normalizeAptosAddress(stream.sender);
59
+ this.senderTokens = normalizeAptosAddress(stream.sender);
60
+ this.recipient = normalizeAptosAddress(stream.recipient);
61
+ this.recipientTokens = normalizeAptosAddress(stream.recipient);
62
+ this.mint = tokenId;
63
+ this.escrowTokens = "";
64
+ this.streamflowTreasury = "";
65
+ this.streamflowTreasuryTokens = "";
66
+ this.streamflowFeeTotal = new BN(0);
67
+ this.streamflowFeeWithdrawn = new BN(0);
68
+ this.streamflowFeePercent = parseInt(stream.fees.streamflow_fee_percentage) / 10000;
69
+ this.partnerFeeTotal = new BN(0);
70
+ this.partnerFeeWithdrawn = new BN(0);
71
+ this.partnerFeePercent = 0;
72
+ this.partner = "";
73
+ this.partnerTokens = "";
74
+ this.start = parseInt(stream.start);
75
+ this.depositedAmount = new BN(stream.amount);
76
+ this.period = parseInt(stream.period);
77
+ this.amountPerPeriod = new BN(stream.amount_per_period);
78
+ this.cliff = parseInt(stream.start);
79
+ this.cliffAmount = new BN(stream.cliff_amount);
80
+ this.cancelableBySender = stream.meta.cancelable_by_sender;
81
+ this.cancelableByRecipient = stream.meta.cancelable_by_recipient;
82
+ this.automaticWithdrawal = stream.meta.automatic_withdrawal;
83
+ this.transferableBySender = stream.meta.transferable_by_sender;
84
+ this.transferableByRecipient = stream.meta.transferable_by_recipient;
85
+ this.canTopup = stream.meta.can_topup;
86
+ const name = stream.meta.contract_name.replace("0x", "");
87
+ this.name = Buffer.from(name, "hex").toString("utf8");
88
+ this.withdrawalFrequency = parseInt(stream.meta.withdrawal_frequency);
89
+ this.closed = stream.closed;
90
+ this.currentPauseStart = parseInt(stream.current_pause_start);
91
+ this.pauseCumulative = new BN(stream.pause_cumulative);
92
+ this.lastRateChangeTime = parseInt(stream.last_rate_change_time);
93
+ this.fundsUnlockedAtLastRateChange = new BN(stream.funds_unlocked_at_last_rate_change);
94
+ this.type = buildStreamType(this);
95
+ }
96
+ unlocked(currentTimestamp) {
97
+ return calculateUnlockedAmount({
98
+ ...this,
99
+ currentTimestamp,
100
+ });
101
+ }
102
+ remaining(decimals) {
103
+ return getNumberFromBN(this.depositedAmount.sub(this.withdrawnAmount), decimals);
104
+ }
105
+ }
@@ -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,8 +1,8 @@
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";
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
6
  import { AptosStreamClient, ICreateStreamAptosExt, ITransactionAptosExt } from "../aptos";
7
7
  import { EvmStreamClient } from "../evm";
8
8
  import { SolanaStreamClient, ICreateStreamSolanaExt, IInteractStreamSolanaExt, ITopUpStreamSolanaExt } from "../solana";
@@ -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";
5
+ import { EvmStreamClient } from "../evm";
6
+ import { SolanaStreamClient } from "../solana";
7
+ import { SuiStreamClient } from "../sui";
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 BN from "bn.js";
2
+ export const BASE_FEE = 1009900; // Buffer to include usual fees when calculating stream amount
3
+ export const WITHDRAW_AVAILABLE_AMOUNT = new BN("18446744073709551615"); // Magical number to withdraw all available amount from a Contract
@@ -1,5 +1,5 @@
1
1
  import BN from "bn.js";
2
- import { StreamType } from "./types";
2
+ import { StreamType } from "./types.js";
3
3
  interface ICalculateUnlockedAmount {
4
4
  depositedAmount: BN;
5
5
  cliff: number;
@@ -0,0 +1,42 @@
1
+ import BN from "bn.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 new BN(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 = new BN(Math.floor((currentTimestamp - savedUnlockedFundsTime) / period))
12
+ .mul(amountPerPeriod)
13
+ .add(savedUnlockedFunds);
14
+ return streamed.lt(deposited) ? streamed : deposited;
15
+ };
16
+ export const isCliffCloseToDepositedAmount = (streamData) => {
17
+ return streamData.cliffAmount.gte(streamData.depositedAmount.sub(new BN("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
+ };