forked from Lead-Studios/veritix-contract-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplitter.ts
More file actions
429 lines (394 loc) · 13.9 KB
/
Copy pathsplitter.ts
File metadata and controls
429 lines (394 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
/**
* @module modules/splitter
* Payment splitter operations exposed by the VeriTix Soroban contract.
*/
import { SorobanRpc, Keypair, Account, xdr } from '@stellar/stellar-sdk';
import { addressToScVal, scValToBigint, scValToNumber } from '../utils/scval';
import { buildContractCall, simulateTransaction, submitTransaction } from '../utils/transaction';
import { parseSorobanError, VeriTixError, VeriTixErrorCode } from '../utils/errors';
import { DUMMY_PUBLIC_KEY } from '../utils/network';
import type {
NetworkConfig,
SplitRecord,
SplitRecipient,
TransactionResult,
RevenueSplitParams,
} from '../types/index';
export interface CreateSplitParams {
recipients: SplitRecipient[];
totalAmount: bigint;
}
export interface ValidationResult {
valid: boolean;
errors: string[];
}
export class SplitterModule {
private readonly config: NetworkConfig;
private readonly server: SorobanRpc.Server;
private readonly keypair: Keypair | undefined;
constructor(config: NetworkConfig, server: SorobanRpc.Server, keypair?: Keypair) {
this.config = config;
this.server = server;
this.keypair = keypair;
}
/**
* Fetches the on-chain record for an existing split.
*
* @param _id - Numeric split identifier.
* @returns The {@link SplitRecord}, or `null` if it does not exist.
*
* @example
* ```ts
* const split = await client.splitter.getSplit(2n);
* console.log('Distributed:', split?.distributed);
* ```
*/
async getSplit(_id: bigint): Promise<SplitRecord | null> {
// TODO: implement
void this.config;
void this.server;
throw new VeriTixError(
VeriTixErrorCode.NotImplemented,
'SplitterModule.getSplit: not implemented'
);
}
/**
* Returns all split IDs created by a given sender address.
*
* @param _sender - Stellar account address of the sender.
* @returns Array of split IDs.
*
* @example
* ```ts
* const ids = await client.splitter.getSplitsBySender('GABC…');
* console.log('Splits created:', ids.length);
* ```
*/
async getSplitsBySender(_sender: string): Promise<bigint[]> {
return [];
}
/**
* Returns all split IDs in which `address` is a recipient.
*
* @param address - Stellar account address of the recipient.
* @returns Array of split IDs.
*
* @example
* ```ts
* const ids = await client.splitter.getSplitsForRecipient('GABC…');
* ```
*/
async getSplitsForRecipient(address: string): Promise<bigint[]> {
const sourceAccount = new Account(DUMMY_PUBLIC_KEY, '0');
const tx = await buildContractCall(
this.server,
sourceAccount,
this.config.contractId,
'get_splits_for_recipient',
[addressToScVal(address)],
this.config.networkPassphrase,
);
const rawResult = await this.server.simulateTransaction(tx);
if (SorobanRpc.Api.isSimulationError(rawResult)) {
throw parseSorobanError(rawResult.error);
}
const retval = rawResult.result?.retval;
if (!retval) return [];
const vec = (retval as any).vec as any[];
return vec.map((v) => scValToBigint(v));
}
/**
* Validates a list of recipients without submitting a transaction.
* Checks for duplicate addresses, non-positive shares, >20 recipients, and
* total bps != 10 000.
*
* @param recipients - Array of {@link SplitRecipient} to validate.
* @returns `{ valid, errors }`.
*
* @example
* ```ts
* const { valid, errors } = client.splitter.validateRecipients([
* { address: 'GABC…', shareBps: 5000 },
* { address: 'GXYZ…', shareBps: 5000 },
* ]);
* if (!valid) console.error(errors);
* ```
*/
validateRecipients(recipients: SplitRecipient[]): ValidationResult {
const errors: string[] = [];
recipients.forEach((r, i) => {
if (r.shareBps <= 0) errors.push(`Recipient #${i + 1} has non-positive shareBps`);
});
const seen = new Set<string>();
recipients.forEach((r) => {
const lc = r.address.toLowerCase();
if (seen.has(lc)) errors.push(`Duplicate address: ${r.address}`);
seen.add(lc);
});
if (recipients.length > 20) errors.push(`Too many recipients: ${recipients.length} (max 20)`);
const totalBps = recipients.reduce((sum, r) => sum + r.shareBps, 0);
if (totalBps !== 10_000) errors.push(`Total basis points must equal 10 000, got ${totalBps}`);
return { valid: errors.length === 0, errors };
}
/**
* Returns aggregate splitter statistics.
*
* @returns Object with `totalSplits`, `distributedCount`, `cancelledCount`, and `totalDistributedValue`.
* @throws {VeriTixError} If the contract returns no data or an unexpected format.
*
* @example
* ```ts
* const stats = await client.splitter.getSplitterStats();
* console.log('Total splits:', stats.totalSplits);
* ```
*/
async getSplitterStats(): Promise<{
totalSplits: number;
distributedCount: number;
cancelledCount: number;
totalDistributedValue: bigint;
}> {
const sourceAccount = new Account(DUMMY_PUBLIC_KEY, '0');
const tx = await buildContractCall(
this.server,
sourceAccount,
this.config.contractId,
'get_splitter_stats',
[],
this.config.networkPassphrase,
);
const raw = await this.server.simulateTransaction(tx);
if (SorobanRpc.Api.isSimulationError(raw)) {
throw parseSorobanError(raw.error);
}
const returnValue =
SorobanRpc.Api.isSimulationSuccess(raw) && raw.result ? raw.result.retval : undefined;
if (!returnValue || returnValue.switch() === xdr.ScValType.scvVoid()) {
throw new VeriTixError(VeriTixErrorCode.Unknown, 'SplitterModule.getSplitterStats: no data returned');
}
if (returnValue.switch() !== xdr.ScValType.scvMap()) {
throw new VeriTixError(VeriTixErrorCode.Unknown, 'SplitterModule.getSplitterStats: expected ScMap result');
}
const map = returnValue.map() ?? [];
const get = (key: string): xdr.ScVal | undefined =>
map.find((e) => e.key().sym() === key)?.val();
const totalSplitsVal = get('total_splits');
const distributedCountVal = get('distributed_count');
const cancelledCountVal = get('cancelled_count');
const totalDistributedValueVal = get('total_distributed_value');
if (!totalSplitsVal || !distributedCountVal || !cancelledCountVal || !totalDistributedValueVal) {
throw new VeriTixError(VeriTixErrorCode.Unknown, 'SplitterModule.getSplitterStats: incomplete stats map');
}
return {
totalSplits: scValToNumber(totalSplitsVal),
distributedCount: scValToNumber(distributedCountVal),
cancelledCount: scValToNumber(cancelledCountVal),
totalDistributedValue: scValToBigint(totalDistributedValueVal),
};
}
/**
* Creates a new payment split instruction on-chain.
* Recipient `shareBps` values must sum to exactly 10 000.
*
* @param params - `{ recipients, totalAmount }`.
* @returns A {@link TransactionResult} on success.
*
* @example
* ```ts
* await client.splitter.createSplit({
* recipients: [
* { address: 'GABC…', shareBps: 7000 },
* { address: 'GXYZ…', shareBps: 3000 },
* ],
* totalAmount: 10_000_000n,
* });
* ```
*/
async createSplit(params: CreateSplitParams): Promise<TransactionResult> {
if (!this.keypair) {
throw new VeriTixError(VeriTixErrorCode.ReadOnlyClient, 'A Keypair is required for write operations.');
}
const totalBps = params.recipients.reduce((s, r) => s + r.shareBps, 0);
if (totalBps !== 10_000) {
throw new VeriTixError(VeriTixErrorCode.SplitInvalidShares, 'Recipient shares must sum to 10 000 basis points.');
}
// TODO: build & submit contract call
void simulateTransaction;
void submitTransaction;
throw new VeriTixError(
VeriTixErrorCode.NotImplemented,
'SplitterModule.createSplit: not implemented'
);
}
/**
* Convenience wrapper that creates a three-way revenue split between
* organizer, artist, and platform.
* The platform's share is `10 000 - organizerBps - artistBps`.
*
* @param params - {@link RevenueSplitParams}
* @returns A {@link TransactionResult} on success.
*
* @deprecated Since 0.2.0 — use {@link createSplit} with an explicit
* `recipients` array instead. `createRevenueSplit` is a thin wrapper
* that only supports a fixed three-party split and will be removed in
* 0.3.0. Migrate to:
* ```ts
* await client.splitter.createSplit({
* recipients: [
* { address: organizer, shareBps: organizerBps },
* { address: artist, shareBps: artistBps },
* { address: platform, shareBps: 10_000 - organizerBps - artistBps },
* ],
* totalAmount,
* });
* ```
*
* @example
* ```ts
* // ❌ Deprecated — will be removed in 0.3.0
* await client.splitter.createRevenueSplit({
* organizer: 'GORG…', organizerBps: 6000,
* artist: 'GART…', artistBps: 3000,
* platform: 'GPLT…',
* totalAmount: 20_000_000n,
* });
* ```
*/
async createRevenueSplit(params: RevenueSplitParams): Promise<TransactionResult> {
const { organizer, organizerBps, artist, artistBps, platform, totalAmount } = params;
const totalBps = organizerBps + artistBps;
if (totalBps >= 10_000) {
throw new VeriTixError(VeriTixErrorCode.SplitInvalidShares, 'organizerBps + artistBps must be < 10 000.');
}
const recipients: SplitRecipient[] = [
{ address: organizer, shareBps: organizerBps },
{ address: artist, shareBps: artistBps },
{ address: platform, shareBps: 10_000 - totalBps },
];
return this.createSplit({ recipients, totalAmount });
}
/**
* Returns a preview of how a revenue split would distribute funds to recipients,
* without performing any on-chain mutation. Useful for estimating payouts before
* committing to a split.
*
* @param params - Revenue split parameters (organizer, artist, platform, totalAmount).
* @returns Array of recipient addresses with their calculated share amounts.
*
* @example
* ```ts
* const preview = await client.splitter.getRevenueSharePreview({
* organizer: 'GABC…', organizerBps: 4000,
* artist: 'GXYZ…', artistBps: 3500,
* platform: 'GDEF…', totalAmount: 10_000_000n,
* });
* preview.forEach(r => console.log(`${r.address}: ${r.amount}`));
* ```
*/
getRevenueSharePreview(params: RevenueSplitParams): Array<{ address: string; amount: bigint }> {
const { organizer, organizerBps, artist, artistBps, platform, totalAmount } = params;
const platformBps = 10_000 - organizerBps - artistBps;
return [
{ address: organizer, amount: (totalAmount * BigInt(organizerBps)) / 10_000n },
{ address: artist, amount: (totalAmount * BigInt(artistBps)) / 10_000n },
{ address: platform, amount: (totalAmount * BigInt(platformBps)) / 10_000n },
];
}
/**
* Replaces a compromised recipient address in an existing split.
* Must be called by the split sender.
*
* @param splitId - The split ID containing the recipient to replace.
* @param oldRecipient - The current recipient address to replace.
* @param newRecipient - The new recipient address.
* @returns A {@link TransactionResult} on success.
* @throws {Error} If no signing keypair is available.
*
* @example
* ```ts
* await client.splitter.replaceRecipient(2n, 'GOLD…', 'NEW…');
* ```
*/
async replaceRecipient(
splitId: bigint,
oldRecipient: string,
newRecipient: string,
): Promise<TransactionResult> {
if (!this.keypair) {
throw new VeriTixError(VeriTixErrorCode.ReadOnlyClient, 'SplitterModule.replaceRecipient: signing keypair required');
}
const sender = this.keypair.publicKey();
const tx = await buildContractCall(
this.server,
new Account(sender, '0'),
this.config.contractId,
'replace_recipient',
[
bigintToScVal(splitId, 'u64'),
addressToScVal(oldRecipient),
addressToScVal(newRecipient),
],
this.config.networkPassphrase,
);
const raw = await this.server.simulateTransaction(tx);
if (SorobanRpc.Api.isSimulationError(raw)) {
throw parseSorobanError(raw.error);
}
const returnValue =
SorobanRpc.Api.isSimulationSuccess(raw) && raw.result ? raw.result.retval : undefined;
const assembled = SorobanRpc.assembleTransaction(tx, raw).build();
const result = await submitTransaction(this.server, assembled, this.keypair);
return {
...result,
returnValue,
};
}
/**
* Distributes the split funds to all recipients on-chain.
*
* @param _id - Numeric split identifier.
* @returns A {@link TransactionResult} on success.
*
* @example
* ```ts
* const result = await client.splitter.distribute(2n);
* console.log('Distributed in tx:', result.hash);
* ```
*/
async distribute(_id: bigint): Promise<TransactionResult> {
void this.server;
void _id;
throw new VeriTixError(
VeriTixErrorCode.NotImplemented,
'SplitterModule.distribute: not implemented'
);
}
/**
* Distributes multiple splits in a single transaction. Collects failures
* without throwing — returns a summary of results.
*
* @param ids - Array of numeric split identifiers to distribute.
* @returns Summary with distributed and failed split IDs.
*
* @example
* ```ts
* const { distributed, failed } = await client.splitter.bulkDistribute([1n, 2n, 3n]);
* ```
*/
async bulkDistribute(_ids: bigint[]): Promise<{ distributed: bigint[]; failed: bigint[] }> {
if (!this.keypair) {
throw new VeriTixError(VeriTixErrorCode.ReadOnlyClient, 'A Keypair is required for write operations.');
}
const distributed: bigint[] = [];
const failed: bigint[] = [];
for (const id of _ids) {
try {
await this.distribute(id);
distributed.push(id);
} catch {
failed.push(id);
}
}
return { distributed, failed };
}
}