Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/builder.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { StrKey, Address, Memo, SorobanRpc, nativeToScVal } from '@stellar/stellar-sdk';

Check warning on line 1 in src/builder.ts

View workflow job for this annotation

GitHub Actions / Lint & typecheck

'SorobanRpc' import from '@stellar/stellar-sdk' is restricted. SorobanRpc is deprecated in @stellar/stellar-sdk v12. Import rpc instead
import { bigintSafeStringify, toStroops, isValidAddress } from './utils.js';
import {
boolToScVal,
Expand Down Expand Up @@ -149,17 +149,17 @@
* @returns The builder instance for chaining.
*/
amount(val: number | bigint | string): this {
let normalized: number | bigint = typeof val === 'string' ? Number(val.trim()) : val;

Check warning on line 152 in src/builder.ts

View workflow job for this annotation

GitHub Actions / Lint & typecheck

Ensure you are not calling Number() on stroop or amount values. These are u128 values that must use BigInt or string arithmetic to avoid precision loss (e.g., Number(stroopAmount), Number(depositAmount))
if (typeof val === 'string') {
const trimmed = val.trim();
if (/^-?\d+$/.test(trimmed)) {
try {
normalized = BigInt(trimmed);
} catch {
normalized = Number(trimmed);

Check warning on line 159 in src/builder.ts

View workflow job for this annotation

GitHub Actions / Lint & typecheck

Ensure you are not calling Number() on stroop or amount values. These are u128 values that must use BigInt or string arithmetic to avoid precision loss (e.g., Number(stroopAmount), Number(depositAmount))
}
} else {
normalized = Number(trimmed);

Check warning on line 162 in src/builder.ts

View workflow job for this annotation

GitHub Actions / Lint & typecheck

Ensure you are not calling Number() on stroop or amount values. These are u128 values that must use BigInt or string arithmetic to avoid precision loss (e.g., Number(stroopAmount), Number(depositAmount))
}
}
if (typeof normalized === 'bigint') {
Expand All @@ -184,17 +184,17 @@
* @returns The builder instance for chaining.
*/
ratePerSecond(val: number | bigint | string): this {
let normalized: number | bigint = typeof val === 'string' ? Number(val.trim()) : val;

Check warning on line 187 in src/builder.ts

View workflow job for this annotation

GitHub Actions / Lint & typecheck

Ensure you are not calling Number() on stroop or amount values. These are u128 values that must use BigInt or string arithmetic to avoid precision loss (e.g., Number(stroopAmount), Number(depositAmount))
if (typeof val === 'string') {
const trimmed = val.trim();
if (/^-?\d+$/.test(trimmed)) {
try {
normalized = BigInt(trimmed);
} catch {
normalized = Number(trimmed);

Check warning on line 194 in src/builder.ts

View workflow job for this annotation

GitHub Actions / Lint & typecheck

Ensure you are not calling Number() on stroop or amount values. These are u128 values that must use BigInt or string arithmetic to avoid precision loss (e.g., Number(stroopAmount), Number(depositAmount))
}
} else {
normalized = Number(trimmed);

Check warning on line 197 in src/builder.ts

View workflow job for this annotation

GitHub Actions / Lint & typecheck

Ensure you are not calling Number() on stroop or amount values. These are u128 values that must use BigInt or string arithmetic to avoid precision loss (e.g., Number(stroopAmount), Number(depositAmount))
}
}
if (typeof normalized === 'bigint') {
Expand Down Expand Up @@ -258,6 +258,53 @@
return this;
}

/**
* Sets the vesting cliff from a `Date`, an ISO/date string, or Unix seconds.
*
* A vesting cliff is a client-side scheduling convention, not contract state:
* the stream's `startTime` is set to the cliff end, so nothing accrues before
* it. This is the same model documented for `CliffReached` in `events.ts` and
* used by `examples/vesting-schedule.ts`. Equivalent to calling
* {@link startTime} with the resolved timestamp; prefer this method when the
* cliff is expressed as a calendar date, since it removes the manual
* second-conversion (and the timezone/DST mistakes that go with it).
*
* @param date - A `Date`, an ISO-8601/date string, or a non-negative integer
* Unix timestamp in seconds.
* @returns The builder instance for chaining.
* @throws {Error} If the value cannot be resolved to a valid Unix timestamp,
* or if the resolved cliff is in the past (same rule as {@link startTime}).
*/
withCliffDate(date: Date | string | number): this {
let seconds: number;

if (date instanceof Date) {
seconds = Math.floor(date.getTime() / 1000);
} else if (typeof date === 'number') {
seconds = date;
} else if (typeof date === 'string') {
const trimmed = date.trim();
if (trimmed === '') {
throw new Error('Invalid StreamBuilder parameter: withCliffDate received an empty string');
}
seconds = /^\d+$/.test(trimmed)
? Number(trimmed)

Check warning on line 291 in src/builder.ts

View workflow job for this annotation

GitHub Actions / Lint & typecheck

Ensure you are not calling Number() on stroop or amount values. These are u128 values that must use BigInt or string arithmetic to avoid precision loss (e.g., Number(stroopAmount), Number(depositAmount))
: Math.floor(new Date(trimmed).getTime() / 1000);
} else {
throw new Error(
'Invalid StreamBuilder parameter: withCliffDate expects a Date, an ISO date string, or Unix seconds',
);
}

if (!Number.isFinite(seconds)) {
throw new Error(
`Invalid StreamBuilder parameter: withCliffDate could not resolve a valid date from ${String(date)}`,
);
}

return this.startTime(seconds);
}

/** Sets whether the stream may be cancelled after creation. */
setCancelable(cancelable: boolean): this {
if (typeof cancelable !== 'boolean') {
Expand Down
128 changes: 128 additions & 0 deletions src/tests/builder-cliff-date.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import { describe, it, expect } from 'vitest';
import { StreamBuilder } from '../builder.js';

const TOKEN = 'CAAQCAIBAEAQCAIBAEAQCAIBAEAQCAIBAEAQCAIBAEAQCAIBAEAQC526';
const SENDER = 'GAAQCAIBAEAQCAIBAEAQCAIBAEAQCAIBAEAQCAIBAEAQCAIBAEAQDZ7H';
const RECIPIENT = 'GABAEAQCAIBAEAQCAIBAEAQCAIBAEAQCAIBAEAQCAIBAEAQCAIBAEJXA';

/** Timestamp for "now + days", so tests never depend on a fixed wall clock. */
function inDays(days: number): number {
return Math.floor(Date.now() / 1000) + days * 86_400;
}

function baseBuilder(): StreamBuilder {
return new StreamBuilder().token(TOKEN).sender(SENDER).recipient(RECIPIENT).amount(1000);
}

describe('StreamBuilder.withCliffDate', () => {
it('accepts a Date object and stores it as Unix seconds in startTime', () => {
const cliff = new Date(inDays(30) * 1000);
const config = baseBuilder().withCliffDate(cliff).build();

expect(config.startTime).toBe(Math.floor(cliff.getTime() / 1000));
});

it('accepts an ISO-8601 string', () => {
const iso = new Date(inDays(10) * 1000).toISOString();
const config = baseBuilder().withCliffDate(iso).build();

expect(config.startTime).toBe(Math.floor(new Date(iso).getTime() / 1000));
});

it('accepts a date-only string (YYYY-MM-DD)', () => {
const config = baseBuilder().withCliffDate('2030-01-15').build();

expect(config.startTime).toBe(Math.floor(new Date('2030-01-15').getTime() / 1000));
});

it('accepts a raw numeric Unix timestamp', () => {
const seconds = inDays(45);
const config = baseBuilder().withCliffDate(seconds).build();

expect(config.startTime).toBe(seconds);
});

it('accepts a numeric string as Unix seconds, not as a year', () => {
const seconds = String(inDays(60));
const config = baseBuilder().withCliffDate(seconds).build();

// A naive `new Date("1893456000")` would parse as a year; digit strings
// must be read as absolute seconds instead.
expect(config.startTime).toBe(Number(seconds));
});

it('truncates sub-second precision from a Date', () => {
const cliff = new Date(inDays(5) * 1000 + 750);
const config = baseBuilder().withCliffDate(cliff).build();

expect(config.startTime).toBe(inDays(5));
expect(Number.isInteger(config.startTime)).toBe(true);
});

it('is chainable and equivalent to startTime(seconds)', () => {
const seconds = inDays(20);
const viaCliff = baseBuilder().withCliffDate(seconds).build();
const viaStart = baseBuilder().startTime(seconds).build();

expect(viaCliff).toEqual(viaStart);
});

it('produces the same contract arguments as startTime for a cliff', () => {
const seconds = inDays(30);
const withCliff = baseBuilder()
.ratePerSecond(10)
.withCliffDate(seconds)
.toContractArgs();
const withStart = baseBuilder().ratePerSecond(10).startTime(seconds).toContractArgs();

expect(withCliff).toEqual(withStart);
});

it('rejects a cliff in the past', () => {
expect(() => baseBuilder().withCliffDate(new Date(Date.now() - 86_400_000))).toThrow(
/startTime cannot be in the past/,
);
});

it('rejects an empty or blank string', () => {
expect(() => baseBuilder().withCliffDate('')).toThrow(/empty string/);
expect(() => baseBuilder().withCliffDate(' ')).toThrow(/empty string/);
});

it('rejects an unparseable string', () => {
expect(() => baseBuilder().withCliffDate('not-a-real-date')).toThrow(
/could not resolve a valid date/,
);
});

it('rejects an invalid Date instance', () => {
expect(() => baseBuilder().withCliffDate(new Date('nope'))).toThrow(
/could not resolve a valid date/,
);
});

it('rejects a non-integer timestamp passed as a number', () => {
expect(() => baseBuilder().withCliffDate(inDays(10) + 0.5)).toThrow(
/non-negative integer Unix timestamp/,
);
});

it('rejects a negative timestamp', () => {
expect(() => baseBuilder().withCliffDate(-1)).toThrow(/non-negative integer Unix timestamp/);
});

it('is cleared by reset()', () => {
const builder = baseBuilder().withCliffDate(inDays(15));
builder.reset().token(TOKEN).sender(SENDER).recipient(RECIPIENT).amount(1000);

expect(builder.build().startTime).toBeUndefined();
});

it('is preserved by clone()', () => {
const seconds = inDays(25);
const original = baseBuilder().withCliffDate(seconds);
const copy = original.clone();

expect(copy.build().startTime).toBe(seconds);
});
});
Loading