Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/timestamps #6

Open
wants to merge 7 commits into
base: develop
Choose a base branch
from
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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ node_modules/
build/
package/
.idea/
.vscode/
.vscode/
*.wat
75 changes: 75 additions & 0 deletions as-pect.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
module.exports = {
/**
* A set of globs passed to the glob package that qualify typescript files for testing.
*/
include: ["lib/__tests__/**/*.spec.ts"],
/**
* A set of globs passed to the glob package that quality files to be added to each test.
*/
add: ["lib/__tests__/**/*.include.ts"],
/**
* All the compiler flags needed for this test suite. Make sure that a binary file is output.
*/
flags: {
// "--debug": [],
/** This is required. Do not change this. The filename is ignored, but required by the compiler. */
"--binaryFile": ["output.wasm"],
/** To enable wat file output, use the following flag. The filename is ignored, but required by the compiler. */
"--textFile": ["output.wat"],
"--runtime": ["stub"], // Acceptable values are: full, half, stub (arena), and none,
"--baseDir": process.cwd(),
// "--runPasses": ["dce"]
},
/**
* A set of regexp that will disclude source files from testing.
*/
disclude: [/node_modules/],
/**
* Add your required AssemblyScript imports here.
*/
imports: {
'graph-ts': './node_modules/@graphprotocol/graph-ts'
},
/**
* All performance statistics reporting can be configured here.
*/
performance: {
/** Enable performance statistics gathering. */
enabled: false,
/** Set the maximum number of samples to run for each test. */
maxSamples: 10000,
/** Set the maximum test run time in milliseconds. */
maxTestRunTime: 2000,
/** Set the number of decimal places to round to. */
roundDecimalPlaces: 3,
/** Report the median time in the default reporter. */
reportMedian: true,
/** Report the average time in milliseconds. */
reportAverage: true,
/** Report the standard deviation. */
reportStandardDeviation: false,
/** Report the maximum run time in milliseconds. */
reportMax: false,
/** Report the minimum run time in milliseconds. */
reportMin: false,
/** Report the variance. */
reportVariance: false,
},
/**
* Add a custom reporter here if you want one. The following example is in typescript.
*
* @example
* import { TestReporter, TestGroup, TestResult, TestContext } from "as-pect";
*
* export class CustomReporter extends TestReporter {
* // implement each abstract method here
* public abstract onStart(suite: TestContext): void;
* public abstract onGroupStart(group: TestGroup): void;
* public abstract onGroupFinish(group: TestGroup): void;
* public abstract onTestStart(group: TestGroup, result: TestResult): void;
* public abstract onTestFinish(group: TestGroup, result: TestResult): void;
* public abstract onFinish(suite: TestContext): void;
* }
*/
// reporter: new CustomReporter(),
};
5 changes: 4 additions & 1 deletion index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
export * from './lib'
export * from './lib/constants'
export * from './lib/metrics'
export * from './lib/utils'
export * from './src/date'
1 change: 1 addition & 0 deletions lib/__tests__/as-pect.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="@as-pect/assembly/types/as-pect" />
35 changes: 35 additions & 0 deletions lib/__tests__/date.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import {datetime, Timestamp} from "../../lib/date"

// Tuesday, March 29, 2022 12:00:00 PM
var timestamp: i64 = 1648555200

describe("datetime test group", () => {
it("should truncate five minutes", () => {
// Tuesday, March 29, 2022 11:55:00 AM -> 1648554900
let truncateFiveMinutes = datetime.truncateMinutes(timestamp, 5)
assert(truncateFiveMinutes == 1648554900, `Actual value ${truncateFiveMinutes}`);
})

it("should truncate an hour", () => {
// Tuesday, March 29, 2022 11:00:00 AM -> 1648551600
let truncateAnHour = datetime.truncateHours(timestamp, 1)
assert(truncateAnHour == 1648551600, `Actual value ${truncateAnHour}`);
})

it("should truncate a day", () => {
// Monday, March 28, 2022 12:00:00 PM -> 1648468800
let truncateADay = datetime.truncateDays(timestamp, 1)
assert(truncateADay == 1648468800, `Actual value ${truncateADay}`);
})

it("should truncate a week", () => {
// Tuesday, March 22, 2022 12:00:00 PM -> 1647950400
let truncateAWeek = datetime.truncateWeeks(timestamp, 1)
assert(truncateAWeek == 1647950400, `Actual value ${truncateAWeek}`);
})

it("should have date string from timestamp", () => {
let timestampClass = new Timestamp(timestamp)
assert(timestampClass.toString() == '2022-3-29', `Actual value ${timestampClass}`)
})
})
6 changes: 6 additions & 0 deletions lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,9 @@ export const ZERO_HASH = HASH_ZERO

export const MAX_UINT_256 = '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'
export const MAX_UINT = MAX_UINT_256

// Time
export const SECONDS_IN_MINUTE = 60
export const SECONDS_IN_HOUR = SECONDS_IN_MINUTE * 60
export const SECONDS_IN_DAY = SECONDS_IN_HOUR * 24
export const SECONDS_IN_WEEK = SECONDS_IN_DAY * 7
54 changes: 54 additions & 0 deletions lib/date.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import {SECONDS_IN_MINUTE, SECONDS_IN_HOUR, SECONDS_IN_DAY, SECONDS_IN_WEEK} from './constants'

var truncateDate: (timestamp: i64, interval: i32) => i64 =
(timestamp: i64, interval: i32): i64 => {
return interval == 0 ? timestamp : timestamp - interval
}

