A Discord bot that allows you to conduct cryptographically secure elections over discord and sell electoral bonds with automated price discovery!
๐ฅ Invite ElectionBot to Your Server
Ready to run democratic elections with token-based campaign finance? Click the link above to add ElectionBot to your Discord server instantly!
Featurinng democratic elections with token-based campaign finance using GitHub Gists for persistent storage.
Check user coin balances and financial status
Create political parties with custom emojis and agendas

Request to join existing political parties
Monitor individual user account balances
- Democratic Elections: Create time-bound elections with multiple parties
- Token-Based Finance: Parties can issue bonds with bonding curve mechanics
- Cryptographic Voting: RSA signature-based vote verification
- Campaign System: Spend campaign funds to promote your party
- GitHub Gist Storage: All data stored remotely in GitHub Gists (no local database)
- Party Management: Create parties, join/leave, manage agendas
- Settlement: Automatic end-of-election token liquidation and fund distribution
- Market Analytics: Real-time bond curves and price history visualization
- Dockerized Deployment: Production-ready containerization
- ๐ธ Screenshots & Demo
- ๐ Add to Your Discord Server
- Setup
- Usage
- Bond Finance Mechanics
- System Architecture
- Security Considerations
- Development
- Node.js v18+ OR Docker
- Discord application with bot token
- GitHub Personal Access Token with gist permissions
The easiest way to run the bot:
- Clone and configure:
git clone <repository-url>
cd election-bot
cp .env.example .env
# Edit .env with your tokens- Run with Docker Compose:
docker-compose up -d
docker-compose exec election-bot npm run deploy-commandsSee DOCKER.md for detailed Docker deployment guide.
- Clone this repository:
git clone <repository-url>
cd election-bot- Install dependencies:
npm install- Set up environment variables:
cp .env.example .envEdit .env with your credentials:
DISCORD_TOKEN=your_discord_bot_token_here
DISCORD_CLIENT_ID=your_discord_client_id_here
GITHUB_TOKEN=your_github_personal_access_token_here
# Optional configuration
DEFAULT_DURATION_HOURS=24
DEFAULT_ACTIVITY_WINDOW_HOURS=24
DEFAULT_ACTIVITY_POOL_COINS=50
MICROCOINS_PER_COIN=1000000
DEFAULT_ON_EMPTY_PARTY_VAULT=burn- Build the project:
npm run build- Deploy slash commands:
npm run deploy-commands- Start the bot:
npm start- Create a role named exactly
electionBotAdminin your Discord server - Assign this role to users who should be able to create/delete elections
/create <name> [start] [duration]- Create a new election with specified name and timeline/delete- Delete the current active election and all associated data/settle- End the election and distribute funds to winning token holders/listelections- Display all elections and their current status/resetbot- Reset all bot data (use with caution)
/createparty <election> <name> <emoji> <agenda>- Create a political party in an election/joinparty <party>- Request to join an existing party (requires leader approval)/leaveparty <party>- Leave a party you're currently a member of/editparty <party> [emoji] [agenda]- Update your party's emoji or agenda (leaders only)/deleteparty <party>- Delete your party (leaders only, requires confirmation)/listparties- Display all parties in the current election
/createbonds <party> <amount> <tokens> <alpha>- Issue bonds for your party (leaders only)/buybonds <party> <amount>- Buy party bonds to invest in their success/sellbonds <party> <tokens>- Sell your bonds back to the market/plotbondcurve <party>- Display interactive bond pricing curve/plotpricehistory <party>- Show historical price data and recent transactions
/balance- Check your current coin balance/transfertoparty <party> <amount>- Transfer coins from your account to party vault
/register <election> <publickey>- Register RSA public key for secure voting/vote <election> <party> <message> <signature>- Cast your vote using RSA signature
/campaign <party> <headline> <body>- Create a campaign post (costs party funds)
/help- Display comprehensive bot usage guide and command reference
ElectionBot implements a sophisticated token-based campaign finance system using bonding curves for price discovery and automated market making.
Step 1: Initialize Party Bonds
/createbonds party:DemocratParty amount:100 tokens:50 alpha:0.7- Initial Pool: 100 coins committed by party leader
- Token Supply: 50 tokens issued for trading
- Alpha Parameter: 0.7 (70% of purchases go to liquidity, 30% to vault)
- Initial Price:
pool รท tokens = 100 รท 50 = 2.0 coins/token
Simple Supply-Demand Model (Updated from constant product):
- Current Price =
Pool รท Remaining Tokens - After Purchase: Price =
(Pool + New Money) รท (Tokens - Sold Tokens)
Example Price Evolution:
- Initial: 100 coins รท 50 tokens = 2.0 coins/token
- After buying 10 tokens with 25 coins: (100 + 17.5) รท (50 - 10) = 2.94 coins/token
- Market dynamics: More demand โ Higher prices โ Incentivizes early supporters
When a user buys bonds with X coins:
User Payment (X coins)
โ
Split by Alpha
โ
โโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโ
โ Pool Fund โ Vault Fund โ
โ (Alpha ร X) โ (1-Alpha) ร X โ
โ โ โ
โ โข Price calc โ โข Campaign fund โ
โ โข Liquidity โ โข Operations โ
โ โข Buybacks โ โข Member payoutsโ
โโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโ
Alpha Parameter Effects:
- High Alpha (0.8-1.0): Liquid market, stable pricing, less campaign funds
- Medium Alpha (0.5-0.7): Balanced liquidity and operations
- Low Alpha (0.1-0.4): More campaign funds, volatile pricing
Buying Bonds:
/buybonds party:DemocratParty amount:50- User spends 50 coins
- Pool gets
alpha ร 50coins (e.g., 35 coins if alpha=0.7) - Vault gets
(1-alpha) ร 50coins (e.g., 15 coins if alpha=0.7) - User receives tokens based on current price
- Price increases due to reduced supply
Selling Bonds:
/sellbonds party:DemocratParty tokens:10- User sells 10 tokens back to the system
- Coins refunded from pool based on current price
- Price decreases as token supply increases
- Only works during election period
Real-time Bond Curve:
/plotbondcurve party:DemocratParty- Visual ASCII chart showing price vs tokens sold
- Current market status and metrics
- Helps users understand pricing dynamics
Historical Price Tracking:
/plotpricehistory party:DemocratParty- Time-series plot of all buy/sell transactions
- Price evolution over election period
- Market sentiment analysis
For Early Supporters:
- Lower entry prices when buying early
- Higher potential returns if party wins
- Influence party agenda through financial stake
For Party Leaders:
- Campaign funding through bond sales
- Market validation of party support
- Incentive to maintain supporter confidence
For Traders:
- Speculation on election outcomes
- Arbitrage opportunities between parties
- Risk/reward based on political analysis
During Election End:
- Pool Consolidation: All party pools merged into winner's pool
- Final Price Calculation:
Final Price = Total Combined Pool รท Winning Party Total Tokens - Winner Token Redemption:
Payout = User's Tokens ร Final Price - Vault Distribution: Each party's vault split equally among members
- Losing Tokens: Become worthless (total loss)
Example Settlement:
Party A (Winner): 200 coin pool, 100 tokens issued
Party B (Loser): 150 coin pool, 75 tokens issued
Combined Pool: 350 coins
Final Price: 350 รท 100 = 3.5 coins/token
Party A token holder with 20 tokens gets: 20 ร 3.5 = 70 coins
Party B tokens become worthless: 0 coins
For Investors:
- Political Risk: Backing losing party = total loss
- Timing Risk: Early vs late entry price differences
- Liquidity Risk: Limited trading during election period
For Parties:
- Market Confidence: Poor performance affects fundraising
- Alpha Selection: Balance between liquidity and campaign funds
- Competition: Multiple parties competing for same investor pool
Price Elasticity:
- Price impact increases as tokens become scarce
- Large purchases have bigger price effects near token depletion
- Symmetric for buying/selling during active trading
Equilibrium Dynamics:
- Market makers balance expected election outcome vs current price
- Price discovery through collective betting on party success
- Self-reinforcing cycles: success โ higher prices โ more funding โ better campaigns
This system creates a prediction market where token prices reflect real-time sentiment about each party's chances of winning, while simultaneously funding their campaigns through the vault mechanism.
When an election ends:
- Pool Merger: All party bond pools are combined
- Winner Price:
final_price = combined_pool รท winning_party_issued_tokens - Token Liquidation: Winning token holders get
tokens ร final_price - Unsold Tokens: Added to winning party's vault at final price
- Vault Distribution: Each party's vault split equally among members
- Losing Tokens: Become worthless
All data is stored in GitHub Gists:
- Public Gist (
public.json): Election state, parties, balances, registrations - Private Gist (
private_votes.json): Votes (kept secret until election ends) - Gist Index: Maps Discord servers to their election gists
- Base Balance: Every user starts with 100 coins
- Activity Rewards: Optional periodic distribution based on message activity
- Bond Trading: Zero-sum between users
- Campaign Spending: Burns coins from party vaults
Configure activity rewards:
- Set
DEFAULT_ACTIVITY_POOL_COINS=0to disable minting - Use
systemReservemode to distribute from fixed pool instead of minting
To vote, users must:
- Generate RSA key pair
- Register public key with
/register - Sign party name with private key
- Submit vote with
/vote <party> <party> <signature>
Example with OpenSSL:
# Generate key pair
openssl genrsa -out private.pem 2048
openssl rsa -in private.pem -pubout -out public.pem
# Sign message
echo -n "PartyName" | openssl dgst -sha256 -sign private.pem | base64- Gist Privacy: Private gists are "secret" but not encrypted. Vote confidentiality depends on gist URL secrecy
- Admin Role:
electionBotAdminrole has full election control - RSA Keys: Users must keep private keys secure; no key recovery mechanism
- Rate Limits: GitHub API limits may affect high-activity servers
- Atomic Updates: Uses optimistic locking to prevent race conditions in gist updates
npm testnpm run devsrc/
โโโ index.ts # Bot entry point
โโโ types.ts # TypeScript type definitions
โโโ commands/ # Slash command implementations
โ โโโ createElection.ts
โ โโโ createParty.ts
โ โโโ vote.ts
โ โโโ ...
โโโ storage/
โ โโโ github.ts # GitHub Gist storage wrapper
โโโ economy/
โ โโโ bonds.ts # Bonding curve mathematics
โ โโโ settlement.ts # End-of-election settlement
โโโ utils/
โโโ crypto.ts # RSA signature verification
โโโ permissions.ts # Role-based access control
โโโ numbers.ts # Safe decimal arithmetic
Environment variables:
| Variable | Default | Description |
|---|---|---|
DEFAULT_DURATION_HOURS |
24 | Default election duration |
DEFAULT_ACTIVITY_WINDOW_HOURS |
24 | Activity tracking window |
DEFAULT_ACTIVITY_POOL_COINS |
50 | Coins per activity period |
MICROCOINS_PER_COIN |
1000000 | Internal precision (1 coin = 1M microcoins) |
DEFAULT_ON_EMPTY_PARTY_VAULT |
burn | What to do with empty party vaults |
- Commands not appearing: Run
npm run deploy-commands - Permission denied: Ensure user has
electionBotAdminrole - GitHub API errors: Check token permissions and rate limits
- Invalid signatures: Verify RSA key format and signing process
The bot logs important events to console. Check for:
- GitHub API errors
- Signature verification failures
- Gist update conflicts
- Command execution errors
MIT License - see LICENSE file for details.
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
For issues and questions:
- Check the troubleshooting section above
- Review bot logs for error messages
- Create an issue in the repository

