Initialize TypeScript library for Telegram Web App wallet integration

- Added configuration files: .eslintrc.js, .gitignore, .npmrc, .prettierrc, and multiple tsconfig files for different module systems.
- Created package.json with dependencies and scripts for building, testing, and publishing.
- Implemented core functionality in src/ directory, including wallet management, encryption, and storage handling.
- Added README.md for documentation on installation, usage, and development setup.
- Introduced initial types and constants for better type safety and code organization.
This commit is contained in:
odiinnn committed 2025-08-28 13:13:57 +03:00
commit a21ea39c36
19 files changed
+5094

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
module.exports = {
parser: '@typescript-eslint/parser',
extends: [
'eslint:recommended',
],
plugins: ['@typescript-eslint'],
env: {
node: true,
es6: true,
},
parserOptions: {
ecmaVersion: 2020,
sourceType: 'module',
},
rules: {
'@typescript-eslint/no-unused-vars': 'error',
'@typescript-eslint/explicit-function-return-type': 'warn',
'@typescript-eslint/no-explicit-any': 'warn',
'prefer-const': 'error',
'no-var': 'error',
'no-undef': 'off',
},
};
+41
View File
@@ -0,0 +1,41 @@
# Dependencies
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Build output
dist/
build/
# TypeScript
*.tsbuildinfo
# Environment variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# IDE
.vscode/
.idea/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
# Logs
logs
*.log
# Coverage
coverage/
.nyc_output
# Temporary files
*.tmp
*.temp
+12
View File
@@ -0,0 +1,12 @@
# NPM Configuration for @varan-wallet organization
registry=https://registry.npmjs.org/
@varan-wallet:registry=https://registry.npmjs.org/
# Ensure public access for scoped packages
access=public
# Save exact versions
save-exact=true
# Package lock file
package-lock=false
+8
View File
@@ -0,0 +1,8 @@
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2,
"useTabs": false
}
+163
View File
@@ -0,0 +1,163 @@
# @varan-wallet/varan-connect
A lightweight TypeScript library for Telegram Web App wallet integration with support for both CommonJS and ES modules.
## Installation
```bash
npm install @varan-wallet/varan-connect
# or
pnpm add @varan-wallet/varan-connect
# or
yarn add @varan-wallet/varan-connect
```
## Usage
### ES Modules (Recommended)
```typescript
import { injectVaranWallet } from '@varan-wallet/varan-connect';
import WebApp from '@twa-dev/sdk';
// Inject the Varan wallet into the window object
injectVaranWallet(WebApp);
// The wallet is now available at window.injectedWeb3.varan
const varanWallet = window.injectedWeb3?.varan;
if (varanWallet) {
// Connect to wallet
const connection = await varanWallet.connect();
// Get accounts
const accounts = await connection.accounts.get();
// Sign transactions
const signer = connection.signer;
const signature = await signer.signRaw({
address: '0x123...',
data: '0x456...'
});
}
```
### CommonJS
```javascript
const { injectVaranWallet } = require('@varan-wallet/varan-connect');
const WebApp = require('@twa-dev/sdk').default;
// Inject the Varan wallet
injectVaranWallet(WebApp);
// Use the injected wallet
const varanWallet = window.injectedWeb3?.varan;
```
## Module Support
This library supports both module systems:
- **ES Modules (ESM)**: Modern JavaScript modules using `import`/`export`
- **CommonJS (CJS)**: Node.js traditional modules using `require`/`module.exports`
The library automatically detects which module system you're using and provides the appropriate format.
## API
### `injectVaranWallet(webApp: WebApp): void`
Injects the Varan wallet into the window object for Telegram Web App integration.
**Parameters:**
- `webApp`: The Telegram Web App instance from `@twa-dev/sdk`
**Returns:** `void`
## Types
The library exports comprehensive TypeScript types:
- `WebApp` - Telegram Web App interface from `@twa-dev/sdk`
- `InjectedWindow` - Extended window interface with injected wallet from `@polkadot/extension-inject`
- `ConnectRequest`, `SignTransactionRequest` - Request interfaces
- `ConnectResult`, `SignTransactionResult` - Result interfaces
- `InjectionConfig` - Configuration options for wallet injection
## Dependencies
**Runtime Dependencies:**
- `@twa-dev/sdk` - Telegram Web App SDK
**Development Dependencies:**
- `@polkadot/extension-inject` - Polkadot extension injection types
- `@polkadot/types` - Polkadot types
- TypeScript for compilation
- ESLint for code quality
- Prettier for code formatting
- Jest for testing
## Build Outputs
The library provides multiple build outputs:
- `dist/esm/` - ES Modules build (`.mjs` compatible)
- `dist/cjs/` - CommonJS build (Node.js compatible)
- `dist/types/` - TypeScript type definitions
## Development
### Setup
```bash
pnpm install
```
### Build
```bash
pnpm run build # Build all formats
pnpm run build:esm # Build ES modules only
pnpm run build:cjs # Build CommonJS only
pnpm run build:types # Build types only
```
### Development mode
```bash
pnpm run dev
```
### Testing
```bash
pnpm test
```
### Linting
```bash
pnpm run lint
```
### Formatting
```bash
pnpm run format
```
### Publishing
```bash
# Publish with automatic version bumping
pnpm run publish:patch # 1.0.0 -> 1.0.1
pnpm run publish:minor # 1.0.0 -> 1.1.0
pnpm run publish:major # 1.0.0 -> 2.0.0
# Manual publish (after building)
pnpm publish
```
## License
MIT
+78
View File
@@ -0,0 +1,78 @@
{
"name": "@varan-wallet/varan-connect",
"version": "1.0.0",
"description": "A lightweight TypeScript library for Telegram Web App wallet integration with support for both CommonJS and ES modules.",
"type": "commonjs",
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"types": "dist/types/index.d.ts",
"exports": {
".": {
"import": "./dist/esm/index.js",
"require": "./dist/cjs/index.js",
"types": "./dist/types/index.d.ts"
}
},
"files": [
"dist"
],
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
},
"scripts": {
"build": "pnpm run build:cjs && pnpm run build:esm && pnpm run build:types",
"build:cjs": "tsc -p tsconfig.cjs.json",
"build:esm": "tsc -p tsconfig.esm.json",
"build:types": "tsc -p tsconfig.types.json",
"dev": "pnpm run build:esm --watch",
"clean": "rimraf dist",
"prebuild": "pnpm run clean",
"prepublishOnly": "pnpm run build && pnpm run test",
"publish:patch": "pnpm version patch && pnpm publish",
"publish:minor": "pnpm version minor && pnpm publish",
"publish:major": "pnpm version major && pnpm publish",
"test": "jest",
"lint": "eslint src --ext .ts",
"format": "prettier --write \"src/**/*.ts\""
},
"keywords": [
"typescript",
"library",
"telegram",
"webapp",
"wallet",
"injection",
"blockchain",
"polkadot"
],
"author": "",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://gitlab.mind-dev.com/varan-wallet/varan-connect.git"
},
"bugs": {
"url": "https://gitlab.mind-dev.com/varan-wallet/varan-connect/issues"
},
"homepage": "https://gitlab.mind-dev.com/varan-wallet/varan-connect#readme",
"dependencies": {
"@twa-dev/sdk": "^8.0.2"
},
"devDependencies": {
"@polkadot/extension-inject": "^0.61.6",
"@polkadot/types": "^16.4.5",
"@types/node": "^20.0.0",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"eslint": "^8.0.0",
"jest": "^29.0.0",
"prettier": "^3.0.0",
"rimraf": "^5.0.0",
"ts-jest": "^29.0.0",
"typescript": "^5.0.0"
},
"engines": {
"node": ">=16.0.0"
}
}
+4217
View File
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
export const VARAN_WALLET_LS_KEY = 'VARAN_WALLET';
window.addEventListener('storage', (ev) => {
if (ev.storageArea !== localStorage || ev.key !== VARAN_WALLET_LS_KEY) return;
})
+19
View File
@@ -0,0 +1,19 @@
import type { ConnectRequest, ConnectResult, SignTransactionRequest, SignTransactionResult } from "./types";
export const encodeRequest = (request: ConnectRequest | SignTransactionRequest): string => {
const jsonString = JSON.stringify(request);
const base64String = btoa(jsonString);
return base64String.replace(/\//g, '_');
};
export const decodeResult = (encodedResult: string): ConnectResult | SignTransactionResult => {
try {
const base64String = encodedResult.replace(/_/g, '/');
const paddedBase64 = base64String + '='.repeat((4 - (base64String.length % 4)) % 4);
const jsonString = atob(paddedBase64);
return JSON.parse(jsonString) as ConnectResult | SignTransactionResult;
} catch (error) {
console.error('Error decoding result:', error);
return { success: false, error: 'Failed to decode result' };
}
};
+21
View File
@@ -0,0 +1,21 @@
import { decodeResult } from "./encryption";
import type { ConnectResult, SignTransactionResult, WebApp } from "./types";
export const parseWalletsFromStartParam = (webApp: WebApp): ConnectResult['wallets'] | null => {
const startParam = webApp.initDataUnsafe?.start_param;
if (!startParam) return null;
const result = decodeResult(startParam);
console.log('parseWalletsFromStartParam', result);
return 'wallets' in result ? result.wallets : null;
};
export const parseSignedTxFromStartParam = (webApp: WebApp): SignTransactionResult | null => {
const startParam = webApp.initDataUnsafe?.start_param;
if (!startParam) return null;
const result = decodeResult(startParam);
return 'signedTx' in result ? result : null;
};
export const generateRequestId = (): number => Math.floor(Math.random() * 90000) + 10000;
+1
View File
@@ -0,0 +1 @@
export { injectVaranWallet } from './varan-wallet';
+140
View File
@@ -0,0 +1,140 @@
import type { InjectedMetadataKnown } from "@polkadot/extension-inject/types";
import { VARAN_WALLET_LS_KEY } from "./constants";
import { generateRequestId } from "./helpers";
import { WalletStorage } from "./types";
type WalletStoreType = {
accounts: string[];
injectedMetadataKnown?: InjectedMetadataKnown;
transactions: {
id: number;
signedTx: string;
status: 'signing' | 'success' | 'failed';
}[];
}
const defaultStore: WalletStoreType = {
accounts: [],
injectedMetadataKnown: undefined,
transactions: [],
}
export class WalletStore {
constructor(
private readonly store: WalletStorage,
) {
this._setupListeners();
}
private callbacks: {
[K in keyof WalletStoreType]: ({
cb: (value: WalletStoreType[K]) => void,
id: number;
})[];
} = {
accounts: [],
injectedMetadataKnown: [],
transactions: [],
};
private get _store(): WalletStoreType {
return JSON.parse(this.store.getItem(VARAN_WALLET_LS_KEY) || '{}') as WalletStoreType;
}
private _setupListeners(): void {
let currentState = this._store;
this.store.subscribe(ev => {
ev.stopImmediatePropagation();
if (ev.key !== VARAN_WALLET_LS_KEY) return;
const data = JSON.parse(ev.newValue || '{}') as WalletStoreType;
currentState = data;
const keys = Object.keys(data) as (keyof WalletStoreType)[];
for (const key of keys) {
if (key === 'injectedMetadataKnown') continue;
if (key === 'accounts') {
const currentAccounts = currentState[key];
const dataAccounts = data[key];
if (currentAccounts.length !== dataAccounts.length) {
this.dispatch(key);
continue;
}
let shouldDispatch = false;
dataAccounts.forEach(account => {
if (!currentAccounts.includes(account)) {
shouldDispatch = true;
}
});
if (shouldDispatch) {
this.dispatch(key);
}
continue;
}
if (key === 'transactions') {
const currentTransactions = currentState[key];
const dataTransactions = data[key];
if (currentTransactions.length !== dataTransactions.length) {
this.dispatch(key);
continue;
}
let shouldDispatch = false;
dataTransactions.forEach(transaction => {
if (!currentTransactions.find(t => t.id === transaction.id)) {
shouldDispatch = true;
}
});
if (shouldDispatch) {
this.dispatch(key);
}
continue;
}
}
});
}
private dispatch<Key extends keyof WalletStoreType>(key: Key): void {
const callbacks = this.callbacks[key];
if (!callbacks || callbacks.length === 0) return;
callbacks.forEach(c => c.cb(this._store[key]));
}
get<Key extends keyof WalletStoreType>(key: Key): WalletStoreType[Key] {
return this._store[key];
}
set<Key extends keyof WalletStoreType>(key: Key, value: WalletStoreType[Key]): void {
this._store[key] = value;
this.store.setItem(VARAN_WALLET_LS_KEY, JSON.stringify(this._store));
}
remove<Key extends keyof WalletStoreType>(key: Key): void {
const value = this._store[key];
if (value) {
this._store[key] = defaultStore[key];
}
this.store.setItem(VARAN_WALLET_LS_KEY, JSON.stringify(this._store));
}
clear(): void {
this.store.removeItem(VARAN_WALLET_LS_KEY);
}
subscribe<Key extends keyof WalletStoreType>(key: Key, cb: (value: WalletStoreType[Key]) => void): number {
if (this.callbacks[key] == undefined) {
this.callbacks[key] = [];
}
const id = generateRequestId();
this.callbacks[key].push({cb, id});
return id;
}
unsubscribe<Key extends keyof WalletStoreType>(key: Key, id: number): void {
if (this.callbacks[key] == undefined || this.callbacks[key].length === 0) return;
const filtered = this.callbacks[key].filter(c => c.id !== id);
this.callbacks[key] = filtered as typeof this.callbacks[Key];
}
}
+44
View File
@@ -0,0 +1,44 @@
import { default as WebAppConst } from "@twa-dev/sdk";
import type { InjectedWindow } from "@polkadot/extension-inject/types";
declare global {
interface Window extends InjectedWindow {}
}
export type WalletStorage = Storage & {
subscribe: (cb: (ev: StorageEvent) => void) => void;
}
export type InjectionConfig = {
callbackUrl: string;
isDev?: boolean;
connectTimeout?: number;
storage?: WalletStorage;
}
export type WebApp = typeof WebAppConst;
export interface ConnectRequest {
method: 'connect';
callback: string;
}
export interface SignTransactionRequest {
method: 'signTransaction';
id: number;
tx: string;
wallet: string;
callback: string;
}
export interface ConnectResult {
success: boolean;
wallets?: string[];
error?: string;
}
export interface SignTransactionResult {
success: boolean;
id: number;
signedTx?: string;
error?: string;
}
+30
View File
@@ -0,0 +1,30 @@
import type { WebApp, InjectionConfig } from './types';
import { Wallet } from './wallet';
const defaultInjectionConfig: Required<InjectionConfig> = {
get callbackUrl(): string {
throw new Error('Callback URL must be provided to injectVaranWallet');
},
isDev: false,
connectTimeout: 30_000,
storage: {
...localStorage,
subscribe: (cb) => {
window.addEventListener('storage', cb);
},
} ,
}
const injectVaranWallet = (webApp: WebApp, config: InjectionConfig = defaultInjectionConfig): void => {
const isInTelegram = webApp.platform !== 'unknown';
if (!isInTelegram) return;
const wallet = new Wallet(webApp, { ...defaultInjectionConfig, ...config });
window.injectedWeb3 = {
varan: wallet,
}
};
export { injectVaranWallet };
+169
View File
@@ -0,0 +1,169 @@
import type { ConnectRequest, SignTransactionRequest, WebApp } from "./types";
import type { InjectionConfig } from "./types";
import { WalletStore } from "./store";
import type { InjectedAccount, InjectedExtension, InjectedWindowProvider } from "@polkadot/extension-inject/types";
import { encodeRequest } from "./encryption";
import { SignerPayloadRaw, SignerResult } from "@polkadot/types/types";
import { generateRequestId, parseSignedTxFromStartParam, parseWalletsFromStartParam } from "./helpers";
export class Wallet implements InjectedWindowProvider {
private readonly varanWalletUrl!: string;
private readonly store: WalletStore;
private readonly name = 'Varan Wallet';
private readonly callbackUrl: string;
private readonly connectTimeout: number;
constructor(
private readonly webApp: WebApp,
{ callbackUrl, isDev, connectTimeout, storage }: Required<InjectionConfig>,
) {
this.varanWalletUrl = isDev ? 'https://t.me/devReptileBot?startapp=' : 'https://t.me/varanwalletbot?startapp=';
this.store = new WalletStore(storage);
this.callbackUrl = callbackUrl;
this.connectTimeout = connectTimeout;
void this._startParamsCheck();
}
get version(): string {
return '1.0.0';
}
private async _startParamsCheck(): Promise<void> {
let actions = 0;
const newWalletAddresses = parseWalletsFromStartParam(this.webApp);
const currentAccounts = await this.accounts;
if (newWalletAddresses) {
const allWallets = Array.from(
new Set(
currentAccounts
.map(a => a.address)
.concat(newWalletAddresses)
)
)
this.store.set('accounts', allWallets);
actions += 1;
}
const tx = parseSignedTxFromStartParam(this.webApp);
if (tx) {
const currentTransactions = this.store.get('transactions');
const pendingTransactionIndex = currentTransactions.findIndex(t => t.id === tx.id && t.status === 'signing');
if (pendingTransactionIndex === -1) return;
currentTransactions[pendingTransactionIndex] = {
...currentTransactions[pendingTransactionIndex],
status: tx.success ? 'success' : 'failed',
signedTx: tx.signedTx ? tx.signedTx : '',
};
this.store.set('transactions', currentTransactions);
actions += 1;
}
if (actions) {
this.webApp.close();
}
}
private formatAccount(account: string): InjectedAccount {
return {
address: account,
name: account.slice(0, 6) + '...' + account.slice(-4),
};
}
get accounts(): Promise<InjectedAccount[]> {
const accounts = this.store.get('accounts');
return Promise.resolve(accounts.map(this.formatAccount));
}
private async signRawTransaction(raw: SignerPayloadRaw): Promise<SignerResult> {
const accounts = await this.accounts;
if (!accounts.length) throw new Error('No accounts found');
const address = accounts.find(a => a.address === raw.address);
if (!address) throw new Error('Provided account was not found');
const request: SignTransactionRequest = {
method: 'signTransaction',
tx: raw.data,
wallet: raw.address,
callback: this.callbackUrl,
id: generateRequestId(),
};
const encodedRequest = encodeRequest(request);
const botUrl = `${this.varanWalletUrl}${encodedRequest}`;
this.store.set('transactions', [{
id: request.id,
signedTx: '',
status: 'signing',
}]);
this.webApp.openTelegramLink(botUrl);
return new Promise<SignerResult>((resolve) => {
const id = this.store.subscribe('transactions', (transactions) => {
const pendingTransaction = transactions.find(t => t.id === request.id && t.status === 'signing');
if (pendingTransaction) {
this.store.unsubscribe('transactions', id);
resolve({
id: pendingTransaction.id,
signature: pendingTransaction.signedTx,
} as SignerResult);
}
});
});
}
private async _connect(): Promise<void> {
const request: ConnectRequest = {
method: 'connect',
callback: this.callbackUrl,
};
const encodedRequest = encodeRequest(request);
const botUrl = `${this.varanWalletUrl}${encodedRequest}`;
await this.webApp.openTelegramLink(botUrl);
return new Promise<void>((resolve) => {
const id = this.store.subscribe('accounts', (accounts) => {
if (accounts.length) {
this.store.unsubscribe('accounts', id);
resolve();
}
});
});
}
async connect(): Promise<InjectedExtension> {
await Promise.race([
this._connect(),
new Promise<void>((_, reject) => {
setTimeout(() => {
reject(new Error('Connect timeout'));
}, this.connectTimeout);
})
]);
return Promise.resolve({
name: this.name,
version: this.version,
accounts: {
get: () => this.accounts,
subscribe: () => {
return () => {};
},
},
signer: {
signRaw: (raw) => this.signRawTransaction(raw),
},
});
}
}
+32
View File
@@ -0,0 +1,32 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020", "DOM"],
"declaration": false,
"declarationMap": false,
"sourceMap": true,
"outDir": "./dist/cjs",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"noEmit": false
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"dist",
"**/*.test.ts",
"**/*.spec.ts"
]
}
+32
View File
@@ -0,0 +1,32 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"target": "ES2020",
"module": "ES2020",
"lib": ["ES2020", "DOM"],
"declaration": false,
"declarationMap": false,
"sourceMap": true,
"outDir": "./dist/esm",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"noEmit": false
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"dist",
"**/*.test.ts",
"**/*.spec.ts"
]
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"target": "ES2020",
"lib": ["ES2020", "DOM"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"dist",
"**/*.test.ts",
"**/*.spec.ts"
]
}
+33
View File
@@ -0,0 +1,33 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"target": "ES2020",
"module": "ES2020",
"lib": ["ES2020", "DOM"],
"declaration": true,
"declarationMap": true,
"sourceMap": false,
"outDir": "./dist/types",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"emitDeclarationOnly": true,
"noEmit": false
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"dist",
"**/*.test.ts",
"**/*.spec.ts"
]
}