celo-poll/lib/wallet.ts
2025-12-08 16:31:30 +03:00

192 lines
4.9 KiB
TypeScript

/**
* Wallet Management for Protocol
* Handles cUSD transfers and distribution to winners
*/
import { Wallet, JsonRpcProvider, Contract, parseUnits, formatUnits } from 'ethers'
import { CUSD_ADDRESS } from './celo'
// cUSD ERC20 ABI for ethers.js
const CUSD_ABI = [
'function transfer(address to, uint256 amount) returns (bool)',
'function balanceOf(address account) view returns (uint256)',
'function approve(address spender, uint256 amount) returns (bool)',
'function allowance(address owner, address spender) view returns (uint256)',
]
// Initialize provider and wallet
let protocolWallet: Wallet | null = null
let provider: JsonRpcProvider | null = null
let cUSDContract: Contract | null = null
/**
* Initialize protocol wallet
*/
export function initializeWallet(): void {
if (!process.env.PROTOCOL_WALLET_PRIVATE_KEY) {
throw new Error('PROTOCOL_WALLET_PRIVATE_KEY not set')
}
const rpcUrl = process.env.NEXT_PUBLIC_CELO_RPC_URL || 'https://forno.celo.org'
provider = new JsonRpcProvider(rpcUrl)
protocolWallet = new Wallet(process.env.PROTOCOL_WALLET_PRIVATE_KEY, provider)
cUSDContract = new Contract(CUSD_ADDRESS, CUSD_ABI, protocolWallet)
console.log('✅ Protocol wallet initialized:', protocolWallet.address)
}
/**
* Get protocol wallet instance
*/
export function getProtocolWallet(): Wallet {
if (!protocolWallet) {
initializeWallet()
}
return protocolWallet!
}
/**
* Get cUSD contract instance
*/
export function getCUSDContract(): Contract {
if (!cUSDContract) {
initializeWallet()
}
return cUSDContract!
}
/**
* Get protocol wallet address
*/
export function getProtocolWalletAddress(): string {
return process.env.PROTOCOL_WALLET_ADDRESS || getProtocolWallet().address
}
/**
* Get protocol wallet cUSD balance
*/
export async function getProtocolBalance(): Promise<number> {
try {
const contract = getCUSDContract()
const balance = await contract.balanceOf(getProtocolWalletAddress())
return Number(formatUnits(balance, 18))
} catch (error) {
console.error('Failed to get protocol balance:', error)
return 0
}
}
/**
* Send cUSD to an address
*/
export async function sendCUSD(
toAddress: string,
amount: number
): Promise<{ success: boolean; txHash?: string; error?: string }> {
try {
const contract = getCUSDContract()
const amountWei = parseUnits(amount.toString(), 18)
console.log(`💸 Sending ${amount} cUSD to ${toAddress}...`)
const tx = await contract.transfer(toAddress, amountWei)
console.log(`⏳ Transaction sent: ${tx.hash}`)
await tx.wait()
console.log(`✅ Transaction confirmed: ${tx.hash}`)
return {
success: true,
txHash: tx.hash,
}
} catch (error: any) {
console.error(`❌ Failed to send cUSD to ${toAddress}:`, error)
return {
success: false,
error: error.message || 'Transaction failed',
}
}
}
/**
* Send cUSD to multiple addresses (batch)
*/
export async function batchSendCUSD(
recipients: Array<{ address: string; amount: number }>
): Promise<Array<{ address: string; success: boolean; txHash?: string; error?: string }>> {
const results = []
for (const recipient of recipients) {
const result = await sendCUSD(recipient.address, recipient.amount)
results.push({
address: recipient.address,
...result,
})
// Small delay between transactions to avoid nonce issues
await new Promise(resolve => setTimeout(resolve, 2000))
}
return results
}
/**
* Estimate gas for a transaction
*/
export async function estimateGasCost(
toAddress: string,
amount: number
): Promise<number> {
try {
const contract = getCUSDContract()
const amountWei = parseUnits(amount.toString(), 18)
const gasEstimate = await contract.transfer.estimateGas(toAddress, amountWei)
const feeData = await getProtocolWallet().provider!.getFeeData()
const gasCostWei = gasEstimate * (feeData.gasPrice || 0n)
return Number(formatUnits(gasCostWei, 18))
} catch (error) {
console.error('Failed to estimate gas:', error)
return 0.001 // Default estimate
}
}
/**
* Check if wallet has enough balance for distribution
*/
export async function canDistribute(totalAmount: number): Promise<boolean> {
const balance = await getProtocolBalance()
const gasCost = await estimateGasCost(getProtocolWalletAddress(), totalAmount)
return balance >= totalAmount + gasCost
}
/**
* Verify transaction on Celo Explorer
*/
export function getExplorerUrl(txHash: string): string {
return `https://explorer.celo.org/mainnet/tx/${txHash}`
}
/**
* Format cUSD amount for display
*/
export function formatCUSD(amount: number): string {
if (amount >= 1000) {
return `${(amount / 1000).toFixed(1)}K cUSD`
}
if (amount >= 1) {
return `${amount.toFixed(2)} cUSD`
}
return `${amount.toFixed(3)} cUSD`
}
/**
* Validate Celo address
*/
export function isValidAddress(address: string): boolean {
return /^0x[a-fA-F0-9]{40}$/.test(address)
}