Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
lukachi committed Aug 7, 2023
1 parent ea233bf commit 7dfe781
Show file tree
Hide file tree
Showing 106 changed files with 8,185 additions and 970 deletions.
2 changes: 1 addition & 1 deletion .swcrc
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"@/*": ["src/*"]
}
},
"exclude": ["examples","src/tests", ".test.ts"],
"exclude": ["examples", "src/tests", ".test.ts"],
"minify": false,
"sourceMaps": "inline"
}
5 changes: 5 additions & 0 deletions packages/lightspark-wallet-sdk/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
src/**/*.test.ts
jest.config.js
tsconfig.json
tsconfig.build.json
postbuild.js
52 changes: 52 additions & 0 deletions packages/lightspark-wallet-sdk/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# @distributedlab/tools
These packages aim to provide developers with a set of commonly used functions and features for building web applications, such as handling big numbers, date manipulation, subscribing to and receiving notifications when certain events occur with EventEmitter, and more.

![version (scoped package)](https://badgen.net/npm/v/@distributedlab/tools)
![types](https://badgen.net/npm/types/@distributedlab/tools)
![tree-shaking](https://badgen.net/bundlephobia/tree-shaking/@distributedlab/tools)
![checks](https://badgen.net/github/checks/distributed-lab/web-kit/main)

## Getting Started

### Installing

```
yarn add @distributedlab/tools
```

#### Work with big numbers
BN uses 26 (yoctoNEAR + 2 (percent precision)) maximum precision by default.
You can change it by `BN.setConfig` method.

```ts
import { BN } from '@distributedlab/tools';

const amountA = BN.fromRaw(2, 18)
const amountB = BN.fromRaw(3, 18)

console.log(amountA.add(amountB).format({
decimals: 18,
decimalSeparator: '.',
groupSeparator: ',',
groupSize: 3,
}))
```

#### Work with dates
```ts
import { time } from '@distributedlab/tools';

const currentDate = time()

console.log(currentDate.format('YYYY-MM-DD'))
```

## Running the tests

```
yarn test
```

## License

This project is licensed under the MIT License - see the [LICENSE.md](../../LICENSE) file for details
35 changes: 35 additions & 0 deletions packages/lightspark-wallet-sdk/helpers/authHelpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright ©, 2023-present, Lightspark Group, Inc. - All Rights Reserved

export type EnvCredentials = {
accountId: string
jwt: string
pubKey?: string
privKey?: string
baseUrl: string
jwtSigningPrivateKey?: string
}

export const getCredentialsFromEnvOrThrow = (
walletEnvSuffix = ``,
): EnvCredentials => {
const accountId = process.env[`LIGHTSPARK_ACCOUNT_ID`]
const jwtSigningPrivateKey = process.env[`LIGHTSPARK_JWT_PRIV_KEY`]
const jwt = process.env[`LIGHTSPARK_JWT${walletEnvSuffix}`]
const pubKey = process.env[`LIGHTSPARK_WALLET_PUB_KEY${walletEnvSuffix}`]
const privKey = process.env[`LIGHTSPARK_WALLET_PRIV_KEY${walletEnvSuffix}`]
const baseUrl =
process.env[`LIGHTSPARK_EXAMPLE_BASE_URL`] || `api.lightspark.com`
if (!accountId || !jwt) {
throw new Error(
`Missing test credentials. Please set LIGHTSPARK_ACCOUNT_ID and LIGHTSPARK_JWT.`,
)
}
return {
accountId,
jwt,
pubKey,
privKey,
baseUrl,
jwtSigningPrivateKey,
}
}
3 changes: 3 additions & 0 deletions packages/lightspark-wallet-sdk/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
...require('../../jest.config.base.js'),
};
68 changes: 68 additions & 0 deletions packages/lightspark-wallet-sdk/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
{
"name": "@distributedlab/lightspark-wallet-sdk",
"version": "1.0.0-rc.4",
"description": "Wallet SDK for lightning network by Lightspark",
"repository": {
"type": "git",
"url": "https://github.com/distributed-lab/web-kit.git",
"directory": "packages/tools"
},
"homepage": "https://distributed-lab.github.io/web-kit/modules/_distributedlab_lightspark_wallet_sdk.html",
"license": "MIT",
"sideEffects": false,
"typesVersions": {
">=4.2": {
"*": [
"./dist/types/*"
]
}
},
"main": "./dist/cjs/index.js",
"module": "./dist/esm/index.js",
"browser": "./dist/esm/index.js",
"node": "./dist/cjs/index.js",
"unpkg": "./dist/index.js",
"types": "index.d.ts",
"exports": {
".": {
"types": "./dist/types/index.d.ts",
"require": "./dist/cjs/index.js",
"node": "./dist/cjs/index.js",
"import": "./dist/esm/index.js",
"default": "./dist/esm/index.js"
}
},
"scripts": {
"build": "yarn clean && yarn build:types && yarn build:cjs && yarn build:esm && node ./postbuild.js",
"build:types": "tsc -p tsconfig.build.json --outDir ./dist/types --declaration --emitDeclarationOnly",
"build:cjs": "npx swc src -d ./dist/cjs --config-file ../../.swcrc -C module.type=commonjs",
"build:esm": "npx swc src -d ./dist/esm --config-file ../../.swcrc -C module.type=es6 isModule=true",
"clean": "rm -rf dist",
"test": "yarn jest --verbose",
"typecheck": "tsc --noEmit"
},
"publishConfig": {
"access": "public"
},
"devDependencies": {
"@swc/cli": "^0.1.62",
"@swc/core": "^1.3.53",
"@swc/jest": "^0.2.26",
"@types/jest": "^29.5.1",
"@types/node": "^18.14.2",
"jest": "^29.5.0",
"tsc-alias": "^1.8.2"
},
"dependencies": {
"@lightsparkdev/core": "^0.3.9",
"@react-native-async-storage/async-storage": "^1.19.1",
"bignumber.js": "^9.1.1",
"dayjs": "^1.11.7",
"tslib": "^2.5.0"
},
"typedoc": {
"entryPoint": "./src/index.ts",
"readmeFile": "./README.md",
"displayName": "@distributedlab/tools"
}
}
3 changes: 3 additions & 0 deletions packages/lightspark-wallet-sdk/postbuild.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const postbuild = require('../../scripts/postbuild');

postbuild(__dirname)
136 changes: 136 additions & 0 deletions packages/lightspark-wallet-sdk/src/__tests__/general.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { describe, expect, test } from '@jest/globals'

// import { DefaultCrypto } from '@lightsparkdev/core'
import { LightsparkClient } from '@/client'
import {
type InvoiceData,
// KeyType,
TransactionStatus,
WalletStatus,
WithdrawalRequestStatus,
} from '@/objects'

import { getCredentialsFromEnvOrThrow } from '../../helpers/authHelpers'

describe('Sanity tests', () => {
getCredentialsFromEnvOrThrow('_testUser1')

// Let's start by creating a client
const client = new LightsparkClient()

console.log(client)

test('should deploy the wallet', async () => {
const walletStatus: WalletStatus =
await client.deployWalletAndAwaitDeployed()

expect(walletStatus).toBe(WalletStatus.DEPLOYED)
})

test('should init the wallet', async () => {
// const keyPair = await DefaultCrypto.generateSigningKeyPair()
// const signingWalletPublicKey = keyPair.publicKey
// const signingWalletPrivateKey = keyPair.privateKey

// const walletStatus = await client.initializeWalletAndAwaitReady(
// KeyType.RSA_OAEP,
// signingWalletPublicKey as string,
// {
// key: signingWalletPrivateKey as string,
// },
// )

// expect(walletStatus).toBe(WalletStatus.READY)

expect(1).toBe(1)
})

let invoiceData: InvoiceData | null

test('should create an invoice', async () => {
const _invoiceData = await client.createInvoice(100_000, 'mmmmm pizza')

invoiceData = _invoiceData as InvoiceData | null

expect(invoiceData).not.toBe(null)
})

test('should pay an invoice', async () => {
if (!invoiceData?.encodedPaymentRequest)
throw new Error('invoiceData is null')

const payment = await client.payInvoice(
invoiceData.encodedPaymentRequest,
50_000,
)

expect(payment.status).toBe(TransactionStatus.SUCCESS)

expect(1).toBe(1)
})

test('should deposit', async () => {
expect(1).toBe(1)
})

test('should withdraw', async () => {
const withdrawalRequest = await client.requestWithdrawal(
50_000,
'bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq',
)

expect(withdrawalRequest?.status).toBe(WithdrawalRequestStatus.SUCCESSFUL)
})
})

describe('P1 tests', () => {
test('should generate a key', async () => {
expect(1).toBe(1)
})

test('should fetch the current wallet', async () => {
expect(1).toBe(1)
})

test('should list current payment requests', async () => {
expect(1).toBe(1)
})

test('should list recent transactions', async () => {
expect(1).toBe(1)
})

test('should fetch an entity by ID', async () => {
expect(1).toBe(1)
})

test('should terminate a wallet', async () => {
expect(1).toBe(1)
})

test('should decode an invoice', async () => {
expect(1).toBe(1)
})
})

describe('P2 tests', () => {
test('should get bitcoin fee estimates', async () => {
expect(1).toBe(1)
})

test('should send a keysend payment', async () => {
expect(1).toBe(1)
})

test('should create a test mode invoice', async () => {
expect(1).toBe(1)
})

test('should create a test mode payment', async () => {
expect(1).toBe(1)
})

test('should execute a raw graphql query', async () => {
expect(1).toBe(1)
})
})
1 change: 1 addition & 0 deletions packages/lightspark-wallet-sdk/src/auth/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './jwt'
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Copyright ©, 2023-present, Lightspark Group, Inc. - All Rights Reserved

import { type AuthProvider } from '@lightsparkdev/core'

import type { JwtStorage, JwtTokenInfo } from '@/auth'

/**
* A custom [AuthProvider] that uses a JWT token to authenticate requests.
*
* Should generally not be used directly by clients, but rather through the [loginWithJwt] method of a
* [LightsparkWalletClient].
*
* @param tokenStorage A [JwtStorage] implementation that stores or retrieves the current JWT token info.
*/
export class CustomJwtAuthProvider implements AuthProvider {
constructor(private jwtStorage: JwtStorage) {}

public async setTokenInfo(tokenInfo: JwtTokenInfo): Promise<void> {
await this.jwtStorage.replace(tokenInfo)
}

public async logout(): Promise<void> {
await this.jwtStorage.clear()
}

public async addAuthHeaders(headers: any): Promise<any> {
const tokenInfo = await this.jwtStorage.getCurrent()
if (!tokenInfo) {
return headers
}
return Object.assign({}, headers, {
authorization: `Bearer ${tokenInfo.accessToken}`,
})
}

public async isAuthorized(): Promise<boolean> {
const tokenInfo = await this.jwtStorage.getCurrent()
if (!tokenInfo) {
return false
}
return tokenInfo.validUntil > new Date()
}

public async addWsConnectionParams(params: any) {
const tokenInfo = await this.jwtStorage.getCurrent()
if (!tokenInfo) {
return params
}
return Object.assign({}, params, {
access_token: tokenInfo.accessToken,
})
}
}
22 changes: 22 additions & 0 deletions packages/lightspark-wallet-sdk/src/auth/jwt/InMemoryJwtStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Copyright ©, 2023-present, Lightspark Group, Inc. - All Rights Reserved

import type { JwtStorage, JwtTokenInfo } from '@/auth'

/**
* In-memory implementation of {@link JwtStorage}.
*/
export class InMemoryJwtStorage implements JwtStorage {
private tokenInfo: JwtTokenInfo | null = null

async getCurrent(): Promise<JwtTokenInfo | null> {
return this.tokenInfo
}

async replace(tokenInfo: JwtTokenInfo): Promise<void> {
this.tokenInfo = tokenInfo
}

async clear(): Promise<void> {
this.tokenInfo = null
}
}
Loading

0 comments on commit 7dfe781

Please sign in to comment.