export namespace datetime {
export function truncateMinutes(timestamp: i64, minutes: i32 = 0): i64 {
return truncateDate(timestamp, minutes * SECONDS_IN_MINUTE)
}

export function truncateHours(timestamp: i64, hours: i32 = 0): i64 {
return truncateDate(timestamp, hours * SECONDS_IN_HOUR)
}

export function truncateDays(timestamp: i64, days: i32 = 0): i64 {
return truncateDate(timestamp, days * SECONDS_IN_DAY)
}

export function truncateWeeks(timestamp: i64, weeks: i32 = 0): i64 {
return truncateDate(timestamp, weeks * SECONDS_IN_WEEK)
}
}

export class Timestamp {
private currentDate: Date;

constructor(private timestamp: i64) {
this.currentDate = new Date(timestamp * 1000)
}

// Ported from http://howardhinnant.github.io/date_algorithms.html#civil_from_days
toString(): String {
var time = this.currentDate.getTime() / 1000
// you can have leap seconds apparently - but this is good enough for us ;)
let daysSinceEpochStart = time / SECONDS_IN_DAY;
daysSinceEpochStart = daysSinceEpochStart + 719468;

let era = (daysSinceEpochStart >= 0 ? daysSinceEpochStart : daysSinceEpochStart -146096) /146097;
let dayOfEra = (daysSinceEpochStart - era * 146097); // [0, 146096]
let yearOfEra = (dayOfEra - dayOfEra/1460 + dayOfEra/36524 - dayOfEra/146096) / 365; // [0, 399]

let year = yearOfEra + (era * 400);
let dayOfYear = dayOfEra - (365*yearOfEra + yearOfEra/4 - yearOfEra/100); // [0, 365]
let monthZeroIndexed = (5 * dayOfYear + 2) / 153; // [0, 11]
let day = dayOfYear - (153 * monthZeroIndexed + 2) / 5 + 1; // [1, 31]
let month = monthZeroIndexed + (monthZeroIndexed < 10 ? 3 : -9); // [1, 12]

year = month <= 2 ? year + 1 : year;

return year.toString().concat("-").concat(month.toString()).concat("-").concat(day.toString())
}
}
3 changes: 0 additions & 3 deletions lib/index.ts

This file was deleted.

4 changes: 4 additions & 0 deletions lib/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "assemblyscript/std/assembly.json",
"include": ["./**/*.ts", "../index.ts"]
}
2 changes: 1 addition & 1 deletion lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export namespace bytes {
}

export function toUnsignedInt(value: Bytes, bigEndian: boolean = true): BigInt {
return BigInt.fromUnsignedBytes(bigEndian ? (value.reverse() as Bytes) : value)
return BigInt.fromUnsignedBytes(bigEndian ? Bytes.fromUint8Array(value.reverse()) : value)
}

// Helpers
Expand Down
22 changes: 13 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
{
"name": "@protofire/subgraph-toolkit",
"version": "0.1.2",
"version": "0.1.3",
"description": "AssemblyScript helpers for writing subgraph mappings for The Graph",
"repository": "https://github.com/protofire/subgraph-toolkit.git",
"license": "GPL-3.0-only",
"author": "Sebastián Galiano",
"module": "index.ts",
"types": "index.ts",
"dependencies": {
"@protofire/subgraph-prettier-config": "^0.1.1"
"main": "index.ts",
"scripts": {
"lint": "eslint --max-warnings 0 --ext ts \"assembly/**/*.ts\"",
"lint:fix": "yarn lint --fix",
"test": "asp"
},
"devDependencies": {
"@as-pect/cli": "^6.2.4",
"@graphprotocol/graph-ts": ">=0.20.0",
"prettier": "2.1.2"
},
"peerDependencies": {
"@graphprotocol/graph-ts": ">=0.20.0"
"@typescript-eslint/eslint-plugin": "^4.16.0",
"@typescript-eslint/parser": "^4.16.0",
"assemblyscript": "^0.19.3",
"eslint": "^7.21.0",
"typescript": "^4.1.3"
}
}
}
39 changes: 39 additions & 0 deletions src/date.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import * as as from '../lib/date'
import { BigInt } from '@graphprotocol/graph-ts'

interface DateOperations {
truncateMinutes(minutes?: BigInt): BigInt
truncateHours(hours?: BigInt): BigInt
truncateDays(days?: BigInt): BigInt
truncateWeeks(weeks?: BigInt): BigInt
}

class Date implements DateOperations {
private timestamp: BigInt

constructor(value: BigInt) {
this.timestamp = value
}

truncateMinutes(minutes: BigInt = BigInt.zero()): BigInt {
let newtimestamp = as.datetime.truncateMinutes(this.timestamp.toI64(), minutes.toI32())
return BigInt.fromI64(newtimestamp)
}

truncateHours(hours: BigInt = BigInt.zero()): BigInt {
let newtimestamp = as.datetime.truncateHours(this.timestamp.toI64(), hours.toI32())
return BigInt.fromI64(newtimestamp)
}

truncateDays(days: BigInt = BigInt.zero()): BigInt {
let newtimestamp = as.datetime.truncateDays(this.timestamp.toI64(), days.toI32())
return BigInt.fromI64(newtimestamp)
}

truncateWeeks(weeks: BigInt = BigInt.zero()): BigInt {
let newtimestamp = as.datetime.truncateWeeks(this.timestamp.toI64(), weeks.toI32())
return BigInt.fromI64(newtimestamp)
}
}

export class Datetime extends Date {}
5 changes: 0 additions & 5 deletions tsconfig.json

This file was deleted.

Loading