Skip to content

Commit 01f3f2d

Browse files
authored
Add Support for Custom TTL (#1)
1 parent 42451ea commit 01f3f2d

File tree

1 file changed

+7
-7
lines changed

1 file changed

+7
-7
lines changed

src/index.ts

+7-7
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import type { CID } from 'multiformats/cid'
1616

1717
const log = logger('ipns')
1818
const ID_MULTIHASH_CODE = identity.code
19+
const DEFAULT_TTL = BigInt(3.6e+12) // 1 Hour or 3600 Seconds
1920

2021
export const namespace = '/ipns/'
2122
export const namespaceLength = namespace.length
@@ -127,6 +128,7 @@ export interface IDKeys {
127128
}
128129

129130
export interface CreateOptions {
131+
lifetimeNs?: bigint
130132
v1Compatible?: boolean
131133
}
132134

@@ -139,7 +141,8 @@ export interface CreateV2Options {
139141
}
140142

141143
const defaultCreateOptions: CreateOptions = {
142-
v1Compatible: true
144+
v1Compatible: true,
145+
lifetimeNs: DEFAULT_TTL
143146
}
144147

145148
/**
@@ -166,8 +169,7 @@ export async function create (peerId: PeerId, value: CID | PeerId | string, seq:
166169
// Validity in ISOString with nanoseconds precision and validity type EOL
167170
const expirationDate = new NanoDate(Date.now() + Number(lifetime))
168171
const validityType = IpnsEntry.ValidityType.EOL
169-
const [ms, ns] = lifetime.toString().split('.')
170-
const lifetimeNs = (BigInt(ms) * BigInt(100000)) + BigInt(ns ?? '0')
172+
const lifetimeNs = typeof options.lifetimeNs === "bigint" ? options.lifetimeNs : DEFAULT_TTL
171173

172174
return _create(peerId, value, seq, validityType, expirationDate, lifetimeNs, options)
173175
}
@@ -194,11 +196,9 @@ export async function createWithExpiration (peerId: PeerId, value: CID | PeerId
194196
export async function createWithExpiration (peerId: PeerId, value: CID | PeerId | string, seq: number | bigint, expiration: string, options: CreateOptions = defaultCreateOptions): Promise<IPNSRecord> {
195197
const expirationDate = NanoDate.fromString(expiration)
196198
const validityType = IpnsEntry.ValidityType.EOL
199+
const lifetimeNs = typeof options.lifetimeNs === "bigint" ? options.lifetimeNs : DEFAULT_TTL
197200

198-
const ttlMs = expirationDate.toDate().getTime() - Date.now()
199-
const ttlNs = (BigInt(ttlMs) * BigInt(100000)) + BigInt(expirationDate.getNano())
200-
201-
return _create(peerId, value, seq, validityType, expirationDate, ttlNs, options)
201+
return _create(peerId, value, seq, validityType, expirationDate, lifetimeNs, options)
202202
}
203203

204204
const _create = async (peerId: PeerId, value: CID | PeerId | string, seq: number | bigint, validityType: IpnsEntry.ValidityType, expirationDate: NanoDate, ttl: bigint, options: CreateOptions = defaultCreateOptions): Promise<IPNSRecord> => {

0 commit comments

Comments
 (0)