@streamflow/stream 7.5.2 → 7.5.3-alpha.cffa362.20250508190445

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 (154) hide show
  1. package/dist/cjs/BaseStreamClient-CQOC8m8V.d.cts +542 -0
  2. package/dist/cjs/aptos/index.cjs +460 -0
  3. package/dist/cjs/aptos/index.cjs.map +1 -0
  4. package/dist/cjs/aptos/index.d.cts +14 -0
  5. package/dist/cjs/evm/index.cjs +1917 -0
  6. package/dist/cjs/evm/index.cjs.map +1 -0
  7. package/dist/cjs/evm/index.d.cts +13 -0
  8. package/dist/cjs/index-CYu6i--S.d.cts +136 -0
  9. package/dist/cjs/index-DUVcpIhD.d.cts +203 -0
  10. package/dist/cjs/index-b7Qo5mCj.d.cts +664 -0
  11. package/dist/cjs/index-fNLnPKzv.d.cts +213 -0
  12. package/dist/cjs/index.cjs +7205 -0
  13. package/dist/cjs/index.cjs.map +1 -0
  14. package/dist/cjs/index.d.cts +192 -0
  15. package/dist/cjs/solana/descriptor/streamflow_aligned_unlocks.cjs +4 -0
  16. package/dist/cjs/solana/descriptor/streamflow_aligned_unlocks.cjs.map +1 -0
  17. package/dist/cjs/solana/descriptor/streamflow_aligned_unlocks.d.cts +1234 -0
  18. package/dist/cjs/solana/index.cjs +3763 -0
  19. package/dist/cjs/solana/index.cjs.map +1 -0
  20. package/dist/cjs/solana/index.d.cts +17 -0
  21. package/dist/cjs/sui/index.cjs +1023 -0
  22. package/dist/cjs/sui/index.cjs.map +1 -0
  23. package/dist/cjs/sui/index.d.cts +13 -0
  24. package/dist/esm/BaseStreamClient-CQOC8m8V.d.ts +542 -0
  25. package/dist/esm/aptos/index.d.ts +14 -4
  26. package/dist/esm/aptos/index.js +447 -4
  27. package/dist/esm/aptos/index.js.map +1 -0
  28. package/dist/esm/evm/index.d.ts +13 -5
  29. package/dist/esm/evm/index.js +1904 -5
  30. package/dist/esm/evm/index.js.map +1 -0
  31. package/dist/esm/index-BEo0O2IG.d.ts +664 -0
  32. package/dist/esm/index-CWmb3-x9.d.ts +136 -0
  33. package/dist/esm/index-Cgv37xlG.d.ts +213 -0
  34. package/dist/esm/index-D6QYg8hn.d.ts +203 -0
  35. package/dist/esm/index.d.ts +192 -10
  36. package/dist/esm/index.js +7112 -10
  37. package/dist/esm/index.js.map +1 -0
  38. package/dist/esm/solana/descriptor/idl/streamflow_aligned_unlocks.json +917 -1368
  39. package/dist/esm/solana/descriptor/streamflow_aligned_unlocks.d.ts +3 -1
  40. package/dist/esm/solana/descriptor/streamflow_aligned_unlocks.js +3 -1
  41. package/dist/esm/solana/descriptor/streamflow_aligned_unlocks.js.map +1 -0
  42. package/dist/esm/solana/index.d.ts +17 -7
  43. package/dist/esm/solana/index.js +3707 -7
  44. package/dist/esm/solana/index.js.map +1 -0
  45. package/dist/esm/sui/index.d.ts +13 -4
  46. package/dist/esm/sui/index.js +1013 -4
  47. package/dist/esm/sui/index.js.map +1 -0
  48. package/package.json +57 -27
  49. package/dist/cjs/__tests__/aptos/streamClient.spec.js +0 -111
  50. package/dist/cjs/__tests__/common/GenericStreamClient.spec.js +0 -45
  51. package/dist/cjs/aptos/StreamClient.js +0 -226
  52. package/dist/cjs/aptos/constants.js +0 -27
  53. package/dist/cjs/aptos/index.js +0 -38
  54. package/dist/cjs/aptos/types.js +0 -69
  55. package/dist/cjs/aptos/utils.js +0 -34
  56. package/dist/cjs/aptos/wallet.js +0 -34
  57. package/dist/cjs/common/BaseStreamClient.js +0 -23
  58. package/dist/cjs/common/GenericStreamClient.js +0 -102
  59. package/dist/cjs/common/constants.js +0 -10
  60. package/dist/cjs/common/contractUtils.js +0 -77
  61. package/dist/cjs/common/types.js +0 -141
  62. package/dist/cjs/common/utils.js +0 -69
  63. package/dist/cjs/evm/StreamClient.js +0 -238
  64. package/dist/cjs/evm/abi.js +0 -1257
  65. package/dist/cjs/evm/constants.js +0 -38
  66. package/dist/cjs/evm/ercAbi.js +0 -224
  67. package/dist/cjs/evm/index.js +0 -40
  68. package/dist/cjs/evm/types.js +0 -66
  69. package/dist/cjs/evm/utils.js +0 -11
  70. package/dist/cjs/index.js +0 -43
  71. package/dist/cjs/solana/StreamClient.js +0 -1042
  72. package/dist/cjs/solana/constants.js +0 -95
  73. package/dist/cjs/solana/descriptor/idl/streamflow_aligned_unlocks.json +0 -1437
  74. package/dist/cjs/solana/descriptor/streamflow_aligned_unlocks.js +0 -2
  75. package/dist/cjs/solana/index.js +0 -40
  76. package/dist/cjs/solana/instructionTypes.js +0 -2
  77. package/dist/cjs/solana/instructions.js +0 -298
  78. package/dist/cjs/solana/layout.js +0 -182
  79. package/dist/cjs/solana/lib/derive-accounts.js +0 -17
  80. package/dist/cjs/solana/lib/utils.js +0 -127
  81. package/dist/cjs/solana/timelockIDL.js +0 -422
  82. package/dist/cjs/solana/types.js +0 -93
  83. package/dist/cjs/sui/StreamClient.js +0 -416
  84. package/dist/cjs/sui/constants.js +0 -42
  85. package/dist/cjs/sui/index.js +0 -37
  86. package/dist/cjs/sui/types.js +0 -68
  87. package/dist/cjs/sui/utils.js +0 -46
  88. package/dist/cjs/sui/wallet.js +0 -40
  89. package/dist/esm/__tests__/aptos/streamClient.spec.d.ts +0 -1
  90. package/dist/esm/__tests__/aptos/streamClient.spec.js +0 -106
  91. package/dist/esm/__tests__/common/GenericStreamClient.spec.d.ts +0 -1
  92. package/dist/esm/__tests__/common/GenericStreamClient.spec.js +0 -40
  93. package/dist/esm/aptos/StreamClient.d.ts +0 -53
  94. package/dist/esm/aptos/StreamClient.js +0 -226
  95. package/dist/esm/aptos/constants.d.ts +0 -8
  96. package/dist/esm/aptos/constants.js +0 -24
  97. package/dist/esm/aptos/types.d.ts +0 -109
  98. package/dist/esm/aptos/types.js +0 -105
  99. package/dist/esm/aptos/utils.d.ts +0 -7
  100. package/dist/esm/aptos/utils.js +0 -30
  101. package/dist/esm/aptos/wallet.d.ts +0 -9
  102. package/dist/esm/aptos/wallet.js +0 -33
  103. package/dist/esm/common/BaseStreamClient.d.ts +0 -22
  104. package/dist/esm/common/BaseStreamClient.js +0 -19
  105. package/dist/esm/common/GenericStreamClient.d.ts +0 -72
  106. package/dist/esm/common/GenericStreamClient.js +0 -101
  107. package/dist/esm/common/constants.d.ts +0 -4
  108. package/dist/esm/common/constants.js +0 -4
  109. package/dist/esm/common/contractUtils.d.ts +0 -63
  110. package/dist/esm/common/contractUtils.js +0 -61
  111. package/dist/esm/common/types.d.ts +0 -353
  112. package/dist/esm/common/types.js +0 -135
  113. package/dist/esm/common/utils.d.ts +0 -32
  114. package/dist/esm/common/utils.js +0 -59
  115. package/dist/esm/evm/StreamClient.d.ts +0 -32
  116. package/dist/esm/evm/StreamClient.js +0 -237
  117. package/dist/esm/evm/abi.d.ts +0 -111
  118. package/dist/esm/evm/abi.js +0 -1255
  119. package/dist/esm/evm/constants.d.ts +0 -20
  120. package/dist/esm/evm/constants.js +0 -35
  121. package/dist/esm/evm/ercAbi.d.ts +0 -39
  122. package/dist/esm/evm/ercAbi.js +0 -222
  123. package/dist/esm/evm/types.d.ts +0 -98
  124. package/dist/esm/evm/types.js +0 -102
  125. package/dist/esm/evm/utils.d.ts +0 -1
  126. package/dist/esm/evm/utils.js +0 -8
  127. package/dist/esm/solana/StreamClient.d.ts +0 -150
  128. package/dist/esm/solana/StreamClient.js +0 -1017
  129. package/dist/esm/solana/constants.d.ts +0 -70
  130. package/dist/esm/solana/constants.js +0 -92
  131. package/dist/esm/solana/instructionTypes.d.ts +0 -101
  132. package/dist/esm/solana/instructionTypes.js +0 -1
  133. package/dist/esm/solana/instructions.d.ts +0 -142
  134. package/dist/esm/solana/instructions.js +0 -265
  135. package/dist/esm/solana/layout.d.ts +0 -27
  136. package/dist/esm/solana/layout.js +0 -155
  137. package/dist/esm/solana/lib/derive-accounts.d.ts +0 -4
  138. package/dist/esm/solana/lib/derive-accounts.js +0 -11
  139. package/dist/esm/solana/lib/utils.d.ts +0 -22
  140. package/dist/esm/solana/lib/utils.js +0 -117
  141. package/dist/esm/solana/timelockIDL.d.ts +0 -22
  142. package/dist/esm/solana/timelockIDL.js +0 -420
  143. package/dist/esm/solana/types.d.ts +0 -180
  144. package/dist/esm/solana/types.js +0 -142
  145. package/dist/esm/sui/StreamClient.d.ts +0 -82
  146. package/dist/esm/sui/StreamClient.js +0 -417
  147. package/dist/esm/sui/constants.d.ts +0 -10
  148. package/dist/esm/sui/constants.js +0 -39
  149. package/dist/esm/sui/types.d.ts +0 -167
  150. package/dist/esm/sui/types.js +0 -104
  151. package/dist/esm/sui/utils.d.ts +0 -11
  152. package/dist/esm/sui/utils.js +0 -39
  153. package/dist/esm/sui/wallet.d.ts +0 -17
  154. package/dist/esm/sui/wallet.js +0 -38
