@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,123 @@
1
+ import { PublicKey } from "@solana/web3.js";
2
+ import { executeTransaction, isSignerKeypair, isSignerWallet, } from "@streamflow/common/solana";
3
+ import BigNumber from "bignumber.js";
4
+ import { streamLayout } from "./layout.js";
5
+ import { SOLANA_ERROR_MAP, SOLANA_ERROR_MATCH_REGEX } from "./constants.js";
6
+ const decoder = new TextDecoder("utf-8");
7
+ const toUInt64String = (uintArr) => new DataView(uintArr.buffer, uintArr.byteOffset, uintArr.byteLength).getBigUint64(0, true).toString();
8
+ const toUInt8 = (uintArr) => new DataView(uintArr.buffer, uintArr.byteOffset, uintArr.byteLength).getUint8(0);
9
+ export const toBuffer = (bigNumber) => {
10
+ const dv = new DataView(new ArrayBuffer(8), 0);
11
+ dv.setBigUint64(0, BigInt(bigNumber.integerValue().toString()), true);
12
+ return Buffer.from(dv.buffer);
13
+ };
14
+ export const decodeStream = (buf) => {
15
+ const raw = streamLayout.decode(buf);
16
+ return {
17
+ magic: BigNumber(toUInt64String(raw.magic)),
18
+ version: BigNumber(toUInt8(raw.version)),
19
+ createdAt: BigNumber(toUInt64String(raw.created_at)),
20
+ withdrawnAmount: BigNumber(toUInt64String(raw.withdrawn_amount)),
21
+ canceledAt: BigNumber(toUInt64String(raw.canceled_at)),
22
+ end: BigNumber(toUInt64String(raw.end_time)),
23
+ lastWithdrawnAt: BigNumber(toUInt64String(raw.last_withdrawn_at)),
24
+ sender: new PublicKey(raw.sender),
25
+ senderTokens: new PublicKey(raw.sender_tokens),
26
+ recipient: new PublicKey(raw.recipient),
27
+ recipientTokens: new PublicKey(raw.recipient_tokens),
28
+ mint: new PublicKey(raw.mint),
29
+ escrowTokens: new PublicKey(raw.escrow_tokens),
30
+ streamflowTreasury: new PublicKey(raw.streamflow_treasury),
31
+ streamflowTreasuryTokens: new PublicKey(raw.streamflow_treasury_tokens),
32
+ streamflowFeeTotal: BigNumber(toUInt64String(raw.streamflow_fee_total)),
33
+ streamflowFeeWithdrawn: BigNumber(toUInt64String(raw.streamflow_fee_withdrawn)),
34
+ streamflowFeePercent: BigNumber(raw.streamflow_fee_percent),
35
+ partnerFeeTotal: BigNumber(toUInt64String(raw.partner_fee_total)),
36
+ partnerFeeWithdrawn: BigNumber(toUInt64String(raw.partner_fee_withdrawn)),
37
+ partnerFeePercent: BigNumber(raw.partner_fee_percent),
38
+ partner: new PublicKey(raw.partner),
39
+ partnerTokens: new PublicKey(raw.partner_tokens),
40
+ start: BigNumber(toUInt64String(raw.start_time)),
41
+ depositedAmount: BigNumber(toUInt64String(raw.net_amount_deposited)),
42
+ period: BigNumber(toUInt64String(raw.period)),
43
+ amountPerPeriod: BigNumber(toUInt64String(raw.amount_per_period)),
44
+ cliff: BigNumber(toUInt64String(raw.cliff)),
45
+ cliffAmount: BigNumber(toUInt64String(raw.cliff_amount)),
46
+ cancelableBySender: Boolean(raw.cancelable_by_sender),
47
+ cancelableByRecipient: Boolean(raw.cancelable_by_recipient),
48
+ automaticWithdrawal: Boolean(raw.automatic_withdrawal),
49
+ transferableBySender: Boolean(raw.transferable_by_sender),
50
+ transferableByRecipient: Boolean(raw.transferable_by_recipient),
51
+ canTopup: Boolean(raw.can_topup),
52
+ name: decoder.decode(raw.stream_name),
53
+ withdrawFrequency: BigNumber(toUInt64String(raw.withdraw_frequency)),
54
+ closed: Boolean(raw.closed),
55
+ currentPauseStart: BigNumber(toUInt64String(raw.current_pause_start)),
56
+ pauseCumulative: BigNumber(toUInt64String(raw.pause_cumulative)),
57
+ lastRateChangeTime: BigNumber(toUInt64String(raw.last_rate_change_time)),
58
+ fundsUnlockedAtLastRateChange: BigNumber(toUInt64String(raw.funds_unlocked_at_last_rate_change)),
59
+ };
60
+ };
61
+ /**
62
+ * Sign passed BatchItems with wallet request or KeyPair
63
+ * @param {Keypair | SignerWalletAdapter} sender - Wallet or Keypair of sendin account
64
+ * @param {BatchItem[]} items - Multiple recipient contracts split into separate items
65
+ * @return {BatchItem[]} - Returns items with signatures.
66
+ */
67
+ export async function signAllTransactionWithRecipients(sender, items) {
68
+ const isKeypair = isSignerKeypair(sender);
69
+ const isWallet = isSignerWallet(sender);
70
+ if (isKeypair) {
71
+ return items.map((t) => {
72
+ t.tx.sign([sender]);
73
+ return { tx: t.tx, recipient: t.recipient };
74
+ });
75
+ }
76
+ else if (isWallet) {
77
+ const signedTxs = await sender.signAllTransactions(items.map((t) => t.tx));
78
+ return items.map((item, index) => ({
79
+ ...item,
80
+ tx: signedTxs[index],
81
+ }));
82
+ }
83
+ else {
84
+ // If signer is not passed
85
+ return [];
86
+ }
87
+ }
88
+ /**
89
+ * Sign passed BatchItems with wallet request or KeyPair
90
+ * @param {Connection} connection - Solana web3 connection object.
91
+ * @param {BatchItem} batchItem - Signed transaction ready to be send.
92
+ * @param confirmationParams - Confirmation Params that will be used for execution
93
+ * @param throttleParams - rate or throttler instance to throttle TX sending - to not spam the blockchain too much
94
+ * @return {Promise<BatchItemResult>} - Returns settled transaction item
95
+ */
96
+ export async function sendAndConfirmStreamRawTransaction(connection, batchItem, confirmationParams, throttleParams) {
97
+ try {
98
+ const completedTxSignature = await executeTransaction(connection, batchItem.tx, confirmationParams, throttleParams);
99
+ return { ...batchItem, signature: completedTxSignature };
100
+ }
101
+ catch (error) {
102
+ throw {
103
+ recipient: batchItem.recipient,
104
+ error,
105
+ };
106
+ }
107
+ }
108
+ export function extractSolanaErrorCode(errorText, logs) {
109
+ let match = SOLANA_ERROR_MATCH_REGEX.exec(errorText);
110
+ if (!match && logs) {
111
+ for (const logLine of logs) {
112
+ match = SOLANA_ERROR_MATCH_REGEX.exec(logLine);
113
+ if (match !== null) {
114
+ break;
115
+ }
116
+ }
117
+ }
118
+ if (!match) {
119
+ return null;
120
+ }
121
+ const errorCode = Number(match[1]);
122
+ return SOLANA_ERROR_MAP[errorCode] || null;
123
+ }
@@ -1,6 +1,6 @@
1
- import { BaseStreamClient } from "../common/BaseStreamClient";
2
- import { ICancelData, ICluster, ICreateMultipleStreamData, ICreateResult, ICreateStreamData, IGetFeesData, IGetOneData, IFees, IMultiTransactionResult, ITopUpData, ITransactionResult, ITransferData, IUpdateData, IWithdrawData } from "../common/types";
3
- import { Contract, ICreateStreamSuiExt, ITransactionSuiExt, ISuiIdParameters } from "./types";
1
+ import { BaseStreamClient } from "../common/BaseStreamClient.js";
2
+ import { ICancelData, ICluster, ICreateMultipleStreamData, ICreateResult, ICreateStreamData, IGetFeesData, IGetOneData, IFees, IMultiTransactionResult, ITopUpData, ITransactionResult, ITransferData, IUpdateData, IWithdrawData } from "../common/types.js";
3
+ import { Contract, ICreateStreamSuiExt, ITransactionSuiExt, ISuiIdParameters } from "./types.js";
4
4
  export default class SuiStreamClient extends BaseStreamClient {
5
5
  private programId;
6
6
  private configId;
@@ -0,0 +1,403 @@
1
+ import { SuiClient } from "@mysten/sui.js/client";
2
+ import { TransactionBlock } from "@mysten/sui.js/transactions";
3
+ import { SUI_CLOCK_OBJECT_ID, SUI_TYPE_ARG } from "@mysten/sui.js/utils";
4
+ import { BaseStreamClient } from "../common/BaseStreamClient.js";
5
+ import { ICluster, } from "../common/types.js";
6
+ import { SUI_PROGRAM_IDS, SUI_FEE_TABLE_IDS, SUI_CONFIG_IDS } from "./constants.js";
7
+ import { Contract, } from "./types.js";
8
+ import { extractSuiErrorInfo } from "./utils.js";
9
+ import { SuiWalletWrapper } from "./wallet.js";
10
+ import { calculateTotalAmountToDeposit } from "../common/utils.js";
11
+ import { WITHDRAW_AVAILABLE_AMOUNT } from "../common/constants.js";
12
+ export default class SuiStreamClient extends BaseStreamClient {
13
+ programId;
14
+ configId;
15
+ feeTableId;
16
+ client;
17
+ constructor(clusterUrl, cluster = ICluster.Mainnet, ids) {
18
+ super();
19
+ this.programId = ids?.program ? ids.program : SUI_PROGRAM_IDS[cluster];
20
+ this.configId = ids?.config ? ids.config : SUI_CONFIG_IDS[cluster];
21
+ this.feeTableId = ids?.feeTable ? ids.feeTable : SUI_FEE_TABLE_IDS[cluster];
22
+ this.client = new SuiClient({ url: clusterUrl });
23
+ }
24
+ /**
25
+ * Creates a new stream/vesting contract.
26
+ */
27
+ async create(streamData, { senderWallet }) {
28
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
29
+ const totalFee = await this.getTotalFee({
30
+ address: streamData.partner ?? wallet.address,
31
+ });
32
+ const [txb] = await this.generateCreateBlock(wallet.address, {
33
+ ...streamData,
34
+ recipients: [{ ...streamData }],
35
+ }, totalFee);
36
+ const { digest, events } = await wallet.signAndExecuteTransactionBlock({
37
+ transactionBlock: txb,
38
+ options: { showEvents: true },
39
+ });
40
+ return {
41
+ ixs: [],
42
+ txId: digest,
43
+ metadataId: events[0].parsedJson.address,
44
+ };
45
+ }
46
+ /**
47
+ * Creates multiple stream/vesting contracts.
48
+ * We don't chain transactions in one Block so that one failed transaction does not revert all others.
49
+ */
50
+ async createMultiple(multipleStreamData, { senderWallet }) {
51
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
52
+ const totalFee = await this.getTotalFee({
53
+ address: multipleStreamData.partner ?? wallet.address,
54
+ });
55
+ const [txb, firstIndex] = await this.generateCreateBlock(wallet.address, multipleStreamData, totalFee);
56
+ const txs = [];
57
+ const metadatas = [];
58
+ const metadataToRecipient = {};
59
+ const errors = [];
60
+ try {
61
+ const { digest, events, effects } = await wallet.signAndExecuteTransactionBlock({
62
+ transactionBlock: txb,
63
+ options: { showEffects: true, showEvents: true },
64
+ });
65
+ txs.push(digest);
66
+ if (effects.status.status === "failure") {
67
+ multipleStreamData.recipients.forEach((recipient) => {
68
+ errors.push({
69
+ error: effects.status.error ?? "Unknown error!",
70
+ recipient: recipient.recipient,
71
+ });
72
+ });
73
+ }
74
+ else {
75
+ multipleStreamData.recipients.forEach((recipient, index) => {
76
+ const metadataId = events[index].parsedJson.address;
77
+ metadatas.push(metadataId);
78
+ metadataToRecipient[metadataId] = recipient;
79
+ });
80
+ }
81
+ }
82
+ catch (e) {
83
+ const errorInfo = extractSuiErrorInfo(e.toString() ?? "Unknown error!");
84
+ multipleStreamData.recipients.forEach((recipient, index) => {
85
+ if (errorInfo.index === undefined ||
86
+ errorInfo.index < index + firstIndex ||
87
+ errorInfo.index >= multipleStreamData.recipients.length + firstIndex ||
88
+ errorInfo.index === index + firstIndex) {
89
+ errors.push({
90
+ error: errorInfo.text,
91
+ recipient: recipient.recipient,
92
+ contractErrorCode: errorInfo.parsed?.name,
93
+ });
94
+ }
95
+ });
96
+ }
97
+ return {
98
+ txs,
99
+ metadatas,
100
+ metadataToRecipient,
101
+ errors,
102
+ };
103
+ }
104
+ /**
105
+ * Attempts withdrawing from the specified stream.
106
+ */
107
+ async withdraw({ id, amount = WITHDRAW_AVAILABLE_AMOUNT }, { senderWallet, tokenId }) {
108
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
109
+ const txb = new TransactionBlock();
110
+ txb.moveCall({
111
+ target: `${this.programId}::protocol::withdraw`,
112
+ typeArguments: [tokenId],
113
+ arguments: [
114
+ txb.object(id),
115
+ txb.object(this.configId),
116
+ txb.object(SUI_CLOCK_OBJECT_ID),
117
+ txb.pure(amount.toString()),
118
+ ],
119
+ });
120
+ const { digest } = await wallet.signAndExecuteTransactionBlock({
121
+ transactionBlock: txb,
122
+ });
123
+ return {
124
+ ixs: [],
125
+ txId: digest,
126
+ };
127
+ }
128
+ /**
129
+ * Attempts canceling the specified stream.
130
+ */
131
+ async cancel(cancelData, { senderWallet, tokenId }) {
132
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
133
+ const txb = new TransactionBlock();
134
+ txb.moveCall({
135
+ target: `${this.programId}::protocol::cancel`,
136
+ typeArguments: [tokenId],
137
+ arguments: [txb.object(cancelData.id), txb.object(this.configId), txb.object(SUI_CLOCK_OBJECT_ID)],
138
+ });
139
+ const { digest } = await wallet.signAndExecuteTransactionBlock({
140
+ transactionBlock: txb,
141
+ });
142
+ return {
143
+ ixs: [],
144
+ txId: digest,
145
+ };
146
+ }
147
+ /**
148
+ * Attempts changing the stream/vesting contract's recipient (effectively transferring the stream/vesting contract).
149
+ */
150
+ async transfer(transferData, { senderWallet, tokenId }) {
151
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
152
+ const txb = new TransactionBlock();
153
+ txb.moveCall({
154
+ target: `${this.programId}::protocol::transfer`,
155
+ typeArguments: [tokenId],
156
+ arguments: [txb.object(transferData.id), txb.pure(transferData.newRecipient)],
157
+ });
158
+ const { digest } = await wallet.signAndExecuteTransactionBlock({
159
+ transactionBlock: txb,
160
+ });
161
+ return {
162
+ ixs: [],
163
+ txId: digest,
164
+ };
165
+ }
166
+ /**
167
+ * Tops up stream account with specified amount.
168
+ */
169
+ async topup(topupData, { senderWallet, tokenId }) {
170
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
171
+ const txb = new TransactionBlock();
172
+ const coins = await this.getAllCoins(wallet.address, tokenId);
173
+ const stream = await this.getOne({ id: topupData.id });
174
+ const totalFee = (stream.partnerFeePercent + stream.streamflowFeePercent) / 100;
175
+ const coinObject = this.splitCoinObjectForAmount(txb, topupData.amount, tokenId, coins, totalFee);
176
+ txb.moveCall({
177
+ target: `${this.programId}::protocol::topup`,
178
+ typeArguments: [tokenId],
179
+ arguments: [
180
+ txb.object(topupData.id),
181
+ txb.object(this.configId),
182
+ coinObject,
183
+ txb.gas,
184
+ txb.pure(topupData.amount.toString()),
185
+ ],
186
+ });
187
+ this.returnSplittedCoinObject(txb, tokenId, coins, coinObject);
188
+ const { digest } = await wallet.signAndExecuteTransactionBlock({
189
+ transactionBlock: txb,
190
+ });
191
+ return {
192
+ ixs: [],
193
+ txId: digest,
194
+ };
195
+ }
196
+ /**
197
+ * Fetch stream data by its id (address).
198
+ */
199
+ async getOne({ id }) {
200
+ const response = await this.client.getObject({
201
+ id,
202
+ options: {
203
+ showContent: true,
204
+ },
205
+ });
206
+ if (!response.data) {
207
+ throw new Error(`Contract with id ${id} could not be found!`);
208
+ }
209
+ const content = response.data.content;
210
+ if (content.dataType !== "moveObject") {
211
+ throw new Error(`Not a Move Object!`);
212
+ }
213
+ return new Contract(content.fields, "0x97e9a9fb1392e9785319f5512d0bfde6ecf7757b09c6de41cec89e798dd361f2::strmt::STRMT");
214
+ }
215
+ async get() {
216
+ throw new Error("Get all method is not supported for Sui chain!");
217
+ }
218
+ /**
219
+ * Attempts updating the stream auto withdrawal params and amount per period
220
+ */
221
+ async update(updateData, { senderWallet, tokenId }) {
222
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
223
+ const txb = new TransactionBlock();
224
+ txb.moveCall({
225
+ target: `${this.programId}::protocol::update`,
226
+ typeArguments: [tokenId],
227
+ arguments: [
228
+ txb.object(updateData.id),
229
+ txb.object(this.configId),
230
+ txb.object(SUI_CLOCK_OBJECT_ID),
231
+ txb.gas,
232
+ txb.pure(updateData.enableAutomaticWithdrawal !== undefined ? [updateData.enableAutomaticWithdrawal] : [], "vector<bool>"),
233
+ txb.pure(updateData.withdrawFrequency !== undefined ? [updateData.withdrawFrequency.toString()] : [], "vector<u64>"),
234
+ txb.pure(updateData.amountPerPeriod !== undefined ? [updateData.amountPerPeriod.toString()] : [], "vector<u64>"),
235
+ ],
236
+ });
237
+ const { digest } = await wallet.signAndExecuteTransactionBlock({
238
+ transactionBlock: txb,
239
+ });
240
+ return {
241
+ ixs: [],
242
+ txId: digest,
243
+ };
244
+ }
245
+ extractErrorCode(err) {
246
+ const errorInfo = extractSuiErrorInfo(err.toString() ?? "Unknown error!");
247
+ return errorInfo?.parsed?.name || null;
248
+ }
249
+ async getFees({ address }) {
250
+ const response = await this.client.getObject({
251
+ id: this.feeTableId,
252
+ options: {
253
+ showContent: true,
254
+ },
255
+ });
256
+ const content = response.data.content;
257
+ if (content.dataType !== "moveObject") {
258
+ throw new Error(`Not a Move Object!`);
259
+ }
260
+ const fields = content.fields;
261
+ const fieldsResponse = await this.client.getDynamicFields({
262
+ parentId: fields.values.fields.id.id,
263
+ });
264
+ const partnerDynamicField = fieldsResponse.data.filter((item) => item.name.value === address)[0];
265
+ if (!partnerDynamicField) {
266
+ return null;
267
+ }
268
+ const valueResponse = await this.client.getObject({
269
+ id: partnerDynamicField.objectId,
270
+ options: {
271
+ showContent: true,
272
+ },
273
+ });
274
+ const valueContent = valueResponse.data.content;
275
+ if (valueContent.dataType !== "moveObject") {
276
+ throw new Error(`Not a Move Object!`);
277
+ }
278
+ const valueFields = valueContent.fields.value.fields;
279
+ return {
280
+ streamflowFee: Number(valueFields.streamflow_fee) / 100,
281
+ partnerFee: Number(valueFields.partner_fee) / 100,
282
+ };
283
+ }
284
+ async getDefaultStreamflowFee() {
285
+ const response = await this.client.getObject({
286
+ id: this.configId,
287
+ options: {
288
+ showContent: true,
289
+ },
290
+ });
291
+ const content = response.data.content;
292
+ if (content.dataType !== "moveObject") {
293
+ throw new Error(`Not a Move Object!`);
294
+ }
295
+ const fields = content.fields;
296
+ return Number(fields.streamflow_fee) / 100;
297
+ }
298
+ /**
299
+ * Returns StreamClient protocol program ID.
300
+ */
301
+ getProgramId() {
302
+ return this.programId;
303
+ }
304
+ /**
305
+ * Utility function to generate Transaction Block to create streams
306
+ */
307
+ async generateCreateBlock(walletAddress, multipleStreamData, totalFee) {
308
+ let coins = await this.getAllCoins(walletAddress, multipleStreamData.tokenId);
309
+ const totalAmount = multipleStreamData.recipients
310
+ .map((recipiient) => recipiient.amount)
311
+ .reduce((prev, current) => current.plus(prev));
312
+ const txb = new TransactionBlock();
313
+ const coinObject = this.splitCoinObjectForAmount(txb, totalAmount, multipleStreamData.tokenId, coins, totalFee);
314
+ coins = [coins[0]];
315
+ let firstIndex = null;
316
+ multipleStreamData.recipients.forEach((recipient) => {
317
+ const result = txb.moveCall({
318
+ target: `${this.programId}::protocol::create`,
319
+ typeArguments: [multipleStreamData.tokenId],
320
+ arguments: [
321
+ txb.object(this.configId),
322
+ txb.object(this.feeTableId),
323
+ txb.object(SUI_CLOCK_OBJECT_ID),
324
+ coinObject,
325
+ txb.gas,
326
+ txb.pure(recipient.amount.toString()),
327
+ txb.pure(multipleStreamData.period),
328
+ txb.pure(recipient.amountPerPeriod.toString()),
329
+ txb.pure(multipleStreamData.start),
330
+ txb.pure(recipient.cliffAmount.toString()),
331
+ txb.pure(multipleStreamData.cancelableBySender),
332
+ txb.pure(multipleStreamData.cancelableByRecipient),
333
+ txb.pure(multipleStreamData.transferableBySender),
334
+ txb.pure(multipleStreamData.transferableByRecipient),
335
+ txb.pure(multipleStreamData.canTopup),
336
+ txb.pure(!!multipleStreamData.canPause),
337
+ txb.pure(!!multipleStreamData.canUpdateRate),
338
+ txb.pure(!!multipleStreamData.automaticWithdrawal),
339
+ txb.pure(multipleStreamData.withdrawalFrequency || 0),
340
+ txb.pure(recipient.name),
341
+ txb.pure(recipient.recipient),
342
+ txb.pure(multipleStreamData.partner || walletAddress),
343
+ ],
344
+ });
345
+ if (result.kind === "Result" && firstIndex === null) {
346
+ firstIndex = result.index;
347
+ }
348
+ });
349
+ this.returnSplittedCoinObject(txb, multipleStreamData.tokenId, coins, coinObject);
350
+ return [txb, firstIndex];
351
+ }
352
+ /**
353
+ * Returns all coins owned by a Wallet
354
+ * @param walletAddress wallet address
355
+ * @param coinType coin type
356
+ * @returns Array of Coin Structs
357
+ */
358
+ async getAllCoins(walletAddress, coinType) {
359
+ let coinsResponse = await this.client.getCoins({
360
+ owner: walletAddress,
361
+ coinType: coinType,
362
+ });
363
+ const coins = coinsResponse.data;
364
+ while (coinsResponse.hasNextPage) {
365
+ coinsResponse = await this.client.getCoins({
366
+ owner: walletAddress,
367
+ coinType: coinType,
368
+ cursor: coinsResponse.nextCursor,
369
+ });
370
+ coins.push(...coinsResponse.data);
371
+ }
372
+ return coins;
373
+ }
374
+ /**
375
+ * Utility function to split Coin object and use splitted object for stream operations.
376
+ * We do it like thid to mitigate risk of Transaction reverting in case Stream is created for Sui Coin object.
377
+ * This way we can safely pass splitted Sui Coin object in Stream payload and use another object for gas/withdrawal fees.
378
+ * @param txb current transanction block
379
+ * @param amount minimal amount of coins requried
380
+ * @param coinType coin type
381
+ * @param coins array of owned coins of the same type
382
+ * @returns Coin Object to use in a Move Call
383
+ */
384
+ splitCoinObjectForAmount(txb, amount, coinType, coins, totalFee) {
385
+ const coinObject = coinType === SUI_TYPE_ARG ? txb.gas : txb.object(coins[0].coinObjectId);
386
+ if (coins.length > 1) {
387
+ txb.mergeCoins(coinObject, coins.slice(1).map((item) => txb.object(item.coinObjectId)));
388
+ }
389
+ const totalAmount = calculateTotalAmountToDeposit(amount, totalFee);
390
+ return txb.splitCoins(coinObject, [txb.pure(totalAmount.toString())])[0];
391
+ }
392
+ /**
393
+ * Return previously splitted Coin Object to owner and merge it to to rebate storage fees
394
+ * @param txb current transanction block
395
+ * @param coinType coin type
396
+ * @param coinObject splitted object
397
+ * @param coins array of objects used in
398
+ */
399
+ returnSplittedCoinObject(txb, coinType, coins, coinObject) {
400
+ const firstCoinObject = coinType === SUI_TYPE_ARG ? txb.gas : txb.object(coins[0].coinObjectId);
401
+ txb.mergeCoins(firstCoinObject, [coinObject]);
402
+ }
403
+ }
@@ -1,4 +1,4 @@
1
- import { ICluster } from "../common/types";
1
+ import { ICluster } from "../common/types.js";
2
2
  export declare const SUI_PROGRAM_IDS: Record<ICluster, string>;
3
3
  export declare const SUI_CONFIG_IDS: Record<ICluster, string>;
4
4
  export declare const SUI_FEE_TABLE_IDS: Record<ICluster, string>;
@@ -0,0 +1,39 @@
1
+ import { ContractErrorCode, ICluster } from "../common/types.js";
2
+ // TODO: remove Devnet and Local addresses as they are not deployed, they are just a copy Testnet values
3
+ export const SUI_PROGRAM_IDS = {
4
+ [ICluster.Mainnet]: "0xe456a3a1d4e58e85b4b7175fabe6dae895b983f1379bb8948d6ec2f137b08a7b",
5
+ [ICluster.Devnet]: "0x34dacd839e1758ebb70bdcd4e08f18fbfef5e2b96d9aa7ce2b4a71d96ca0df5a",
6
+ [ICluster.Testnet]: "0x34dacd839e1758ebb70bdcd4e08f18fbfef5e2b96d9aa7ce2b4a71d96ca0df5a",
7
+ [ICluster.Local]: "0x34dacd839e1758ebb70bdcd4e08f18fbfef5e2b96d9aa7ce2b4a71d96ca0df5a",
8
+ };
9
+ export const SUI_CONFIG_IDS = {
10
+ [ICluster.Mainnet]: "0x6cf6760b64245b8d23ef57c28ddceb6adbd540a23a509fef29b82237da4ab87b",
11
+ [ICluster.Devnet]: "0xd6c9f5074584f58074ce56e3c5cc436d82258ec3285f186a0d6438a60bacdbf8",
12
+ [ICluster.Testnet]: "0xd6c9f5074584f58074ce56e3c5cc436d82258ec3285f186a0d6438a60bacdbf8",
13
+ [ICluster.Local]: "0xd6c9f5074584f58074ce56e3c5cc436d82258ec3285f186a0d6438a60bacdbf8",
14
+ };
15
+ export const SUI_FEE_TABLE_IDS = {
16
+ [ICluster.Mainnet]: "0xad9b75399632583fb9fcae6b5bcca34e6542ab3bedb630ecbd3f15cb1cc48dbe",
17
+ [ICluster.Devnet]: "0x6057b093904c5bdfec1067d2b8a4dc35f65bcab03b3029ad716c4882b0f36078",
18
+ [ICluster.Testnet]: "0x6057b093904c5bdfec1067d2b8a4dc35f65bcab03b3029ad716c4882b0f36078",
19
+ [ICluster.Local]: "0x6057b093904c5bdfec1067d2b8a4dc35f65bcab03b3029ad716c4882b0f36078",
20
+ };
21
+ export const SUI_ERROR_MATCH_REGEX = /MoveAbort\(MoveLocation \{ module: ModuleId \{ address: (\w+), name: Identifier\("([\w_]+)"\) }, function: \d+, instruction: \d+, function_name: Some\("([\w_]+)"\) }, (\d+)\) in command (\d+)/;
22
+ export const SUI_MODULE_ERROR_MAP = {
23
+ protocol: {
24
+ 1: ContractErrorCode.ECONTRACT_NOT_INIT,
25
+ 2: ContractErrorCode.EBAD_AMOUNT,
26
+ 3: ContractErrorCode.ENO_PERMISSIONS,
27
+ 4: ContractErrorCode.EBADINPUT,
28
+ 5: ContractErrorCode.ECLOSED,
29
+ 6: ContractErrorCode.EBAD_INPUT_AMOUNT_PER_PERIOD,
30
+ 8: ContractErrorCode.EBAD_INPUT_UPDATE_RATE,
31
+ 9: ContractErrorCode.EBAD_INPUT_CLIFF_AMOUNT,
32
+ 10: ContractErrorCode.EBAD_INPUT_PERIOD,
33
+ 11: ContractErrorCode.EBAD_INPUT_START,
34
+ 13: ContractErrorCode.EBAD_INSUFFICIENT_WITHDRAWAL_FEES,
35
+ 14: ContractErrorCode.EBAD_INSUFFICIENT_AMOUNT,
36
+ 15: ContractErrorCode.EPAUSED,
37
+ 16: ContractErrorCode.ENOTPAUSED,
38
+ },
39
+ };
@@ -0,0 +1,4 @@
1
+ export { default as SuiStreamClient } from "./StreamClient.js";
2
+ export * from "./utils.js";
3
+ export * from "./types.js";
4
+ export * as constants from "./constants.js";
@@ -0,0 +1,4 @@
1
+ export { default as SuiStreamClient } from "./StreamClient.js";
2
+ export * from "./utils.js";
3
+ export * from "./types.js";
4
+ export * as constants from "./constants.js";
@@ -2,8 +2,8 @@ import { Keypair } from "@mysten/sui.js/cryptography";
2
2
  import { WalletContextState } from "@suiet/wallet-kit";
3
3
  import { TransactionBlock } from "@mysten/sui.js/transactions";
4
4
  import { ExecuteTransactionRequestType, SuiTransactionBlockResponseOptions } from "@mysten/sui.js/client";
5
- import BN from "bn.js";
6
- import { Stream, StreamType } from "../common/types";
5
+ import BigNumber from "bignumber.js";
6
+ import { Stream, StreamType } from "../common/types.js";
7
7
  export interface ICreateStreamSuiExt {
8
8
  senderWallet: WalletContextState | Keypair;
9
9
  }
@@ -106,7 +106,7 @@ export declare class Contract implements Stream {
106
106
  magic: number;
107
107
  version: number;
108
108
  createdAt: number;
109
- withdrawnAmount: BN;
109
+ withdrawnAmount: BigNumber;
110
110
  canceledAt: number;
111
111
  end: number;
112
112
  lastWithdrawnAt: number;
@@ -118,20 +118,20 @@ export declare class Contract implements Stream {
118
118
  escrowTokens: string;
119
119
  streamflowTreasury: string;
120
120
  streamflowTreasuryTokens: string;
121
- streamflowFeeTotal: BN;
122
- streamflowFeeWithdrawn: BN;
121
+ streamflowFeeTotal: BigNumber;
122
+ streamflowFeeWithdrawn: BigNumber;
123
123
  streamflowFeePercent: number;
124
- partnerFeeTotal: BN;
125
- partnerFeeWithdrawn: BN;
124
+ partnerFeeTotal: BigNumber;
125
+ partnerFeeWithdrawn: BigNumber;
126
126
  partnerFeePercent: number;
127
127
  partner: string;
128
128
  partnerTokens: string;
129
129
  start: number;
130
- depositedAmount: BN;
130
+ depositedAmount: BigNumber;
131
131
  period: number;
132
- amountPerPeriod: BN;
132
+ amountPerPeriod: BigNumber;
133
133
  cliff: number;
134
- cliffAmount: BN;
134
+ cliffAmount: BigNumber;
135
135
  cancelableBySender: boolean;
136
136
  cancelableByRecipient: boolean;
137
137
  automaticWithdrawal: boolean;
@@ -142,12 +142,12 @@ export declare class Contract implements Stream {
142
142
  withdrawalFrequency: number;
143
143
  closed: boolean;
144
144
  currentPauseStart: number;
145
- pauseCumulative: BN;
145
+ pauseCumulative: BigNumber;
146
146
  lastRateChangeTime: number;
147
- fundsUnlockedAtLastRateChange: BN;
147
+ fundsUnlockedAtLastRateChange: BigNumber;
148
148
  type: StreamType;
149
149
  constructor(stream: StreamResource, tokenId: string);
150
- unlocked(currentTimestamp: number): BN;
150
+ unlocked(currentTimestamp: number): BigNumber;
151
151
  remaining(decimals: number): number;
152
152
  }
153
153
  export interface SuiParsedError {