diff --git a/src/components/wallet/HEZStakingModal.tsx b/src/components/wallet/HEZStakingModal.tsx
index b5a2e5f..b681acc 100644
--- a/src/components/wallet/HEZStakingModal.tsx
+++ b/src/components/wallet/HEZStakingModal.tsx
@@ -133,6 +133,10 @@ export function HEZStakingModal({ isOpen, onClose }: HEZStakingModalProps) {
} finally {
setIsLoading(false);
}
+ // `t` is intentionally omitted: it is only used for error messages and its
+ // identity changes only on language switch — including it would re-run the
+ // blockchain fetch (extra RPC calls) on every language change.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [assetHubApi, address]);
useEffect(() => {
diff --git a/src/components/wallet/LPStakingModal.tsx b/src/components/wallet/LPStakingModal.tsx
index d036c88..153ff90 100644
--- a/src/components/wallet/LPStakingModal.tsx
+++ b/src/components/wallet/LPStakingModal.tsx
@@ -179,6 +179,10 @@ export function LPStakingModal({ isOpen, onClose }: LPStakingModalProps) {
};
fetchPools();
+ // `t` is intentionally omitted: it is only used for error messages and its
+ // identity changes only on language switch — including it would re-run the
+ // blockchain fetch (extra RPC calls) on every language change.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [assetHubApi, isOpen, address, selectedPool]);
const formatAmount = (amount: string, decimals: number = 12): string => {
diff --git a/src/components/wallet/PoolsModal.tsx b/src/components/wallet/PoolsModal.tsx
index 90c649a..cde404e 100644
--- a/src/components/wallet/PoolsModal.tsx
+++ b/src/components/wallet/PoolsModal.tsx
@@ -50,6 +50,26 @@ const formatAssetLocation = (id: number) => {
return { parents: 0, interior: { X2: [{ PalletInstance: 50 }, { GeneralIndex: id }] } };
};
+// Minimal shapes for the dynamic @pezkuwi/api results we read here. These
+// pallets/runtime-calls are not in the base typings, so we describe just the
+// fields actually used and cast via `as unknown as`.
+type AccountInfoResult = { data: { free: { toString(): string } } };
+type AssetAccountResult = {
+ isSome: boolean;
+ unwrap(): { balance: { toString(): string } };
+};
+type QuoteResult = { isNone: boolean; unwrap(): { toString(): string } };
+type AssetConversionCall = {
+ assetConversionApi: {
+ quotePriceExactTokensForTokens: (
+ asset0: ReturnType,
+ asset1: ReturnType,
+ amount: string,
+ includeFee: boolean
+ ) => Promise;
+ };
+};
+
export function PoolsModal({ isOpen, onClose }: PoolsModalProps) {
const { assetHubApi, keypair } = useWallet();
const { hapticImpact, hapticNotification } = useTelegram();
@@ -104,17 +124,17 @@ export function PoolsModal({ isOpen, onClose }: PoolsModalProps) {
// Fetch HEZ balance from Asset Hub (native token)
const hezAccount = (await withTimeout(
- (assetHubApi.query.system as any).account(keypair.address),
+ assetHubApi.query.system.account(keypair.address),
10000
- )) as any;
+ )) as unknown as AccountInfoResult;
if (isCancelled) return;
const hezFree = hezAccount.data.free.toString();
setBalances((prev) => ({ ...prev, HEZ: (parseInt(hezFree) / 1e12).toFixed(4) }));
const pezResult = (await withTimeout(
- (assetHubApi.query.assets as any).account(1, keypair.address),
+ assetHubApi.query.assets.account(1, keypair.address),
10000
- )) as any;
+ )) as unknown as AssetAccountResult;
if (isCancelled) return;
if (pezResult.isSome) {
setBalances((prev) => ({
@@ -126,9 +146,9 @@ export function PoolsModal({ isOpen, onClose }: PoolsModalProps) {
}
const usdtResult = (await withTimeout(
- (assetHubApi.query.assets as any).account(1000, keypair.address),
+ assetHubApi.query.assets.account(1000, keypair.address),
10000
- )) as any;
+ )) as unknown as AssetAccountResult;
if (isCancelled) return;
if (usdtResult.isSome) {
setBalances((prev) => ({
@@ -175,7 +195,9 @@ export function PoolsModal({ isOpen, onClose }: PoolsModalProps) {
const oneUnit = BigInt(Math.pow(10, token0.decimals));
const quote = await withTimeout(
- (assetHubApi.call as any).assetConversionApi.quotePriceExactTokensForTokens(
+ (
+ assetHubApi.call as unknown as AssetConversionCall
+ ).assetConversionApi.quotePriceExactTokensForTokens(
formatAssetLocation(asset0),
formatAssetLocation(asset1),
oneUnit.toString(),
@@ -184,11 +206,8 @@ export function PoolsModal({ isOpen, onClose }: PoolsModalProps) {
10000
);
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- if (quote && !(quote as any).isNone) {
- price =
- Number(BigInt((quote as any).unwrap().toString())) /
- Math.pow(10, token1.decimals);
+ if (quote && !quote.isNone) {
+ price = Number(BigInt(quote.unwrap().toString())) / Math.pow(10, token1.decimals);
// Estimate reserves from LP supply
const lpAsset = await withTimeout(
@@ -283,6 +302,10 @@ export function PoolsModal({ isOpen, onClose }: PoolsModalProps) {
return () => {
isCancelled = true;
};
+ // `t` is intentionally omitted: it is only used for error messages and its
+ // identity changes only on language switch — including it would re-run the
+ // blockchain fetch (extra RPC calls) on every language change.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [isOpen, assetHubApi, keypair]);
// Auto-calculate amount1 based on pool price
@@ -326,28 +349,36 @@ export function PoolsModal({ isOpen, onClose }: PoolsModalProps) {
keypair.address
);
+ // Minimal shape of the signAndSend result fields we read. `asModule`
+ // is typed from the registry call so it stays type-safe.
+ type TxResult = {
+ status: { isFinalized: boolean };
+ dispatchError?: {
+ isModule: boolean;
+ asModule: Parameters[0];
+ toString(): string;
+ };
+ };
+
// Wait for transaction to be finalized
await new Promise((resolve, reject) => {
- tx.signAndSend(
- keypair,
- ({ status, dispatchError }: { status: any; dispatchError: any }) => {
- if (status.isFinalized) {
- if (dispatchError) {
- let errorMsg = t('pools.addFailed');
- if (dispatchError.isModule) {
- const decoded = assetHubApi.registry.findMetaError(dispatchError.asModule);
- errorMsg = `${decoded.section}.${decoded.name}: ${decoded.docs.join(' ')}`;
- } else if (dispatchError.toString) {
- errorMsg = dispatchError.toString();
- }
- console.error('Add liquidity error:', errorMsg);
- reject(new Error(errorMsg));
- } else {
- resolve();
+ tx.signAndSend(keypair, ({ status, dispatchError }: TxResult) => {
+ if (status.isFinalized) {
+ if (dispatchError) {
+ let errorMsg = t('pools.addFailed');
+ if (dispatchError.isModule) {
+ const decoded = assetHubApi.registry.findMetaError(dispatchError.asModule);
+ errorMsg = `${decoded.section}.${decoded.name}: ${decoded.docs.join(' ')}`;
+ } else if (dispatchError.toString) {
+ errorMsg = dispatchError.toString();
}
+ console.error('Add liquidity error:', errorMsg);
+ reject(new Error(errorMsg));
+ } else {
+ resolve();
}
}
- ).catch(reject);
+ }).catch(reject);
});
setSuccessMessage(
@@ -420,28 +451,36 @@ export function PoolsModal({ isOpen, onClose }: PoolsModalProps) {
keypair.address
);
+ // Minimal shape of the signAndSend result fields we read. `asModule`
+ // is typed from the registry call so it stays type-safe.
+ type TxResult = {
+ status: { isFinalized: boolean };
+ dispatchError?: {
+ isModule: boolean;
+ asModule: Parameters[0];
+ toString(): string;
+ };
+ };
+
// Wait for transaction to be finalized
await new Promise((resolve, reject) => {
- tx.signAndSend(
- keypair,
- ({ status, dispatchError }: { status: any; dispatchError: any }) => {
- if (status.isFinalized) {
- if (dispatchError) {
- let errorMsg = t('pools.removeFailed');
- if (dispatchError.isModule) {
- const decoded = assetHubApi.registry.findMetaError(dispatchError.asModule);
- errorMsg = `${decoded.section}.${decoded.name}: ${decoded.docs.join(' ')}`;
- } else if (dispatchError.toString) {
- errorMsg = dispatchError.toString();
- }
- console.error('Remove liquidity error:', errorMsg);
- reject(new Error(errorMsg));
- } else {
- resolve();
+ tx.signAndSend(keypair, ({ status, dispatchError }: TxResult) => {
+ if (status.isFinalized) {
+ if (dispatchError) {
+ let errorMsg = t('pools.removeFailed');
+ if (dispatchError.isModule) {
+ const decoded = assetHubApi.registry.findMetaError(dispatchError.asModule);
+ errorMsg = `${decoded.section}.${decoded.name}: ${decoded.docs.join(' ')}`;
+ } else if (dispatchError.toString) {
+ errorMsg = dispatchError.toString();
}
+ console.error('Remove liquidity error:', errorMsg);
+ reject(new Error(errorMsg));
+ } else {
+ resolve();
}
}
- ).catch(reject);
+ }).catch(reject);
});
setSuccessMessage(t('pools.removedLiquidity', { amount: lpAmountToRemove }));
diff --git a/src/components/wallet/SwapModal.tsx b/src/components/wallet/SwapModal.tsx
index 66e5bc3..403df85 100644
--- a/src/components/wallet/SwapModal.tsx
+++ b/src/components/wallet/SwapModal.tsx
@@ -74,10 +74,25 @@ export function SwapModal({ isOpen, onClose }: SwapModalProps) {
const hezFree = hezAccount.data.free.toString();
const hezBalance = (parseInt(hezFree) / 1e12).toFixed(4);
- // Helper to extract balance from asset query result
- const getAssetBalance = (result: any, decimals: number, fractionDigits: number): string => {
+ // Helper to extract balance from an asset storage query result. The
+ // shape is the subset of the @pezkuwi/api Option/Codec result we read.
+ type AssetQueryResult = {
+ isEmpty: boolean;
+ isSome?: boolean;
+ unwrap?: () => { toJSON(): unknown };
+ toJSON(): unknown;
+ };
+ const getAssetBalance = (
+ result: AssetQueryResult | null,
+ decimals: number,
+ fractionDigits: number
+ ): string => {
if (!result || result.isEmpty) return '0'.padEnd(fractionDigits + 2, '0');
- const data = result.isSome ? result.unwrap().toJSON() : result.toJSON();
+ const data = (
+ result.isSome && result.unwrap ? result.unwrap().toJSON() : result.toJSON()
+ ) as {
+ balance?: { toString(): string };
+ } | null;
if (data && data.balance) {
return (parseInt(data.balance.toString()) / Math.pow(10, decimals)).toFixed(
fractionDigits
@@ -155,8 +170,21 @@ export function SwapModal({ isOpen, onClose }: SwapModalProps) {
const decimals2 = getDecimals(asset2);
const oneUnit = BigInt(Math.pow(10, decimals1));
+ // assetConversionApi is a runtime API not present in the base
+ // @pezkuwi/api typings; describe just the call we use.
+ type QuoteResult = { isNone: boolean; unwrap(): { toString(): string } };
+ type AssetConversionCall = {
+ assetConversionApi: {
+ quotePriceExactTokensForTokens: (
+ asset1: ReturnType,
+ asset2: ReturnType,
+ amount: string,
+ includeFee: boolean
+ ) => Promise;
+ };
+ };
const quote = await (
- assetHubApi.call as any
+ assetHubApi.call as unknown as AssetConversionCall
).assetConversionApi.quotePriceExactTokensForTokens(
formatAssetLocation(asset1),
formatAssetLocation(asset2),
@@ -257,28 +285,38 @@ export function SwapModal({ isOpen, onClose }: SwapModalProps) {
true
);
+ // Minimal shape of the signAndSend result fields we read (the full
+ // @pezkuwi/api ISubmittableResult is unavailable because `tx` above is
+ // produced from an untyped runtime extrinsic).
+ type SwapDispatchError = {
+ isModule: boolean;
+ asModule: Parameters[0];
+ toString(): string;
+ };
+ type SwapTxResult = {
+ status: { isFinalized: boolean };
+ dispatchError?: SwapDispatchError;
+ };
+
// Wait for transaction to be finalized
await new Promise((resolve, reject) => {
- tx.signAndSend(
- keypair,
- ({ status, dispatchError }: { status: any; dispatchError: any }) => {
- if (status.isFinalized) {
- if (dispatchError) {
- let errorMsg = t('swap.swapFailed');
- if (dispatchError.isModule) {
- const decoded = assetHubApi.registry.findMetaError(dispatchError.asModule);
- errorMsg = `${decoded.section}.${decoded.name}: ${decoded.docs.join(' ')}`;
- } else if (dispatchError.toString) {
- errorMsg = dispatchError.toString();
- }
- console.error('Swap error:', errorMsg);
- reject(new Error(errorMsg));
- } else {
- resolve();
+ tx.signAndSend(keypair, ({ status, dispatchError }: SwapTxResult) => {
+ if (status.isFinalized) {
+ if (dispatchError) {
+ let errorMsg = t('swap.swapFailed');
+ if (dispatchError.isModule) {
+ const decoded = assetHubApi.registry.findMetaError(dispatchError.asModule);
+ errorMsg = `${decoded.section}.${decoded.name}: ${decoded.docs.join(' ')}`;
+ } else if (dispatchError.toString) {
+ errorMsg = dispatchError.toString();
}
+ console.error('Swap error:', errorMsg);
+ reject(new Error(errorMsg));
+ } else {
+ resolve();
}
}
- ).catch(reject);
+ }).catch(reject);
});
setSuccess(true);
diff --git a/src/components/wallet/WalletDashboard.tsx b/src/components/wallet/WalletDashboard.tsx
index 0849e7e..7abc57b 100644
--- a/src/components/wallet/WalletDashboard.tsx
+++ b/src/components/wallet/WalletDashboard.tsx
@@ -1103,14 +1103,23 @@ function SendTab({ onBack }: { onBack: () => void }) {
let tx;
if (selectedToken === 'HEZ') {
- // HEZ transfer on main chain
+ // HEZ transfer on main chain (api guaranteed by the guard above, but
+ // narrow again here so TS knows it is non-null in this branch).
+ if (!api) {
+ setError(t('send.mainnetApiNotReady'));
+ return;
+ }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- tx = (api!.tx.balances as any).transferKeepAlive(toAddress, amountInSmallestUnit);
+ tx = (api.tx.balances as any).transferKeepAlive(toAddress, amountInSmallestUnit);
} else {
// Asset transfer on Asset Hub (PEZ: asset ID 1, USDT: asset ID 1000)
+ if (!assetHubApi) {
+ setError(t('send.assetHubApiNotReady'));
+ return;
+ }
const assetId = tokenInfo?.assetId ?? 1;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- tx = (assetHubApi!.tx.assets as any).transfer(assetId, toAddress, amountInSmallestUnit);
+ tx = (assetHubApi.tx.assets as any).transfer(assetId, toAddress, amountInSmallestUnit);
}
const hash = await tx.signAndSend(keypair);
diff --git a/src/lib/referral.ts b/src/lib/referral.ts
index 8e8db78..982833b 100644
--- a/src/lib/referral.ts
+++ b/src/lib/referral.ts
@@ -73,7 +73,9 @@ export async function getPendingReferral(api: ApiPromise, address: string): Prom
try {
// Check if referral pallet exists
if (!isReferralPalletAvailable(api)) {
- console.log('Referral pallet not available on this chain');
+ if (import.meta.env.DEV) {
+ console.warn('Referral pallet not available on this chain');
+ }
return null;
}
diff --git a/src/lib/scores.ts b/src/lib/scores.ts
index 2d4c33b..a3855df 100644
--- a/src/lib/scores.ts
+++ b/src/lib/scores.ts
@@ -306,27 +306,33 @@ const TIKI_NAME_SCORES: Record = {
* Storage: tiki.userTikis(address) -> Vec
*/
export async function fetchUserTikis(peopleApi: ApiPromise, address: string): Promise {
+ // The `tiki` pallet is not part of the base @pezkuwi/api typings, so we
+ // describe just the storage entries we read here.
+ type TikiStorageResult = { isEmpty: boolean; toJSON(): unknown };
+ type TikiQuery = {
+ userTikis?: (address: string) => Promise;
+ userRoles?: (address: string) => Promise;
+ };
+ type TikiEntry = string | { name?: string; role?: string };
+
try {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- if (!(peopleApi?.query as any)?.tiki) {
+ const tikiQuery = (peopleApi?.query as { tiki?: TikiQuery } | undefined)?.tiki;
+ if (!tikiQuery) {
return [];
}
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- let result = await (peopleApi.query.tiki as any).userTikis?.(address);
+ let result = await tikiQuery.userTikis?.(address);
// Fallback to userRoles if userTikis doesn't exist
- if (!result && (peopleApi.query.tiki as any).userRoles) {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- result = await (peopleApi.query.tiki as any).userRoles?.(address);
+ if (!result && tikiQuery.userRoles) {
+ result = await tikiQuery.userRoles?.(address);
}
if (!result || result.isEmpty) {
return [];
}
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const tikis = result.toJSON() as any[];
+ const tikis = result.toJSON() as TikiEntry[];
return tikis.map((tiki, index) => {
const name = typeof tiki === 'string' ? tiki : tiki.name || tiki.role || 'Unknown';
diff --git a/src/main.tsx b/src/main.tsx
index 64cc83e..42d6521 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -9,13 +9,16 @@ import { LanguageProvider } from './i18n';
import App from './App';
import './index.css';
-// Suppress console logs in production
+// Suppress non-critical console output in production. This is the one place
+// that legitimately overrides console.log/debug/info — warn/error are kept for
+// critical issues. The no-console rule is disabled only for these assignments.
if (import.meta.env.PROD) {
const noop = () => {};
- console.log = noop;
- console.debug = noop;
- console.info = noop;
- // Keep console.warn and console.error for critical issues
+ const suppressed: Array<'log' | 'debug' | 'info'> = ['log', 'debug', 'info'];
+ for (const method of suppressed) {
+ // eslint-disable-next-line no-console
+ console[method] = noop;
+ }
}
// Initialize Telegram WebApp
From fd6b2cc28e84adfd271326b8857a04b44ee099b5 Mon Sep 17 00:00:00 2001
From: Kurdistan Tech Ministry
Date: Sun, 28 Jun 2026 11:16:24 -0700
Subject: [PATCH 13/18] feat(bot): Groq as primary AI provider, Claude fallback
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
The Telegram assistant now answers via Groq (free) first and falls back to
Claude when ANTHROPIC has credit. Keys come from env (GROQ_API_KEY /
ANTHROPIC_API_KEY) — no secrets in source. Wallet/p2p logic untouched.
---
package.json | 2 +-
src/version.json | 6 +-
supabase/functions/telegram-bot/index.ts | 74 +++++++++++++++++-------
3 files changed, 58 insertions(+), 24 deletions(-)
diff --git a/package.json b/package.json
index 62d4d71..6649ee6 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "pezkuwi-telegram-miniapp",
- "version": "1.0.235",
+ "version": "1.0.236",
"type": "module",
"description": "Pezkuwichain Telegram Mini App - Forum, Announcements, Rewards",
"author": "Pezkuwichain Team",
diff --git a/src/version.json b/src/version.json
index 02890ed..681b084 100644
--- a/src/version.json
+++ b/src/version.json
@@ -1,5 +1,5 @@
{
- "version": "1.0.233",
- "buildTime": "2026-06-13T04:42:17.513Z",
- "buildNumber": 1781325737513
+ "version": "1.0.236",
+ "buildTime": "2026-06-28T18:16:24.919Z",
+ "buildNumber": 1782670584920
}
diff --git a/supabase/functions/telegram-bot/index.ts b/supabase/functions/telegram-bot/index.ts
index 02ec3e2..9f85203 100644
--- a/supabase/functions/telegram-bot/index.ts
+++ b/supabase/functions/telegram-bot/index.ts
@@ -26,6 +26,8 @@ const MINI_APP_URLS: Record = {
};
const ANTHROPIC_API_KEY = Deno.env.get('ANTHROPIC_API_KEY') || '';
+// AI provider: Groq (free) is primary; Claude is fallback when it has credit.
+const GROQ_API_KEY = Deno.env.get('GROQ_API_KEY') || '';
function getBotId(req: Request): string {
const url = new URL(req.url);
@@ -234,24 +236,59 @@ async function handleAIChat(token: string, chatId: number, userMessage: string,
});
try {
- const response = await fetch('https://api.anthropic.com/v1/messages', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'x-api-key': ANTHROPIC_API_KEY,
- 'anthropic-version': '2023-06-01',
- },
- body: JSON.stringify({
- model: 'claude-sonnet-4-20250514',
- max_tokens: 1024,
- system: CLAUDE_SYSTEM_PROMPT,
- messages: [{ role: 'user', content: userMessage }],
- }),
- });
+ // Primary provider: Groq (free). Fallback: Claude when it has credit.
+ let aiReply: string | null = null;
- if (!response.ok) {
- const errorText = await response.text();
- console.error('[AI] Claude API error:', response.status, errorText);
+ if (GROQ_API_KEY) {
+ try {
+ const gr = await fetch('https://api.groq.com/openai/v1/chat/completions', {
+ method: 'POST',
+ headers: { Authorization: 'Bearer ' + GROQ_API_KEY, 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ model: 'llama-3.3-70b-versatile',
+ temperature: 0.3,
+ max_tokens: 900,
+ messages: [
+ { role: 'system', content: CLAUDE_SYSTEM_PROMPT },
+ { role: 'user', content: userMessage },
+ ],
+ }),
+ });
+ if (gr.ok) {
+ const gd = await gr.json();
+ aiReply = gd.choices?.[0]?.message?.content || null;
+ } else {
+ console.error('[AI] Groq error:', gr.status, await gr.text());
+ }
+ } catch (e) {
+ console.error('[AI] Groq exception:', e);
+ }
+ }
+
+ if (!aiReply && ANTHROPIC_API_KEY) {
+ const response = await fetch('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'x-api-key': ANTHROPIC_API_KEY,
+ 'anthropic-version': '2023-06-01',
+ },
+ body: JSON.stringify({
+ model: 'claude-sonnet-4-20250514',
+ max_tokens: 1024,
+ system: CLAUDE_SYSTEM_PROMPT,
+ messages: [{ role: 'user', content: userMessage }],
+ }),
+ });
+ if (response.ok) {
+ const result = await response.json();
+ aiReply = result.content?.[0]?.text || null;
+ } else {
+ console.error('[AI] Claude API error:', response.status, await response.text());
+ }
+ }
+
+ if (!aiReply) {
await sendTelegramRequest(token, 'sendMessage', {
chat_id: chatId,
text: 'Sorry, I could not process your question right now. Please try again.',
@@ -259,9 +296,6 @@ async function handleAIChat(token: string, chatId: number, userMessage: string,
return;
}
- const result = await response.json();
- const aiReply = result.content?.[0]?.text || 'No response generated.';
-
// Telegram message limit is 4096 chars
if (aiReply.length <= 4096) {
await sendTelegramRequest(token, 'sendMessage', {
From 0dd4d3d62b0de3eec8c2d89a3a83ae26d19f7f44 Mon Sep 17 00:00:00 2001
From: Satoshi Qazi Muhammed
Date: Sat, 11 Jul 2026 13:42:51 -0700
Subject: [PATCH 14/18] fix(security): remove hardcoded bot token from webhook
setup script
Token was committed in plaintext since the initial commit in a public
repo and was used to deface the bot profile. Script now requires
BOT_TOKEN via environment variable instead.
---
package.json | 2 +-
scripts/setup-telegram-webhook.sh | 8 +++++++-
src/version.json | 6 +++---
3 files changed, 11 insertions(+), 5 deletions(-)
diff --git a/package.json b/package.json
index 6649ee6..8d86f38 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "pezkuwi-telegram-miniapp",
- "version": "1.0.236",
+ "version": "1.0.237",
"type": "module",
"description": "Pezkuwichain Telegram Mini App - Forum, Announcements, Rewards",
"author": "Pezkuwichain Team",
diff --git a/scripts/setup-telegram-webhook.sh b/scripts/setup-telegram-webhook.sh
index ead8b18..5bfcbf1 100755
--- a/scripts/setup-telegram-webhook.sh
+++ b/scripts/setup-telegram-webhook.sh
@@ -2,8 +2,14 @@
# PezkuwiChain Telegram Bot Webhook Setup
# Run this script from a machine that can access Telegram API
+# Usage: BOT_TOKEN="..." ./scripts/setup-telegram-webhook.sh
+
+if [ -z "$BOT_TOKEN" ]; then
+ echo "Error: BOT_TOKEN environment variable is not set."
+ echo "Usage: BOT_TOKEN=\"\" ./scripts/setup-telegram-webhook.sh"
+ exit 1
+fi
-BOT_TOKEN="8548408481:AAEsoyiVBllk_x0T3Jelj8N8VrUiuc9jXQw"
WEBHOOK_URL="https://vbhftvdayqfmcgmzdxfv.supabase.co/functions/v1/telegram-bot"
echo "Setting up Telegram webhook..."
diff --git a/src/version.json b/src/version.json
index 681b084..c35610d 100644
--- a/src/version.json
+++ b/src/version.json
@@ -1,5 +1,5 @@
{
- "version": "1.0.236",
- "buildTime": "2026-06-28T18:16:24.919Z",
- "buildNumber": 1782670584920
+ "version": "1.0.237",
+ "buildTime": "2026-07-11T20:42:51.109Z",
+ "buildNumber": 1783802571110
}
From c4384c8eb91724cce8b90f3e872d966046d133fc Mon Sep 17 00:00:00 2001
From: Satoshi Qazi Muhammed
Date: Sun, 12 Jul 2026 05:04:24 -0700
Subject: [PATCH 15/18] fix: update social links to canonical accounts, add
news.pex.mom AI assistant function
- Correct Instagram/TikTok/Telegram/X/Facebook URLs to official accounts
- Apply same Telegram channel fix to bot welcome messages
- Add ask edge function powering the AI assistant on news.pex.mom
---
package.json | 2 +-
src/components/SocialLinks.tsx | 10 +-
src/version.json | 6 +-
supabase/functions/ask/index.ts | 222 +++++++++++++++++++++++
supabase/functions/telegram-bot/index.ts | 6 +-
5 files changed, 234 insertions(+), 12 deletions(-)
create mode 100644 supabase/functions/ask/index.ts
diff --git a/package.json b/package.json
index 8d86f38..0cfaa08 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "pezkuwi-telegram-miniapp",
- "version": "1.0.237",
+ "version": "1.0.238",
"type": "module",
"description": "Pezkuwichain Telegram Mini App - Forum, Announcements, Rewards",
"author": "Pezkuwichain Team",
diff --git a/src/components/SocialLinks.tsx b/src/components/SocialLinks.tsx
index 472fc52..1894a2c 100644
--- a/src/components/SocialLinks.tsx
+++ b/src/components/SocialLinks.tsx
@@ -13,14 +13,14 @@ interface SocialLink {
const SOCIAL_LINKS: SocialLink[] = [
{
name: 'Instagram',
- url: 'https://www.instagram.com/pezkuwichain',
+ url: 'https://www.instagram.com/pezkuwichaindks',
icon: '📸',
color: 'from-pink-500 to-purple-600',
descriptionKey: 'social.instagram',
},
{
name: 'TikTok',
- url: 'https://www.tiktok.com/@pezkuwi.chain',
+ url: 'https://www.tiktok.com/@satoshiqazimohamm',
icon: '🎵',
color: 'from-gray-800 to-gray-900',
descriptionKey: 'social.tiktok',
@@ -34,14 +34,14 @@ const SOCIAL_LINKS: SocialLink[] = [
},
{
name: 'Telegram',
- url: 'https://t.me/dijitalkurdistan',
+ url: 'https://t.me/kurdishmedya',
icon: '📢',
color: 'from-blue-400 to-blue-600',
descriptionKey: 'social.telegram',
},
{
name: 'X (Twitter)',
- url: 'https://x.com/pezkuwichain',
+ url: 'https://x.com/bizinikiwi',
icon: '𝕏',
color: 'from-gray-700 to-gray-900',
descriptionKey: 'social.twitter',
@@ -55,7 +55,7 @@ const SOCIAL_LINKS: SocialLink[] = [
},
{
name: 'Facebook',
- url: 'https://www.facebook.com/people/Pezkuwi-Chain/61587122224932/',
+ url: 'https://www.facebook.com/share/1BG26niuRE/',
icon: '📘',
color: 'from-blue-600 to-blue-800',
descriptionKey: 'social.facebook',
diff --git a/src/version.json b/src/version.json
index c35610d..04e211e 100644
--- a/src/version.json
+++ b/src/version.json
@@ -1,5 +1,5 @@
{
- "version": "1.0.237",
- "buildTime": "2026-07-11T20:42:51.109Z",
- "buildNumber": 1783802571110
+ "version": "1.0.238",
+ "buildTime": "2026-07-12T12:04:24.521Z",
+ "buildNumber": 1783857864522
}
diff --git a/supabase/functions/ask/index.ts b/supabase/functions/ask/index.ts
new file mode 100644
index 0000000..b3e5788
--- /dev/null
+++ b/supabase/functions/ask/index.ts
@@ -0,0 +1,222 @@
+import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
+
+const ANTHROPIC_API_KEY = Deno.env.get('ANTHROPIC_API_KEY') || '';
+const SUPABASE_URL = Deno.env.get('SUPABASE_URL') || '';
+const SERVICE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') || '';
+
+const SYSTEM = `You are the official PezkuwiChain AI Assistant on the news site news.pex.mom. You answer questions about PezkuwiChain based on the whitepaper and technical documentation below.
+
+RULES:
+- Answer in the SAME LANGUAGE the user writes in. If they write in Kurdish (Kurmancî), answer in Kurdish. If Turkish, answer in Turkish. If English, answer in English. If Arabic, answer in Arabic. If Persian, answer in Persian.
+- Be concise — website answers should be short, clear and helpful.
+- Use plain text, no markdown headers. You can use bold with *text* sparingly.
+- If you don't know something, say so honestly.
+- Never make up information not in the whitepaper.
+- You represent PezkuwiChain officially — be professional and helpful.
+- Do not discuss other blockchain projects comparatively unless asked.
+- For technical questions about source code, direct users to: github.com/pezkuwichain/pezkuwi-sdk
+- For the wallet app, direct users to: @DKSKurdistanBot on Telegram (they can click "Open PezkuwiChain App" after /start)
+- INVESTOR/IDEA REFERRAL: If a user expresses genuine interest in investing in PezkuwiChain, partnering, contributing financially, or proposes a serious idea for the development of DijitalKurdistan, direct them to contact @Pezkuw on Telegram. Only do this when the user's intent is clearly serious — not for casual questions about tokenomics or "how to buy". Example triggers: "I want to invest", "I have funding", "I represent a fund/company", "I have a business proposal", "I want to contribute to the project's development".
+
+PEZKUWICHAIN WHITEPAPER v5.0 — KNOWLEDGE BASE:
+
+PezkuwiChain is a Layer-1 blockchain built on the Pezkuwi SDK (828 crates forked from Polkadot SDK stable2512). It introduces TNPoS (Trust-based Nominated Proof of Stake), a novel consensus mechanism integrating social trust, education, and community participation into validator selection alongside economic stake. Launched mainnet in January 2026.
+
+ARCHITECTURE — Three-Chain System:
+1. Relay Chain: 6-second block time, 1-hour epoch (600 blocks), 21 active validators, BABE + GRANDPA consensus. Native token: HEZ.
+2. Asset Hub TeyrChain (Para ID 1000): 12-second block time, Aura consensus, collators Azad and Beritan. Manages PEZ governance token, trust-backed assets, NFTs, liquidity pools.
+3. People Chain TeyrChain (Para ID 1004): 12-second block time, Aura consensus, collators Erin and Firaz. Manages identity, citizenship, trust scoring, education, governance.
+
+Technology: Rust (98.8%), WebAssembly, libp2p, RocksDB, sr25519/ed25519, SS58 addresses, JSON-RPC 2.0.
+
+PEZKUWI SDK — Naming:
+sp-* → pezsp-*, sc-* → pezsc-*, frame-* → pezframe-*, pallet-* → pezpallet-*, cumulus-* → pezcumulus-*. Substrate → Bizinikiwi, Parachain → TeyrChain, Westend → Zagros testnet. 7,364 Rust source files, 1,926 dependencies.
+
+TNPoS CONSENSUS:
+Trust Score Formula: trust_score = S × (100×S + 300×R + 300×E + 300×T) / B
+S = Staking score (0-100), R = Referral score (0-500), E = Education score, T = Role score, B = ScoreMultiplierBase.
+If S = 0, trust score = 0. Social components carry 9x the weight of pure staking.
+
+Staking Score: Based on HEZ bonded + duration. 1-100 HEZ: 20pts, 101-250: 30pts, 251-750: 40pts, 751+: 50pts. Duration multiplier 1.0x (<1 month) to 2.0x (12+ months).
+Referral Score: 0 referrals: 0pts. 1-10: count×10. 11-50: 100+(count-10)×5. 51-100: 300+(count-50)×4. 101+: 500 max.
+Education Score: On-chain courses via pezpallet-perwerde. IPFS-linked content, verified completion.
+Role Score: Soulbound NFT roles via pezpallet-tiki. 49 variants: Applicant (Daxwazkar), Citizen (Welati), Parliamentarian (Parlementer), Core (Bingehin), Teachers (Mamoste), Ministers (Wezir), President (Serok), Judge (Dadwer).
+
+Validator Pool: 10 Stake Validators + 6 Parliamentary Validators + 5 Merit Validators = 21 total.
+
+DUAL-TOKEN ECONOMY:
+HEZ Token (Security): 200M genesis, 8% annual inflation, 85% stakers / 15% treasury. 12 decimals (TYR base unit).
+Genesis: 100M (50%) presale pool, 40M (20%) Kurdistan Treasury, 40M (20%) airdrop reserve, 20M (10%) founder.
+Fee: 80% treasury, 20% block author. Tips: 100% block author.
+
+PEZ Token (Governance): 5 billion fixed supply, 96.25% treasury, 48-month halving.
+Genesis: 4,812,500,000 PEZ (96.25%) treasury, 93,750,000 PEZ (1.875%) presale, 93,750,000 PEZ (1.875%) founder.
+Halving: Cycle 1 (2026-2030): 100%, Cycle 2: 50%, Cycle 3: 25%, Cycle 4: 12.5%, Cycle 5: 6.25%.
+PEZ Rewards: Monthly epochs (432,000 blocks). user_reward = (user_trust_score / total_trust_scores) × epoch_reward_pool.
+
+Presale: 2% tx fee: 50% treasury, 25% burned, 25% staking rewards.
+
+HOW TO BECOME A CITIZEN (VERY IMPORTANT — users frequently ask this):
+Becoming a citizen (Welati) requires completing a 3-step KYC process. You need minimum 2 HEZ in your People Chain wallet for the on-chain transaction fee.
+
+Step 1 — APPLY (Başvuru Yap / Daxwaz Bike):
+Open the PezkuwiChain app (Telegram MiniApp via @DKSKurdistanBot, web app, or Android app). Create a wallet, go to the Citizens section, fill in your identity information and submit your KYC application. You must have at least 2 HEZ in your People Chain wallet at the time of application (for on-chain transaction fee). If you cannot obtain 2 HEZ, leave your wallet address as a comment on any post on PezkuwiChain's X (Twitter) account (@pezkuwichain) — the PezkuwiChain team will send you 2 HEZ for free. Your identity data is stored as encrypted H256 hashes on-chain — your personal data is never exposed.
+
+Step 2 — WAIT FOR REFERRER APPROVAL (Referrer Onayını Bekle / Li Benda Pejirandina Referrer Bimîne):
+Your referrer (the existing citizen who referred you) must review and approve your application. The referrer validates your identity off-chain and confirms on-chain. If you don't have a referrer, your application falls into Qazi Muhammad's pool — if you are a real person, he will approve you.
+
+Step 3 — SIGN YOUR CITIZENSHIP (Vatandaşlığını İmzala / Welatîbûna Xwe Îmze Bike):
+After your referrer approves, you must sign (confirm) your citizenship on-chain. Once signed, you automatically receive a Welati (Citizen) soulbound NFT — non-transferable, permanent. This gives you 10 trust score points and unlocks access to governance, PEZ rewards, and other citizen-only features.
+
+IMPORTANT: Trust score requirements (300+, 600+) are ONLY for running as a candidate in governance elections (parliament, presidency), NOT for basic citizenship. Any person can become a citizen through the 3-step KYC process above.
+
+DIGITAL NATION PALLETS (14 custom):
+- pezpallet-identity-kyc: Multi-level KYC, H256 hashes on-chain, feeless for applicants
+- pezpallet-tiki: Soulbound NFT roles, 39 role variants. Full list with trust score bonuses:
+ GOVERNANCE: Serok/President (200pts, unique, elected), SerokWeziran/Prime Minister (125pts, appointed), SerokiMeclise/Speaker of Parliament (150pts, unique, elected), Parlementer/Parliament Member (100pts, elected)
+ JUDICIARY: EndameDiwane/Constitutional Court Member (175pts), Dadger/Judge (150pts), Dozger/Prosecutor (120pts), Hiquqnas/Lawyer (75pts)
+ MINISTERS (all 100pts, appointed): Wezir (generic), WezireDarayiye/Finance, WezireParez/Defense, WezireDad/Justice, WezireBelaw/Communications, WezireTend/Health, WezireAva/Construction, WezireCand/Culture
+ SENIOR OFFICIALS: Xezinedar/Treasurer (100pts, unique), PisporêEwlehiyaSîber/Cybersecurity Expert (100pts), Mufetîs/Inspector (90pts), Balyoz/Ambassador (80pts, unique), Berdevk/Spokesperson (70pts)
+ EDUCATION & COMMUNITY: Mamoste/Teacher (70pts, earned), Perwerdekar/Educator (40pts), Rewsenbîr/Intellectual (40pts, earned), Mela/Cleric (50pts), Feqî/Student Scholar (50pts)
+ EXPERTS: Axa/Elder Expert (250pts, earned), RêveberêProjeyê/Project Manager (250pts), Pêseng/Pioneer (80pts), Hekem/Wise (30pts), Sêwirmend/Counselor (20pts)
+ COMMUNITY: SerokêKomele/Community Leader (100pts, earned), ModeratorêCivakê/Community Moderator (200pts, earned)
+ TECHNICAL: OperatorêTorê/Network Operator (60pts), GerinendeyeCavkaniye/Resource Manager (40pts), GerinendeyeDaneye/Data Manager (40pts), KalîteKontrolker/QA (30pts)
+ ECONOMIC: Bazargan/Merchant (60pts), Navbeynkar/Mediator (30pts)
+ ADMINISTRATIVE: Qeydkar/Registrar (25pts), Noter/Notary (50pts), Bacgir/Tax Collector (50pts), ParêzvaneÇandî/Cultural Protector (25pts)
+ BASE: Welati/Citizen (10pts, automatic after KYC)
+ Role assignment types: Automatic (Welati - after KYC), Elected (Serok, Parlementer, SerokiMeclise), Earned (Axa, Mamoste, Rewsenbîr, SerokêKomele, ModeratorêCivakê), Appointed (all others - by admin)
+- pezpallet-trust: Central trust scoring
+- pezpallet-referral: Community growth with accountability
+- pezpallet-staking-score: Time-weighted reputation
+- pezpallet-perwerde: On-chain education (courses, enrollment, points)
+- pezpallet-welati: Governance — Parliament (201 seats), Presidency, Constitutional Court (Diwan), Cabinet (9 ministers)
+- pezpallet-pez-treasury: PEZ reserves with halving
+- pezpallet-presale: Token sales
+- pezpallet-token-wrapper: 1:1 HEZ/wHEZ wrapping
+- pezpallet-pez-rewards: Trust-based distribution
+- pezpallet-validator-pool: TNPoS categorization
+- pezpallet-staking-async: Async staking on Asset Hub
+
+GOVERNANCE (for elected positions — NOT for basic citizenship):
+Parliament (Meclis): 201 seats via election. Presidency (Serok): 50%+ required. Constitutional Court (Diwan). Cabinet: 9 ministers.
+Trust requirements FOR CANDIDACY ONLY: Presidential candidate: 600+ score, 1000 endorsements. Parliamentary candidate: 300+ score, 100 endorsements.
+These are NOT requirements for becoming a citizen. Any person can become a citizen for free.
+Voting: Simple majority 50%+1, Super majority 2/3, Absolute 3/4, Constitutional review 2/3 of Diwan.
+
+CROSS-CHAIN (XCM):
+DMP (Relay→TeyrChain), UMP (TeyrChain→Relay), XCMP (TeyrChain↔TeyrChain).
+Trusted Teleporters: Asset Hub (1000), Contracts (1002), Encointer (1003), People Chain (1004), Broker (1005).
+
+SECURITY: Validators bond HEZ, 28-era bonding (~7 days), slashing for equivocation/unresponsiveness. KYC = Sybil resistance. Rust memory safety, WASM sandboxing, forkless upgrades.
+
+ASSET IDs (Asset Hub):
+1: PEZ (12 decimals), 2: wHEZ (12 decimals), 1000: wUSDT (6 decimals), 1001: wDOT (10 decimals), 1002: wETH (18 decimals), 1003: wBTC (8 decimals). Native: HEZ (12 decimals).
+
+RPC Endpoints:
+Relay Chain: wss://rpc.pezkuwichain.io
+Asset Hub: wss://asset-hub-rpc.pezkuwichain.io
+People Chain: wss://people-rpc.pezkuwichain.io
+
+LINKS:
+Website: pezkuwichain.io
+GitHub: github.com/pezkuwichain/pezkuwi-sdk
+Discord: discord.gg/Y3VyEC6h8W
+Telegram Channel: t.me/kurdishmedya
+Telegram App: @DKSKurdistanBot
+
+PROBLEM SOLVED: Over 100 million stateless people. Kurdish population 40+ million across 4 countries — financial exclusion, identity fragmentation, governance vacuum. PezkuwiChain provides digital nation-state infrastructure.
+
+USE CASES: Digital Identity for stateless individuals, Diaspora Remittances (near-zero cost vs 5-10% fees on $20B+ annual Kurdish flows), Borderless Democracy (201-seat parliament), Education Credentialing, Trust-Based Inclusion.
+
+ROADMAP:
+Completed: SDK development, 14 custom pallets, Zagros testnet, mainnet genesis Jan 2026.
+Current: TeyrChain activation, collator configuration, HRMP channels.
+Phase 2 (2026 Q2-Q4): Full TeyrChain production, governance, presale, dApp ecosystem.
+Phase 3 (2027): Multi-nation onboarding, Nationhood-as-a-Service, bridges (Ethereum, Tron, BSC), full TNPoS.
+Phase 4 (2028+): Cross-chain governance federation, decentralized identity, stablecoin, cultural heritage archival.
+
+License: Apache 2.0, Copyright 2026 Kurdistan Tech Institute. Lead Architect: SatoshiQaziMuhammed.
+
+You are embedded as a chat assistant on the Pezkuwichain news site. Help visitors understand PezkuwiChain, HEZ/PEZ, governance, the wallet, and Kurdish digital-nation topics. If asked something you don't know, say so briefly. Never invent prices or figures.`;
+
+const CORS = {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
+};
+const J = (o: unknown, s = 200) =>
+ new Response(JSON.stringify(o), {
+ status: s,
+ headers: { ...CORS, 'Content-Type': 'application/json' },
+ });
+
+// Per-IP rate limit via a service-role table (cost guard for the public endpoint).
+async function allowed(ip: string): Promise {
+ if (!SUPABASE_URL || !SERVICE_KEY) return true;
+ const h = { apikey: SERVICE_KEY, Authorization: 'Bearer ' + SERVICE_KEY, Prefer: 'count=exact' };
+ const cnt = async (sinceISO: string) => {
+ const u = `${SUPABASE_URL}/rest/v1/ai_chat_log?ip=eq.${encodeURIComponent(ip)}&created_at=gte.${sinceISO}&select=id`;
+ const r = await fetch(u, { headers: { ...h, Range: '0-0' } });
+ const cr = r.headers.get('content-range') || '*/0';
+ return parseInt(cr.split('/')[1] || '0', 10);
+ };
+ const minAgo = new Date(Date.now() - 60_000).toISOString();
+ const dayAgo = new Date(Date.now() - 86_400_000).toISOString();
+ if ((await cnt(minAgo)) >= 8) return false; // 8 / minute
+ if ((await cnt(dayAgo)) >= 120) return false; // 120 / day
+ await fetch(`${SUPABASE_URL}/rest/v1/ai_chat_log`, {
+ method: 'POST',
+ headers: {
+ apikey: SERVICE_KEY,
+ Authorization: 'Bearer ' + SERVICE_KEY,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ ip }),
+ });
+ return true;
+}
+
+serve(async (req) => {
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: CORS });
+ if (req.method !== 'POST') return J({ error: 'method' }, 405);
+ try {
+ const body = await req.json().catch(() => ({}));
+ const q = (body.q || body.question || '').toString().trim();
+ if (!q || q.length > 2000) return J({ error: 'bad_request' }, 400);
+ const ip = (req.headers.get('x-forwarded-for') || '').split(',')[0].trim() || 'unknown';
+ if (!(await allowed(ip)))
+ return J(
+ { answer: "You're asking a lot quickly — please wait a minute and try again." },
+ 429
+ );
+ const hist = Array.isArray(body.history)
+ ? body.history
+ .filter(
+ (m: any) =>
+ m && (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string'
+ )
+ .slice(-6)
+ : [];
+ const messages = [...hist, { role: 'user', content: q }];
+ const r = await fetch('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'x-api-key': ANTHROPIC_API_KEY,
+ 'anthropic-version': '2023-06-01',
+ },
+ body: JSON.stringify({
+ model: 'claude-sonnet-4-20250514',
+ max_tokens: 900,
+ system: SYSTEM,
+ messages,
+ }),
+ });
+ if (!r.ok) return J({ answer: 'Sorry, I could not answer right now. Please try again.' }, 200);
+ const d = await r.json();
+ const answer = (d.content && d.content[0] && d.content[0].text) || '…';
+ return J({ answer }, 200);
+ } catch (_e) {
+ return J({ answer: 'Something went wrong. Please try again.' }, 200);
+ }
+});
diff --git a/supabase/functions/telegram-bot/index.ts b/supabase/functions/telegram-bot/index.ts
index 9f85203..0305944 100644
--- a/supabase/functions/telegram-bot/index.ts
+++ b/supabase/functions/telegram-bot/index.ts
@@ -203,7 +203,7 @@ LINKS:
Website: pezkuwichain.io
GitHub: github.com/pezkuwichain/pezkuwi-sdk
Discord: discord.gg/Y3VyEC6h8W
-Telegram Channel: t.me/dijitalkurdistan
+Telegram Channel: t.me/kurdishmedya
Telegram App: @DKSKurdistanBot
PROBLEM SOLVED: Over 100 million stateless people. Kurdish population 40+ million across 4 countries — financial exclusion, identity fragmentation, governance vacuum. PezkuwiChain provides digital nation-state infrastructure.
@@ -477,7 +477,7 @@ async function sendDksWelcome(token: string, chatId: number) {
[
{
text: '📢 Join Channel / Kanalê Tev Bibin',
- url: 'https://t.me/dijitalkurdistan',
+ url: 'https://t.me/kurdishmedya',
},
],
],
@@ -582,7 +582,7 @@ Just type your question in any language and I'll answer!
Links:
🌐 Website: pezkuwichain.io
-📢 Channel: t.me/dijitalkurdistan
+📢 Channel: t.me/kurdishmedya
💬 Discord: discord.gg/Y3VyEC6h8W
`;
await sendTelegramRequest(token, 'sendMessage', {
From 8d1e5f6af5882d8298f50d9cbc7fee19b8250f41 Mon Sep 17 00:00:00 2001
From: Satoshi Qazi Muhammed
Date: Sun, 12 Jul 2026 19:21:54 -0700
Subject: [PATCH 16/18] fix(deposits): stop runaway duplicate deposit rows, fix
check-deposits reliability
Root cause chain found while investigating why TRC20/TON/Polkadot deposits
were never being credited after the self-hosted Supabase migration:
- DEPOSIT_TRON_HD_MNEMONIC, TRONGRID_API_KEY, DEPOSIT_TON_ADDRESS,
DEPOSIT_POLKADOT_ADDRESS and the pg_cron job itself were never carried
over during the 2026-04-09 migration, so check-deposits never ran.
- Once reconnected, the TRC20 loop was fully sequential (one address at a
time) and hit the edge function's CPU/time budget with 50+ users -
parallelized with a bounded concurrency of 8.
- The dedup check (select-by-tx_hash + .single()) breaks permanently once
2+ rows ever share a tx_hash - .single() then errors on every future
lookup, so the guard silently stops working and every cron tick
reinserts. This is what produced 50k+ and 30k+ duplicate rows for two
historical deposits back in April. Replaced with upsert +
onConflict/ignoreDuplicates against a new unique constraint on tx_hash,
so duplicates are impossible at the DB level regardless of app-level
races.
- deposit_index 0 is the platform admin account and also used as the
treasury sweep destination - excluded from the TRC20 scan so internal
sweep transfers landing on it are never mistaken for a customer deposit.
---
package.json | 2 +-
src/version.json | 6 +-
supabase/functions/check-deposits/index.ts | 197 +++++++++---------
.../20260713_deposits_tx_hash_unique.sql | 8 +
4 files changed, 116 insertions(+), 97 deletions(-)
create mode 100644 supabase/migrations/20260713_deposits_tx_hash_unique.sql
diff --git a/package.json b/package.json
index 023ed0d..007fba4 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "pezkuwi-telegram-miniapp",
- "version": "1.0.239",
+ "version": "1.0.240",
"type": "module",
"description": "Pezkuwichain Telegram Mini App - Forum, Announcements, Rewards",
"author": "Pezkuwichain Team",
diff --git a/src/version.json b/src/version.json
index 189844c..2245489 100644
--- a/src/version.json
+++ b/src/version.json
@@ -1,5 +1,5 @@
{
- "version": "1.0.239",
- "buildTime": "2026-07-12T12:07:48.783Z",
- "buildNumber": 1783858068783
+ "version": "1.0.240",
+ "buildTime": "2026-07-13T02:21:54.972Z",
+ "buildNumber": 1783909314972
}
diff --git a/supabase/functions/check-deposits/index.ts b/supabase/functions/check-deposits/index.ts
index c1c8556..175c3ee 100644
--- a/supabase/functions/check-deposits/index.ts
+++ b/supabase/functions/check-deposits/index.ts
@@ -118,17 +118,6 @@ async function checkTonDeposits(
if (amount < MIN_DEPOSIT) continue;
- // Check if already processed
- const { data: existing } = await supabase
- .from('tg_deposits')
- .select('id')
- .eq('tx_hash', txHash)
- .single();
-
- if (existing) continue;
-
- result.found++;
-
// Find user by memo code
const { data: depositCode } = await supabase
.from('tg_user_deposit_codes')
@@ -144,17 +133,29 @@ async function checkTonDeposits(
// Calculate net amount after platform fee
const netAmount = Math.max(0, amount - TON_FEE);
- // Create deposit record with net amount
- const { error } = await supabase.from('tg_deposits').insert({
- user_id: depositCode.user_id,
- network: 'ton',
- amount: netAmount,
- tx_hash: txHash,
- memo: comment,
- status: 'confirming',
- });
+ // Create deposit record with net amount. tx_hash has a unique DB
+ // constraint - on conflict (already processed on a prior run) this
+ // is a no-op, avoiding the check-then-insert race that used to
+ // produce runaway duplicate rows.
+ const { error, data: inserted } = await supabase
+ .from('tg_deposits')
+ .upsert(
+ {
+ user_id: depositCode.user_id,
+ network: 'ton',
+ amount: netAmount,
+ tx_hash: txHash,
+ memo: comment,
+ status: 'confirming',
+ },
+ { onConflict: 'tx_hash', ignoreDuplicates: true }
+ )
+ .select('id');
- if (!error) result.processed++;
+ if (!error && inserted && inserted.length > 0) {
+ result.found++;
+ result.processed++;
+ }
}
}
} catch (err) {
@@ -201,31 +202,29 @@ async function checkPolkadotDeposits(
if (amount < MIN_DEPOSIT) continue;
- // Check if already processed
- const { data: existing } = await supabase
- .from('tg_deposits')
- .select('id')
- .eq('tx_hash', txHash)
- .single();
-
- if (existing) continue;
-
- result.found++;
-
// Calculate net amount after platform fee
const netAmount = Math.max(0, amount - POLKADOT_FEE);
// For Polkadot, memo might be in extrinsic data
// Try to find user by checking system.remark in same block
// For now, create as pending without user
- const { error } = await supabase.from('tg_deposits').insert({
- network: 'polkadot',
- amount: netAmount,
- tx_hash: txHash,
- status: 'confirming',
- });
+ const { error, data: inserted } = await supabase
+ .from('tg_deposits')
+ .upsert(
+ {
+ network: 'polkadot',
+ amount: netAmount,
+ tx_hash: txHash,
+ status: 'confirming',
+ },
+ { onConflict: 'tx_hash', ignoreDuplicates: true }
+ )
+ .select('id');
- if (!error) result.processed++;
+ if (!error && inserted && inserted.length > 0) {
+ result.found++;
+ result.processed++;
+ }
}
} catch (err) {
result.errors.push(`Polkadot error: ${err}`);
@@ -242,70 +241,82 @@ async function checkTrc20Deposits(
const result = { found: 0, processed: 0, errors: [] as string[] };
try {
- // Get all users with deposit_index
+ // Get all users with deposit_index. deposit_index 0 belongs to the
+ // platform admin account and doubles as the treasury sweep destination -
+ // excluded here so internal sweep transfers landing on it are never
+ // mistaken for a customer deposit.
const { data: users } = await supabase
.from('tg_users')
.select('id, deposit_index')
.not('deposit_index', 'is', null)
+ .neq('deposit_index', 0)
.order('deposit_index', { ascending: true });
if (!users || users.length === 0) return result;
- // Check each user's derived address
- for (const user of users) {
- try {
- const address = deriveTronAddress(hdMnemonic, user.deposit_index);
+ // Check each user's derived address, with bounded concurrency so we
+ // don't exceed the edge function's CPU/time budget on large user counts.
+ const CONCURRENCY = 8;
+ for (let i = 0; i < users.length; i += CONCURRENCY) {
+ const batch = users.slice(i, i + CONCURRENCY);
+ await Promise.all(
+ batch.map(async (user) => {
+ try {
+ const address = deriveTronAddress(hdMnemonic, user.deposit_index);
- // Get TRC20 transfers to this address
- const response = await fetch(
- `${TRON_API}/v1/accounts/${address}/transactions/trc20?limit=20&contract_address=${TRON_USDT_CONTRACT}`,
- {
- headers: { 'TRON-PRO-API-KEY': Deno.env.get('TRONGRID_API_KEY') || '' },
+ // Get TRC20 transfers to this address
+ const response = await fetch(
+ `${TRON_API}/v1/accounts/${address}/transactions/trc20?limit=20&contract_address=${TRON_USDT_CONTRACT}`,
+ {
+ headers: { 'TRON-PRO-API-KEY': Deno.env.get('TRONGRID_API_KEY') || '' },
+ }
+ );
+
+ if (!response.ok) return;
+
+ const data = await response.json();
+ const transfers = data.data || [];
+
+ for (const tx of transfers) {
+ // Only incoming transfers
+ if (tx.to?.toLowerCase() !== address.toLowerCase()) continue;
+
+ const txHash = tx.transaction_id;
+ const amount = parseInt(tx.value) / 1e6; // USDT has 6 decimals
+
+ if (amount < MIN_DEPOSIT) continue;
+
+ // Create deposit record (with fee deduction note). tx_hash
+ // has a unique DB constraint - on conflict this is a no-op,
+ // avoiding the check-then-insert race that used to produce
+ // runaway duplicate rows.
+ const netAmount = Math.max(0, amount - TRC20_FEE);
+
+ const { error, data: inserted } = await supabase
+ .from('tg_deposits')
+ .upsert(
+ {
+ user_id: user.id,
+ network: 'trc20',
+ amount: netAmount, // Store net amount after fee
+ tx_hash: txHash,
+ status: 'confirming',
+ },
+ { onConflict: 'tx_hash', ignoreDuplicates: true }
+ )
+ .select('id');
+
+ if (!error && inserted && inserted.length > 0) {
+ result.found++;
+ result.processed++;
+ }
+ }
+ } catch (err) {
+ // Skip individual user errors
+ return;
}
- );
-
- if (!response.ok) continue;
-
- const data = await response.json();
- const transfers = data.data || [];
-
- for (const tx of transfers) {
- // Only incoming transfers
- if (tx.to?.toLowerCase() !== address.toLowerCase()) continue;
-
- const txHash = tx.transaction_id;
- const amount = parseInt(tx.value) / 1e6; // USDT has 6 decimals
-
- if (amount < MIN_DEPOSIT) continue;
-
- // Check if already processed
- const { data: existing } = await supabase
- .from('tg_deposits')
- .select('id')
- .eq('tx_hash', txHash)
- .single();
-
- if (existing) continue;
-
- result.found++;
-
- // Create deposit record (with fee deduction note)
- const netAmount = Math.max(0, amount - TRC20_FEE);
-
- const { error } = await supabase.from('tg_deposits').insert({
- user_id: user.id,
- network: 'trc20',
- amount: netAmount, // Store net amount after fee
- tx_hash: txHash,
- status: 'confirming',
- });
-
- if (!error) result.processed++;
- }
- } catch (err) {
- // Skip individual user errors
- continue;
- }
+ })
+ );
}
} catch (err) {
result.errors.push(`TRC20 error: ${err}`);
diff --git a/supabase/migrations/20260713_deposits_tx_hash_unique.sql b/supabase/migrations/20260713_deposits_tx_hash_unique.sql
new file mode 100644
index 0000000..3ec670c
--- /dev/null
+++ b/supabase/migrations/20260713_deposits_tx_hash_unique.sql
@@ -0,0 +1,8 @@
+-- Prevent duplicate deposit records for the same on-chain transaction.
+-- Without this constraint, a check-then-insert race in check-deposits
+-- (concurrent invocations, or any transient duplicate) permanently breaks
+-- the .single() dedup lookup once 2+ rows share a tx_hash, causing every
+-- subsequent cron run to re-insert indefinitely. This happened in
+-- production: two tx_hashes accumulated 50k+ and 30k+ duplicate rows
+-- respectively before being cleaned up.
+ALTER TABLE tg_deposits ADD CONSTRAINT tg_deposits_tx_hash_unique UNIQUE (tx_hash);
From 9bb9d2cda35eb53d10183573fa57696f8c56463a Mon Sep 17 00:00:00 2001
From: SatoshiQaziMuhammed
Date: Tue, 21 Jul 2026 07:33:17 -0700
Subject: [PATCH 17/18] fix(ai): Groq intermittent failures + sync git with
actually-deployed source (#8)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
The AI assistant (both @DKSKurdistanBot on Telegram and the news.pex.mom
"ask" widget) was failing to answer most questions while occasionally
succeeding — reported as "only answers about pez mining, says it doesn't
know anything else." Root cause was NOT a knowledge-base gap (the full
whitepaper/wallet/mining/book knowledge was present in both functions all
along) — it was Groq's openai/gpt-oss-120b model returning intermittent
errors (429/5xx, one raw 502) under real load, confirmed live by hitting
the same endpoint repeatedly with trivial questions ("merhaba") and
getting a ~50% failure rate even 15s+ apart (ruling out our own per-IP
rate limiter). The Anthropic fallback couldn't rescue these failures
because that key has no credit.
Fix: retry each Groq call up to 2x with backoff, and fall back to
llama-3.3-70b-versatile (the model this used before switching to
gpt-oss-120b, still free on Groq, not observed to have the same
instability) before ever reaching the Anthropic branch. Verified live
after deploying: failure rate dropped from ~50% to under ~20% across
repeated real test questions.
Also fixed a real (latent, not currently triggered since both keys happen
to be set) bug in telegram-bot: handleAIChat had an early
`if (!ANTHROPIC_API_KEY) return` guard that predates Groq being added as
primary provider — if Anthropic's key were ever removed, this would have
skipped Groq entirely despite Groq being the intended primary. Changed to
only bail if BOTH keys are missing.
Separately: this repo's git history had drifted significantly behind what
was actually deployed — main's checked-in system prompt was missing the
Trust-Score-increase guidance, the full Pezkuwi Wallet feature list, the
Mining Simulation explanation, and the entire "Bulut Ulusu" book section,
none of which showed up in any diff because they'd apparently only ever
been pushed via `supabase functions deploy`, never committed. Discovered
while resolving a merge conflict against origin/main and finding the
"upstream" side of these functions had no Groq support at all — Claude-only,
an older design than what's live. This commit's content was reconciled by
downloading the actual currently-deployed function bodies from Supabase's
Management API and using them as the source of truth, with the Groq
retry/fallback fix layered on top — so git now matches reality.
---
package.json | 2 +-
src/version.json | 6 +-
supabase/functions/ask/index.ts | 150 +++++++++++++++++++---
supabase/functions/telegram-bot/index.ts | 154 ++++++++++++++++++-----
4 files changed, 258 insertions(+), 54 deletions(-)
diff --git a/package.json b/package.json
index 007fba4..15c6075 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "pezkuwi-telegram-miniapp",
- "version": "1.0.240",
+ "version": "1.0.241",
"type": "module",
"description": "Pezkuwichain Telegram Mini App - Forum, Announcements, Rewards",
"author": "Pezkuwichain Team",
diff --git a/src/version.json b/src/version.json
index 2245489..9833611 100644
--- a/src/version.json
+++ b/src/version.json
@@ -1,5 +1,5 @@
{
- "version": "1.0.240",
- "buildTime": "2026-07-13T02:21:54.972Z",
- "buildNumber": 1783909314972
+ "version": "1.0.241",
+ "buildTime": "2026-07-21T14:31:14.612Z",
+ "buildNumber": 1784644274612
}
diff --git a/supabase/functions/ask/index.ts b/supabase/functions/ask/index.ts
index b3e5788..02d3395 100644
--- a/supabase/functions/ask/index.ts
+++ b/supabase/functions/ask/index.ts
@@ -1,6 +1,8 @@
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
const ANTHROPIC_API_KEY = Deno.env.get('ANTHROPIC_API_KEY') || '';
+// AI provider: Groq (free) is primary; Claude is fallback when it has credit.
+const GROQ_API_KEY = Deno.env.get('GROQ_API_KEY') || '';
const SUPABASE_URL = Deno.env.get('SUPABASE_URL') || '';
const SERVICE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') || '';
@@ -8,6 +10,8 @@ const SYSTEM = `You are the official PezkuwiChain AI Assistant on the news site
RULES:
- Answer in the SAME LANGUAGE the user writes in. If they write in Kurdish (Kurmancî), answer in Kurdish. If Turkish, answer in Turkish. If English, answer in English. If Arabic, answer in Arabic. If Persian, answer in Persian.
+- Write NATURAL, fluent, conversational language - especially in Turkish and Kurdish, avoid stilted formal suffixes ("bulunmaktadır", "göstermektedir") and translation-flavored phrasing; short clear sentences, like a knowledgeable friend explaining.
+- STRICTLY plain text: never use markdown (**, ##, bullet asterisks). Simple dashes for lists are fine.
- Be concise — website answers should be short, clear and helpful.
- Use plain text, no markdown headers. You can use bold with *text* sparingly.
- If you don't know something, say so honestly.
@@ -44,6 +48,14 @@ Role Score: Soulbound NFT roles via pezpallet-tiki. 49 variants: Applicant (Daxw
Validator Pool: 10 Stake Validators + 6 Parliamentary Validators + 5 Merit Validators = 21 total.
+TRUST SCORE — HOW TO INCREASE IT (VERY IMPORTANT — users frequently ask this):
+If a user asks "why is my trust score 0?": To have a trust score at all, you must have at least 1.1 HEZ on People Chain and have STAKED at least 1 HEZ. Staking is the multiplier of the whole formula — with zero stake, referrals/education/roles cannot produce any score (S=0 means trust_score=0).
+If a user asks "how do I increase my trust score?": The more you do of these, the higher your score:
+1. Stake more HEZ, and keep it staked longer (staking amount tiers: 1-100 HEZ: 20pts, 101-250: 30pts, 251-750: 40pts, 751+: 50pts; duration multiplier grows from 1.0x up to 2.0x at 12+ months).
+2. Refer more people (each verified referral adds points, up to 500 max at 101+ referrals).
+3. Educate yourself — complete on-chain courses and certificate programs via the Perwerde education network (education score).
+4. Become a citizen (Welati soulbound NFT: +10pts) and earn community roles (teacher, moderator, etc. add larger bonuses).
+
DUAL-TOKEN ECONOMY:
HEZ Token (Security): 200M genesis, 8% annual inflation, 85% stakers / 15% treasury. 12 decimals (TYR base unit).
Genesis: 100M (50%) presale pool, 40M (20%) Kurdistan Treasury, 40M (20%) airdrop reserve, 20M (10%) founder.
@@ -117,12 +129,52 @@ Relay Chain: wss://rpc.pezkuwichain.io
Asset Hub: wss://asset-hub-rpc.pezkuwichain.io
People Chain: wss://people-rpc.pezkuwichain.io
+PEZKUWI WALLET — OFFICIAL ANDROID APP (live on Google Play since July 2026, v1.1.2):
+Download: https://play.google.com/store/apps/details?id=io.pezkuwichain.wallet
+The official mobile wallet of PezkuwiChain / Digital Kurdistan State. Features:
+- Manage HEZ and PEZ tokens, staking, on-chain governance voting
+- Full Polkadot ecosystem support (DOT, Asset Hub tokens) inherited from its Nova Wallet foundation
+- Native multi-chain support: Bitcoin (BTC), Solana (SOL), Tron (TRX + TRC-20 USDT) — send and receive directly on their own chains, real on-chain transactions, keys derived from the same seed phrase
+- USDT Bridge: converts between wUSDT on Pezkuwi Asset Hub and USDT on Polkadot Asset Hub, in both directions. This is the ONLY bridge pair — the app does not bridge SOL, TRX or ETH.
+- Multisig accounts (shared-control wallets with threshold approvals), including approving operations via deep links
+- Trust Score dashboard card showing your on-chain trust score, roles, and citizen count
+- Gift feature: send tokens as a QR/link gift that the recipient claims in-app
+- Cloud backup, multiple wallets, hardware wallet (Polkadot Vault / Ledger) support
+
+PEZ MINING SIMULATION (in the Pezkuwi Wallet app — users frequently ask about this):
+Inside the Trust Score card there is a small "Mining Simulation" square with a diamond counter, labeled "PEZ Airdrop".
+- What it is: a simulation that PREVIEWS your estimated PEZ airdrop. It shows, based on your Trust Score, approximately how much PEZ you could receive from the era's distribution. It is not literal mining — the diamond count is an ESTIMATE.
+- The diamonds cannot be manually converted by the user. The REAL PEZ airdrop is calculated transparently on-chain at the end of each era (~30 days) and distributed AUTOMATICALLY to wallets (trust-score-weighted share of the era pool, via pezpallet-pez-rewards). When the era ends and the real airdrop is paid out, the diamond counter automatically resets to zero. So the counter shows the PEZ airdrop you are estimated to earn.
+- Purpose: to let users SEE how raising their Trust Score — through referrals, staking HEZ, earning tiki roles, and completing education — increases their PEZ airdrop.
+- How the counter works: tap the square to start a 24-hour mining session. While a session is active, diamonds accrue every minute, proportional to your Trust Score: rate = (92.5M PEZ era pool / 43,200 minutes) × (your trust score / 500,000 reference network total). Example: trust score 340 ≈ 1.46 diamonds/minute. When the 24h session ends, accrual stops — tap the square again to start a new session (your accumulated total is kept within the era).
+- If your Trust Score is 0, the counter cannot start — the app shows a warning that your trust score must be greater than 0. To fix this: become a citizen, stake HEZ (required for any trust score), refer others, complete education courses.
+- Colors: red square = inactive (tap to start), gold = actively mining.
+- The small Telegram icon next to it opens the official channel: https://t.me/+DUWJ8wtt5qI4Njgy
+
+"BULUT ULUSU" (CLOUD NATION) — THE BOOK BEHIND PEZKUWICHAIN (chapter-by-chapter knowledge):
+PezkuwiChain's philosophical foundation is the book "Bulut Ulusu" (Cloud Nation), written by the project's architect (a software developer AND sociologist — the "two desks" of the opening chapter). Available in Turkish, English and Kurdish. Core theses:
+- Code is law in a literal sense: every cryptographic design choice is a political claim about who holds authority, how censorship is escaped, and how trust is established without a central institution.
+- "Westphalia's collapse": the 20th-century nation-state model (absolute borders, assimilation) is cracking. Path Dependency explains why humanity stays on inefficient old roads; the Network State ("Fikir Birliği Ulusu" — consensus nation) is the emerging alternative: a nation built on shared ideas and cryptographic consensus rather than territory.
+- Plurality and the mathematics of justice: stories like Berivan (an unbanked Kurdish refugee rejected by traditional finance) show the cost of statelessness; "Hyper-Hawala" — trust networks scaled beyond the Dunbar number by cryptography.
+- The sociology of statelessness: Kurds (40+ million, no state, Agamben's "Homo Sacer") are candidates to be this era's "Vanguard Nation" (Öncü Ulus) — historical victimhood becomes "zero friction" flexibility: no legacy state apparatus to defend, freedom to build a new civilization model from scratch.
+- Three chains, one nation: the multi-chain architecture (Relay + Asset Hub + People Chain) is philosophy made executable — praxis running in compilers and distributed nodes instead of squares and manifestos.
+- TNPoS and "Bext û Soz" (a Kurdish concept: honor and one's word): moving from the dictatorship of money (pure Proof-of-Stake plutocracy) to the transparency of trust — social reputation, education and community roles encoded into consensus.
+- Dual economy: central banks as an "apparatus of capture" (Deleuze & Guattari) facing structural, mathematical inefficiency; HEZ as network fuel and PEZ as the community's value/governance asset.
+- Self-Sovereign Identity (SSI): the modern state turned identity into a file number — a vast alienation. PezkuwiChain returns identity ownership to the person (encrypted hashes on-chain, the person holds the keys).
+- Education's frozen evolution: schools barely changed in 150 years while everything else transformed; the Perwerde network puts verified learning on-chain and rewards it with trust score.
+- A universal Layer 1: not only for Kurds — an infrastructure for 100M+ stateless people worldwide; the excluded are "read-only" in today's systems, PezkuwiChain gives them write access.
+- Capacity thresholds: growth is modeled as concrete capacity thresholds (illustrated by Zana, a stateless Ezidi youth), explicitly avoiding prophecy.
+- The old world's resistance: regulatory, sociological and diplomatic thresholds are expected; the project's stance is COMPLEMENTARY PARTICIPATION — it does not challenge regional states and does not seek to change any border. A digital nation, not a territorial claim.
+- Conclusion: the statelessness experience is no longer a curse but one of humanity's paths to freedom; the book is "not a completed victory but the record of an ongoing construction."
+When asked about the book, its ideas, or "why does PezkuwiChain exist": answer from these theses. The book's preface is deliberately left half-finished — it belongs to the community that will write the future.
+
LINKS:
Website: pezkuwichain.io
GitHub: github.com/pezkuwichain/pezkuwi-sdk
Discord: discord.gg/Y3VyEC6h8W
-Telegram Channel: t.me/kurdishmedya
+Telegram Channel: https://t.me/+DUWJ8wtt5qI4Njgy
Telegram App: @DKSKurdistanBot
+Android App (Pezkuwi Wallet, live on Google Play): https://play.google.com/store/apps/details?id=io.pezkuwichain.wallet
PROBLEM SOLVED: Over 100 million stateless people. Kurdish population 40+ million across 4 countries — financial exclusion, identity fragmentation, governance vacuum. PezkuwiChain provides digital nation-state infrastructure.
@@ -176,6 +228,50 @@ async function allowed(ip: string): Promise {
return true;
}
+// Groq's openai/gpt-oss-120b returns intermittent errors under load (429/5xx,
+// and even a raw 502 from the edge runtime once) unrelated to the question
+// asked — confirmed live 2026-07-21 by hitting this endpoint repeatedly with
+// trivial questions ("merhaba") and seeing a ~50% failure rate with 15s+
+// between calls (ruling out our own per-IP rate limiter above), which 2
+// retries on the same model did not fully fix. Falls back to
+// llama-3.3-70b-versatile (the model this used before switching to
+// gpt-oss-120b for better Turkish/Kurdish — still free on Groq, not observed
+// to have the same instability) if gpt-oss-120b exhausts its retries, before
+// ever reaching the Anthropic fallback below. Doesn't retry a 4xx (bad
+// request/auth) at all — not transient, and switching models wouldn't help.
+const GROQ_MODELS = ['openai/gpt-oss-120b', 'llama-3.3-70b-versatile'];
+
+async function callGroqWithRetry(messages: unknown[], retriesPerModel = 2): Promise {
+ for (const model of GROQ_MODELS) {
+ for (let attempt = 0; attempt <= retriesPerModel; attempt++) {
+ try {
+ const gr = await fetch('https://api.groq.com/openai/v1/chat/completions', {
+ method: 'POST',
+ headers: { Authorization: 'Bearer ' + GROQ_API_KEY, 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ model,
+ temperature: 0.3,
+ max_tokens: 900,
+ messages: [{ role: 'system', content: SYSTEM }, ...messages],
+ }),
+ });
+ if (gr.ok) {
+ const gd = await gr.json();
+ const reply = gd.choices?.[0]?.message?.content || null;
+ if (reply) return reply;
+ } else {
+ console.error('[AI] Groq error:', model, gr.status, await gr.text());
+ if (gr.status !== 429 && gr.status < 500) break; // non-transient, try next model instead
+ }
+ } catch (e) {
+ console.error('[AI] Groq exception:', model, e);
+ }
+ if (attempt < retriesPerModel) await new Promise((r) => setTimeout(r, 400 * (attempt + 1)));
+ }
+ }
+ return null;
+}
+
serve(async (req) => {
if (req.method === 'OPTIONS') return new Response('ok', { headers: CORS });
if (req.method !== 'POST') return J({ error: 'method' }, 405);
@@ -198,23 +294,41 @@ serve(async (req) => {
.slice(-6)
: [];
const messages = [...hist, { role: 'user', content: q }];
- const r = await fetch('https://api.anthropic.com/v1/messages', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'x-api-key': ANTHROPIC_API_KEY,
- 'anthropic-version': '2023-06-01',
- },
- body: JSON.stringify({
- model: 'claude-sonnet-4-20250514',
- max_tokens: 900,
- system: SYSTEM,
- messages,
- }),
- });
- if (!r.ok) return J({ answer: 'Sorry, I could not answer right now. Please try again.' }, 200);
- const d = await r.json();
- const answer = (d.content && d.content[0] && d.content[0].text) || '…';
+
+ // Primary provider: Groq (free). Fallback: Claude when it has credit.
+ let answer: string | null = null;
+
+ if (GROQ_API_KEY) {
+ answer = await callGroqWithRetry(messages);
+ }
+
+ if (!answer && ANTHROPIC_API_KEY) {
+ const r = await fetch('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'x-api-key': ANTHROPIC_API_KEY,
+ 'anthropic-version': '2023-06-01',
+ },
+ body: JSON.stringify({
+ model: 'claude-sonnet-4-20250514',
+ max_tokens: 900,
+ system: SYSTEM,
+ messages,
+ }),
+ });
+ if (r.ok) {
+ const d = await r.json();
+ answer = (d.content && d.content[0] && d.content[0].text) || null;
+ } else {
+ console.error('[AI] Claude API error:', r.status, await r.text());
+ }
+ }
+
+ if (!answer)
+ return J({ answer: 'Sorry, I could not answer right now. Please try again.' }, 200);
+ // Models occasionally emit markdown despite the plain-text rule.
+ answer = answer.replace(/\*\*/g, '').replace(/^#+\s*/gm, '');
return J({ answer }, 200);
} catch (_e) {
return J({ answer: 'Something went wrong. Please try again.' }, 200);
diff --git a/supabase/functions/telegram-bot/index.ts b/supabase/functions/telegram-bot/index.ts
index 0305944..9326611 100644
--- a/supabase/functions/telegram-bot/index.ts
+++ b/supabase/functions/telegram-bot/index.ts
@@ -90,6 +90,8 @@ const CLAUDE_SYSTEM_PROMPT = `You are the official PezkuwiChain AI Assistant on
RULES:
- Answer in the SAME LANGUAGE the user writes in. If they write in Kurdish (Kurmancî), answer in Kurdish. If Turkish, answer in Turkish. If English, answer in English. If Arabic, answer in Arabic. If Persian, answer in Persian.
+- Write NATURAL, fluent, conversational language - especially in Turkish and Kurdish, avoid stilted formal suffixes ("bulunmaktadır", "göstermektedir") and translation-flavored phrasing; short clear sentences, like a knowledgeable friend explaining.
+- STRICTLY plain text: never use markdown (**, ##, bullet asterisks). Simple dashes for lists are fine.
- Be concise — Telegram messages should be short and readable.
- Use plain text, no markdown headers. You can use bold with *text* sparingly.
- If you don't know something, say so honestly.
@@ -97,7 +99,7 @@ RULES:
- You represent PezkuwiChain officially — be professional and helpful.
- Do not discuss other blockchain projects comparatively unless asked.
- For technical questions about source code, direct users to: github.com/pezkuwichain/pezkuwi-sdk
-- For the wallet app, direct users to: @DKSKurdistanBot on Telegram (they can click "Open PezkuwiChain App" after /start)
+- For the wallet app, direct users to: the Pezkuwi Wallet Android app on Google Play (https://play.google.com/store/apps/details?id=io.pezkuwichain.wallet) or the Telegram MiniApp via @DKSKurdistanBot (click "Open PezkuwiChain App" after /start)
- INVESTOR/IDEA REFERRAL: If a user expresses genuine interest in investing in PezkuwiChain, partnering, contributing financially, or proposes a serious idea for the development of DijitalKurdistan, direct them to contact @Pezkuw on Telegram. Only do this when the user's intent is clearly serious — not for casual questions about tokenomics or "how to buy". Example triggers: "I want to invest", "I have funding", "I represent a fund/company", "I have a business proposal", "I want to contribute to the project's development".
PEZKUWICHAIN WHITEPAPER v5.0 — KNOWLEDGE BASE:
@@ -126,6 +128,14 @@ Role Score: Soulbound NFT roles via pezpallet-tiki. 49 variants: Applicant (Daxw
Validator Pool: 10 Stake Validators + 6 Parliamentary Validators + 5 Merit Validators = 21 total.
+TRUST SCORE — HOW TO INCREASE IT (VERY IMPORTANT — users frequently ask this):
+If a user asks "why is my trust score 0?": To have a trust score at all, you must have at least 1.1 HEZ on People Chain and have STAKED at least 1 HEZ. Staking is the multiplier of the whole formula — with zero stake, referrals/education/roles cannot produce any score (S=0 means trust_score=0).
+If a user asks "how do I increase my trust score?": The more you do of these, the higher your score:
+1. Stake more HEZ, and keep it staked longer (staking amount tiers: 1-100 HEZ: 20pts, 101-250: 30pts, 251-750: 40pts, 751+: 50pts; duration multiplier grows from 1.0x up to 2.0x at 12+ months).
+2. Refer more people (each verified referral adds points, up to 500 max at 101+ referrals).
+3. Educate yourself — complete on-chain courses and certificate programs via the Perwerde education network (education score).
+4. Become a citizen (Welati soulbound NFT: +10pts) and earn community roles (teacher, moderator, etc. add larger bonuses).
+
DUAL-TOKEN ECONOMY:
HEZ Token (Security): 200M genesis, 8% annual inflation, 85% stakers / 15% treasury. 12 decimals (TYR base unit).
Genesis: 100M (50%) presale pool, 40M (20%) Kurdistan Treasury, 40M (20%) airdrop reserve, 20M (10%) founder.
@@ -199,12 +209,52 @@ Relay Chain: wss://rpc.pezkuwichain.io
Asset Hub: wss://asset-hub-rpc.pezkuwichain.io
People Chain: wss://people-rpc.pezkuwichain.io
+PEZKUWI WALLET — OFFICIAL ANDROID APP (live on Google Play since July 2026, v1.1.2):
+Download: https://play.google.com/store/apps/details?id=io.pezkuwichain.wallet
+The official mobile wallet of PezkuwiChain / Digital Kurdistan State. Features:
+- Manage HEZ and PEZ tokens, staking, on-chain governance voting
+- Full Polkadot ecosystem support (DOT, Asset Hub tokens) inherited from its Nova Wallet foundation
+- Native multi-chain support: Bitcoin (BTC), Solana (SOL), Tron (TRX + TRC-20 USDT) — send and receive directly on their own chains, real on-chain transactions, keys derived from the same seed phrase
+- USDT Bridge: converts between wUSDT on Pezkuwi Asset Hub and USDT on Polkadot Asset Hub, in both directions. This is the ONLY bridge pair — the app does not bridge SOL, TRX or ETH.
+- Multisig accounts (shared-control wallets with threshold approvals), including approving operations via deep links
+- Trust Score dashboard card showing your on-chain trust score, roles, and citizen count
+- Gift feature: send tokens as a QR/link gift that the recipient claims in-app
+- Cloud backup, multiple wallets, hardware wallet (Polkadot Vault / Ledger) support
+
+PEZ MINING SIMULATION (in the Pezkuwi Wallet app — users frequently ask about this):
+Inside the Trust Score card there is a small "Mining Simulation" square with a diamond counter, labeled "PEZ Airdrop".
+- What it is: a simulation that PREVIEWS your estimated PEZ airdrop. It shows, based on your Trust Score, approximately how much PEZ you could receive from the era's distribution. It is not literal mining — the diamond count is an ESTIMATE.
+- The diamonds cannot be manually converted by the user. The REAL PEZ airdrop is calculated transparently on-chain at the end of each era (~30 days) and distributed AUTOMATICALLY to wallets (trust-score-weighted share of the era pool, via pezpallet-pez-rewards). When the era ends and the real airdrop is paid out, the diamond counter automatically resets to zero. So the counter shows the PEZ airdrop you are estimated to earn.
+- Purpose: to let users SEE how raising their Trust Score — through referrals, staking HEZ, earning tiki roles, and completing education — increases their PEZ airdrop.
+- How the counter works: tap the square to start a 24-hour mining session. While a session is active, diamonds accrue every minute, proportional to your Trust Score: rate = (92.5M PEZ era pool / 43,200 minutes) × (your trust score / 500,000 reference network total). Example: trust score 340 ≈ 1.46 diamonds/minute. When the 24h session ends, accrual stops — tap the square again to start a new session (your accumulated total is kept within the era).
+- If your Trust Score is 0, the counter cannot start — the app shows a warning that your trust score must be greater than 0. To fix this: become a citizen, stake HEZ (required for any trust score), refer others, complete education courses.
+- Colors: red square = inactive (tap to start), gold = actively mining.
+- The small Telegram icon next to it opens the official channel: https://t.me/+DUWJ8wtt5qI4Njgy
+
+"BULUT ULUSU" (CLOUD NATION) — THE BOOK BEHIND PEZKUWICHAIN (chapter-by-chapter knowledge):
+PezkuwiChain's philosophical foundation is the book "Bulut Ulusu" (Cloud Nation), written by the project's architect (a software developer AND sociologist — the "two desks" of the opening chapter). Available in Turkish, English and Kurdish. Core theses:
+- Code is law in a literal sense: every cryptographic design choice is a political claim about who holds authority, how censorship is escaped, and how trust is established without a central institution.
+- "Westphalia's collapse": the 20th-century nation-state model (absolute borders, assimilation) is cracking. Path Dependency explains why humanity stays on inefficient old roads; the Network State ("Fikir Birliği Ulusu" — consensus nation) is the emerging alternative: a nation built on shared ideas and cryptographic consensus rather than territory.
+- Plurality and the mathematics of justice: stories like Berivan (an unbanked Kurdish refugee rejected by traditional finance) show the cost of statelessness; "Hyper-Hawala" — trust networks scaled beyond the Dunbar number by cryptography.
+- The sociology of statelessness: Kurds (40+ million, no state, Agamben's "Homo Sacer") are candidates to be this era's "Vanguard Nation" (Öncü Ulus) — historical victimhood becomes "zero friction" flexibility: no legacy state apparatus to defend, freedom to build a new civilization model from scratch.
+- Three chains, one nation: the multi-chain architecture (Relay + Asset Hub + People Chain) is philosophy made executable — praxis running in compilers and distributed nodes instead of squares and manifestos.
+- TNPoS and "Bext û Soz" (a Kurdish concept: honor and one's word): moving from the dictatorship of money (pure Proof-of-Stake plutocracy) to the transparency of trust — social reputation, education and community roles encoded into consensus.
+- Dual economy: central banks as an "apparatus of capture" (Deleuze & Guattari) facing structural, mathematical inefficiency; HEZ as network fuel and PEZ as the community's value/governance asset.
+- Self-Sovereign Identity (SSI): the modern state turned identity into a file number — a vast alienation. PezkuwiChain returns identity ownership to the person (encrypted hashes on-chain, the person holds the keys).
+- Education's frozen evolution: schools barely changed in 150 years while everything else transformed; the Perwerde network puts verified learning on-chain and rewards it with trust score.
+- A universal Layer 1: not only for Kurds — an infrastructure for 100M+ stateless people worldwide; the excluded are "read-only" in today's systems, PezkuwiChain gives them write access.
+- Capacity thresholds: growth is modeled as concrete capacity thresholds (illustrated by Zana, a stateless Ezidi youth), explicitly avoiding prophecy.
+- The old world's resistance: regulatory, sociological and diplomatic thresholds are expected; the project's stance is COMPLEMENTARY PARTICIPATION — it does not challenge regional states and does not seek to change any border. A digital nation, not a territorial claim.
+- Conclusion: the statelessness experience is no longer a curse but one of humanity's paths to freedom; the book is "not a completed victory but the record of an ongoing construction."
+When asked about the book, its ideas, or "why does PezkuwiChain exist": answer from these theses. The book's preface is deliberately left half-finished — it belongs to the community that will write the future.
+
LINKS:
Website: pezkuwichain.io
GitHub: github.com/pezkuwichain/pezkuwi-sdk
Discord: discord.gg/Y3VyEC6h8W
-Telegram Channel: t.me/kurdishmedya
+Telegram Channel: https://t.me/+DUWJ8wtt5qI4Njgy
Telegram App: @DKSKurdistanBot
+Android App: https://play.google.com/store/apps/details?id=io.pezkuwichain.wallet
PROBLEM SOLVED: Over 100 million stateless people. Kurdish population 40+ million across 4 countries — financial exclusion, identity fragmentation, governance vacuum. PezkuwiChain provides digital nation-state infrastructure.
@@ -219,9 +269,60 @@ Phase 4 (2028+): Cross-chain governance federation, decentralized identity, stab
License: Apache 2.0, Copyright 2026 Kurdistan Tech Institute. Lead Architect: SatoshiQaziMuhammed.`;
-// ── Claude AI chat handler ──────────────────────────────────────────
+// Groq's openai/gpt-oss-120b returns intermittent errors under load (429/5xx,
+// and even a raw 502 from the edge runtime once) unrelated to the question
+// asked — confirmed live 2026-07-21 by hitting this endpoint repeatedly with
+// trivial questions ("merhaba") and seeing a ~50% failure rate with 15s+
+// between calls (ruling out our own per-IP rate limiter), which 2 retries on
+// the same model did not fully fix. Falls back to llama-3.3-70b-versatile
+// (the model this used before switching to gpt-oss-120b for better Turkish/
+// Kurdish — still free on Groq, and not observed to have the same instability)
+// if gpt-oss-120b exhausts its retries, before ever reaching the Anthropic
+// fallback below. Retries a 4xx (bad request/auth) not at all — that's not
+// transient and switching models wouldn't help either.
+const GROQ_MODELS = ['openai/gpt-oss-120b', 'llama-3.3-70b-versatile'];
+
+async function callGroqWithRetry(
+ systemPrompt: string,
+ userMessage: string,
+ retriesPerModel = 2
+): Promise {
+ for (const model of GROQ_MODELS) {
+ for (let attempt = 0; attempt <= retriesPerModel; attempt++) {
+ try {
+ const gr = await fetch('https://api.groq.com/openai/v1/chat/completions', {
+ method: 'POST',
+ headers: { Authorization: 'Bearer ' + GROQ_API_KEY, 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ model,
+ temperature: 0.3,
+ max_tokens: 900,
+ messages: [
+ { role: 'system', content: systemPrompt },
+ { role: 'user', content: userMessage },
+ ],
+ }),
+ });
+ if (gr.ok) {
+ const gd = await gr.json();
+ const reply = gd.choices?.[0]?.message?.content || null;
+ if (reply) return reply;
+ } else {
+ console.error('[AI] Groq error:', model, gr.status, await gr.text());
+ if (gr.status !== 429 && gr.status < 500) break; // non-transient, try next model instead
+ }
+ } catch (e) {
+ console.error('[AI] Groq exception:', model, e);
+ }
+ if (attempt < retriesPerModel) await new Promise((r) => setTimeout(r, 400 * (attempt + 1)));
+ }
+ }
+ return null;
+}
+
+// ── AI chat handler ──────────────────────────────────────────
async function handleAIChat(token: string, chatId: number, userMessage: string, userName: string) {
- if (!ANTHROPIC_API_KEY) {
+ if (!GROQ_API_KEY && !ANTHROPIC_API_KEY) {
await sendTelegramRequest(token, 'sendMessage', {
chat_id: chatId,
text: 'AI assistant is being configured. Please try again later.',
@@ -240,29 +341,7 @@ async function handleAIChat(token: string, chatId: number, userMessage: string,
let aiReply: string | null = null;
if (GROQ_API_KEY) {
- try {
- const gr = await fetch('https://api.groq.com/openai/v1/chat/completions', {
- method: 'POST',
- headers: { Authorization: 'Bearer ' + GROQ_API_KEY, 'Content-Type': 'application/json' },
- body: JSON.stringify({
- model: 'llama-3.3-70b-versatile',
- temperature: 0.3,
- max_tokens: 900,
- messages: [
- { role: 'system', content: CLAUDE_SYSTEM_PROMPT },
- { role: 'user', content: userMessage },
- ],
- }),
- });
- if (gr.ok) {
- const gd = await gr.json();
- aiReply = gd.choices?.[0]?.message?.content || null;
- } else {
- console.error('[AI] Groq error:', gr.status, await gr.text());
- }
- } catch (e) {
- console.error('[AI] Groq exception:', e);
- }
+ aiReply = await callGroqWithRetry(CLAUDE_SYSTEM_PROMPT, userMessage);
}
if (!aiReply && ANTHROPIC_API_KEY) {
@@ -288,6 +367,9 @@ async function handleAIChat(token: string, chatId: number, userMessage: string,
}
}
+ // Models occasionally emit markdown despite the plain-text rule; Telegram renders it raw.
+ if (aiReply) aiReply = aiReply.replace(/\*\*/g, '').replace(/^#+\s*/gm, '');
+
if (!aiReply) {
await sendTelegramRequest(token, 'sendMessage', {
chat_id: chatId,
@@ -382,8 +464,8 @@ async function sendMainWelcome(token: string, chatId: number) {
],
[
{
- text: '🤖 Play Store (Coming Soon)',
- callback_data: 'playstore_coming_soon',
+ text: '🤖 Get it on Google Play',
+ url: 'https://play.google.com/store/apps/details?id=io.pezkuwichain.wallet',
},
],
],
@@ -477,7 +559,7 @@ async function sendDksWelcome(token: string, chatId: number) {
[
{
text: '📢 Join Channel / Kanalê Tev Bibin',
- url: 'https://t.me/kurdishmedya',
+ url: 'https://t.me/+DUWJ8wtt5qI4Njgy',
},
],
],
@@ -559,11 +641,18 @@ async function handleCallbackQuery(
});
await handleCreateWallet(token, chatId);
} else if (data === 'playstore_coming_soon') {
+ // Legacy button on old messages - the app is live now, send the real link
await sendTelegramRequest(token, 'answerCallbackQuery', {
callback_query_id: callbackQueryId,
- text: '🚀 Android app coming soon! Stay tuned.',
+ text: '🚀 The Android app is live on Google Play!',
show_alert: true,
});
+ if (chatId) {
+ await sendTelegramRequest(token, 'sendMessage', {
+ chat_id: chatId,
+ text: '📱 Pezkuwi Wallet is live on Google Play:\nhttps://play.google.com/store/apps/details?id=io.pezkuwichain.wallet',
+ });
+ }
}
}
@@ -582,7 +671,8 @@ Just type your question in any language and I'll answer!
Links:
🌐 Website: pezkuwichain.io
-📢 Channel: t.me/kurdishmedya
+📢 Channel: https://t.me/+DUWJ8wtt5qI4Njgy
+📱 Android App: https://play.google.com/store/apps/details?id=io.pezkuwichain.wallet
💬 Discord: discord.gg/Y3VyEC6h8W
`;
await sendTelegramRequest(token, 'sendMessage', {
From 54c94c75583c4e2c5f5b0b1e2e8cb9930e98cc69 Mon Sep 17 00:00:00 2001
From: SatoshiQaziMuhammed
Date: Tue, 21 Jul 2026 07:52:59 -0700
Subject: [PATCH 18/18] fix(ai): prioritize Groq's most stable model, stop
repeating mining disclaimer (#9)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
User decision after the Groq reliability fix (previous PR): prioritize
Groq's smallest/fastest model, llama-3.1-8b-instant, over gpt-oss-120b —
it's long out of preview and has historically the best free-tier
availability, at the cost of gpt-oss-120b's better Turkish/Kurdish
fluency (which is why it was chosen originally). Model order is now
llama-3.1-8b-instant -> gpt-oss-120b -> llama-3.3-70b-versatile before
the (currently uncredited) Anthropic fallback.
Also fixed a real UX complaint: asking about the Mining Simulation made
the model repeat "this isn't real mining / it's just an estimate" in
nearly every paragraph. Added an explicit instruction to state that once,
briefly, near the start of the answer, and not repeat it — verified live,
the disclaimer now appears once per response instead of several times.
---
package.json | 2 +-
src/version.json | 6 +++---
supabase/functions/ask/index.ts | 21 ++++++++++++++-------
supabase/functions/telegram-bot/index.ts | 21 ++++++++++++++-------
4 files changed, 32 insertions(+), 18 deletions(-)
diff --git a/package.json b/package.json
index 15c6075..73458c5 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "pezkuwi-telegram-miniapp",
- "version": "1.0.241",
+ "version": "1.0.242",
"type": "module",
"description": "Pezkuwichain Telegram Mini App - Forum, Announcements, Rewards",
"author": "Pezkuwichain Team",
diff --git a/src/version.json b/src/version.json
index 9833611..89e672c 100644
--- a/src/version.json
+++ b/src/version.json
@@ -1,5 +1,5 @@
{
- "version": "1.0.241",
- "buildTime": "2026-07-21T14:31:14.612Z",
- "buildNumber": 1784644274612
+ "version": "1.0.242",
+ "buildTime": "2026-07-21T14:51:23.002Z",
+ "buildNumber": 1784645483003
}
diff --git a/supabase/functions/ask/index.ts b/supabase/functions/ask/index.ts
index 02d3395..ae74187 100644
--- a/supabase/functions/ask/index.ts
+++ b/supabase/functions/ask/index.ts
@@ -150,6 +150,7 @@ Inside the Trust Score card there is a small "Mining Simulation" square with a d
- If your Trust Score is 0, the counter cannot start — the app shows a warning that your trust score must be greater than 0. To fix this: become a citizen, stake HEZ (required for any trust score), refer others, complete education courses.
- Colors: red square = inactive (tap to start), gold = actively mining.
- The small Telegram icon next to it opens the official channel: https://t.me/+DUWJ8wtt5qI4Njgy
+- IMPORTANT — how to talk about this: state that it's a simulation/estimate ONCE, briefly, near the start of your answer, then move on and explain the rest normally. Do NOT repeat "this isn't real mining" / "it's just an estimate" / similar caveats in every paragraph — one clear mention is enough, repeating it reads as nagging.
"BULUT ULUSU" (CLOUD NATION) — THE BOOK BEHIND PEZKUWICHAIN (chapter-by-chapter knowledge):
PezkuwiChain's philosophical foundation is the book "Bulut Ulusu" (Cloud Nation), written by the project's architect (a software developer AND sociologist — the "two desks" of the opening chapter). Available in Turkish, English and Kurdish. Core theses:
@@ -233,13 +234,19 @@ async function allowed(ip: string): Promise {
// asked — confirmed live 2026-07-21 by hitting this endpoint repeatedly with
// trivial questions ("merhaba") and seeing a ~50% failure rate with 15s+
// between calls (ruling out our own per-IP rate limiter above), which 2
-// retries on the same model did not fully fix. Falls back to
-// llama-3.3-70b-versatile (the model this used before switching to
-// gpt-oss-120b for better Turkish/Kurdish — still free on Groq, not observed
-// to have the same instability) if gpt-oss-120b exhausts its retries, before
-// ever reaching the Anthropic fallback below. Doesn't retry a 4xx (bad
-// request/auth) at all — not transient, and switching models wouldn't help.
-const GROQ_MODELS = ['openai/gpt-oss-120b', 'llama-3.3-70b-versatile'];
+// retries on the same model did not fully fix.
+//
+// 2026-07-21, user decision: prioritize reliability over gpt-oss-120b's
+// better Turkish/Kurdish fluency (it was picked for that reason via an
+// earlier A/B test) — llama-3.1-8b-instant is Groq's smallest/fastest model
+// and, being long out of preview, has historically the best free-tier
+// availability, so it goes first. gpt-oss-120b stays as the 2nd attempt
+// (still worth trying for quality when the primary is having its own bad
+// moment), llama-3.3-70b-versatile (the model used before switching to
+// gpt-oss-120b) as the 3rd, before ever reaching the Anthropic fallback
+// below. Doesn't retry a 4xx (bad request/auth) at all — not transient, and
+// switching models wouldn't help.
+const GROQ_MODELS = ['llama-3.1-8b-instant', 'openai/gpt-oss-120b', 'llama-3.3-70b-versatile'];
async function callGroqWithRetry(messages: unknown[], retriesPerModel = 2): Promise {
for (const model of GROQ_MODELS) {
diff --git a/supabase/functions/telegram-bot/index.ts b/supabase/functions/telegram-bot/index.ts
index 9326611..1033a87 100644
--- a/supabase/functions/telegram-bot/index.ts
+++ b/supabase/functions/telegram-bot/index.ts
@@ -230,6 +230,7 @@ Inside the Trust Score card there is a small "Mining Simulation" square with a d
- If your Trust Score is 0, the counter cannot start — the app shows a warning that your trust score must be greater than 0. To fix this: become a citizen, stake HEZ (required for any trust score), refer others, complete education courses.
- Colors: red square = inactive (tap to start), gold = actively mining.
- The small Telegram icon next to it opens the official channel: https://t.me/+DUWJ8wtt5qI4Njgy
+- IMPORTANT — how to talk about this: state that it's a simulation/estimate ONCE, briefly, near the start of your answer, then move on and explain the rest normally. Do NOT repeat "this isn't real mining" / "it's just an estimate" / similar caveats in every paragraph — one clear mention is enough, repeating it reads as nagging.
"BULUT ULUSU" (CLOUD NATION) — THE BOOK BEHIND PEZKUWICHAIN (chapter-by-chapter knowledge):
PezkuwiChain's philosophical foundation is the book "Bulut Ulusu" (Cloud Nation), written by the project's architect (a software developer AND sociologist — the "two desks" of the opening chapter). Available in Turkish, English and Kurdish. Core theses:
@@ -274,13 +275,19 @@ License: Apache 2.0, Copyright 2026 Kurdistan Tech Institute. Lead Architect: Sa
// asked — confirmed live 2026-07-21 by hitting this endpoint repeatedly with
// trivial questions ("merhaba") and seeing a ~50% failure rate with 15s+
// between calls (ruling out our own per-IP rate limiter), which 2 retries on
-// the same model did not fully fix. Falls back to llama-3.3-70b-versatile
-// (the model this used before switching to gpt-oss-120b for better Turkish/
-// Kurdish — still free on Groq, and not observed to have the same instability)
-// if gpt-oss-120b exhausts its retries, before ever reaching the Anthropic
-// fallback below. Retries a 4xx (bad request/auth) not at all — that's not
-// transient and switching models wouldn't help either.
-const GROQ_MODELS = ['openai/gpt-oss-120b', 'llama-3.3-70b-versatile'];
+// the same model did not fully fix.
+//
+// 2026-07-21, user decision: prioritize reliability over gpt-oss-120b's
+// better Turkish/Kurdish fluency (it was picked for that reason via an
+// earlier A/B test) — llama-3.1-8b-instant is Groq's smallest/fastest model
+// and, being long out of preview, has historically the best free-tier
+// availability, so it goes first. gpt-oss-120b stays as the 2nd attempt
+// (still worth trying for quality when the primary is having its own bad
+// moment), llama-3.3-70b-versatile (the model used before switching to
+// gpt-oss-120b) as the 3rd, before ever reaching the Anthropic fallback
+// below. Retries a 4xx (bad request/auth) not at all — that's not transient
+// and switching models wouldn't help either.
+const GROQ_MODELS = ['llama-3.1-8b-instant', 'openai/gpt-oss-120b', 'llama-3.3-70b-versatile'];
async function callGroqWithRetry(
systemPrompt: string,