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

+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),
},
});
}
}