@@ -0,0 +1,3763 @@
1
+ 'use strict';
2
+
3
+ var BN6 = require('bn.js');
4
+ var bs58 = require('bs58');
5
+ var buffer = require('buffer');
6
+ var splToken = require('@solana/spl-token');
7
+ var web3_js = require('@solana/web3.js');
8
+ var solana = require('@streamflow/common/solana');
9
+ var borsh = require('borsh');
10
+ var anchor = require('@coral-xyz/anchor');
11
+ var common = require('@streamflow/common');
12
+ require('aptos');
13
+ var BufferLayout = require('@solana/buffer-layout');
14
+
15
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
16
+
17
+ function _interopNamespace(e) {
18
+ if (e && e.__esModule) return e;
19
+ var n = Object.create(null);
20
+ if (e) {
21
+ Object.keys(e).forEach(function (k) {
22
+ if (k !== 'default') {
23
+ var d = Object.getOwnPropertyDescriptor(e, k);
24
+ Object.defineProperty(n, k, d.get ? d : {
25
+ enumerable: true,
26
+ get: function () { return e[k]; }
27
+ });
28
+ }
29
+ });
30
+ }
31
+ n.default = e;
32
+ return Object.freeze(n);
33
+ }
34
+
35
+ var BN6__default = /*#__PURE__*/_interopDefault(BN6);
36
+ var bs58__default = /*#__PURE__*/_interopDefault(bs58);
37
+ var borsh__namespace = /*#__PURE__*/_interopNamespace(borsh);
38
+ var BufferLayout__namespace = /*#__PURE__*/_interopNamespace(BufferLayout);
39
+
40
+ var __defProp = Object.defineProperty;
41
+ var __export = (target, all) => {
42
+ for (var name in all)
43
+ __defProp(target, name, { get: all[name], enumerable: true });
44
+ };
45
+ var MAX_SAFE_UNIX_TIME_VALUE = 864e10;
46
+ var WITHDRAW_AVAILABLE_AMOUNT = new BN6__default.default("18446744073709551615");
47
+
48
+ // common/contractUtils.ts
49
+ var calculateUnlockedAmount = ({
50
+ depositedAmount,
51
+ cliff,
52
+ cliffAmount,
53
+ end,
54
+ currentTimestamp,
55
+ lastRateChangeTime,
56
+ period,
57
+ amountPerPeriod,
58
+ fundsUnlockedAtLastRateChange
59
+ }) => {
60
+ const deposited = depositedAmount;
61
+ if (currentTimestamp < cliff) return new BN6__default.default(0);
62
+ if (currentTimestamp > end) return deposited;
63
+ const savedUnlockedFunds = lastRateChangeTime === 0 ? cliffAmount : fundsUnlockedAtLastRateChange;
64
+ const savedUnlockedFundsTime = lastRateChangeTime === 0 ? cliff : lastRateChangeTime;
65
+ const streamed = new BN6__default.default(Math.floor((currentTimestamp - savedUnlockedFundsTime) / period)).mul(amountPerPeriod).add(savedUnlockedFunds);
66
+ return streamed.lt(deposited) ? streamed : deposited;
67
+ };
68
+ var isCliffCloseToDepositedAmount = (streamData) => {
69
+ return streamData.cliffAmount.gte(streamData.depositedAmount.sub(new BN6__default.default(1)));
70
+ };
71
+ var isVesting = (streamData) => {
72
+ return !streamData.canTopup && !isCliffCloseToDepositedAmount(streamData) && !isDynamicLock(streamData.minPrice, streamData.maxPrice, streamData.minPercentage, streamData.maxPercentage);
73
+ };
74
+ var isCreateAlignedStreamData = (obj) => {
75
+ return "minPrice" in obj && "maxPrice" in obj && "minPercentage" in obj && "maxPercentage" in obj;
76
+ };
77
+ var isDynamicLock = (minPrice, maxPrice, minPercentage, maxPercentage) => {
78
+ return !!minPrice && !!maxPrice && minPrice > 0 && maxPrice - minPrice <= 1 && minPercentage === 0 && maxPercentage === 100;
79
+ };
80
+ var isTokenLock = (streamData) => {
81
+ return !streamData.canTopup && !streamData.automaticWithdrawal && !streamData.cancelableBySender && !streamData.cancelableByRecipient && !streamData.transferableBySender && !streamData.transferableByRecipient && (isCliffCloseToDepositedAmount(streamData) || isDynamicLock(streamData.minPrice, streamData.maxPrice, streamData.minPercentage, streamData.maxPercentage));
82
+ };
83
+ var buildStreamType = (streamData) => {
84
+ if (isVesting(streamData)) {
85
+ return "vesting" /* Vesting */;
86
+ }
87
+ if (isTokenLock(streamData)) {
88
+ return "lock" /* Lock */;
89
+ }
90
+ return "payment" /* Payment */;
91
+ };
92
+ var decodeEndTime = (endTime) => {
93
+ if (endTime.gt(new BN6__default.default(MAX_SAFE_UNIX_TIME_VALUE))) {
94
+ return MAX_SAFE_UNIX_TIME_VALUE;
95
+ }
96
+ return endTime.toNumber();
97
+ };
98
+ var FEE_PRECISION = 4;
99
+ var FEE_NORMALIZER = 10 ** FEE_PRECISION;
100
+ var FEE_MULTIPLIER = new BN6__default.default(10 ** 6);
101
+ var getNumberFromBN = (value, decimals) => value.gt(new BN6__default.default(2 ** 53 - 1)) ? value.div(new BN6__default.default(10 ** decimals)).toNumber() : value.toNumber() / 10 ** decimals;
102
+ var calculateTotalAmountToDeposit = (depositedAmount, totalFee) => {
103
+ const totalFeeNormalized = new BN6__default.default(totalFee * FEE_NORMALIZER);
104
+ return depositedAmount.mul(totalFeeNormalized.add(FEE_MULTIPLIER)).div(FEE_MULTIPLIER);
105
+ };
106
+
107
+ // solana/constants.ts
108
+ var constants_exports = {};
109
+ __export(constants_exports, {
110
+ AIRDROP_AMOUNT: () => AIRDROP_AMOUNT,
111
+ AIRDROP_TEST_TOKEN: () => AIRDROP_TEST_TOKEN,
112
+ ALIGNED_COMPUTE_LIMIT: () => ALIGNED_COMPUTE_LIMIT,
113
+ ALIGNED_PRECISION_FACTOR_POW: () => ALIGNED_PRECISION_FACTOR_POW,
114
+ ALIGNED_UNLOCKS_PROGRAM_ID: () => ALIGNED_UNLOCKS_PROGRAM_ID,
115
+ CONTRACT_DISCRIMINATOR: () => CONTRACT_DISCRIMINATOR,
116
+ CONTRACT_SEED: () => CONTRACT_SEED,
117
+ CREATE_PARAMS_PADDING: () => CREATE_PARAMS_PADDING,
118
+ DEFAULT_STREAMFLOW_FEE: () => DEFAULT_STREAMFLOW_FEE,
119
+ ESCROW_SEED: () => ESCROW_SEED,
120
+ FEES_METADATA_SEED: () => FEES_METADATA_SEED,
121
+ FEE_ORACLE_PUBLIC_KEY: () => FEE_ORACLE_PUBLIC_KEY,
122
+ ORIGINAL_CONTRACT_SENDER_OFFSET: () => ORIGINAL_CONTRACT_SENDER_OFFSET,
123
+ PARTNERS_SCHEMA: () => PARTNERS_SCHEMA,
124
+ PARTNER_ORACLE_PROGRAM_ID: () => PARTNER_ORACLE_PROGRAM_ID,
125
+ PARTNER_SCHEMA: () => PARTNER_SCHEMA,
126
+ PROGRAM_ID: () => PROGRAM_ID,
127
+ SOLANA_ERROR_MAP: () => SOLANA_ERROR_MAP,
128
+ SOLANA_ERROR_MATCH_REGEX: () => SOLANA_ERROR_MATCH_REGEX,
129
+ STREAMFLOW_TREASURY_PUBLIC_KEY: () => STREAMFLOW_TREASURY_PUBLIC_KEY,
130
+ STREAM_STRUCT_OFFSETS: () => STREAM_STRUCT_OFFSETS,
131
+ STREAM_STRUCT_OFFSET_CLOSED: () => STREAM_STRUCT_OFFSET_CLOSED,
132
+ STREAM_STRUCT_OFFSET_MINT: () => STREAM_STRUCT_OFFSET_MINT,
133
+ STREAM_STRUCT_OFFSET_RECIPIENT: () => STREAM_STRUCT_OFFSET_RECIPIENT,
134
+ STREAM_STRUCT_OFFSET_SENDER: () => STREAM_STRUCT_OFFSET_SENDER,
135
+ TEST_ORACLE_DISCRIMINATOR: () => TEST_ORACLE_DISCRIMINATOR,
136
+ TEST_ORACLE_SEED: () => TEST_ORACLE_SEED,
137
+ TX_FINALITY_CONFIRMED: () => TX_FINALITY_CONFIRMED,
138
+ WITHDRAWOR_PUBLIC_KEY: () => WITHDRAWOR_PUBLIC_KEY
139
+ });
140
+ var TX_FINALITY_CONFIRMED = "confirmed";
141
+ var ORIGINAL_CONTRACT_SENDER_OFFSET = 9;
142
+ var STREAM_STRUCT_OFFSET_SENDER = 49;
143
+ var STREAM_STRUCT_OFFSET_RECIPIENT = 113;
144
+ var STREAM_STRUCT_OFFSET_MINT = 177;
145
+ var STREAM_STRUCT_OFFSET_CLOSED = 671;
146
+ var ALIGNED_PRECISION_FACTOR_POW = 9;
147
+ var STREAM_STRUCT_OFFSETS = {
148
+ mint: STREAM_STRUCT_OFFSET_MINT,
149
+ recipient: STREAM_STRUCT_OFFSET_RECIPIENT,
150
+ sender: STREAM_STRUCT_OFFSET_SENDER,
151
+ closed: STREAM_STRUCT_OFFSET_CLOSED
152
+ };
153
+ var CREATE_PARAMS_PADDING = 126;
154
+ var PROGRAM_ID = {
155
+ [common.ICluster.Devnet]: "HqDGZjaVRXJ9MGRQEw7qDc2rAr6iH1n1kAQdCZaCMfMZ",
156
+ [common.ICluster.Mainnet]: "strmRqUCoQUgGUan5YhzUZa6KqdzwX5L6FpUxfmKg5m",
157
+ [common.ICluster.Testnet]: "HqDGZjaVRXJ9MGRQEw7qDc2rAr6iH1n1kAQdCZaCMfMZ",
158
+ [common.ICluster.Local]: "HqDGZjaVRXJ9MGRQEw7qDc2rAr6iH1n1kAQdCZaCMfMZ"
159
+ };
160
+ var ALIGNED_UNLOCKS_PROGRAM_ID = {
161
+ [common.ICluster.Devnet]: "aSTRM2NKoKxNnkmLWk9sz3k74gKBk9t7bpPrTGxMszH",
162
+ [common.ICluster.Mainnet]: "aSTRM2NKoKxNnkmLWk9sz3k74gKBk9t7bpPrTGxMszH",
163
+ [common.ICluster.Testnet]: "aSTRM2NKoKxNnkmLWk9sz3k74gKBk9t7bpPrTGxMszH",
164
+ [common.ICluster.Local]: "aSTRM2NKoKxNnkmLWk9sz3k74gKBk9t7bpPrTGxMszH"
165
+ };
166
+ var ALIGNED_COMPUTE_LIMIT = 3e5;
167
+ var CONTRACT_DISCRIMINATOR = [172, 138, 115, 242, 121, 67, 183, 26];
168
+ var TEST_ORACLE_DISCRIMINATOR = [198, 49, 63, 134, 232, 251, 168, 28];
169
+ var CONTRACT_SEED = buffer.Buffer.from("contract", "utf-8");
170
+ var ESCROW_SEED = buffer.Buffer.from("strm", "utf-8");
171
+ var TEST_ORACLE_SEED = buffer.Buffer.from("test-oracle", "utf-8");
172
+ var PARTNER_ORACLE_PROGRAM_ID = "pardpVtPjC8nLj1Dwncew62mUzfChdCX1EaoZe8oCAa";
173
+ var STREAMFLOW_TREASURY_PUBLIC_KEY = new web3_js.PublicKey("5SEpbdjFK5FxwTvfsGMXVQTD2v4M2c5tyRTxhdsPkgDw");
174
+ var WITHDRAWOR_PUBLIC_KEY = new web3_js.PublicKey("wdrwhnCv4pzW8beKsbPa4S2UDZrXenjg16KJdKSpb5u");
175
+ var FEE_ORACLE_PUBLIC_KEY = new web3_js.PublicKey("B743wFVk2pCYhV91cn287e1xY7f1vt4gdY48hhNiuQmT");
176
+ var AIRDROP_TEST_TOKEN = "Gssm3vfi8s65R31SBdmQRq6cKeYojGgup7whkw4VCiQj";
177
+ var FEES_METADATA_SEED = buffer.Buffer.from("strm_fees");
178
+ var DEFAULT_STREAMFLOW_FEE = 0.99;
179
+ var AIRDROP_AMOUNT = 1;
180
+ var PARTNER_SCHEMA = {
181
+ struct: {
182
+ pubkey: { array: { type: "u8", len: 32 } },
183
+ partner_fee: "f32",
184
+ strm_fee: "f32"
185
+ }
186
+ };
187
+ var PARTNERS_SCHEMA = { array: { type: PARTNER_SCHEMA } };
188
+ var SOLANA_ERROR_MATCH_REGEX = /custom program error: (0x\d{2})/;
189
+ var SOLANA_ERROR_MAP = {
190
+ 96: "AccountsNotWritable" /* AccountsNotWritable */,
191
+ 97: "InvalidMetadata" /* InvalidMetadata */,
192
+ 98: "InvalidMetadataAccount" /* InvalidMetadataAccount */,
193
+ 99: "MetadataAccountMismatch" /* MetadataAccountMismatch */,
194
+ 100: "InvalidEscrowAccount" /* InvalidEscrowAccount */,
195
+ 101: "NotAssociated" /* NotAssociated */,
196
+ 102: "MintMismatch" /* MintMismatch */,
197
+ 103: "TransferNotAllowed" /* TransferNotAllowed */,
198
+ 104: "ContractClosed" /* ContractClosed */,
199
+ 105: "InvalidTreasury" /* InvalidTreasury */,
200
+ 112: "InvalidTimestamps" /* InvalidTimestamps */,
201
+ 113: "InvalidDepositConfiguration" /* InvalidDepositConfiguration */,
202
+ 114: "AmountIsZero" /* AmountIsZero */,
203
+ 115: "AmountMoreThanAvailable" /* AmountMoreThanAvailable */,
204
+ 116: "AmountAvailableIsZero" /* AmountAvailableIsZero */,
205
+ 128: "ArithmeticError" /* ArithmeticError */,
206
+ 129: "InvalidMetadataSize" /* InvalidMetadataSize */,
207
+ 130: "UninitializedMetadata" /* UninitializedMetadata */,
208
+ 131: "Unauthorized" /* Unauthorized */,
209
+ 132: "SelfTransfer" /* SelfTransfer */,
210
+ 133: "AlreadyPaused" /* AlreadyPaused */,
211
+ 134: "NotPaused" /* NotPaused */,
212
+ 135: "MetadataNotRentExempt" /* MetadataNotRentExempt */,
213
+ 6e3: "Unauthorized" /* Unauthorized */,
214
+ 6001: "ArithmeticError" /* ArithmeticError */,
215
+ 6002: "UnsupportedTokenExtensions" /* UnsupportedTokenExtensions */,
216
+ 6003: "PeriodTooShort" /* PeriodTooShort */,
217
+ 6004: "InvalidTickSize" /* InvalidTickSize */,
218
+ 6005: "InvalidPercentageBoundaries" /* InvalidPercentageBoundaries */,
219
+ 6006: "InvalidPriceBoundaries" /* InvalidPriceBoundaries */,
220
+ 6007: "UnsupportedOracle" /* UnsupportedOracle */,
221
+ 6008: "InvalidOracleAccount" /* InvalidOracleAccount */,
222
+ 6009: "InvalidOraclePrice" /* InvalidOraclePrice */,
223
+ 6010: "InvalidStreamMetadata" /* InvalidStreamMetadata */,
224
+ 6011: "AmountAlreadyUpdated" /* AmountAlreadyUpdated */,
225
+ 6012: "AllFundsUnlocked" /* AllFundsUnlocked */
226
+ };
227
+ var Contract = class {
228
+ constructor(stream) {
229
+ this.magic = stream.magic.toNumber();
230
+ this.version = stream.version.toNumber();
231
+ this.createdAt = stream.createdAt.toNumber();
232
+ this.withdrawnAmount = stream.withdrawnAmount;
233
+ this.canceledAt = stream.canceledAt.toNumber();
234
+ this.end = decodeEndTime(stream.end);
235
+ this.lastWithdrawnAt = stream.lastWithdrawnAt.toNumber();
236
+ this.sender = stream.sender.toBase58();
237
+ this.senderTokens = stream.senderTokens.toBase58();
238
+ this.recipient = stream.recipient.toBase58();
239
+ this.recipientTokens = stream.recipientTokens.toBase58();
240
+ this.mint = stream.mint.toBase58();
241
+ this.escrowTokens = stream.escrowTokens.toBase58();
242
+ this.streamflowTreasury = stream.streamflowTreasury.toBase58();
243
+ this.streamflowTreasuryTokens = stream.streamflowTreasuryTokens.toBase58();
244
+ this.streamflowFeeTotal = stream.streamflowFeeTotal;
245
+ this.streamflowFeeWithdrawn = stream.streamflowFeeWithdrawn;
246
+ this.streamflowFeePercent = stream.streamflowFeePercent.toNumber();
247
+ this.partnerFeeTotal = stream.partnerFeeTotal;
248
+ this.partnerFeeWithdrawn = stream.partnerFeeWithdrawn;
249
+ this.partnerFeePercent = stream.partnerFeePercent.toNumber();
250
+ this.partner = stream.partner.toBase58();
251
+ this.partnerTokens = stream.partnerTokens?.toBase58();
252
+ this.start = stream.start.toNumber();
253
+ this.depositedAmount = stream.depositedAmount;
254
+ this.period = stream.period.toNumber();
255
+ this.amountPerPeriod = stream.amountPerPeriod;
256
+ this.cliff = stream.cliff.toNumber();
257
+ this.cliffAmount = stream.cliffAmount;
258
+ this.cancelableBySender = stream.cancelableBySender;
259
+ this.cancelableByRecipient = stream.cancelableByRecipient;
260
+ this.automaticWithdrawal = stream.automaticWithdrawal;
261
+ this.transferableBySender = stream.transferableBySender;
262
+ this.transferableByRecipient = stream.transferableByRecipient;
263
+ this.canTopup = stream.canTopup;
264
+ this.name = stream.name;
265
+ this.withdrawalFrequency = stream.withdrawFrequency.toNumber();
266
+ this.closed = stream.closed;
267
+ this.currentPauseStart = stream.currentPauseStart.toNumber();
268
+ this.pauseCumulative = stream.pauseCumulative;
269
+ this.lastRateChangeTime = stream.lastRateChangeTime.toNumber();
270
+ this.fundsUnlockedAtLastRateChange = stream.fundsUnlockedAtLastRateChange;
271
+ this.type = buildStreamType(this);
272
+ this.isAligned = false;
273
+ }
274
+ unlocked(currentTimestamp) {
275
+ return calculateUnlockedAmount({
276
+ ...this,
277
+ currentTimestamp
278
+ });
279
+ }
280
+ remaining(decimals) {
281
+ return getNumberFromBN(this.depositedAmount.sub(this.withdrawnAmount), decimals);
282
+ }
283
+ };
284
+ var AlignedContract = class extends Contract {
285
+ constructor(stream, alignedProxy) {
286
+ super(stream);
287
+ this.minPrice = getNumberFromBN(alignedProxy.minPrice, ALIGNED_PRECISION_FACTOR_POW);
288
+ this.maxPrice = getNumberFromBN(alignedProxy.maxPrice, ALIGNED_PRECISION_FACTOR_POW);
289
+ this.minPercentage = getNumberFromBN(alignedProxy.minPercentage, ALIGNED_PRECISION_FACTOR_POW);
290
+ this.maxPercentage = getNumberFromBN(alignedProxy.maxPercentage, ALIGNED_PRECISION_FACTOR_POW);
291
+ this.oracleType = Object.keys(alignedProxy.priceOracleType).find((key) => !!key) || "none";
292
+ this.tickSize = alignedProxy.tickSize.toNumber();
293
+ this.priceOracle = this.oracleType === "none" ? void 0 : alignedProxy.priceOracle.toBase58();
294
+ this.sender = alignedProxy.sender.toBase58();
295
+ this.canceledAt = alignedProxy.streamCanceledTime.toNumber();
296
+ this.proxyAddress = stream.sender.toBase58();
297
+ this.initialAmountPerPeriod = alignedProxy.initialAmountPerPeriod;
298
+ this.initialPrice = getNumberFromBN(alignedProxy.initialPrice, ALIGNED_PRECISION_FACTOR_POW);
299
+ this.lastPrice = getNumberFromBN(alignedProxy.lastPrice, ALIGNED_PRECISION_FACTOR_POW);
300
+ this.lastAmountUpdateTime = alignedProxy.lastAmountUpdateTime.toNumber();
301
+ this.initialNetAmount = alignedProxy.initialNetAmount;
302
+ this.type = buildStreamType(this);
303
+ this.isAligned = true;
304
+ }
305
+ };
306
+ var streamLayout = BufferLayout__namespace.struct([
307
+ BufferLayout__namespace.blob(8, "magic"),
308
+ BufferLayout__namespace.blob(1, "version"),
309
+ BufferLayout__namespace.blob(8, "created_at"),
310
+ BufferLayout__namespace.blob(8, "withdrawn_amount"),
311
+ BufferLayout__namespace.blob(8, "canceled_at"),
312
+ BufferLayout__namespace.blob(8, "end_time"),
313
+ BufferLayout__namespace.blob(8, "last_withdrawn_at"),
314
+ BufferLayout__namespace.blob(32, "sender"),
315
+ BufferLayout__namespace.blob(32, "sender_tokens"),
316
+ BufferLayout__namespace.blob(32, "recipient"),
317
+ BufferLayout__namespace.blob(32, "recipient_tokens"),
318
+ BufferLayout__namespace.blob(32, "mint"),
319
+ BufferLayout__namespace.blob(32, "escrow_tokens"),
320
+ BufferLayout__namespace.blob(32, "streamflow_treasury"),
321
+ BufferLayout__namespace.blob(32, "streamflow_treasury_tokens"),
322
+ BufferLayout__namespace.blob(8, "streamflow_fee_total"),
323
+ BufferLayout__namespace.blob(8, "streamflow_fee_withdrawn"),
324
+ BufferLayout__namespace.f32("streamflow_fee_percent"),
325
+ BufferLayout__namespace.blob(32, "partner"),
326
+ BufferLayout__namespace.blob(32, "partner_tokens"),
327
+ BufferLayout__namespace.blob(8, "partner_fee_total"),
328
+ BufferLayout__namespace.blob(8, "partner_fee_withdrawn"),
329
+ BufferLayout__namespace.f32("partner_fee_percent"),
330
+ BufferLayout__namespace.blob(8, "start_time"),
331
+ BufferLayout__namespace.blob(8, "net_amount_deposited"),
332
+ BufferLayout__namespace.blob(8, "period"),
333
+ BufferLayout__namespace.blob(8, "amount_per_period"),
334
+ BufferLayout__namespace.blob(8, "cliff"),
335
+ BufferLayout__namespace.blob(8, "cliff_amount"),
336
+ BufferLayout__namespace.u8("cancelable_by_sender"),
337
+ BufferLayout__namespace.u8("cancelable_by_recipient"),
338
+ BufferLayout__namespace.u8("automatic_withdrawal"),
339
+ BufferLayout__namespace.u8("transferable_by_sender"),
340
+ BufferLayout__namespace.u8("transferable_by_recipient"),
341
+ BufferLayout__namespace.u8("can_topup"),
342
+ BufferLayout__namespace.blob(64, "stream_name"),
343
+ BufferLayout__namespace.blob(8, "withdraw_frequency"),
344
+ // Unused, kept for backward compatibility™
345
+ BufferLayout__namespace.blob(4, "ghost"),
346
+ BufferLayout__namespace.u8("pausable"),
347
+ BufferLayout__namespace.u8("can_update_rate"),
348
+ BufferLayout__namespace.blob(4, "create_stream_params_padding_length"),
349
+ BufferLayout__namespace.seq(BufferLayout__namespace.u8(), CREATE_PARAMS_PADDING, "create_params_padding"),
350
+ BufferLayout__namespace.u8("closed"),
351
+ BufferLayout__namespace.blob(8, "current_pause_start"),
352
+ BufferLayout__namespace.blob(8, "pause_cumulative"),
353
+ BufferLayout__namespace.blob(8, "last_rate_change_time"),
354
+ BufferLayout__namespace.blob(8, "funds_unlocked_at_last_rate_change")
355
+ ]);
356
+ BufferLayout__namespace.struct([
357
+ BufferLayout__namespace.blob(32, "pubkey"),
358
+ BufferLayout__namespace.f32("partner_fee"),
359
+ BufferLayout__namespace.f32("strm_fee")
360
+ ]);
361
+ var createStreamLayout = BufferLayout__namespace.struct([
362
+ BufferLayout__namespace.blob(8, "start_time"),
363
+ BufferLayout__namespace.blob(8, "net_amount_deposited"),
364
+ BufferLayout__namespace.blob(8, "period"),
365
+ BufferLayout__namespace.blob(8, "amount_per_period"),
366
+ BufferLayout__namespace.blob(8, "cliff"),
367
+ BufferLayout__namespace.blob(8, "cliff_amount"),
368
+ BufferLayout__namespace.u8("cancelable_by_sender"),
369
+ BufferLayout__namespace.u8("cancelable_by_recipient"),
370
+ BufferLayout__namespace.u8("automatic_withdrawal"),
371
+ BufferLayout__namespace.u8("transferable_by_sender"),
372
+ BufferLayout__namespace.u8("transferable_by_recipient"),
373
+ BufferLayout__namespace.u8("can_topup"),
374
+ BufferLayout__namespace.blob(64, "stream_name"),
375
+ BufferLayout__namespace.blob(8, "withdraw_frequency"),
376
+ // discriminator for optional field
377
+ BufferLayout__namespace.u8("_pausable_discriminator"),
378
+ BufferLayout__namespace.u8("pausable"),
379
+ // discriminator for optional field
380
+ BufferLayout__namespace.u8("_can_update_rate_discriminator"),
381
+ BufferLayout__namespace.u8("can_update_rate")
382
+ ]);
383
+ var createUncheckedStreamLayout = BufferLayout__namespace.struct([
384
+ BufferLayout__namespace.blob(8, "start_time"),
385
+ BufferLayout__namespace.blob(8, "net_amount_deposited"),
386
+ BufferLayout__namespace.blob(8, "period"),
387
+ BufferLayout__namespace.blob(8, "amount_per_period"),
388
+ BufferLayout__namespace.blob(8, "cliff"),
389
+ BufferLayout__namespace.blob(8, "cliff_amount"),
390
+ BufferLayout__namespace.u8("cancelable_by_sender"),
391
+ BufferLayout__namespace.u8("cancelable_by_recipient"),
392
+ BufferLayout__namespace.u8("automatic_withdrawal"),
393
+ BufferLayout__namespace.u8("transferable_by_sender"),
394
+ BufferLayout__namespace.u8("transferable_by_recipient"),
395
+ BufferLayout__namespace.u8("can_topup"),
396
+ BufferLayout__namespace.blob(64, "stream_name"),
397
+ BufferLayout__namespace.blob(8, "withdraw_frequency"),
398
+ BufferLayout__namespace.blob(32, "recipient"),
399
+ BufferLayout__namespace.blob(32, "partner"),
400
+ BufferLayout__namespace.u8("pausable"),
401
+ BufferLayout__namespace.u8("can_update_rate")
402
+ ]);
403
+ var withdrawStreamLayout = BufferLayout__namespace.struct([
404
+ BufferLayout__namespace.blob(8, "amount")
405
+ ]);
406
+ var encodeUpdateStream = (values, data) => {
407
+ const structs = [];
408
+ if (values.enable_automatic_withdrawal) {
409
+ structs.push(BufferLayout__namespace.u8("enable_automatic_withdrawal_exists"));
410
+ structs.push(BufferLayout__namespace.u8("enable_automatic_withdrawal"));
411
+ } else {
412
+ structs.push(BufferLayout__namespace.u8("enable_automatic_withdrawal_exists"));
413
+ }
414
+ if (values.withdraw_frequency) {
415
+ structs.push(BufferLayout__namespace.u8("withdraw_frequency_exists"));
416
+ structs.push(BufferLayout__namespace.blob(8, "withdraw_frequency"));
417
+ } else {
418
+ structs.push(BufferLayout__namespace.u8("withdraw_frequency_exists"));
419
+ }
420
+ if (values.amount_per_period) {
421
+ structs.push(BufferLayout__namespace.u8("amount_per_period_exists"));
422
+ structs.push(BufferLayout__namespace.blob(8, "amount_per_period"));
423
+ } else {
424
+ structs.push(BufferLayout__namespace.u8("amount_per_period_exists"));
425
+ }
426
+ return BufferLayout__namespace.struct(structs).encode(
427
+ {
428
+ enable_automatic_withdrawal_exists: values.enable_automatic_withdrawal ? 1 : 0,
429
+ enable_automatic_withdrawal: values.enable_automatic_withdrawal ?? 0,
430
+ withdraw_frequency_exists: values.withdraw_frequency ? 1 : 0,
431
+ withdraw_frequency: values.withdraw_frequency ?? 0,
432
+ amount_per_period_exists: values.amount_per_period ? 1 : 0,
433
+ amount_per_period: values.amount_per_period ?? 0
434
+ },
435
+ data
436
+ );
437
+ };
438
+ var topupStreamLayout = BufferLayout__namespace.struct([
439
+ BufferLayout__namespace.blob(8, "amount")
440
+ ]);
441
+
442
+ // solana/lib/utils.ts
443
+ var decoder = new TextDecoder("utf-8");
444
+ var LE = "le";
445
+ var decodeStream = (buf) => {
446
+ const raw = streamLayout.decode(buf);
447
+ return {
448
+ magic: new BN6__default.default(raw.magic, LE),
449
+ version: new BN6__default.default(raw.version, LE),
450
+ createdAt: new BN6__default.default(raw.created_at, LE),
451
+ withdrawnAmount: new BN6__default.default(raw.withdrawn_amount, LE),
452
+ canceledAt: new BN6__default.default(raw.canceled_at, LE),
453
+ end: new BN6__default.default(raw.end_time, LE),
454
+ lastWithdrawnAt: new BN6__default.default(raw.last_withdrawn_at, LE),
455
+ sender: new web3_js.PublicKey(raw.sender),
456
+ senderTokens: new web3_js.PublicKey(raw.sender_tokens),
457
+ recipient: new web3_js.PublicKey(raw.recipient),
458
+ recipientTokens: new web3_js.PublicKey(raw.recipient_tokens),
459
+ mint: new web3_js.PublicKey(raw.mint),
460
+ escrowTokens: new web3_js.PublicKey(raw.escrow_tokens),
461
+ streamflowTreasury: new web3_js.PublicKey(raw.streamflow_treasury),
462
+ streamflowTreasuryTokens: new web3_js.PublicKey(raw.streamflow_treasury_tokens),
463
+ streamflowFeeTotal: new BN6__default.default(raw.streamflow_fee_total, LE),
464
+ streamflowFeeWithdrawn: new BN6__default.default(raw.streamflow_fee_withdrawn, LE),
465
+ streamflowFeePercent: new BN6__default.default(raw.streamflow_fee_percent, LE),
466
+ partnerFeeTotal: new BN6__default.default(raw.partner_fee_total, LE),
467
+ partnerFeeWithdrawn: new BN6__default.default(raw.partner_fee_withdrawn, LE),
468
+ partnerFeePercent: new BN6__default.default(raw.partner_fee_percent, LE),
469
+ partner: new web3_js.PublicKey(raw.partner),
470
+ partnerTokens: new web3_js.PublicKey(raw.partner_tokens),
471
+ start: new BN6__default.default(raw.start_time, LE),
472
+ depositedAmount: new BN6__default.default(raw.net_amount_deposited, LE),
473
+ period: new BN6__default.default(raw.period, LE),
474
+ amountPerPeriod: new BN6__default.default(raw.amount_per_period, LE),
475
+ cliff: new BN6__default.default(raw.cliff, LE),
476
+ cliffAmount: new BN6__default.default(raw.cliff_amount, LE),
477
+ cancelableBySender: Boolean(raw.cancelable_by_sender),
478
+ cancelableByRecipient: Boolean(raw.cancelable_by_recipient),
479
+ automaticWithdrawal: Boolean(raw.automatic_withdrawal),
480
+ transferableBySender: Boolean(raw.transferable_by_sender),
481
+ transferableByRecipient: Boolean(raw.transferable_by_recipient),
482
+ canTopup: Boolean(raw.can_topup),
483
+ name: decoder.decode(raw.stream_name),
484
+ withdrawFrequency: new BN6__default.default(raw.withdraw_frequency, LE),
485
+ closed: Boolean(raw.closed),
486
+ currentPauseStart: new BN6__default.default(raw.current_pause_start, LE),
487
+ pauseCumulative: new BN6__default.default(raw.pause_cumulative, LE),
488
+ lastRateChangeTime: new BN6__default.default(raw.last_rate_change_time, LE),
489
+ fundsUnlockedAtLastRateChange: new BN6__default.default(raw.funds_unlocked_at_last_rate_change, LE)
490
+ };
491
+ };
492
+ async function signAllTransactionWithRecipients(sender, items) {
493
+ const isKeypair = solana.isSignerKeypair(sender);
494
+ const isWallet = solana.isSignerWallet(sender);
495
+ if (isKeypair) {
496
+ return items.map((t) => {
497
+ t.tx.sign([sender]);
498
+ return { tx: t.tx, recipient: t.recipient };
499
+ });
500
+ } else if (isWallet) {
501
+ const signedTxs = await sender.signAllTransactions(items.map((t) => t.tx));
502
+ return items.map((item, index) => ({
503
+ ...item,
504
+ tx: signedTxs[index]
505
+ }));
506
+ } else {
507
+ return [];
508
+ }
509
+ }
510
+ async function sendAndConfirmStreamRawTransaction(connection, batchItem, confirmationParams, throttleParams) {
511
+ try {
512
+ const completedTxSignature = await solana.executeTransaction(connection, batchItem.tx, confirmationParams, throttleParams);
513
+ return { ...batchItem, signature: completedTxSignature };
514
+ } catch (error) {
515
+ throw {
516
+ recipient: batchItem.recipient,
517
+ error
518
+ };
519
+ }
520
+ }
521
+ function extractSolanaErrorCode(errorText, logs) {
522
+ let match = SOLANA_ERROR_MATCH_REGEX.exec(errorText);
523
+ if (!match && logs) {
524
+ for (const logLine of logs) {
525
+ match = SOLANA_ERROR_MATCH_REGEX.exec(logLine);
526
+ if (match !== null) {
527
+ break;
528
+ }
529
+ }
530
+ }
531
+ if (!match) {
532
+ return null;
533
+ }
534
+ const errorCode = Number(match[1]);
535
+ return SOLANA_ERROR_MAP[errorCode] || null;
536
+ }
537
+ var sha256 = {
538
+ digest: async (data) => {
539
+ const dataBuffer = new TextEncoder().encode(data);
540
+ const hashBuffer = await globalThis.crypto.subtle.digest("SHA-256", dataBuffer);
541
+ return new Uint8Array(hashBuffer);
542
+ }
543
+ };
544
+ var createStreamInstruction = async (data, programId, accounts) => {
545
+ const keys = [
546
+ { pubkey: accounts.sender, isSigner: true, isWritable: true },
547
+ { pubkey: accounts.senderTokens, isSigner: false, isWritable: true },
548
+ { pubkey: accounts.recipient, isSigner: false, isWritable: true },
549
+ { pubkey: accounts.metadata, isSigner: true, isWritable: true },
550
+ { pubkey: accounts.escrowTokens, isSigner: false, isWritable: true },
551
+ { pubkey: accounts.recipientTokens, isSigner: false, isWritable: true },
552
+ {
553
+ pubkey: accounts.streamflowTreasury,
554
+ isSigner: false,
555
+ isWritable: true
556
+ },
557
+ {
558
+ pubkey: accounts.streamflowTreasuryTokens,
559
+ isSigner: false,
560
+ isWritable: true
561
+ },
562
+ { pubkey: accounts.withdrawor, isSigner: false, isWritable: true },
563
+ { pubkey: accounts.partner, isSigner: false, isWritable: true },
564
+ { pubkey: accounts.partnerTokens, isSigner: false, isWritable: true },
565
+ { pubkey: accounts.mint, isSigner: false, isWritable: false },
566
+ { pubkey: accounts.feeOracle, isSigner: false, isWritable: false },
567
+ { pubkey: accounts.rent, isSigner: false, isWritable: false },
568
+ { pubkey: accounts.timelockProgram, isSigner: false, isWritable: false },
569
+ { pubkey: accounts.tokenProgram, isSigner: false, isWritable: false },
570
+ {
571
+ pubkey: accounts.associatedTokenProgram,
572
+ isSigner: false,
573
+ isWritable: false
574
+ },
575
+ { pubkey: accounts.systemProgram, isSigner: false, isWritable: false }
576
+ ];
577
+ let bufferData = buffer.Buffer.alloc(createStreamLayout.span);
578
+ const encodedUIntArray = new TextEncoder().encode(data.name);
579
+ const streamNameBuffer = buffer.Buffer.alloc(64).fill(encodedUIntArray, 0, encodedUIntArray.byteLength);
580
+ const decodedData = {
581
+ start_time: data.start.toArrayLike(buffer.Buffer, "le", 8),
582
+ net_amount_deposited: data.depositedAmount.toArrayLike(buffer.Buffer, "le", 8),
583
+ period: data.period.toArrayLike(buffer.Buffer, "le", 8),
584
+ amount_per_period: data.amountPerPeriod.toArrayLike(buffer.Buffer, "le", 8),
585
+ cliff: data.cliff.toArrayLike(buffer.Buffer, "le", 8),
586
+ cliff_amount: data.cliffAmount.toArrayLike(buffer.Buffer, "le", 8),
587
+ cancelable_by_sender: Number(data.cancelableBySender),
588
+ cancelable_by_recipient: Number(data.cancelableByRecipient),
589
+ automatic_withdrawal: Number(data.automaticWithdrawal),
590
+ transferable_by_sender: Number(data.transferableBySender),
591
+ transferable_by_recipient: Number(data.transferableByRecipient),
592
+ can_topup: Number(data.canTopup),
593
+ _pausable_discriminator: 1,
594
+ can_update_rate: Number(data.canUpdateRate),
595
+ _can_update_rate_discriminator: 1,
596
+ pausable: Number(data.canPause),
597
+ stream_name: streamNameBuffer,
598
+ withdraw_frequency: data.withdrawFrequency.toArrayLike(buffer.Buffer, "le", 8)
599
+ };
600
+ const encodeLength = createStreamLayout.encode(decodedData, bufferData);
601
+ bufferData = bufferData.slice(0, encodeLength);
602
+ bufferData = buffer.Buffer.concat([
603
+ buffer.Buffer.from(await sha256.digest("global:create")).slice(0, 8),
604
+ bufferData,
605
+ buffer.Buffer.alloc(10)
606
+ ]);
607
+ return new web3_js.TransactionInstruction({
608
+ keys,
609
+ programId,
610
+ data: bufferData
611
+ });
612
+ };
613
+ var createUncheckedStreamInstruction = async (data, programId, accounts) => {
614
+ const keys = [
615
+ { pubkey: accounts.sender, isSigner: true, isWritable: true },
616
+ { pubkey: accounts.senderTokens, isSigner: false, isWritable: true },
617
+ { pubkey: accounts.metadata, isSigner: false, isWritable: true },
618
+ { pubkey: accounts.escrowTokens, isSigner: false, isWritable: true },
619
+ { pubkey: accounts.withdrawor, isSigner: false, isWritable: true },
620
+ { pubkey: accounts.mint, isSigner: false, isWritable: false },
621
+ { pubkey: accounts.feeOracle, isSigner: false, isWritable: false },
622
+ { pubkey: accounts.rent, isSigner: false, isWritable: false },
623
+ { pubkey: accounts.timelockProgram, isSigner: false, isWritable: false },
624
+ { pubkey: accounts.tokenProgram, isSigner: false, isWritable: false },
625
+ { pubkey: accounts.systemProgram, isSigner: false, isWritable: false }
626
+ ];
627
+ if (accounts.payer) {
628
+ keys.unshift({
629
+ pubkey: accounts.payer,
630
+ isSigner: true,
631
+ isWritable: true
632
+ });
633
+ }
634
+ let bufferData = buffer.Buffer.alloc(createUncheckedStreamLayout.span);
635
+ const encodedUIntArray = new TextEncoder().encode(data.name);
636
+ const streamNameBuffer = buffer.Buffer.alloc(64).fill(encodedUIntArray, 0, encodedUIntArray.byteLength);
637
+ const decodedData = {
638
+ start_time: data.start.toArrayLike(buffer.Buffer, "le", 8),
639
+ net_amount_deposited: data.depositedAmount.toArrayLike(buffer.Buffer, "le", 8),
640
+ period: data.period.toArrayLike(buffer.Buffer, "le", 8),
641
+ amount_per_period: data.amountPerPeriod.toArrayLike(buffer.Buffer, "le", 8),
642
+ cliff: data.cliff.toArrayLike(buffer.Buffer, "le", 8),
643
+ cliff_amount: data.cliffAmount.toArrayLike(buffer.Buffer, "le", 8),
644
+ cancelable_by_sender: Number(data.cancelableBySender),
645
+ cancelable_by_recipient: Number(data.cancelableByRecipient),
646
+ automatic_withdrawal: Number(data.automaticWithdrawal),
647
+ transferable_by_sender: Number(data.transferableBySender),
648
+ transferable_by_recipient: Number(data.transferableByRecipient),
649
+ can_topup: Number(data.canTopup),
650
+ stream_name: streamNameBuffer,
651
+ withdraw_frequency: data.withdrawFrequency.toArrayLike(buffer.Buffer, "le", 8),
652
+ recipient: data.recipient.toBuffer(),
653
+ partner: data.partner.toBuffer(),
654
+ pausable: Number(data.canPause),
655
+ can_update_rate: Number(data.canUpdateRate)
656
+ };
657
+ const encodeLength = createUncheckedStreamLayout.encode(decodedData, bufferData);
658
+ bufferData = bufferData.slice(0, encodeLength);
659
+ const digest = accounts.payer ? await sha256.digest("global:create_unchecked_with_payer") : await sha256.digest("global:create_unchecked");
660
+ bufferData = buffer.Buffer.concat([buffer.Buffer.from(digest).slice(0, 8), bufferData, buffer.Buffer.alloc(10)]);
661
+ return new web3_js.TransactionInstruction({
662
+ keys,
663
+ programId,
664
+ data: bufferData
665
+ });
666
+ };
667
+ var withdrawStreamInstruction = async (amount, programId, {
668
+ authority,
669
+ recipient,
670
+ recipientTokens,
671
+ metadata,
672
+ escrowTokens,
673
+ streamflowTreasury,
674
+ streamflowTreasuryTokens,
675
+ partner,
676
+ partnerTokens,
677
+ mint,
678
+ tokenProgram
679
+ }) => {
680
+ const keys = [
681
+ { pubkey: authority, isSigner: true, isWritable: true },
682
+ { pubkey: recipient, isSigner: false, isWritable: true },
683
+ { pubkey: recipientTokens, isSigner: false, isWritable: true },
684
+ { pubkey: metadata, isSigner: false, isWritable: true },
685
+ { pubkey: escrowTokens, isSigner: false, isWritable: true },
686
+ {
687
+ pubkey: streamflowTreasury,
688
+ isSigner: false,
689
+ isWritable: true
690
+ },
691
+ { pubkey: streamflowTreasuryTokens, isSigner: false, isWritable: true },
692
+ { pubkey: partner, isSigner: false, isWritable: true },
693
+ { pubkey: partnerTokens, isSigner: false, isWritable: true },
694
+ { pubkey: mint, isSigner: false, isWritable: true },
695
+ { pubkey: tokenProgram, isSigner: false, isWritable: false }
696
+ ];
697
+ let data = buffer.Buffer.alloc(withdrawStreamLayout.span);
698
+ const decodedData = { amount: amount.toArrayLike(buffer.Buffer, "le", 8) };
699
+ const encodeLength = withdrawStreamLayout.encode(decodedData, data);
700
+ data = data.slice(0, encodeLength);
701
+ data = buffer.Buffer.concat([buffer.Buffer.from(await sha256.digest("global:withdraw")).slice(0, 8), data, buffer.Buffer.alloc(10)]);
702
+ return new web3_js.TransactionInstruction({
703
+ keys,
704
+ programId,
705
+ data
706
+ });
707
+ };
708
+ var updateStreamInstruction = async (params, programId, { authority, metadata, withdrawor, systemProgram }) => {
709
+ const keys = [
710
+ { pubkey: authority, isSigner: true, isWritable: true },
711
+ { pubkey: metadata, isSigner: false, isWritable: true },
712
+ { pubkey: withdrawor, isSigner: false, isWritable: true },
713
+ { pubkey: systemProgram, isSigner: false, isWritable: false }
714
+ ];
715
+ let data = buffer.Buffer.alloc(100);
716
+ const decodedData = {
717
+ enable_automatic_withdrawal: Number(params.enableAutomaticWithdrawal),
718
+ withdraw_frequency: params.withdrawFrequency ? params.withdrawFrequency.toArrayLike(buffer.Buffer, "le", 8) : void 0,
719
+ amount_per_period: params.amountPerPeriod ? params.amountPerPeriod.toArrayLike(buffer.Buffer, "le", 8) : void 0
720
+ };
721
+ const encodeLength = encodeUpdateStream(decodedData, data);
722
+ data = data.slice(0, encodeLength);
723
+ data = buffer.Buffer.concat([buffer.Buffer.from(await sha256.digest("global:update")).slice(0, 8), data, buffer.Buffer.alloc(20)]);
724
+ return new web3_js.TransactionInstruction({
725
+ keys,
726
+ programId,
727
+ data
728
+ });
729
+ };
730
+ var cancelStreamInstruction = async (programId, {
731
+ authority,
732
+ sender,
733
+ senderTokens,
734
+ recipient,
735
+ recipientTokens,
736
+ metadata,
737
+ escrowTokens,
738
+ streamflowTreasury,
739
+ streamflowTreasuryTokens,
740
+ partner,
741
+ partnerTokens,
742
+ mint,
743
+ tokenProgram
744
+ }) => {
745
+ const keys = [
746
+ { pubkey: authority, isSigner: true, isWritable: false },
747
+ { pubkey: sender, isSigner: false, isWritable: true },
748
+ { pubkey: senderTokens, isSigner: false, isWritable: true },
749
+ { pubkey: recipient, isSigner: false, isWritable: true },
750
+ { pubkey: recipientTokens, isSigner: false, isWritable: true },
751
+ { pubkey: metadata, isSigner: false, isWritable: true },
752
+ { pubkey: escrowTokens, isSigner: false, isWritable: true },
753
+ {
754
+ pubkey: streamflowTreasury,
755
+ isSigner: false,
756
+ isWritable: true
757
+ },
758
+ { pubkey: streamflowTreasuryTokens, isSigner: false, isWritable: true },
759
+ { pubkey: partner, isSigner: false, isWritable: true },
760
+ { pubkey: partnerTokens, isSigner: false, isWritable: true },
761
+ { pubkey: mint, isSigner: false, isWritable: true },
762
+ { pubkey: tokenProgram, isSigner: false, isWritable: false }
763
+ ];
764
+ const data = buffer.Buffer.concat([buffer.Buffer.from(await sha256.digest("global:cancel")).slice(0, 8), buffer.Buffer.alloc(10)]);
765
+ return new web3_js.TransactionInstruction({
766
+ keys,
767
+ programId,
768
+ data
769
+ });
770
+ };
771
+ var transferStreamInstruction = async (programId, {
772
+ authority,
773
+ newRecipient,
774
+ newRecipientTokens,
775
+ metadata,
776
+ mint,
777
+ rent,
778
+ tokenProgram,
779
+ associatedTokenProgram,
780
+ systemProgram
781
+ }) => {
782
+ const keys = [
783
+ { pubkey: authority, isSigner: true, isWritable: true },
784
+ { pubkey: newRecipient, isSigner: false, isWritable: true },
785
+ { pubkey: newRecipientTokens, isSigner: false, isWritable: true },
786
+ { pubkey: metadata, isSigner: false, isWritable: true },
787
+ { pubkey: mint, isSigner: false, isWritable: false },
788
+ { pubkey: rent, isSigner: false, isWritable: false },
789
+ { pubkey: tokenProgram, isSigner: false, isWritable: false },
790
+ { pubkey: associatedTokenProgram, isSigner: false, isWritable: false },
791
+ { pubkey: systemProgram, isSigner: false, isWritable: false }
792
+ ];
793
+ const data = buffer.Buffer.concat([
794
+ buffer.Buffer.from(await sha256.digest("global:transfer_recipient")).slice(0, 8),
795
+ buffer.Buffer.alloc(10)
796
+ ]);
797
+ return new web3_js.TransactionInstruction({
798
+ keys,
799
+ programId,
800
+ data
801
+ });
802
+ };
803
+ var topupStreamInstruction = async (amount, programId, {
804
+ sender,
805
+ senderTokens,
806
+ metadata,
807
+ escrowTokens,
808
+ streamflowTreasury,
809
+ streamflowTreasuryTokens,
810
+ partner,
811
+ partnerTokens,
812
+ mint,
813
+ tokenProgram,
814
+ withdrawor,
815
+ systemProgram
816
+ }) => {
817
+ const keys = [
818
+ { pubkey: sender, isSigner: true, isWritable: true },
819
+ { pubkey: senderTokens, isSigner: false, isWritable: true },
820
+ { pubkey: metadata, isSigner: false, isWritable: true },
821
+ { pubkey: escrowTokens, isSigner: false, isWritable: true },
822
+ {
823
+ pubkey: streamflowTreasury,
824
+ isSigner: false,
825
+ isWritable: true
826
+ },
827
+ { pubkey: streamflowTreasuryTokens, isSigner: false, isWritable: true },
828
+ { pubkey: withdrawor, isSigner: false, isWritable: true },
829
+ { pubkey: partner, isSigner: false, isWritable: true },
830
+ { pubkey: partnerTokens, isSigner: false, isWritable: true },
831
+ { pubkey: mint, isSigner: false, isWritable: false },
832
+ { pubkey: tokenProgram, isSigner: false, isWritable: false },
833
+ { pubkey: systemProgram, isSigner: false, isWritable: false }
834
+ ];
835
+ let data = buffer.Buffer.alloc(topupStreamLayout.span);
836
+ const decodedData = { amount: amount.toArrayLike(buffer.Buffer, "le", 8) };
837
+ const encodeLength = topupStreamLayout.encode(decodedData, data);
838
+ data = data.slice(0, encodeLength);
839
+ data = buffer.Buffer.concat([buffer.Buffer.from(await sha256.digest("global:topup")).slice(0, 8), data, buffer.Buffer.alloc(10)]);
840
+ return new web3_js.TransactionInstruction({
841
+ keys,
842
+ programId,
843
+ data
844
+ });
845
+ };
846
+
847
+ // common/BaseStreamClient.ts
848
+ var BaseStreamClient = class {
849
+ /**
850
+ * Returns total fee percent, streamflow fees + partner fees
851
+ * @param getFeesData structure with address for which we need to derive fee, either sender or partner usually
852
+ * @param chainSpecificParams additional parameters required by chain client
853
+ * @returns fee as floating number, so if fee is 0.99%, it will return 0.99
854
+ */
855
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
856
+ async getTotalFee(getFeesData, chainSpecificParams) {
857
+ const fees = await this.getFees(getFeesData, chainSpecificParams);
858
+ if (fees) {
859
+ return fees.partnerFee + fees.streamflowFee;
860
+ }
861
+ return this.getDefaultStreamflowFee(chainSpecificParams);
862
+ }
863
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
864
+ extractErrorCode(err) {
865
+ return null;
866
+ }
867
+ };
868
+
869
+ // solana/descriptor/idl/streamflow_aligned_unlocks.json
870
+ var streamflow_aligned_unlocks_default = {
871
+ address: "aSTRM2NKoKxNnkmLWk9sz3k74gKBk9t7bpPrTGxMszH",
872
+ metadata: {
873
+ name: "streamflow_aligned_unlocks",
874
+ version: "1.1.1",
875
+ spec: "0.1.0",
876
+ description: "Proxy to update unlock amount within Streamflow vesting protocol according to Token performance and other metrics"
877
+ },
878
+ instructions: [
879
+ {
880
+ name: "cancel",
881
+ discriminator: [232, 219, 223, 41, 219, 236, 220, 190],
882
+ accounts: [
883
+ {
884
+ name: "sender",
885
+ writable: true,
886
+ signer: true
887
+ },
888
+ {
889
+ name: "sender_tokens",
890
+ docs: ["Associated token account address of `sender`."],
891
+ writable: true,
892
+ pda: {
893
+ seeds: [
894
+ {
895
+ kind: "account",
896
+ path: "sender"
897
+ },
898
+ {
899
+ kind: "account",
900
+ path: "token_program"
901
+ },
902
+ {
903
+ kind: "account",
904
+ path: "mint"
905
+ }
906
+ ],
907
+ program: {
908
+ kind: "const",
909
+ value: [
910
+ 140,
911
+ 151,
912
+ 37,
913
+ 143,
914
+ 78,
915
+ 36,
916
+ 137,
917
+ 241,
918
+ 187,
919
+ 61,
920
+ 16,
921
+ 41,
922
+ 20,
923
+ 142,
924
+ 13,
925
+ 131,
926
+ 11,
927
+ 90,
928
+ 19,
929
+ 153,
930
+ 218,
931
+ 255,
932
+ 16,
933
+ 132,
934
+ 4,
935
+ 142,
936
+ 123,
937
+ 216,
938
+ 219,
939
+ 233,
940
+ 248,
941
+ 89
942
+ ]
943
+ }
944
+ }
945
+ },
946
+ {
947
+ name: "recipient",
948
+ writable: true
949
+ },
950
+ {
951
+ name: "recipient_tokens",
952
+ docs: ["CHECK; Associated token account address of `recipient`."],
953
+ writable: true,
954
+ pda: {
955
+ seeds: [
956
+ {
957
+ kind: "account",
958
+ path: "recipient"
959
+ },
960
+ {
961
+ kind: "account",
962
+ path: "token_program"
963
+ },
964
+ {
965
+ kind: "account",
966
+ path: "mint"
967
+ }
968
+ ],
969
+ program: {
970
+ kind: "const",
971
+ value: [
972
+ 140,
973
+ 151,
974
+ 37,
975
+ 143,
976
+ 78,
977
+ 36,
978
+ 137,
979
+ 241,
980
+ 187,
981
+ 61,
982
+ 16,
983
+ 41,
984
+ 20,
985
+ 142,
986
+ 13,
987
+ 131,
988
+ 11,
989
+ 90,
990
+ 19,
991
+ 153,
992
+ 218,
993
+ 255,
994
+ 16,
995
+ 132,
996
+ 4,
997
+ 142,
998
+ 123,
999
+ 216,
1000
+ 219,
1001
+ 233,
1002
+ 248,
1003
+ 89
1004
+ ]
1005
+ }
1006
+ }
1007
+ },
1008
+ {
1009
+ name: "proxy_metadata",
1010
+ docs: ["Proxy Contract"],
1011
+ writable: true,
1012
+ pda: {
1013
+ seeds: [
1014
+ {
1015
+ kind: "const",
1016
+ value: [99, 111, 110, 116, 114, 97, 99, 116]
1017
+ },
1018
+ {
1019
+ kind: "account",
1020
+ path: "stream_metadata"
1021
+ }
1022
+ ]
1023
+ }
1024
+ },
1025
+ {
1026
+ name: "proxy_tokens",
1027
+ writable: true,
1028
+ pda: {
1029
+ seeds: [
1030
+ {
1031
+ kind: "account",
1032
+ path: "proxy_metadata"
1033
+ },
1034
+ {
1035
+ kind: "account",
1036
+ path: "token_program"
1037
+ },
1038
+ {
1039
+ kind: "account",
1040
+ path: "mint"
1041
+ }
1042
+ ],
1043
+ program: {
1044
+ kind: "const",
1045
+ value: [
1046
+ 140,
1047
+ 151,
1048
+ 37,
1049
+ 143,
1050
+ 78,
1051
+ 36,
1052
+ 137,
1053
+ 241,
1054
+ 187,
1055
+ 61,
1056
+ 16,
1057
+ 41,
1058
+ 20,
1059
+ 142,
1060
+ 13,
1061
+ 131,
1062
+ 11,
1063
+ 90,
1064
+ 19,
1065
+ 153,
1066
+ 218,
1067
+ 255,
1068
+ 16,
1069
+ 132,
1070
+ 4,
1071
+ 142,
1072
+ 123,
1073
+ 216,
1074
+ 219,
1075
+ 233,
1076
+ 248,
1077
+ 89
1078
+ ]
1079
+ }
1080
+ }
1081
+ },
1082
+ {
1083
+ name: "stream_metadata",
1084
+ writable: true
1085
+ },
1086
+ {
1087
+ name: "escrow_tokens",
1088
+ writable: true
1089
+ },
1090
+ {
1091
+ name: "streamflow_treasury",
1092
+ writable: true
1093
+ },
1094
+ {
1095
+ name: "streamflow_treasury_tokens",
1096
+ writable: true,
1097
+ pda: {
1098
+ seeds: [
1099
+ {
1100
+ kind: "account",
1101
+ path: "streamflow_treasury"
1102
+ },
1103
+ {
1104
+ kind: "account",
1105
+ path: "token_program"
1106
+ },
1107
+ {
1108
+ kind: "account",
1109
+ path: "mint"
1110
+ }
1111
+ ],
1112
+ program: {
1113
+ kind: "const",
1114
+ value: [
1115
+ 140,
1116
+ 151,
1117
+ 37,
1118
+ 143,
1119
+ 78,
1120
+ 36,
1121
+ 137,
1122
+ 241,
1123
+ 187,
1124
+ 61,
1125
+ 16,
1126
+ 41,
1127
+ 20,
1128
+ 142,
1129
+ 13,
1130
+ 131,
1131
+ 11,
1132
+ 90,
1133
+ 19,
1134
+ 153,
1135
+ 218,
1136
+ 255,
1137
+ 16,
1138
+ 132,
1139
+ 4,
1140
+ 142,
1141
+ 123,
1142
+ 216,
1143
+ 219,
1144
+ 233,
1145
+ 248,
1146
+ 89
1147
+ ]
1148
+ }
1149
+ }
1150
+ },
1151
+ {
1152
+ name: "partner",
1153
+ writable: true
1154
+ },
1155
+ {
1156
+ name: "partner_tokens",
1157
+ writable: true,
1158
+ pda: {
1159
+ seeds: [
1160
+ {
1161
+ kind: "account",
1162
+ path: "partner"
1163
+ },
1164
+ {
1165
+ kind: "account",
1166
+ path: "token_program"
1167
+ },
1168
+ {
1169
+ kind: "account",
1170
+ path: "mint"
1171
+ }
1172
+ ],
1173
+ program: {
1174
+ kind: "const",
1175
+ value: [
1176
+ 140,
1177
+ 151,
1178
+ 37,
1179
+ 143,
1180
+ 78,
1181
+ 36,
1182
+ 137,
1183
+ 241,
1184
+ 187,
1185
+ 61,
1186
+ 16,
1187
+ 41,
1188
+ 20,
1189
+ 142,
1190
+ 13,
1191
+ 131,
1192
+ 11,
1193
+ 90,
1194
+ 19,
1195
+ 153,
1196
+ 218,
1197
+ 255,
1198
+ 16,
1199
+ 132,
1200
+ 4,
1201
+ 142,
1202
+ 123,
1203
+ 216,
1204
+ 219,
1205
+ 233,
1206
+ 248,
1207
+ 89
1208
+ ]
1209
+ }
1210
+ }
1211
+ },
1212
+ {
1213
+ name: "mint",
1214
+ docs: ["The SPL token mint account."],
1215
+ writable: true
1216
+ },
1217
+ {
1218
+ name: "streamflow_program",
1219
+ address: "strmRqUCoQUgGUan5YhzUZa6KqdzwX5L6FpUxfmKg5m"
1220
+ },
1221
+ {
1222
+ name: "token_program",
1223
+ docs: ["The SPL program needed in case an associated account", "for the new recipient is being created."]
1224
+ }
1225
+ ],
1226
+ args: []
1227
+ },
1228
+ {
1229
+ name: "change_oracle",
1230
+ discriminator: [177, 227, 230, 103, 13, 72, 141, 248],
1231
+ accounts: [
1232
+ {
1233
+ name: "sender",
1234
+ writable: true,
1235
+ signer: true
1236
+ },
1237
+ {
1238
+ name: "proxy_metadata",
1239
+ docs: ["Proxy Contract"],
1240
+ writable: true
1241
+ },
1242
+ {
1243
+ name: "new_price_oracle"
1244
+ }
1245
+ ],
1246
+ args: [
1247
+ {
1248
+ name: "params",
1249
+ type: {
1250
+ defined: {
1251
+ name: "ChangeOracleParams"
1252
+ }
1253
+ }
1254
+ }
1255
+ ]
1256
+ },
1257
+ {
1258
+ name: "create",
1259
+ discriminator: [24, 30, 200, 40, 5, 28, 7, 119],
1260
+ accounts: [
1261
+ {
1262
+ name: "payer",
1263
+ docs: ["Rent payer"],
1264
+ writable: true,
1265
+ signer: true
1266
+ },
1267
+ {
1268
+ name: "sender",
1269
+ writable: true,
1270
+ signer: true
1271
+ },
1272
+ {
1273
+ name: "sender_tokens",
1274
+ docs: ["Associated token account address of `payer`."],
1275
+ writable: true,
1276
+ pda: {
1277
+ seeds: [
1278
+ {
1279
+ kind: "account",
1280
+ path: "sender"
1281
+ },
1282
+ {
1283
+ kind: "account",
1284
+ path: "token_program"
1285
+ },
1286
+ {
1287
+ kind: "account",
1288
+ path: "mint"
1289
+ }
1290
+ ],
1291
+ program: {
1292
+ kind: "const",
1293
+ value: [
1294
+ 140,
1295
+ 151,
1296
+ 37,
1297
+ 143,
1298
+ 78,
1299
+ 36,
1300
+ 137,
1301
+ 241,
1302
+ 187,
1303
+ 61,
1304
+ 16,
1305
+ 41,
1306
+ 20,
1307
+ 142,
1308
+ 13,
1309
+ 131,
1310
+ 11,
1311
+ 90,
1312
+ 19,
1313
+ 153,
1314
+ 218,
1315
+ 255,
1316
+ 16,
1317
+ 132,
1318
+ 4,
1319
+ 142,
1320
+ 123,
1321
+ 216,
1322
+ 219,
1323
+ 233,
1324
+ 248,
1325
+ 89
1326
+ ]
1327
+ }
1328
+ }
1329
+ },
1330
+ {
1331
+ name: "recipient"
1332
+ },
1333
+ {
1334
+ name: "recipient_tokens",
1335
+ pda: {
1336
+ seeds: [
1337
+ {
1338
+ kind: "account",
1339
+ path: "recipient"
1340
+ },
1341
+ {
1342
+ kind: "account",
1343
+ path: "token_program"
1344
+ },
1345
+ {
1346
+ kind: "account",
1347
+ path: "mint"
1348
+ }
1349
+ ],
1350
+ program: {
1351
+ kind: "const",
1352
+ value: [
1353
+ 140,
1354
+ 151,
1355
+ 37,
1356
+ 143,
1357
+ 78,
1358
+ 36,
1359
+ 137,
1360
+ 241,
1361
+ 187,
1362
+ 61,
1363
+ 16,
1364
+ 41,
1365
+ 20,
1366
+ 142,
1367
+ 13,
1368
+ 131,
1369
+ 11,
1370
+ 90,
1371
+ 19,
1372
+ 153,
1373
+ 218,
1374
+ 255,
1375
+ 16,
1376
+ 132,
1377
+ 4,
1378
+ 142,
1379
+ 123,
1380
+ 216,
1381
+ 219,
1382
+ 233,
1383
+ 248,
1384
+ 89
1385
+ ]
1386
+ }
1387
+ }
1388
+ },
1389
+ {
1390
+ name: "proxy_metadata",
1391
+ writable: true,
1392
+ pda: {
1393
+ seeds: [
1394
+ {
1395
+ kind: "const",
1396
+ value: [99, 111, 110, 116, 114, 97, 99, 116]
1397
+ },
1398
+ {
1399
+ kind: "account",
1400
+ path: "stream_metadata"
1401
+ }
1402
+ ]
1403
+ }
1404
+ },
1405
+ {
1406
+ name: "proxy_tokens",
1407
+ writable: true,
1408
+ pda: {
1409
+ seeds: [
1410
+ {
1411
+ kind: "account",
1412
+ path: "proxy_metadata"
1413
+ },
1414
+ {
1415
+ kind: "account",
1416
+ path: "token_program"
1417
+ },
1418
+ {
1419
+ kind: "account",
1420
+ path: "mint"
1421
+ }
1422
+ ],
1423
+ program: {
1424
+ kind: "const",
1425
+ value: [
1426
+ 140,
1427
+ 151,
1428
+ 37,
1429
+ 143,
1430
+ 78,
1431
+ 36,
1432
+ 137,
1433
+ 241,
1434
+ 187,
1435
+ 61,
1436
+ 16,
1437
+ 41,
1438
+ 20,
1439
+ 142,
1440
+ 13,
1441
+ 131,
1442
+ 11,
1443
+ 90,
1444
+ 19,
1445
+ 153,
1446
+ 218,
1447
+ 255,
1448
+ 16,
1449
+ 132,
1450
+ 4,
1451
+ 142,
1452
+ 123,
1453
+ 216,
1454
+ 219,
1455
+ 233,
1456
+ 248,
1457
+ 89
1458
+ ]
1459
+ }
1460
+ }
1461
+ },
1462
+ {
1463
+ name: "stream_metadata",
1464
+ writable: true,
1465
+ signer: true
1466
+ },
1467
+ {
1468
+ name: "escrow_tokens",
1469
+ writable: true
1470
+ },
1471
+ {
1472
+ name: "withdrawor",
1473
+ writable: true
1474
+ },
1475
+ {
1476
+ name: "partner"
1477
+ },
1478
+ {
1479
+ name: "mint"
1480
+ },
1481
+ {
1482
+ name: "fee_oracle"
1483
+ },
1484
+ {
1485
+ name: "price_oracle"
1486
+ },
1487
+ {
1488
+ name: "rent",
1489
+ address: "SysvarRent111111111111111111111111111111111"
1490
+ },
1491
+ {
1492
+ name: "streamflow_program",
1493
+ address: "strmRqUCoQUgGUan5YhzUZa6KqdzwX5L6FpUxfmKg5m"
1494
+ },
1495
+ {
1496
+ name: "token_program"
1497
+ },
1498
+ {
1499
+ name: "associated_token_program",
1500
+ address: "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
1501
+ },
1502
+ {
1503
+ name: "system_program",
1504
+ address: "11111111111111111111111111111111"
1505
+ }
1506
+ ],
1507
+ args: [
1508
+ {
1509
+ name: "ix",
1510
+ type: {
1511
+ defined: {
1512
+ name: "CreateParams"
1513
+ }
1514
+ }
1515
+ }
1516
+ ]
1517
+ },
1518
+ {
1519
+ name: "create_test_oracle",
1520
+ discriminator: [183, 110, 4, 11, 131, 220, 84, 12],
1521
+ accounts: [
1522
+ {
1523
+ name: "creator",
1524
+ writable: true,
1525
+ signer: true
1526
+ },
1527
+ {
1528
+ name: "mint"
1529
+ },
1530
+ {
1531
+ name: "test_oracle",
1532
+ writable: true,
1533
+ pda: {
1534
+ seeds: [
1535
+ {
1536
+ kind: "const",
1537
+ value: [116, 101, 115, 116, 45, 111, 114, 97, 99, 108, 101]
1538
+ },
1539
+ {
1540
+ kind: "account",
1541
+ path: "mint"
1542
+ },
1543
+ {
1544
+ kind: "account",
1545
+ path: "creator"
1546
+ }
1547
+ ]
1548
+ }
1549
+ },
1550
+ {
1551
+ name: "system_program",
1552
+ address: "11111111111111111111111111111111"
1553
+ }
1554
+ ],
1555
+ args: [
1556
+ {
1557
+ name: "params",
1558
+ type: {
1559
+ defined: {
1560
+ name: "CreateTestOracleParams"
1561
+ }
1562
+ }
1563
+ }
1564
+ ]
1565
+ },
1566
+ {
1567
+ name: "set_test_oracle_authority",
1568
+ discriminator: [26, 66, 233, 99, 38, 118, 181, 247],
1569
+ accounts: [
1570
+ {
1571
+ name: "authority",
1572
+ writable: true,
1573
+ signer: true
1574
+ },
1575
+ {
1576
+ name: "test_oracle",
1577
+ writable: true
1578
+ },
1579
+ {
1580
+ name: "new_authority"
1581
+ }
1582
+ ],
1583
+ args: []
1584
+ },
1585
+ {
1586
+ name: "update_amount",
1587
+ discriminator: [212, 178, 69, 133, 251, 180, 212, 71],
1588
+ accounts: [
1589
+ {
1590
+ name: "authority",
1591
+ docs: ["Wallet authorised to call this method"],
1592
+ writable: true,
1593
+ signer: true
1594
+ },
1595
+ {
1596
+ name: "proxy_metadata",
1597
+ writable: true,
1598
+ pda: {
1599
+ seeds: [
1600
+ {
1601
+ kind: "const",
1602
+ value: [99, 111, 110, 116, 114, 97, 99, 116]
1603
+ },
1604
+ {
1605
+ kind: "account",
1606
+ path: "stream_metadata"
1607
+ }
1608
+ ]
1609
+ }
1610
+ },
1611
+ {
1612
+ name: "stream_metadata",
1613
+ writable: true
1614
+ },
1615
+ {
1616
+ name: "withdrawor",
1617
+ writable: true
1618
+ },
1619
+ {
1620
+ name: "price_oracle",
1621
+ relations: ["proxy_metadata"]
1622
+ },
1623
+ {
1624
+ name: "streamflow_program",
1625
+ address: "strmRqUCoQUgGUan5YhzUZa6KqdzwX5L6FpUxfmKg5m"
1626
+ },
1627
+ {
1628
+ name: "system_program",
1629
+ address: "11111111111111111111111111111111"
1630
+ }
1631
+ ],
1632
+ args: []
1633
+ },
1634
+ {
1635
+ name: "update_test_oracle",
1636
+ discriminator: [158, 147, 215, 74, 34, 123, 80, 76],
1637
+ accounts: [
1638
+ {
1639
+ name: "authority",
1640
+ writable: true,
1641
+ signer: true
1642
+ },
1643
+ {
1644
+ name: "test_oracle",
1645
+ writable: true
1646
+ }
1647
+ ],
1648
+ args: [
1649
+ {
1650
+ name: "params",
1651
+ type: {
1652
+ defined: {
1653
+ name: "UpdateTestOracleParams"
1654
+ }
1655
+ }
1656
+ }
1657
+ ]
1658
+ }
1659
+ ],
1660
+ accounts: [
1661
+ {
1662
+ name: "Contract",
1663
+ discriminator: [172, 138, 115, 242, 121, 67, 183, 26]
1664
+ },
1665
+ {
1666
+ name: "TestOracle",
1667
+ discriminator: [198, 49, 63, 134, 232, 251, 168, 28]
1668
+ }
1669
+ ],
1670
+ errors: [
1671
+ {
1672
+ code: 6e3,
1673
+ name: "Unauthorized",
1674
+ msg: "Authority does not have permission for this action"
1675
+ },
1676
+ {
1677
+ code: 6001,
1678
+ name: "ArithmeticError",
1679
+ msg: "Arithmetic error"
1680
+ },
1681
+ {
1682
+ code: 6002,
1683
+ name: "UnsupportedTokenExtensions",
1684
+ msg: "Mint has unsupported Token Extensions"
1685
+ },
1686
+ {
1687
+ code: 6003,
1688
+ name: "PeriodTooShort",
1689
+ msg: "Provided period is too short, should be equal or more than 30 seconds"
1690
+ },
1691
+ {
1692
+ code: 6004,
1693
+ name: "InvalidTickSize",
1694
+ msg: "Provided percentage tick size is invalid"
1695
+ },
1696
+ {
1697
+ code: 6005,
1698
+ name: "InvalidPercentageBoundaries",
1699
+ msg: "Provided percentage bounds are invalid"
1700
+ },
1701
+ {
1702
+ code: 6006,
1703
+ name: "InvalidPriceBoundaries",
1704
+ msg: "Provided price bounds are invalid"
1705
+ },
1706
+ {
1707
+ code: 6007,
1708
+ name: "UnsupportedOracle",
1709
+ msg: "Unsupported price oracle"
1710
+ },
1711
+ {
1712
+ code: 6008,
1713
+ name: "InvalidOracleAccount",
1714
+ msg: "Invalid oracle account"
1715
+ },
1716
+ {
1717
+ code: 6009,
1718
+ name: "InvalidOraclePrice",
1719
+ msg: "Invalid oracle price"
1720
+ },
1721
+ {
1722
+ code: 6010,
1723
+ name: "InvalidStreamMetadata",
1724
+ msg: "Invalid Stream Metadata"
1725
+ },
1726
+ {
1727
+ code: 6011,
1728
+ name: "AmountAlreadyUpdated",
1729
+ msg: "Release amount has already been updated in this period"
1730
+ },
1731
+ {
1732
+ code: 6012,
1733
+ name: "AllFundsUnlocked",
1734
+ msg: "All funds are already unlocked"
1735
+ }
1736
+ ],
1737
+ types: [
1738
+ {
1739
+ name: "ChangeOracleParams",
1740
+ type: {
1741
+ kind: "struct",
1742
+ fields: [
1743
+ {
1744
+ name: "oracle_type",
1745
+ type: {
1746
+ defined: {
1747
+ name: "OracleType"
1748
+ }
1749
+ }
1750
+ }
1751
+ ]
1752
+ }
1753
+ },
1754
+ {
1755
+ name: "Contract",
1756
+ type: {
1757
+ kind: "struct",
1758
+ fields: [
1759
+ {
1760
+ name: "bump",
1761
+ docs: ["Bump Seed used to sign transactions"],
1762
+ type: "u8"
1763
+ },
1764
+ {
1765
+ name: "sender",
1766
+ docs: ["Original Contract sender"],
1767
+ type: "pubkey"
1768
+ },
1769
+ {
1770
+ name: "sender_tokens",
1771
+ docs: ["Original Contract sender tokens address"],
1772
+ type: "pubkey"
1773
+ },
1774
+ {
1775
+ name: "stream",
1776
+ docs: ["Vesting Stream address"],
1777
+ type: "pubkey"
1778
+ },
1779
+ {
1780
+ name: "price_oracle_type",
1781
+ docs: ["Type of the Oracle used to derive Token Price"],
1782
+ type: {
1783
+ defined: {
1784
+ name: "OracleType"
1785
+ }
1786
+ }
1787
+ },
1788
+ {
1789
+ name: "price_oracle",
1790
+ docs: ["Address of the Price Oracle"],
1791
+ type: "pubkey"
1792
+ },
1793
+ {
1794
+ name: "min_price",
1795
+ docs: ["Min price boundary"],
1796
+ type: "u64"
1797
+ },
1798
+ {
1799
+ name: "max_price",
1800
+ docs: ["Max price boundary"],
1801
+ type: "u64"
1802
+ },
1803
+ {
1804
+ name: "min_percentage",
1805
+ docs: ["Min percentage boundary, can be 0 that equals 1 Raw Token"],
1806
+ type: "u64"
1807
+ },
1808
+ {
1809
+ name: "max_percentage",
1810
+ docs: ["Max percentage boundary"],
1811
+ type: "u64"
1812
+ },
1813
+ {
1814
+ name: "tick_size",
1815
+ docs: ["Ticket size for percentage boundaries"],
1816
+ type: "u64"
1817
+ },
1818
+ {
1819
+ name: "start_time",
1820
+ docs: [
1821
+ "unlock_start from Stream contract for our worker to be able to fetch it in one call with the proxy contract"
1822
+ ],
1823
+ type: "u64"
1824
+ },
1825
+ {
1826
+ name: "end_time",
1827
+ docs: [
1828
+ "Copy end_time from Stream contract for our worker to be able to fetch it in one call with the proxy contract"
1829
+ ],
1830
+ type: "u64"
1831
+ },
1832
+ {
1833
+ name: "period",
1834
+ docs: [
1835
+ "Copy period from Stream contract for our worker to be able to fetch it in one call with the proxy contract"
1836
+ ],
1837
+ type: "u64"
1838
+ },
1839
+ {
1840
+ name: "last_amount_update_time",
1841
+ docs: [
1842
+ "Copy last_rate_change_time from Stream contract for our worker to be able to fetch it in one call with the proxy contract"
1843
+ ],
1844
+ type: "u64"
1845
+ },
1846
+ {
1847
+ name: "last_price",
1848
+ docs: ["Price used on last amount calculation"],
1849
+ type: "u64"
1850
+ },
1851
+ {
1852
+ name: "stream_canceled_time",
1853
+ docs: ["Timestamp when stream was cancelled"],
1854
+ type: "u64"
1855
+ },
1856
+ {
1857
+ name: "initial_amount_per_period",
1858
+ docs: ["Amount per period to use as base for calculations"],
1859
+ type: "u64"
1860
+ },
1861
+ {
1862
+ name: "initial_price",
1863
+ docs: ["Initial token price at the time of Contract creation"],
1864
+ type: "u64"
1865
+ },
1866
+ {
1867
+ name: "initial_net_amount",
1868
+ docs: ["Initial deposited amount"],
1869
+ type: "u64"
1870
+ },
1871
+ {
1872
+ name: "mint",
1873
+ docs: ["Mint for which the contract was created"],
1874
+ type: "pubkey"
1875
+ },
1876
+ {
1877
+ name: "buffer",
1878
+ docs: ["Buffer for additional fields"],
1879
+ type: {
1880
+ array: ["u8", 32]
1881
+ }
1882
+ }
1883
+ ]
1884
+ }
1885
+ },
1886
+ {
1887
+ name: "CreateParams",
1888
+ type: {
1889
+ kind: "struct",
1890
+ fields: [
1891
+ {
1892
+ name: "start_time",
1893
+ docs: ["Timestamp when the tokens start vesting"],
1894
+ type: "u64"
1895
+ },
1896
+ {
1897
+ name: "net_amount_deposited",
1898
+ docs: ["Deposited amount of tokens"],
1899
+ type: "u64"
1900
+ },
1901
+ {
1902
+ name: "period",
1903
+ docs: ["Time step (period) in seconds per which the vesting/release occurs"],
1904
+ type: "u64"
1905
+ },
1906
+ {
1907
+ name: "amount_per_period",
1908
+ docs: ["Base Amount released per period. Combined with `period`, we get a release rate."],
1909
+ type: "u64"
1910
+ },
1911
+ {
1912
+ name: "cliff",
1913
+ docs: ['Vesting contract "cliff" timestamp'],
1914
+ type: "u64"
1915
+ },
1916
+ {
1917
+ name: "cliff_amount",
1918
+ docs: ['Amount unlocked at the "cliff" timestamp'],
1919
+ type: "u64"
1920
+ },
1921
+ {
1922
+ name: "cancelable_by_sender",
1923
+ docs: ["Whether a stream can be canceled by a sender"],
1924
+ type: "bool"
1925
+ },
1926
+ {
1927
+ name: "cancelable_by_recipient",
1928
+ docs: ["Whether a stream can be canceled by a recipient"],
1929
+ type: "bool"
1930
+ },
1931
+ {
1932
+ name: "transferable_by_sender",
1933
+ docs: ["Whether the sender can transfer the stream"],
1934
+ type: "bool"
1935
+ },
1936
+ {
1937
+ name: "transferable_by_recipient",
1938
+ docs: ["Whether the recipient can transfer the stream"],
1939
+ type: "bool"
1940
+ },
1941
+ {
1942
+ name: "can_topup",
1943
+ docs: ["Whether topup is enabled"],
1944
+ type: "bool"
1945
+ },
1946
+ {
1947
+ name: "stream_name",
1948
+ docs: ["The name of this stream"],
1949
+ type: {
1950
+ array: ["u8", 64]
1951
+ }
1952
+ },
1953
+ {
1954
+ name: "min_price",
1955
+ type: "u64"
1956
+ },
1957
+ {
1958
+ name: "max_price",
1959
+ type: "u64"
1960
+ },
1961
+ {
1962
+ name: "min_percentage",
1963
+ type: "u64"
1964
+ },
1965
+ {
1966
+ name: "max_percentage",
1967
+ type: "u64"
1968
+ },
1969
+ {
1970
+ name: "tick_size",
1971
+ type: "u64"
1972
+ },
1973
+ {
1974
+ name: "skip_initial",
1975
+ docs: ["Whether to skip initial calculation of amount per period"],
1976
+ type: "bool"
1977
+ },
1978
+ {
1979
+ name: "oracle_type",
1980
+ docs: ["Type of Oracle to use to derive Token Price"],
1981
+ type: {
1982
+ defined: {
1983
+ name: "OracleType"
1984
+ }
1985
+ }
1986
+ }
1987
+ ]
1988
+ }
1989
+ },
1990
+ {
1991
+ name: "CreateTestOracleParams",
1992
+ type: {
1993
+ kind: "struct",
1994
+ fields: [
1995
+ {
1996
+ name: "price",
1997
+ type: "u64"
1998
+ },
1999
+ {
2000
+ name: "expo",
2001
+ type: "i32"
2002
+ },
2003
+ {
2004
+ name: "conf",
2005
+ type: "u64"
2006
+ },
2007
+ {
2008
+ name: "publish_time",
2009
+ type: "i64"
2010
+ }
2011
+ ]
2012
+ }
2013
+ },
2014
+ {
2015
+ name: "OracleType",
2016
+ type: {
2017
+ kind: "enum",
2018
+ variants: [
2019
+ {
2020
+ name: "None"
2021
+ },
2022
+ {
2023
+ name: "Test"
2024
+ },
2025
+ {
2026
+ name: "Pyth"
2027
+ },
2028
+ {
2029
+ name: "Switchboard"
2030
+ }
2031
+ ]
2032
+ }
2033
+ },
2034
+ {
2035
+ name: "TestOracle",
2036
+ type: {
2037
+ kind: "struct",
2038
+ fields: [
2039
+ {
2040
+ name: "price",
2041
+ type: "u64"
2042
+ },
2043
+ {
2044
+ name: "expo",
2045
+ type: "i32"
2046
+ },
2047
+ {
2048
+ name: "conf",
2049
+ type: "u64"
2050
+ },
2051
+ {
2052
+ name: "publish_time",
2053
+ type: "i64"
2054
+ },
2055
+ {
2056
+ name: "creator",
2057
+ type: "pubkey"
2058
+ },
2059
+ {
2060
+ name: "authority",
2061
+ type: "pubkey"
2062
+ },
2063
+ {
2064
+ name: "mint",
2065
+ type: "pubkey"
2066
+ }
2067
+ ]
2068
+ }
2069
+ },
2070
+ {
2071
+ name: "UpdateTestOracleParams",
2072
+ type: {
2073
+ kind: "struct",
2074
+ fields: [
2075
+ {
2076
+ name: "price",
2077
+ type: "u64"
2078
+ },
2079
+ {
2080
+ name: "expo",
2081
+ type: "i32"
2082
+ },
2083
+ {
2084
+ name: "conf",
2085
+ type: "u64"
2086
+ },
2087
+ {
2088
+ name: "publish_time",
2089
+ type: "i64"
2090
+ }
2091
+ ]
2092
+ }
2093
+ }
2094
+ ]
2095
+ };
2096
+ var deriveContractPDA = (programId, streamMetadata) => {
2097
+ return web3_js.PublicKey.findProgramAddressSync([CONTRACT_SEED, streamMetadata.toBuffer()], programId)[0];
2098
+ };
2099
+ var deriveEscrowPDA = (programId, streamMetadata) => {
2100
+ return web3_js.PublicKey.findProgramAddressSync([ESCROW_SEED, streamMetadata.toBuffer()], programId)[0];
2101
+ };
2102
+ var deriveTestOraclePDA = (programId, mint, creator) => {
2103
+ return web3_js.PublicKey.findProgramAddressSync([TEST_ORACLE_SEED, mint.toBuffer(), creator.toBuffer()], programId)[0];
2104
+ };
2105
+
2106
+ // solana/StreamClient.ts
2107
+ var METADATA_ACC_SIZE = 1104;
2108
+ var ALIGNED_METADATA_ACC_SIZE = 320;
2109
+ var SolanaStreamClient = class extends BaseStreamClient {
2110
+ /**
2111
+ * Create Stream instance
2112
+ */
2113
+ constructor(optionsOrClusterUrl, cluster = common.ICluster.Mainnet, commitment = "confirmed", programId = "", sendRate = 1, sendThrottler) {
2114
+ super();
2115
+ if (typeof optionsOrClusterUrl === "string") {
2116
+ this.commitment = commitment;
2117
+ this.connection = new web3_js.Connection(optionsOrClusterUrl, this.commitment);
2118
+ this.programId = programId !== "" ? new web3_js.PublicKey(programId) : new web3_js.PublicKey(PROGRAM_ID[cluster]);
2119
+ this.schedulingParams = {
2120
+ sendThrottler: sendThrottler ?? solana.buildSendThrottler(sendRate)
2121
+ };
2122
+ } else {
2123
+ const {
2124
+ clusterUrl,
2125
+ cluster: cluster2 = common.ICluster.Mainnet,
2126
+ commitment: commitment2 = "confirmed",
2127
+ programId: programId2 = "",
2128
+ sendScheduler
2129
+ } = optionsOrClusterUrl;
2130
+ this.commitment = commitment2;
2131
+ this.connection = new web3_js.Connection(clusterUrl, this.commitment);
2132
+ this.programId = programId2 !== "" ? new web3_js.PublicKey(programId2) : new web3_js.PublicKey(PROGRAM_ID[cluster2]);
2133
+ const schedulingOptions = sendScheduler && "sendRate" in sendScheduler ? sendScheduler : void 0;
2134
+ const sendThrottler2 = !sendScheduler ? solana.buildSendThrottler(1) : "sendRate" in sendScheduler ? solana.buildSendThrottler(sendScheduler.sendRate ?? 1, sendScheduler.sendInterval) : sendScheduler;
2135
+ this.schedulingParams = {
2136
+ ...schedulingOptions,
2137
+ sendThrottler: sendThrottler2
2138
+ };
2139
+ }
2140
+ const alignedUnlocksProgram = {
2141
+ ...streamflow_aligned_unlocks_default,
2142
+ address: streamflow_aligned_unlocks_default.address
2143
+ };
2144
+ this.alignedProxyProgram = new anchor.Program(alignedUnlocksProgram, { connection: this.connection });
2145
+ }
2146
+ getConnection() {
2147
+ return this.connection;
2148
+ }
2149
+ getCommitment() {
2150
+ return typeof this.commitment == "string" ? this.commitment : this.commitment.commitment;
2151
+ }
2152
+ getProgramId() {
2153
+ return this.programId.toBase58();
2154
+ }
2155
+ /**
2156
+ * Creates a new stream/vesting contract.
2157
+ * All fees are paid by sender (escrow metadata account rent, escrow token account rent, recipient's associated token account rent, Streamflow's service fee).
2158
+ */
2159
+ async create(data, extParams) {
2160
+ const { partner, amount, tokenProgramId } = data;
2161
+ const { isNative, sender, customInstructions } = extParams;
2162
+ const partnerPublicKey = partner ? new web3_js.PublicKey(partner) : WITHDRAWOR_PUBLIC_KEY;
2163
+ const mintPublicKey = new web3_js.PublicKey(data.tokenId);
2164
+ if (!sender.publicKey) {
2165
+ throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
2166
+ }
2167
+ const ixs = await this.getCreateATAInstructions(
2168
+ [STREAMFLOW_TREASURY_PUBLIC_KEY, partnerPublicKey],
2169
+ mintPublicKey,
2170
+ sender,
2171
+ true,
2172
+ tokenProgramId ? new web3_js.PublicKey(tokenProgramId) : void 0
2173
+ );
2174
+ const { ixs: createIxs, metadata, metadataPubKey } = await this.prepareCreateInstructions(data, extParams);
2175
+ ixs.push(...createIxs);
2176
+ if (isNative) {
2177
+ const totalFee = await this.getTotalFee({
2178
+ address: partnerPublicKey.toString()
2179
+ });
2180
+ const totalAmount = calculateTotalAmountToDeposit(amount, totalFee);
2181
+ ixs.push(...await solana.prepareWrappedAccount(this.connection, sender.publicKey, totalAmount));
2182
+ }
2183
+ await this.applyCustomAfterInstructions(ixs, customInstructions, metadataPubKey);
2184
+ const { tx, hash, context } = await solana.prepareTransaction(this.connection, ixs, sender.publicKey, void 0, metadata);
2185
+ const signature = await solana.signAndExecuteTransaction(
2186
+ this.connection,
2187
+ extParams.sender,
2188
+ tx,
2189
+ {
2190
+ hash,
2191
+ context,
2192
+ commitment: this.getCommitment()
2193
+ },
2194
+ this.schedulingParams
2195
+ );
2196
+ return { ixs, txId: signature, metadataId: metadataPubKey.toBase58() };
2197
+ }
2198
+ async prepareCreateInstructions(streamParams, extParams) {
2199
+ const { ixs, metadata, metadataPubKey } = isCreateAlignedStreamData(streamParams) ? await this.prepareCreateAlignedUnlockInstructions(streamParams, extParams) : await this.prepareCreateStreamInstructions(streamParams, extParams);
2200
+ return { ixs, metadata, metadataPubKey };
2201
+ }
2202
+ async prepareCreateAlignedUnlockInstructions(streamParams, extParams) {
2203
+ const {
2204
+ tokenId: mint,
2205
+ start,
2206
+ period,
2207
+ cliff,
2208
+ canTopup,
2209
+ cancelableBySender,
2210
+ cancelableByRecipient,
2211
+ transferableBySender,
2212
+ transferableByRecipient,
2213
+ partner,
2214
+ recipient,
2215
+ cliffAmount,
2216
+ amountPerPeriod,
2217
+ amount: depositedAmount,
2218
+ name: streamName,
2219
+ minPrice,
2220
+ maxPercentage,
2221
+ minPercentage,
2222
+ maxPrice,
2223
+ skipInitial,
2224
+ tickSize,
2225
+ priceOracle,
2226
+ oracleType,
2227
+ tokenProgramId: streamTokenProgramId
2228
+ } = streamParams;
2229
+ const { isNative, sender, computeLimit, computePrice, metadataPubKeys } = extParams;
2230
+ if (!sender.publicKey) {
2231
+ throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
2232
+ }
2233
+ if (!priceOracle && oracleType && oracleType !== "none") {
2234
+ throw new Error("Price oracle is required for the specified oracle type");
2235
+ }
2236
+ const recipientPublicKey = new web3_js.PublicKey(recipient);
2237
+ const mintPublicKey = isNative ? splToken.NATIVE_MINT : new web3_js.PublicKey(mint);
2238
+ const metadata = !metadataPubKeys ? web3_js.Keypair.generate() : void 0;
2239
+ const metadataPubKey = metadata ? metadata.publicKey : metadataPubKeys[0];
2240
+ if (!metadataPubKey) {
2241
+ throw new Error("Metadata public key is required");
2242
+ }
2243
+ let tokenProgramId = streamTokenProgramId ? new web3_js.PublicKey(streamTokenProgramId) : void 0;
2244
+ if (!tokenProgramId) {
2245
+ tokenProgramId = (await solana.getMintAndProgram(this.connection, mintPublicKey)).tokenProgramId;
2246
+ }
2247
+ const partnerPublicKey = partner ? new web3_js.PublicKey(partner) : WITHDRAWOR_PUBLIC_KEY;
2248
+ const streamflowProgramPublicKey = new web3_js.PublicKey(this.programId);
2249
+ const escrowPDA = deriveEscrowPDA(streamflowProgramPublicKey, metadataPubKey);
2250
+ const oracle = priceOracle ?? deriveTestOraclePDA(this.alignedProxyProgram.programId, mintPublicKey, sender.publicKey);
2251
+ const ixs = solana.prepareBaseInstructions(this.connection, {
2252
+ computePrice,
2253
+ computeLimit: computeLimit ?? ALIGNED_COMPUTE_LIMIT
2254
+ });
2255
+ ixs.push(
2256
+ ...await this.getCreateATAInstructions([recipientPublicKey], mintPublicKey, sender, true, tokenProgramId)
2257
+ );
2258
+ const encodedUIntArray = new TextEncoder().encode(streamName);
2259
+ const streamNameArray = Array.from(encodedUIntArray);
2260
+ const createIx = await this.alignedProxyProgram.methods.create({
2261
+ startTime: new BN6__default.default(start),
2262
+ netAmountDeposited: depositedAmount,
2263
+ period: new BN6__default.default(period),
2264
+ amountPerPeriod,
2265
+ cliff: new BN6__default.default(cliff),
2266
+ cliffAmount,
2267
+ transferableBySender,
2268
+ transferableByRecipient,
2269
+ cancelableByRecipient,
2270
+ cancelableBySender,
2271
+ canTopup,
2272
+ oracleType: !!oracleType ? { [oracleType]: {} } : { none: {} },
2273
+ streamName: streamNameArray,
2274
+ minPrice: minPrice instanceof BN6__default.default ? minPrice : common.getBN(minPrice, ALIGNED_PRECISION_FACTOR_POW),
2275
+ maxPrice: maxPrice instanceof BN6__default.default ? maxPrice : common.getBN(maxPrice, ALIGNED_PRECISION_FACTOR_POW),
2276
+ minPercentage: minPercentage instanceof BN6__default.default ? minPercentage : common.getBN(minPercentage, ALIGNED_PRECISION_FACTOR_POW),
2277
+ maxPercentage: maxPercentage instanceof BN6__default.default ? maxPercentage : common.getBN(maxPercentage, ALIGNED_PRECISION_FACTOR_POW),
2278
+ tickSize: new BN6__default.default(tickSize || 1),
2279
+ skipInitial: skipInitial ?? false
2280
+ }).accountsPartial({
2281
+ payer: sender.publicKey,
2282
+ sender: sender.publicKey,
2283
+ streamMetadata: metadataPubKey,
2284
+ escrowTokens: escrowPDA,
2285
+ mint: mintPublicKey,
2286
+ partner: partnerPublicKey,
2287
+ recipient: recipientPublicKey,
2288
+ withdrawor: WITHDRAWOR_PUBLIC_KEY,
2289
+ feeOracle: FEE_ORACLE_PUBLIC_KEY,
2290
+ priceOracle: oracle,
2291
+ tokenProgram: tokenProgramId,
2292
+ streamflowProgram: this.programId
2293
+ }).instruction();
2294
+ ixs.push(createIx);
2295
+ return { ixs, metadata, metadataPubKey };
2296
+ }
2297
+ /**
2298
+ * Creates a new stream/vesting contract.
2299
+ * All fees are paid by sender (escrow metadata account rent, escrow token account rent, recipient's associated token account rent, Streamflow's service fee).
2300
+ */
2301
+ async prepareCreateStreamInstructions({
2302
+ recipient,
2303
+ tokenId: mint,
2304
+ start,
2305
+ amount: depositedAmount,
2306
+ period,
2307
+ cliff,
2308
+ cliffAmount,
2309
+ amountPerPeriod,
2310
+ name,
2311
+ canPause,
2312
+ canUpdateRate,
2313
+ canTopup,
2314
+ cancelableBySender,
2315
+ cancelableByRecipient,
2316
+ transferableBySender,
2317
+ transferableByRecipient,
2318
+ automaticWithdrawal = false,
2319
+ withdrawalFrequency = 0,
2320
+ partner,
2321
+ tokenProgramId: streamTokenProgramId
2322
+ }, { sender, metadataPubKeys, isNative = false, computePrice, computeLimit }) {
2323
+ if (!sender.publicKey) {
2324
+ throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
2325
+ }
2326
+ const ixs = solana.prepareBaseInstructions(this.connection, {
2327
+ computePrice,
2328
+ computeLimit
2329
+ });
2330
+ const mintPublicKey = isNative ? splToken.NATIVE_MINT : new web3_js.PublicKey(mint);
2331
+ const recipientPublicKey = new web3_js.PublicKey(recipient);
2332
+ const { metadata, metadataPubKey } = this.getOrCreateStreamMetadata(metadataPubKeys);
2333
+ const [escrowTokens] = web3_js.PublicKey.findProgramAddressSync(
2334
+ [buffer.Buffer.from("strm"), metadataPubKey.toBuffer()],
2335
+ this.programId
2336
+ );
2337
+ let tokenProgramId = streamTokenProgramId ? new web3_js.PublicKey(streamTokenProgramId) : void 0;
2338
+ if (!tokenProgramId) {
2339
+ tokenProgramId = (await solana.getMintAndProgram(this.connection, mintPublicKey)).tokenProgramId;
2340
+ }
2341
+ const senderTokens = await solana.ata(mintPublicKey, sender.publicKey, tokenProgramId);
2342
+ const recipientTokens = await solana.ata(mintPublicKey, recipientPublicKey, tokenProgramId);
2343
+ const streamflowTreasuryTokens = await solana.ata(mintPublicKey, STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
2344
+ const partnerPublicKey = partner ? new web3_js.PublicKey(partner) : WITHDRAWOR_PUBLIC_KEY;
2345
+ const partnerTokens = await solana.ata(mintPublicKey, partnerPublicKey, tokenProgramId);
2346
+ ixs.push(
2347
+ await createStreamInstruction(
2348
+ {
2349
+ start: new BN6__default.default(start),
2350
+ depositedAmount,
2351
+ period: new BN6__default.default(period),
2352
+ amountPerPeriod,
2353
+ cliff: new BN6__default.default(cliff),
2354
+ cliffAmount: new BN6__default.default(cliffAmount),
2355
+ cancelableBySender,
2356
+ cancelableByRecipient,
2357
+ automaticWithdrawal,
2358
+ transferableBySender,
2359
+ transferableByRecipient,
2360
+ canTopup,
2361
+ canUpdateRate: !!canUpdateRate,
2362
+ canPause: !!canPause,
2363
+ name,
2364
+ withdrawFrequency: new BN6__default.default(automaticWithdrawal ? withdrawalFrequency : period)
2365
+ },
2366
+ this.programId,
2367
+ {
2368
+ sender: sender.publicKey,
2369
+ senderTokens,
2370
+ recipient: new web3_js.PublicKey(recipient),
2371
+ metadata: metadataPubKey,
2372
+ escrowTokens,
2373
+ recipientTokens,
2374
+ streamflowTreasury: STREAMFLOW_TREASURY_PUBLIC_KEY,
2375
+ streamflowTreasuryTokens,
2376
+ partner: partnerPublicKey,
2377
+ partnerTokens,
2378
+ mint: new web3_js.PublicKey(mint),
2379
+ feeOracle: FEE_ORACLE_PUBLIC_KEY,
2380
+ rent: web3_js.SYSVAR_RENT_PUBKEY,
2381
+ timelockProgram: this.programId,
2382
+ tokenProgram: tokenProgramId,
2383
+ associatedTokenProgram: splToken.ASSOCIATED_TOKEN_PROGRAM_ID,
2384
+ withdrawor: WITHDRAWOR_PUBLIC_KEY,
2385
+ systemProgram: web3_js.SystemProgram.programId
2386
+ }
2387
+ )
2388
+ );
2389
+ return { ixs, metadata, metadataPubKey };
2390
+ }
2391
+ /**
2392
+ * Creates a new stream/vesting contract using unchecked instruction.
2393
+ *
2394
+ * Unchecked instruction differs from the regular in:
2395
+ * - does not check for initialized associated token account (wallets with no control over their ATA should not be used
2396
+ * as sender/recipient/partner or there are risks of funds being locked in the contract)
2397
+ * - initialized contract PDA off chain
2398
+ *
2399
+ * If you are not sure if you should use create or create_unchecked, go for create to be safer.
2400
+ */
2401
+ async createUnchecked(data, extParams) {
2402
+ const { ixs, metadata, metadataPubKey } = await this.prepareCreateUncheckedInstructions(data, extParams);
2403
+ const { tx, hash, context } = await solana.prepareTransaction(
2404
+ this.connection,
2405
+ ixs,
2406
+ extParams.sender.publicKey,
2407
+ void 0,
2408
+ metadata
2409
+ );
2410
+ const signature = await solana.signAndExecuteTransaction(
2411
+ this.connection,
2412
+ extParams.sender,
2413
+ tx,
2414
+ {
2415
+ hash,
2416
+ context,
2417
+ commitment: this.getCommitment()
2418
+ },
2419
+ this.schedulingParams
2420
+ );
2421
+ return { ixs, txId: signature, metadataId: metadataPubKey.toBase58() };
2422
+ }
2423
+ /**
2424
+ * Create Transaction instructions for `createUnchecked`
2425
+ */
2426
+ async prepareCreateUncheckedInstructions({
2427
+ recipient,
2428
+ tokenId: mint,
2429
+ start,
2430
+ amount: depositedAmount,
2431
+ period,
2432
+ cliff,
2433
+ cliffAmount,
2434
+ amountPerPeriod,
2435
+ name,
2436
+ canTopup,
2437
+ canUpdateRate,
2438
+ canPause,
2439
+ cancelableBySender,
2440
+ cancelableByRecipient,
2441
+ transferableBySender,
2442
+ transferableByRecipient,
2443
+ automaticWithdrawal = false,
2444
+ withdrawalFrequency = 0,
2445
+ partner
2446
+ }, { sender, metadataPubKeys, isNative = false, computePrice, computeLimit }) {
2447
+ if (!sender.publicKey) {
2448
+ throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
2449
+ }
2450
+ const mintPublicKey = new web3_js.PublicKey(mint);
2451
+ const recipientPublicKey = new web3_js.PublicKey(recipient);
2452
+ const { metadata, metadataPubKey } = this.getOrCreateStreamMetadata(metadataPubKeys);
2453
+ const rentToExempt = await this.connection.getMinimumBalanceForRentExemption(METADATA_ACC_SIZE);
2454
+ const createMetadataInstruction = web3_js.SystemProgram.createAccount({
2455
+ programId: this.programId,
2456
+ space: METADATA_ACC_SIZE,
2457
+ lamports: rentToExempt,
2458
+ fromPubkey: sender?.publicKey,
2459
+ newAccountPubkey: metadataPubKey
2460
+ });
2461
+ const [escrowTokens] = web3_js.PublicKey.findProgramAddressSync(
2462
+ [buffer.Buffer.from("strm"), metadataPubKey.toBuffer()],
2463
+ this.programId
2464
+ );
2465
+ const { tokenProgramId } = await solana.getMintAndProgram(this.connection, mintPublicKey);
2466
+ const senderTokens = await solana.ata(mintPublicKey, sender.publicKey, tokenProgramId);
2467
+ const partnerPublicKey = partner ? new web3_js.PublicKey(partner) : WITHDRAWOR_PUBLIC_KEY;
2468
+ const ixs = solana.prepareBaseInstructions(this.connection, {
2469
+ computePrice,
2470
+ computeLimit
2471
+ });
2472
+ if (isNative) {
2473
+ const totalFee = await this.getTotalFee({ address: partnerPublicKey.toString() });
2474
+ const totalAmount = calculateTotalAmountToDeposit(depositedAmount, totalFee);
2475
+ ixs.push(...await solana.prepareWrappedAccount(this.connection, sender.publicKey, totalAmount));
2476
+ }
2477
+ const createInstruction = await createUncheckedStreamInstruction(
2478
+ {
2479
+ start: new BN6__default.default(start),
2480
+ depositedAmount,
2481
+ period: new BN6__default.default(period),
2482
+ amountPerPeriod,
2483
+ cliff: new BN6__default.default(cliff),
2484
+ cliffAmount: new BN6__default.default(cliffAmount),
2485
+ cancelableBySender,
2486
+ cancelableByRecipient,
2487
+ automaticWithdrawal,
2488
+ transferableBySender,
2489
+ transferableByRecipient,
2490
+ canTopup,
2491
+ canUpdateRate: !!canUpdateRate,
2492
+ canPause: !!canPause,
2493
+ name,
2494
+ withdrawFrequency: new BN6__default.default(automaticWithdrawal ? withdrawalFrequency : period),
2495
+ recipient: recipientPublicKey,
2496
+ partner: partnerPublicKey
2497
+ },
2498
+ this.programId,
2499
+ {
2500
+ sender: sender.publicKey,
2501
+ senderTokens,
2502
+ metadata: metadataPubKey,
2503
+ escrowTokens,
2504
+ mint: new web3_js.PublicKey(mint),
2505
+ feeOracle: FEE_ORACLE_PUBLIC_KEY,
2506
+ rent: web3_js.SYSVAR_RENT_PUBKEY,
2507
+ timelockProgram: this.programId,
2508
+ tokenProgram: tokenProgramId,
2509
+ withdrawor: WITHDRAWOR_PUBLIC_KEY,
2510
+ systemProgram: web3_js.SystemProgram.programId
2511
+ }
2512
+ );
2513
+ ixs.push(createMetadataInstruction, createInstruction);
2514
+ return { ixs, metadata, metadataPubKey };
2515
+ }
2516
+ /**
2517
+ * Creates multiple stream/vesting contracts.
2518
+ * All fees are paid by sender (escrow metadata account rent, escrow token account rent, recipient's associated token account rent, Streamflow's service fee).
2519
+ */
2520
+ async createMultiple(data, extParams) {
2521
+ const { recipients, ...streamParams } = data;
2522
+ const {
2523
+ sender,
2524
+ metadataPubKeys: metadataPubKeysExt,
2525
+ isNative,
2526
+ computePrice,
2527
+ computeLimit,
2528
+ customInstructions
2529
+ } = extParams;
2530
+ const metadatas = [];
2531
+ const metadataToRecipient = {};
2532
+ const errors = [];
2533
+ const signatures = [];
2534
+ const batch = [];
2535
+ const instructionsBatch = [];
2536
+ const metadataPubKeys = metadataPubKeysExt || [];
2537
+ const partnerPublicKey = data.partner ? new web3_js.PublicKey(data.partner) : WITHDRAWOR_PUBLIC_KEY;
2538
+ const mintPublicKey = new web3_js.PublicKey(data.tokenId);
2539
+ if (recipients.length === 0) {
2540
+ throw new Error("Recipients array is empty!");
2541
+ }
2542
+ if (!sender.publicKey) {
2543
+ throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
2544
+ }
2545
+ for (let i = 0; i < recipients.length; i++) {
2546
+ const recipientData = recipients[i];
2547
+ const createStreamData = { ...streamParams, ...recipientData };
2548
+ const createStreamExtParams = {
2549
+ sender,
2550
+ metadataPubKeys: metadataPubKeys[i] ? [metadataPubKeys[i]] : void 0,
2551
+ computePrice,
2552
+ computeLimit,
2553
+ customInstructions
2554
+ };
2555
+ const { ixs, metadata, metadataPubKey } = await this.prepareCreateInstructions(
2556
+ createStreamData,
2557
+ createStreamExtParams
2558
+ );
2559
+ await this.applyCustomAfterInstructions(ixs, customInstructions, metadataPubKey);
2560
+ metadataToRecipient[metadataPubKey.toBase58()] = recipientData;
2561
+ metadatas.push(metadataPubKey.toBase58());
2562
+ instructionsBatch.push({
2563
+ ixs,
2564
+ metadata,
2565
+ recipient: recipientData.recipient
2566
+ });
2567
+ }
2568
+ const { value: hash, context } = await this.connection.getLatestBlockhashAndContext();
2569
+ for (const { ixs, metadata, recipient } of instructionsBatch) {
2570
+ const messageV0 = new web3_js.TransactionMessage({
2571
+ payerKey: sender.publicKey,
2572
+ recentBlockhash: hash.blockhash,
2573
+ instructions: ixs
2574
+ }).compileToV0Message();
2575
+ const tx = new web3_js.VersionedTransaction(messageV0);
2576
+ if (metadata) {
2577
+ tx.sign([metadata]);
2578
+ }
2579
+ batch.push({ tx, recipient });
2580
+ }
2581
+ const prepareInstructions = await this.getCreateATAInstructions(
2582
+ [STREAMFLOW_TREASURY_PUBLIC_KEY, partnerPublicKey],
2583
+ mintPublicKey,
2584
+ sender,
2585
+ true
2586
+ );
2587
+ if (isNative) {
2588
+ const totalDepositedAmount = recipients.reduce((acc, recipient) => recipient.amount.add(acc), new BN6__default.default(0));
2589
+ const nativeInstructions = await solana.prepareWrappedAccount(this.connection, sender.publicKey, totalDepositedAmount);
2590
+ prepareInstructions.push(...nativeInstructions);
2591
+ }
2592
+ if (prepareInstructions.length > 0) {
2593
+ const messageV0 = new web3_js.TransactionMessage({
2594
+ payerKey: sender.publicKey,
2595
+ recentBlockhash: hash.blockhash,
2596
+ instructions: prepareInstructions
2597
+ }).compileToV0Message();
2598
+ const tx = new web3_js.VersionedTransaction(messageV0);
2599
+ batch.push({
2600
+ tx,
2601
+ recipient: sender.publicKey.toBase58()
2602
+ });
2603
+ }
2604
+ const signedBatch = await signAllTransactionWithRecipients(sender, batch);
2605
+ if (prepareInstructions.length > 0) {
2606
+ const prepareTx = signedBatch.pop();
2607
+ await sendAndConfirmStreamRawTransaction(this.connection, prepareTx, { hash, context }, this.schedulingParams);
2608
+ }
2609
+ const responses = [];
2610
+ if (metadataPubKeys.length > 0) {
2611
+ for (const batchTx of signedBatch) {
2612
+ responses.push(
2613
+ ...await Promise.allSettled([
2614
+ solana.executeTransaction(this.connection, batchTx.tx, { hash, context }, this.schedulingParams)
2615
+ ])
2616
+ );
2617
+ }
2618
+ } else {
2619
+ responses.push(
2620
+ ...await solana.executeMultipleTransactions(
2621
+ this.connection,
2622
+ signedBatch.map((item) => item.tx),
2623
+ { hash, context },
2624
+ this.schedulingParams
2625
+ )
2626
+ );
2627
+ }
2628
+ responses.forEach((item, index) => {
2629
+ if (item.status === "fulfilled") {
2630
+ signatures.push(item.value);
2631
+ } else {
2632
+ errors.push({
2633
+ recipient: signedBatch[index].recipient,
2634
+ error: item.reason,
2635
+ contractErrorCode: this.extractErrorCode(item.reason) || void 0
2636
+ });
2637
+ }
2638
+ });
2639
+ return { txs: signatures, metadatas, metadataToRecipient, errors };
2640
+ }
2641
+ /**
2642
+ * Creates multiple stream/vesting contracts, and send all transactions sequentially.
2643
+ * All fees are paid by sender (escrow metadata account rent, escrow token account rent, recipient's associated token account rent, Streamflow's service fee).
2644
+ * In most cases, createMultiple should be used instead.
2645
+ */
2646
+ async createMultipleSequential(data, extParams) {
2647
+ const { recipients, ...streamParams } = data;
2648
+ const {
2649
+ sender,
2650
+ metadataPubKeys: metadataPubKeysExt,
2651
+ isNative,
2652
+ computePrice,
2653
+ computeLimit,
2654
+ customInstructions
2655
+ } = extParams;
2656
+ const metadatas = [];
2657
+ const metadataToRecipient = {};
2658
+ const errors = [];
2659
+ const signatures = [];
2660
+ const batch = [];
2661
+ const instructionsBatch = [];
2662
+ const metadataPubKeys = metadataPubKeysExt || [];
2663
+ const partnerPublicKey = data.partner ? new web3_js.PublicKey(data.partner) : WITHDRAWOR_PUBLIC_KEY;
2664
+ const mintPublicKey = new web3_js.PublicKey(data.tokenId);
2665
+ if (recipients.length === 0) {
2666
+ throw new Error("Recipients array is empty!");
2667
+ }
2668
+ if (!sender.publicKey) {
2669
+ throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
2670
+ }
2671
+ for (let i = 0; i < recipients.length; i++) {
2672
+ const recipientData = recipients[i];
2673
+ const createStreamData = { ...streamParams, ...recipientData };
2674
+ const createStreamExtParams = {
2675
+ sender,
2676
+ metadataPubKeys: metadataPubKeys[i] ? [metadataPubKeys[i]] : void 0,
2677
+ computePrice,
2678
+ computeLimit,
2679
+ customInstructions
2680
+ };
2681
+ const { ixs, metadata, metadataPubKey } = await this.prepareCreateInstructions(
2682
+ createStreamData,
2683
+ createStreamExtParams
2684
+ );
2685
+ await this.applyCustomAfterInstructions(ixs, customInstructions, metadataPubKey);
2686
+ metadataToRecipient[metadataPubKey.toBase58()] = recipientData;
2687
+ metadatas.push(metadataPubKey.toBase58());
2688
+ instructionsBatch.push({
2689
+ ixs,
2690
+ metadata,
2691
+ recipient: recipientData.recipient
2692
+ });
2693
+ }
2694
+ const { value: hash, context } = await this.connection.getLatestBlockhashAndContext();
2695
+ for (const { ixs, metadata, recipient } of instructionsBatch) {
2696
+ const messageV0 = new web3_js.TransactionMessage({
2697
+ payerKey: sender.publicKey,
2698
+ recentBlockhash: hash.blockhash,
2699
+ instructions: ixs
2700
+ }).compileToV0Message();
2701
+ const tx = new web3_js.VersionedTransaction(messageV0);
2702
+ if (metadata) {
2703
+ tx.sign([metadata]);
2704
+ }
2705
+ batch.push({ tx, recipient });
2706
+ }
2707
+ const prepareInstructions = await this.getCreateATAInstructions(
2708
+ [STREAMFLOW_TREASURY_PUBLIC_KEY, partnerPublicKey],
2709
+ mintPublicKey,
2710
+ sender,
2711
+ true
2712
+ );
2713
+ if (isNative) {
2714
+ const totalDepositedAmount = recipients.reduce((acc, recipient) => recipient.amount.add(acc), new BN6__default.default(0));
2715
+ const nativeInstructions = await solana.prepareWrappedAccount(this.connection, sender.publicKey, totalDepositedAmount);
2716
+ prepareInstructions.push(...nativeInstructions);
2717
+ }
2718
+ if (prepareInstructions.length > 0) {
2719
+ const messageV0 = new web3_js.TransactionMessage({
2720
+ payerKey: sender.publicKey,
2721
+ recentBlockhash: hash.blockhash,
2722
+ instructions: prepareInstructions
2723
+ }).compileToV0Message();
2724
+ const tx = new web3_js.VersionedTransaction(messageV0);
2725
+ batch.push({
2726
+ tx,
2727
+ recipient: sender.publicKey.toBase58()
2728
+ });
2729
+ }
2730
+ const signedBatch = await signAllTransactionWithRecipients(sender, batch);
2731
+ if (prepareInstructions.length > 0) {
2732
+ const prepareTx = signedBatch.shift();
2733
+ await sendAndConfirmStreamRawTransaction(this.connection, prepareTx, { hash, context }, this.schedulingParams);
2734
+ }
2735
+ const responses = [];
2736
+ for (const batchTx of signedBatch) {
2737
+ responses.push(
2738
+ ...await Promise.allSettled([
2739
+ solana.executeTransaction(this.connection, batchTx.tx, { hash, context }, this.schedulingParams)
2740
+ ])
2741
+ );
2742
+ }
2743
+ responses.forEach((item, index) => {
2744
+ if (item.status === "fulfilled") {
2745
+ signatures.push(item.value);
2746
+ } else {
2747
+ errors.push({
2748
+ recipient: signedBatch[index].recipient,
2749
+ error: item.reason,
2750
+ contractErrorCode: this.extractErrorCode(item.reason) || void 0
2751
+ });
2752
+ }
2753
+ });
2754
+ return { txs: signatures, metadatas, metadataToRecipient, errors };
2755
+ }
2756
+ /**
2757
+ * Attempts withdrawing from the specified stream.
2758
+ */
2759
+ async withdraw({ id, amount = WITHDRAW_AVAILABLE_AMOUNT }, extParams) {
2760
+ const { invoker, customInstructions } = extParams;
2761
+ if (!invoker.publicKey) {
2762
+ throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
2763
+ }
2764
+ const ixs = await this.prepareWithdrawInstructions({ id, amount }, extParams);
2765
+ const metadata = new web3_js.PublicKey(id);
2766
+ await this.applyCustomAfterInstructions(ixs, customInstructions, metadata);
2767
+ const { tx, hash, context } = await solana.prepareTransaction(this.connection, ixs, invoker.publicKey);
2768
+ const signature = await solana.signAndExecuteTransaction(
2769
+ this.connection,
2770
+ extParams.invoker,
2771
+ tx,
2772
+ {
2773
+ hash,
2774
+ context,
2775
+ commitment: this.getCommitment()
2776
+ },
2777
+ this.schedulingParams
2778
+ );
2779
+ return { ixs, txId: signature };
2780
+ }
2781
+ /**
2782
+ * Creates Transaction Instructions for withdrawal
2783
+ */
2784
+ async prepareWithdrawInstructions({ id, amount = WITHDRAW_AVAILABLE_AMOUNT }, { invoker, checkTokenAccounts, computePrice, computeLimit }) {
2785
+ if (!invoker.publicKey) {
2786
+ throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
2787
+ }
2788
+ const ixs = solana.prepareBaseInstructions(this.connection, {
2789
+ computePrice,
2790
+ computeLimit
2791
+ });
2792
+ const streamPublicKey = new web3_js.PublicKey(id);
2793
+ const escrow = await this.connection.getAccountInfo(streamPublicKey);
2794
+ if (!escrow?.data) {
2795
+ throw new Error("Couldn't get account info");
2796
+ }
2797
+ const data = decodeStream(escrow.data);
2798
+ const { sender, recipient, mint, streamflowTreasury, partner, recipientTokens, escrowTokens } = data;
2799
+ const { tokenProgramId } = await solana.getMintAndProgram(this.connection, mint);
2800
+ const streamflowTreasuryTokens = await solana.ata(mint, STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
2801
+ const partnerTokens = await solana.ata(mint, partner, tokenProgramId);
2802
+ const ataIx = await this.getCreateATAInstructions(
2803
+ [sender, recipient, streamflowTreasury, partner],
2804
+ mint,
2805
+ invoker,
2806
+ checkTokenAccounts,
2807
+ tokenProgramId
2808
+ );
2809
+ ixs.push(
2810
+ ...ataIx,
2811
+ await withdrawStreamInstruction(amount, this.programId, {
2812
+ partner,
2813
+ partnerTokens,
2814
+ mint,
2815
+ streamflowTreasuryTokens,
2816
+ recipientTokens,
2817
+ escrowTokens,
2818
+ authority: invoker.publicKey,
2819
+ recipient: invoker.publicKey,
2820
+ metadata: streamPublicKey,
2821
+ streamflowTreasury: STREAMFLOW_TREASURY_PUBLIC_KEY,
2822
+ tokenProgram: tokenProgramId
2823
+ })
2824
+ );
2825
+ return ixs;
2826
+ }
2827
+ /**
2828
+ * Attempts canceling the specified stream.
2829
+ */
2830
+ async cancel(cancelData, extParams) {
2831
+ const ixs = await this.prepareCancelInstructions(cancelData, extParams);
2832
+ const { tx, hash, context } = await solana.prepareTransaction(this.connection, ixs, extParams.invoker.publicKey);
2833
+ const signature = await solana.signAndExecuteTransaction(
2834
+ this.connection,
2835
+ extParams.invoker,
2836
+ tx,
2837
+ {
2838
+ hash,
2839
+ context,
2840
+ commitment: this.getCommitment()
2841
+ },
2842
+ this.schedulingParams
2843
+ );
2844
+ return { ixs, txId: signature };
2845
+ }
2846
+ async prepareCancelInstructions(cancelData, extParams) {
2847
+ const streamPublicKey = new web3_js.PublicKey(cancelData.id);
2848
+ const account = await this.connection.getAccountInfo(streamPublicKey);
2849
+ if (!account) {
2850
+ throw new Error("Impossible to cancel a stream contract that does not exist");
2851
+ }
2852
+ const { sender: senderPublicKey } = decodeStream(account.data);
2853
+ const isAlignedUnlock = this.isAlignedUnlock(streamPublicKey, senderPublicKey);
2854
+ const ixs = isAlignedUnlock ? await this.prepareCancelAlignedUnlockInstructions(cancelData, extParams) : await this.prepareCancelStreamInstructions(cancelData, extParams);
2855
+ return ixs;
2856
+ }
2857
+ async prepareCancelAlignedUnlockInstructions({ id }, { invoker, checkTokenAccounts, computePrice, computeLimit }) {
2858
+ if (!invoker.publicKey) {
2859
+ throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
2860
+ }
2861
+ const streamPublicKey = new web3_js.PublicKey(id);
2862
+ const escrowAcc = await this.connection.getAccountInfo(streamPublicKey);
2863
+ if (!escrowAcc?.data) {
2864
+ throw new Error("Couldn't get account info");
2865
+ }
2866
+ const streamData = decodeStream(escrowAcc.data);
2867
+ const { sender, recipient, mint, streamflowTreasury, partner, escrowTokens } = streamData;
2868
+ const { tokenProgramId } = await solana.getMintAndProgram(this.connection, mint);
2869
+ const ixs = solana.prepareBaseInstructions(this.connection, {
2870
+ computePrice,
2871
+ computeLimit: computeLimit ?? ALIGNED_COMPUTE_LIMIT
2872
+ });
2873
+ const ataIx = await this.getCreateATAInstructions(
2874
+ [sender, recipient, partner, streamflowTreasury],
2875
+ mint,
2876
+ invoker,
2877
+ checkTokenAccounts,
2878
+ tokenProgramId
2879
+ );
2880
+ const cancelIx = await this.alignedProxyProgram.methods.cancel().accountsPartial({
2881
+ mint,
2882
+ partner,
2883
+ recipient,
2884
+ escrowTokens,
2885
+ sender: invoker.publicKey,
2886
+ streamMetadata: streamPublicKey,
2887
+ streamflowTreasury: STREAMFLOW_TREASURY_PUBLIC_KEY,
2888
+ tokenProgram: tokenProgramId,
2889
+ streamflowProgram: this.programId
2890
+ }).instruction();
2891
+ ixs.push(...ataIx, cancelIx);
2892
+ return ixs;
2893
+ }
2894
+ /**
2895
+ * Creates Transaction Instructions for cancel
2896
+ */
2897
+ async prepareCancelStreamInstructions({ id }, { invoker, checkTokenAccounts, computePrice, computeLimit }) {
2898
+ if (!invoker.publicKey) {
2899
+ throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
2900
+ }
2901
+ const streamPublicKey = new web3_js.PublicKey(id);
2902
+ const escrowAcc = await this.connection.getAccountInfo(streamPublicKey);
2903
+ if (!escrowAcc?.data) {
2904
+ throw new Error("Couldn't get account info");
2905
+ }
2906
+ const data = decodeStream(escrowAcc.data);
2907
+ const { sender, recipient, partner, streamflowTreasury, mint, senderTokens, recipientTokens, escrowTokens } = data;
2908
+ const { tokenProgramId } = await solana.getMintAndProgram(this.connection, mint);
2909
+ const streamflowTreasuryTokens = await solana.ata(mint, STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
2910
+ const partnerTokens = await solana.ata(mint, partner, tokenProgramId);
2911
+ const ixs = solana.prepareBaseInstructions(this.connection, {
2912
+ computePrice,
2913
+ computeLimit
2914
+ });
2915
+ const ixsAta = await this.getCreateATAInstructions(
2916
+ [sender, recipient, partner, streamflowTreasury],
2917
+ mint,
2918
+ invoker,
2919
+ checkTokenAccounts,
2920
+ tokenProgramId
2921
+ );
2922
+ ixs.push(
2923
+ ...ixsAta,
2924
+ await cancelStreamInstruction(this.programId, {
2925
+ sender,
2926
+ senderTokens,
2927
+ recipient,
2928
+ recipientTokens,
2929
+ streamflowTreasuryTokens,
2930
+ partner,
2931
+ partnerTokens,
2932
+ mint,
2933
+ escrowTokens,
2934
+ authority: invoker.publicKey,
2935
+ metadata: streamPublicKey,
2936
+ streamflowTreasury: STREAMFLOW_TREASURY_PUBLIC_KEY,
2937
+ tokenProgram: tokenProgramId
2938
+ })
2939
+ );
2940
+ return ixs;
2941
+ }
2942
+ /**
2943
+ * Attempts changing the stream/vesting contract's recipient (effectively transferring the stream/vesting contract).
2944
+ * Potential associated token account rent fee (to make it rent-exempt) is paid by the transaction initiator.
2945
+ */
2946
+ async transfer({ id, newRecipient }, extParams) {
2947
+ const ixs = await this.prepareTransferInstructions({ id, newRecipient }, extParams);
2948
+ const { tx, hash, context } = await solana.prepareTransaction(this.connection, ixs, extParams.invoker.publicKey);
2949
+ const signature = await solana.signAndExecuteTransaction(
2950
+ this.connection,
2951
+ extParams.invoker,
2952
+ tx,
2953
+ {
2954
+ hash,
2955
+ context,
2956
+ commitment: this.getCommitment()
2957
+ },
2958
+ this.schedulingParams
2959
+ );
2960
+ return { ixs, txId: signature };
2961
+ }
2962
+ /**
2963
+ * Attempts changing the stream/vesting contract's recipient (effectively transferring the stream/vesting contract).
2964
+ * Potential associated token account rent fee (to make it rent-exempt) is paid by the transaction initiator.
2965
+ */
2966
+ async prepareTransferInstructions({ id, newRecipient }, { invoker, computePrice, computeLimit = 100001 }) {
2967
+ if (!invoker.publicKey) {
2968
+ throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
2969
+ }
2970
+ const ixs = solana.prepareBaseInstructions(this.connection, {
2971
+ computePrice,
2972
+ computeLimit
2973
+ });
2974
+ const stream = new web3_js.PublicKey(id);
2975
+ const newRecipientPublicKey = new web3_js.PublicKey(newRecipient);
2976
+ const escrow = await this.connection.getAccountInfo(stream);
2977
+ if (!escrow?.data) {
2978
+ throw new Error("Couldn't get account info");
2979
+ }
2980
+ const { mint } = decodeStream(escrow?.data);
2981
+ const { tokenProgramId } = await solana.getMintAndProgram(this.connection, mint);
2982
+ const newRecipientTokens = await solana.ata(mint, newRecipientPublicKey, tokenProgramId);
2983
+ ixs.push(
2984
+ await transferStreamInstruction(this.programId, {
2985
+ authority: invoker.publicKey,
2986
+ newRecipient: newRecipientPublicKey,
2987
+ newRecipientTokens,
2988
+ metadata: stream,
2989
+ mint,
2990
+ rent: web3_js.SYSVAR_RENT_PUBKEY,
2991
+ tokenProgram: tokenProgramId,
2992
+ associatedTokenProgram: splToken.ASSOCIATED_TOKEN_PROGRAM_ID,
2993
+ systemProgram: web3_js.SystemProgram.programId
2994
+ })
2995
+ );
2996
+ return ixs;
2997
+ }
2998
+ /**
2999
+ * Tops up stream account with specified amount.
3000
+ */
3001
+ async topup({ id, amount }, extParams) {
3002
+ const ixs = await this.prepareTopupInstructions({ id, amount }, extParams);
3003
+ const { tx, hash, context } = await solana.prepareTransaction(this.connection, ixs, extParams.invoker.publicKey);
3004
+ const signature = await solana.signAndExecuteTransaction(
3005
+ this.connection,
3006
+ extParams.invoker,
3007
+ tx,
3008
+ {
3009
+ hash,
3010
+ context,
3011
+ commitment: this.getCommitment()
3012
+ },
3013
+ this.schedulingParams
3014
+ );
3015
+ return { ixs, txId: signature };
3016
+ }
3017
+ /**
3018
+ * Create Transaction instructions for topup
3019
+ */
3020
+ async prepareTopupInstructions({ id, amount }, { invoker, isNative, computePrice, computeLimit }) {
3021
+ if (!invoker.publicKey) {
3022
+ throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
3023
+ }
3024
+ const ixs = solana.prepareBaseInstructions(this.connection, {
3025
+ computePrice,
3026
+ computeLimit
3027
+ });
3028
+ const streamPublicKey = new web3_js.PublicKey(id);
3029
+ const escrow = await this.connection.getAccountInfo(streamPublicKey);
3030
+ if (!escrow?.data) {
3031
+ throw new Error("Couldn't get account info");
3032
+ }
3033
+ const { mint, partner, senderTokens, escrowTokens } = decodeStream(escrow?.data);
3034
+ const { tokenProgramId } = await solana.getMintAndProgram(this.connection, mint);
3035
+ const streamflowTreasuryTokens = await solana.ata(mint, STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
3036
+ const partnerTokens = await solana.ata(mint, partner, tokenProgramId);
3037
+ if (isNative) {
3038
+ ixs.push(...await solana.prepareWrappedAccount(this.connection, invoker.publicKey, amount));
3039
+ }
3040
+ ixs.push(
3041
+ await topupStreamInstruction(amount, this.programId, {
3042
+ sender: invoker.publicKey,
3043
+ senderTokens,
3044
+ metadata: streamPublicKey,
3045
+ escrowTokens,
3046
+ streamflowTreasury: STREAMFLOW_TREASURY_PUBLIC_KEY,
3047
+ streamflowTreasuryTokens,
3048
+ partner,
3049
+ partnerTokens,
3050
+ mint,
3051
+ tokenProgram: tokenProgramId,
3052
+ withdrawor: WITHDRAWOR_PUBLIC_KEY,
3053
+ systemProgram: web3_js.SystemProgram.programId
3054
+ })
3055
+ );
3056
+ return ixs;
3057
+ }
3058
+ /**
3059
+ * Fetch stream data by its id (address).
3060
+ */
3061
+ async getOne({ id }) {
3062
+ const streamPublicKey = new web3_js.PublicKey(id);
3063
+ const escrow = await this.connection.getAccountInfo(streamPublicKey, TX_FINALITY_CONFIRMED);
3064
+ if (!escrow?.data) {
3065
+ throw new Error("Couldn't get account info.");
3066
+ }
3067
+ const stream = decodeStream(escrow.data);
3068
+ if (this.isAlignedUnlock(streamPublicKey, stream.sender)) {
3069
+ const alignedProxy = await this.alignedProxyProgram.account.contract.fetch(
3070
+ deriveContractPDA(this.alignedProxyProgram.programId, streamPublicKey)
3071
+ );
3072
+ if (!alignedProxy) {
3073
+ throw new Error("Couldn't get proxy account info.");
3074
+ }
3075
+ return new AlignedContract(stream, alignedProxy);
3076
+ }
3077
+ return new Contract(stream);
3078
+ }
3079
+ /**
3080
+ * Fetch all aligned outgoing streams/contracts by the provided public key.
3081
+ */
3082
+ async getOutgoingAlignedStreams(sender) {
3083
+ const streams = {};
3084
+ const alignedOutgoingProgramAccounts = await this.alignedProxyProgram.account.contract.all([
3085
+ {
3086
+ memcmp: {
3087
+ offset: ORIGINAL_CONTRACT_SENDER_OFFSET,
3088
+ bytes: sender
3089
+ }
3090
+ },
3091
+ {
3092
+ dataSize: ALIGNED_METADATA_ACC_SIZE
3093
+ }
3094
+ ]);
3095
+ const streamPubKeys = alignedOutgoingProgramAccounts.map((account) => account.account.stream);
3096
+ const streamAccounts = await solana.getMultipleAccountsInfoBatched(this.connection, streamPubKeys, TX_FINALITY_CONFIRMED);
3097
+ streamAccounts.forEach((account, index) => {
3098
+ if (account) {
3099
+ const alignedData = alignedOutgoingProgramAccounts[index].account;
3100
+ streams[streamPubKeys[index].toBase58()] = new AlignedContract(decodeStream(account.data), alignedData);
3101
+ }
3102
+ });
3103
+ return streams;
3104
+ }
3105
+ async getIncomingAlignedStreams(streamRecord) {
3106
+ const streams = {};
3107
+ const alignedStreamsPubKeys = Object.keys(streamRecord);
3108
+ const alignedProxyPDAs = alignedStreamsPubKeys.map(
3109
+ (streamPubKey) => deriveContractPDA(this.alignedProxyProgram.programId, new web3_js.PublicKey(streamPubKey))
3110
+ );
3111
+ const alignedProxyAccounts = await solana.getMultipleAccountsInfoBatched(this.connection, alignedProxyPDAs);
3112
+ alignedProxyAccounts.forEach((account, index) => {
3113
+ if (account && account.data.length === ALIGNED_METADATA_ACC_SIZE) {
3114
+ const alignedData = streamRecord[alignedStreamsPubKeys[index]];
3115
+ streams[alignedStreamsPubKeys[index]] = new AlignedContract(
3116
+ alignedData,
3117
+ this.alignedProxyProgram.account.contract.coder.accounts.decode("contract", account.data)
3118
+ );
3119
+ }
3120
+ });
3121
+ return streams;
3122
+ }
3123
+ /**
3124
+ * Fetch streams/contracts by providing direction.
3125
+ * Streams are sorted by start time in ascending order.
3126
+ */
3127
+ async get({
3128
+ address,
3129
+ type = "all" /* All */,
3130
+ direction = "all" /* All */
3131
+ }) {
3132
+ const publicKey = new web3_js.PublicKey(address);
3133
+ let streams = {};
3134
+ const shouldFetchAligned = type === "all" /* All */ || type === "vesting" /* Vesting */;
3135
+ if (direction !== "incoming" /* Incoming */) {
3136
+ const outgoingStreamAccounts = await solana.getProgramAccounts(
3137
+ this.connection,
3138
+ publicKey,
3139
+ STREAM_STRUCT_OFFSET_SENDER,
3140
+ this.programId
3141
+ );
3142
+ outgoingStreamAccounts.forEach((account) => {
3143
+ streams[account.pubkey.toBase58()] = new Contract(decodeStream(account.account.data));
3144
+ });
3145
+ if (shouldFetchAligned) {
3146
+ const alignedStreams = await this.getOutgoingAlignedStreams(address);
3147
+ streams = { ...streams, ...alignedStreams };
3148
+ }
3149
+ }
3150
+ if (direction !== "outgoing" /* Outgoing */) {
3151
+ const allIncomingAccounts = await solana.getProgramAccounts(
3152
+ this.connection,
3153
+ publicKey,
3154
+ STREAM_STRUCT_OFFSET_RECIPIENT,
3155
+ this.programId
3156
+ );
3157
+ const allIncomingStreams = allIncomingAccounts.map((account) => decodeStream(account.account.data));
3158
+ const alignedDecoded = {};
3159
+ allIncomingAccounts.forEach((account, index) => {
3160
+ if (this.isAlignedUnlock(account.pubkey, allIncomingStreams[index].sender)) {
3161
+ alignedDecoded[account.pubkey.toBase58()] = allIncomingStreams[index];
3162
+ } else {
3163
+ streams[account.pubkey.toBase58()] = new Contract(allIncomingStreams[index]);
3164
+ }
3165
+ });
3166
+ if (shouldFetchAligned) {
3167
+ const incomingAlignedStreams = await this.getIncomingAlignedStreams(alignedDecoded);
3168
+ streams = { ...streams, ...incomingAlignedStreams };
3169
+ }
3170
+ }
3171
+ const sortedStreams = Object.entries(streams).sort(([, stream1], [, stream2]) => stream2.start - stream1.start);
3172
+ if (type === "all" /* All */) return sortedStreams;
3173
+ return sortedStreams.filter((stream) => stream[1].type === type);
3174
+ }
3175
+ async searchStreams(data) {
3176
+ const filters = Object.entries(data).filter(([_, value]) => value !== void 0).map(([key, value]) => ({
3177
+ memcmp: {
3178
+ offset: STREAM_STRUCT_OFFSETS[key],
3179
+ bytes: typeof value === "boolean" ? bs58__default.default.encode([Number(value)]) : value.toString()
3180
+ }
3181
+ }));
3182
+ filters.push({ dataSize: METADATA_ACC_SIZE });
3183
+ const accounts = await this.connection.getProgramAccounts(this.programId, {
3184
+ filters
3185
+ });
3186
+ return accounts.map(({ pubkey, account }) => ({
3187
+ publicKey: pubkey,
3188
+ account: new Contract(decodeStream(account.data))
3189
+ }));
3190
+ }
3191
+ /**
3192
+ * Attempts updating the stream auto withdrawal params and amount per period
3193
+ */
3194
+ async update(data, extParams) {
3195
+ const ixs = await this.prepareUpdateInstructions(data, extParams);
3196
+ const { tx, hash, context } = await solana.prepareTransaction(this.connection, ixs, extParams.invoker.publicKey);
3197
+ const signature = await solana.signAndExecuteTransaction(
3198
+ this.connection,
3199
+ extParams.invoker,
3200
+ tx,
3201
+ {
3202
+ hash,
3203
+ context,
3204
+ commitment: this.getCommitment()
3205
+ },
3206
+ this.schedulingParams
3207
+ );
3208
+ return {
3209
+ ixs,
3210
+ txId: signature
3211
+ };
3212
+ }
3213
+ /**
3214
+ * Create Transaction instructions for update
3215
+ */
3216
+ async prepareUpdateInstructions(data, { invoker, computePrice, computeLimit }) {
3217
+ if (!invoker.publicKey) {
3218
+ throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
3219
+ }
3220
+ const streamPublicKey = new web3_js.PublicKey(data.id);
3221
+ const escrow = await this.connection.getAccountInfo(streamPublicKey);
3222
+ if (!escrow) {
3223
+ throw new Error("Couldn't get account info");
3224
+ }
3225
+ const ixs = solana.prepareBaseInstructions(this.connection, {
3226
+ computePrice,
3227
+ computeLimit
3228
+ });
3229
+ ixs.push(
3230
+ await updateStreamInstruction(data, this.programId, {
3231
+ authority: invoker.publicKey,
3232
+ metadata: streamPublicKey,
3233
+ withdrawor: WITHDRAWOR_PUBLIC_KEY,
3234
+ systemProgram: web3_js.SystemProgram.programId
3235
+ })
3236
+ );
3237
+ return ixs;
3238
+ }
3239
+ async getFees({ address }) {
3240
+ const [metadataPubKey] = web3_js.PublicKey.findProgramAddressSync(
3241
+ [buffer.Buffer.from(FEES_METADATA_SEED)],
3242
+ new web3_js.PublicKey(PARTNER_ORACLE_PROGRAM_ID)
3243
+ );
3244
+ const data = await this.connection.getAccountInfo(metadataPubKey);
3245
+ if (!data) {
3246
+ return null;
3247
+ }
3248
+ const partners = borsh__namespace.deserialize(PARTNERS_SCHEMA, data.data);
3249
+ const filteredPartners = partners.filter((item) => new web3_js.PublicKey(item.pubkey).toString() === address);
3250
+ if (filteredPartners.length === 0) {
3251
+ return null;
3252
+ }
3253
+ return {
3254
+ streamflowFee: Number(filteredPartners[0].strm_fee.toFixed(4)),
3255
+ partnerFee: Number(filteredPartners[0].partner_fee.toFixed(4))
3256
+ };
3257
+ }
3258
+ async getDefaultStreamflowFee() {
3259
+ return DEFAULT_STREAMFLOW_FEE;
3260
+ }
3261
+ extractErrorCode(err) {
3262
+ const logs = "logs" in err && Array.isArray(err.logs) ? err.logs : void 0;
3263
+ return extractSolanaErrorCode(err.toString() ?? "Unknown error!", logs);
3264
+ }
3265
+ /**
3266
+ * Utility function to generate metadata for a Contract or return existing Pubkey
3267
+ */
3268
+ getOrCreateStreamMetadata(metadataPubKeys) {
3269
+ let metadata;
3270
+ let metadataPubKey;
3271
+ if (!metadataPubKeys) {
3272
+ metadata = web3_js.Keypair.generate();
3273
+ metadataPubKey = metadata.publicKey;
3274
+ } else {
3275
+ metadataPubKey = metadataPubKeys[0];
3276
+ }
3277
+ return { metadata, metadataPubKey };
3278
+ }
3279
+ /**
3280
+ * Utility function that checks whether the associated stream address is an aligned unlock contract, indicated by whether the sender/creator is a PDA
3281
+ */
3282
+ isAlignedUnlock(streamPublicKey, senderPublicKey) {
3283
+ const pda = deriveContractPDA(this.alignedProxyProgram.programId, streamPublicKey);
3284
+ return senderPublicKey.equals(pda);
3285
+ }
3286
+ /**
3287
+ * Returns insrtuctions for creating associated token accounts for the provided owners
3288
+ */
3289
+ async getCreateATAInstructions(owners, mint, invoker, checkTokenAccounts, programId) {
3290
+ if (!checkTokenAccounts) {
3291
+ return [];
3292
+ }
3293
+ const uniqueOwners = Array.from(new Set(owners.map((owner) => owner.toBase58()))).map(
3294
+ (pkString) => new web3_js.PublicKey(pkString)
3295
+ );
3296
+ return solana.checkOrCreateAtaBatch(this.connection, uniqueOwners, mint, invoker, programId);
3297
+ }
3298
+ async applyCustomAfterInstructions(ixs, customInstructions, metadata) {
3299
+ if (customInstructions?.after) {
3300
+ const afterInstructions = typeof customInstructions.after === "function" ? await customInstructions.after({
3301
+ instructions: ixs,
3302
+ metadata
3303
+ }) : customInstructions.after;
3304
+ ixs.push(...afterInstructions);
3305
+ }
3306
+ }
3307
+ };
3308
+
3309
+ // solana/timelockIDL.ts
3310
+ var timelockIDL_default = {
3311
+ version: "0.1.0",
3312
+ name: "timelock",
3313
+ instructions: [
3314
+ {
3315
+ name: "create",
3316
+ accounts: [
3317
+ {
3318
+ name: "sender",
3319
+ isMut: true,
3320
+ isSigner: true
3321
+ },
3322
+ {
3323
+ name: "senderTokens",
3324
+ isMut: true,
3325
+ isSigner: false
3326
+ },
3327
+ {
3328
+ name: "recipient",
3329
+ isMut: true,
3330
+ isSigner: false
3331
+ },
3332
+ {
3333
+ name: "metadata",
3334
+ isMut: true,
3335
+ isSigner: true
3336
+ },
3337
+ {
3338
+ name: "escrowTokens",
3339
+ isMut: true,
3340
+ isSigner: false
3341
+ },
3342
+ {
3343
+ name: "recipientTokens",
3344
+ isMut: true,
3345
+ isSigner: false
3346
+ },
3347
+ {
3348
+ name: "streamflowTreasury",
3349
+ isMut: true,
3350
+ isSigner: false
3351
+ },
3352
+ {
3353
+ name: "streamflowTreasuryTokens",
3354
+ isMut: true,
3355
+ isSigner: false
3356
+ },
3357
+ {
3358
+ name: "withdrawor",
3359
+ isMut: true,
3360
+ isSigner: false
3361
+ },
3362
+ {
3363
+ name: "partner",
3364
+ isMut: true,
3365
+ isSigner: false
3366
+ },
3367
+ {
3368
+ name: "partnerTokens",
3369
+ isMut: true,
3370
+ isSigner: false
3371
+ },
3372
+ {
3373
+ name: "mint",
3374
+ isMut: false,
3375
+ isSigner: false
3376
+ },
3377
+ {
3378
+ name: "feeOracle",
3379
+ isMut: false,
3380
+ isSigner: false
3381
+ },
3382
+ {
3383
+ name: "rent",
3384
+ isMut: false,
3385
+ isSigner: false
3386
+ },
3387
+ {
3388
+ name: "timelockProgram",
3389
+ isMut: false,
3390
+ isSigner: false
3391
+ },
3392
+ {
3393
+ name: "tokenProgram",
3394
+ isMut: false,
3395
+ isSigner: false
3396
+ },
3397
+ {
3398
+ name: "associatedTokenProgram",
3399
+ isMut: false,
3400
+ isSigner: false
3401
+ },
3402
+ {
3403
+ name: "systemProgram",
3404
+ isMut: false,
3405
+ isSigner: false
3406
+ }
3407
+ ],
3408
+ args: [
3409
+ {
3410
+ name: "startTime",
3411
+ type: "u64"
3412
+ },
3413
+ {
3414
+ name: "netAmountDeposited",
3415
+ type: "u64"
3416
+ },
3417
+ {
3418
+ name: "period",
3419
+ type: "u64"
3420
+ },
3421
+ {
3422
+ name: "amountPerPeriod",
3423
+ type: "u64"
3424
+ },
3425
+ {
3426
+ name: "cliff",
3427
+ type: "u64"
3428
+ },
3429
+ {
3430
+ name: "cliffAmount",
3431
+ type: "u64"
3432
+ },
3433
+ {
3434
+ name: "cancelableBySender",
3435
+ type: "bool"
3436
+ },
3437
+ {
3438
+ name: "cancelableByRecipient",
3439
+ type: "bool"
3440
+ },
3441
+ {
3442
+ name: "automaticWithdrawal",
3443
+ type: "bool"
3444
+ },
3445
+ {
3446
+ name: "transferableBySender",
3447
+ type: "bool"
3448
+ },
3449
+ {
3450
+ name: "transferableByRecipient",
3451
+ type: "bool"
3452
+ },
3453
+ {
3454
+ name: "canTopup",
3455
+ type: "bool"
3456
+ },
3457
+ {
3458
+ name: "streamName",
3459
+ type: {
3460
+ array: ["u8", 64]
3461
+ }
3462
+ },
3463
+ {
3464
+ name: "withdrawFrequency",
3465
+ type: "u64"
3466
+ }
3467
+ ]
3468
+ },
3469
+ {
3470
+ name: "withdraw",
3471
+ accounts: [
3472
+ {
3473
+ name: "authority",
3474
+ isMut: false,
3475
+ isSigner: true
3476
+ },
3477
+ {
3478
+ name: "recipient",
3479
+ isMut: true,
3480
+ isSigner: false
3481
+ },
3482
+ {
3483
+ name: "recipientTokens",
3484
+ isMut: true,
3485
+ isSigner: false
3486
+ },
3487
+ {
3488
+ name: "metadata",
3489
+ isMut: true,
3490
+ isSigner: false
3491
+ },
3492
+ {
3493
+ name: "escrowTokens",
3494
+ isMut: true,
3495
+ isSigner: false
3496
+ },
3497
+ {
3498
+ name: "streamflowTreasury",
3499
+ isMut: true,
3500
+ isSigner: false
3501
+ },
3502
+ {
3503
+ name: "streamflowTreasuryTokens",
3504
+ isMut: true,
3505
+ isSigner: false
3506
+ },
3507
+ {
3508
+ name: "partner",
3509
+ isMut: true,
3510
+ isSigner: false
3511
+ },
3512
+ {
3513
+ name: "partnerTokens",
3514
+ isMut: true,
3515
+ isSigner: false
3516
+ },
3517
+ {
3518
+ name: "mint",
3519
+ isMut: false,
3520
+ isSigner: false
3521
+ },
3522
+ {
3523
+ name: "tokenProgram",
3524
+ isMut: false,
3525
+ isSigner: false
3526
+ }
3527
+ ],
3528
+ args: [
3529
+ {
3530
+ name: "amount",
3531
+ type: "u64"
3532
+ }
3533
+ ]
3534
+ },
3535
+ {
3536
+ name: "cancel",
3537
+ accounts: [
3538
+ {
3539
+ name: "authority",
3540
+ isMut: false,
3541
+ isSigner: true
3542
+ },
3543
+ {
3544
+ name: "sender",
3545
+ isMut: true,
3546
+ isSigner: false
3547
+ },
3548
+ {
3549
+ name: "senderTokens",
3550
+ isMut: true,
3551
+ isSigner: false
3552
+ },
3553
+ {
3554
+ name: "recipient",
3555
+ isMut: true,
3556
+ isSigner: false
3557
+ },
3558
+ {
3559
+ name: "recipientTokens",
3560
+ isMut: true,
3561
+ isSigner: false
3562
+ },
3563
+ {
3564
+ name: "metadata",
3565
+ isMut: true,
3566
+ isSigner: false
3567
+ },
3568
+ {
3569
+ name: "escrowTokens",
3570
+ isMut: true,
3571
+ isSigner: false
3572
+ },
3573
+ {
3574
+ name: "streamflowTreasury",
3575
+ isMut: true,
3576
+ isSigner: false
3577
+ },
3578
+ {
3579
+ name: "streamflowTreasuryTokens",
3580
+ isMut: true,
3581
+ isSigner: false
3582
+ },
3583
+ {
3584
+ name: "partner",
3585
+ isMut: true,
3586
+ isSigner: false
3587
+ },
3588
+ {
3589
+ name: "partnerTokens",
3590
+ isMut: true,
3591
+ isSigner: false
3592
+ },
3593
+ {
3594
+ name: "mint",
3595
+ isMut: false,
3596
+ isSigner: false
3597
+ },
3598
+ {
3599
+ name: "tokenProgram",
3600
+ isMut: false,
3601
+ isSigner: false
3602
+ }
3603
+ ],
3604
+ args: []
3605
+ },
3606
+ {
3607
+ name: "transferRecipient",
3608
+ accounts: [
3609
+ {
3610
+ name: "authority",
3611
+ isMut: true,
3612
+ isSigner: true
3613
+ },
3614
+ {
3615
+ name: "newRecipient",
3616
+ isMut: true,
3617
+ isSigner: false
3618
+ },
3619
+ {
3620
+ name: "newRecipientTokens",
3621
+ isMut: true,
3622
+ isSigner: false
3623
+ },
3624
+ {
3625
+ name: "metadata",
3626
+ isMut: true,
3627
+ isSigner: false
3628
+ },
3629
+ {
3630
+ name: "mint",
3631
+ isMut: false,
3632
+ isSigner: false
3633
+ },
3634
+ {
3635
+ name: "rent",
3636
+ isMut: false,
3637
+ isSigner: false
3638
+ },
3639
+ {
3640
+ name: "tokenProgram",
3641
+ isMut: false,
3642
+ isSigner: false
3643
+ },
3644
+ {
3645
+ name: "associatedTokenProgram",
3646
+ isMut: false,
3647
+ isSigner: false
3648
+ },
3649
+ {
3650
+ name: "systemProgram",
3651
+ isMut: false,
3652
+ isSigner: false
3653
+ }
3654
+ ],
3655
+ args: []
3656
+ },
3657
+ {
3658
+ name: "topup",
3659
+ accounts: [
3660
+ {
3661
+ name: "sender",
3662
+ isMut: true,
3663
+ isSigner: true
3664
+ },
3665
+ {
3666
+ name: "senderTokens",
3667
+ isMut: true,
3668
+ isSigner: false
3669
+ },
3670
+ {
3671
+ name: "metadata",
3672
+ isMut: true,
3673
+ isSigner: false
3674
+ },
3675
+ {
3676
+ name: "escrowTokens",
3677
+ isMut: true,
3678
+ isSigner: false
3679
+ },
3680
+ {
3681
+ name: "streamflowTreasury",
3682
+ isMut: true,
3683
+ isSigner: false
3684
+ },
3685
+ {
3686
+ name: "streamflowTreasuryTokens",
3687
+ isMut: true,
3688
+ isSigner: false
3689
+ },
3690
+ {
3691
+ name: "withdrawor",
3692
+ isMut: true,
3693
+ isSigner: false
3694
+ },
3695
+ {
3696
+ name: "partner",
3697
+ isMut: true,
3698
+ isSigner: false
3699
+ },
3700
+ {
3701
+ name: "partnerTokens",
3702
+ isMut: true,
3703
+ isSigner: false
3704
+ },
3705
+ {
3706
+ name: "mint",
3707
+ isMut: false,
3708
+ isSigner: false
3709
+ },
3710
+ {
3711
+ name: "tokenProgram",
3712
+ isMut: false,
3713
+ isSigner: false
3714
+ },
3715
+ {
3716
+ name: "systemProgram",
3717
+ isMut: false,
3718
+ isSigner: false
3719
+ }
3720
+ ],
3721
+ args: [
3722
+ {
3723
+ name: "amount",
3724
+ type: "u64"
3725
+ }
3726
+ ]
3727
+ }
3728
+ ]
3729
+ };
3730
+
3731
+ Object.defineProperty(exports, "ContractError", {
3732
+ enumerable: true,
3733
+ get: function () { return common.ContractError; }
3734
+ });
3735
+ Object.defineProperty(exports, "IChain", {
3736
+ enumerable: true,
3737
+ get: function () { return common.IChain; }
3738
+ });
3739
+ Object.defineProperty(exports, "ICluster", {
3740
+ enumerable: true,
3741
+ get: function () { return common.ICluster; }
3742
+ });
3743
+ exports.AlignedContract = AlignedContract;
3744
+ exports.Contract = Contract;
3745
+ exports.SolanaStreamClient = SolanaStreamClient;
3746
+ exports.cancelStreamInstruction = cancelStreamInstruction;
3747
+ exports.constants = constants_exports;
3748
+ exports.createStreamInstruction = createStreamInstruction;
3749
+ exports.createUncheckedStreamInstruction = createUncheckedStreamInstruction;
3750
+ exports.decodeStream = decodeStream;
3751
+ exports.deriveContractPDA = deriveContractPDA;
3752
+ exports.deriveEscrowPDA = deriveEscrowPDA;
3753
+ exports.deriveTestOraclePDA = deriveTestOraclePDA;
3754
+ exports.extractSolanaErrorCode = extractSolanaErrorCode;
3755
+ exports.sendAndConfirmStreamRawTransaction = sendAndConfirmStreamRawTransaction;
3756
+ exports.signAllTransactionWithRecipients = signAllTransactionWithRecipients;
3757
+ exports.timelockIDL = timelockIDL_default;
3758
+ exports.topupStreamInstruction = topupStreamInstruction;
3759
+ exports.transferStreamInstruction = transferStreamInstruction;
3760
+ exports.updateStreamInstruction = updateStreamInstruction;
3761
+ exports.withdrawStreamInstruction = withdrawStreamInstruction;
3762
+ //# sourceMappingURL=index.cjs.map
3763
+ //# sourceMappingURL=index.cjs.map