Docs

Discover how Phala's AI Agent Contract offers the essential tools to develop and profit from intelligent applications.

Explore Now

Phat Contract: Redefining Trading Bot Security

2023-09-20

What is a Telegram Crypto Trading Bot?

In the era of intent-centric trading aimed at reducing barriers in the DeFi sector, automated trading bots have become increasingly prevalent in social chat applications. Telegram serves as a prime example of this innovation.

A Telegram crypto trading bot is an automated extension within the Telegram messaging app. Unlike traditional trading platforms, these bots adopt an "intent-centric" approach, allowing users to express complex trading intentions easily. The bots then execute these intentions automatically and in real-time, right within Telegram.

Notable Examples:

  • Unibot: Specializes in intent-centric trading on decentralized exchanges such as Uniswap and Sushiswap.
  • BS Trading Bot: Designed for non-tech-savvy individuals, this bot automates trades based on user-set intentions.
  • Lootbot: Manages automated airdrop farming across multiple EVM-compatible blockchains.
  • Collab.Land: Focuses on community management through token-gating, aligning with user intents to join specific communities.

Why Do Telegram Crypto Trading Bots Matter?

The rise of Telegram crypto trading bots is not just a trend but a significant evolution in the DeFi space. Here's why they're game-changing:

  • User-Friendly: The intent-centric design makes it simpler for both newcomers and experienced traders to navigate the complexities of DeFi.
  • Efficiency and Automation: Pre-set trading parameters enable these bots to carry out numerous microtransactions, aiming for consistent, small gains.
  • Community Building: Beyond trading, bots like Collab.Land are invaluable tools for managing and growing online crypto communities.
  • Broadening Accessibility: By simplifying complex processes, these bots make DeFi activities more accessible, encouraging broader participation.

These bots are influencing the way users interact with DeFi platforms, making it more efficient, user-centric, and inclusive. Their rise is an important step toward making DeFi more mainstream.

Key Features of Crypto Trading Bots on Telegram & Discord

Crypto trading bots on Telegram and Discord offer a plethora of features designed to enhance the DeFi trading experience. These features are grouped into four main categories:

1. Automated Trading

  • Execute trades automatically based on pre-set parameters like market-specific prices and farming airdrops across multiple EVM-compatible chains. Specialized tools like Sniper allow you to copy trades from successful wallets and catch new token launches in real-time.

2. Risk and Performance Oversight

  • Utilize features such as Fail Guard Sell to test if an order will fail ahead of time, saving on gas fees. Safeguard your trades from MEV bots to reduce the risk of frontrunning. Performance tracking lets you monitor your profit and loss with precision.

3. Community Engagement

  • Token-gating ensures only qualified members can join your community, while regular membership checks and a miniapp marketplace further enhance community cohesion and engagement.

4. Versatility and Accessibility

  • Trade on multiple exchanges and with a wide variety of tokens. Subscription options include both freemium and premium models, catering to different budgets and requirements.

These features, tailored to each bot's unique strengths, are transforming the way users interact with DeFi by offering a more user-friendly and efficient trading experience.

Why Crypto Bots are So Popular?

Crypto bots are gaining traction due to the numerous benefits they offer. Here are some of the key advantages that these bots bring to the table:

  • Ease of Trading: Crypto bots simplify the trading process by automating tasks. Users can set parameters for trades, and the bot will execute them when the conditions are met. This makes trading more accessible, even for beginners.
  • Efficiency: These bots can execute trades faster and more accurately than humans. They can run hundreds of micro transactions, generating small profits with stop losses. They also allow for seamless trading on multiple exchanges.
  • Risk Management: Crypto bots offer features that help manage risk. For instance, some bots test whether an order will fail ahead of time, saving gas fees and maximizing returns. Others offer private transactions that are protected from MEV bots, reducing the chance of being caught in a frontrun or sandwich attack.
  • Performance Tracking: Crypto bots provide tools for tracking profit and loss, giving users a clear picture of their trading performance.
  • Community Management: Some bots offer community management tools, ensuring that each member possesses the required token(s) to participate in a community. They also provide routine checks to confirm members maintain their status.
  • Airdrop Farming: Certain bots enable users to generate wallets and automatically farm airdrops across multiple EVM-compatible chains, providing an additional source of income.
  • Subscription Models: Some bots offer both freemium and premium subscription models, catering to a variety of user needs and budgets.

These benefits have contributed to the rise in popularity of crypto bots, making them an essential tool for many in the crypto trading world.

Security Risks Associated with Crypto Trading Bots

Crypto trading bots come with a host of advantages, but they aren't without security concerns—especially when it comes to the management of private keys.

The Issue of Self-Custody

Trading bots typically establish a unique wallet for each user and provide private keys to facilitate trading. However, this practice can conflict with the core principle of secure self-custody, which advocates for individuals to manage their own private keys.

The Centralized Risk

Storing private keys on a centralized platform exposes users to considerable risk. A data breach or successful attack on the platform could mean the loss of valuable assets. For example:

  • The Mt. Gox Hack (2014): Lax security measures, including poorly stored private keys, led to the theft of 740,000 bitcoins—6% of all existing bitcoin at the time.
  • The Coincheck Hack (2018): Around 523 million NEM coins were stolen from digital wallets, making it one of the largest thefts in crypto history.

While crypto bots offer unmatched speed and convenience, these benefits should not come at the expense of security. Remember the crypto mantra: "Not your keys, not your coins."

Phat Contract for Telegram Bots: The Ultimate Security Solution

To address the security concerns of crypto trading bots, we introduce Phat Contract, a program running off-chain on the Phala Network. Phat Contract brings computation off-chain, circumventing the limitations of on-chain computation which often has severe limitations and prohibitive costs.

How Phat Contract Makes Smart Contracts Smarter

Phat Contracts are not meant to replace Smart Contracts. Instead, they serve as the missing decentralized computation unit for decentralized applications, combining on-chain verification with off-chain capabilities. This allows Phat Contracts to retain trustlessness, verifiability, and permissionlessness while offering a broader range of features for dApps.

Addressing Security Concerns with Phat Contract:

  • Universal Compatibility: Phat Contracts can easily connect to any blockchain without the need for a bridge. This means they can generate keys as a controller for EVM chains, allowing for an end-to-end handshake between the Telegram bot and the user without a centralized service as a middleman.
  • Access to the Internet: Phat Contracts can send HTTP/HTTPS requests directly, enabling seamless integration with any Web2 APIs. This allows Telegram bots to interact with off-chain data sources, reducing the need for storing sensitive data like private keys on the platform.
  • Complex Logic Execution: Phat Contracts can execute intense off-chain computations in real-time while bypassing transaction fees and network latency. This means they can manage EVM addresses for a Telegram bot, providing enhanced security and ensuring the secrecy of the generated addresses.
  • Verifiable Computation: The computation on Phala Network is provided by a decentralized network: secure, robust, and trustworthy infrastructure. This ensures the fidelity of deployed contracts and their execution, making it harder for attackers to compromise the security of the bots.

Why Choose Phat Contract?

By using Phat Contracts, Telegram bot service providers can replace themselves as a trustless party. Phat Contract is open source, auditable, and verifiable. It runs inside SGX and is secured by the Phala blockchain to ensure no one can act maliciously. It can be used to create and control EVM address funds on Telegram and Discord, significantly enhancing the security of Telegram crypto bots.

Phat-Empowered Crypto Telegram Trading Bot: A Demo

This demo illustrates the transformative impact of Phat Contract on the security and capabilities of Telegram crypto bots. Leveraging the open-source and auditable nature of Phat Contract (source code), we significantly improve the bots' security by generating user addresses securely. This reduces the risk of malicious attacks and ensures address secrecy.

How to Try the Demo

Step 1: Load the Bot

Visit Phatbot Demo to interact with either the Telegram or Discord bot.

Step 2: Activate the Bot

Click 'Start' to activate the bot and access a list of available commands. Wallet addresses will be securely generated via Phat Contract, safeguarding your assets.

Note: The next steps are hypothetical use-cases and aren't live in the current demo.

Potential Features

Step 3: Token Purchases

Future versions could allow token purchases with advanced features like private transactions, fail guards, and frontrun protection. You'd also be able to choose wallets and customize order sizes.

Step 4: Advanced Copytrading

Upcoming iterations may include copytrading tools like Mirror Sniper and Method Sniper, which automatically emulate the trades of specific addresses or purchase new tokens upon launch.

By harnessing the power of Phat Contract, this demo reveals how Telegram crypto bots can become not just more functional, but also far safer for users.

How It Works

Phat Contract can be used to build secure and efficient Telegram bots. Here's a step-by-step guide on how developers can use Phat Contract to build a bot like the one demonstrated in the demo:

Step 1: Set Up the Phat Contract

First, developers need to set up the Phat Contract. This involves writing the phatbot_profile and phatbot_controller contracts in Rust. The phatbot_profile contract is used to create EVM wallets for users and carry out various transaction operations based on these wallets. The phatbot_controller contract is used in conjunction with Bot to perform various automated tasks on the corresponding user's phatbot_profile contract.

Step 2: Guide users to create an EVM wallet on the Website

You need to develop a page that creates EVM wallets. Users sign through the Polkadot wallet on the page and instantiate the phatbot_profile contract to create an EVM wallet belonging to that wallet address based on the Telegram user's ID. The EVM wallet's private key information will be stored on the chain, and the wallet creator can view the created wallet address and private key by calling the contract method get_evm_account_address and get_evm_account_sk.

// phatbot_profile
// ...
impl PhatbotProfile {
    #[ink(constructor)]
    pub fn new(tg_id: String) -> Self {
        let random = signing::derive_sr25519_key(tg_id.as_bytes());
        let sk = random[..32].try_into().unwrap();
        let evm_account = ExternalAccount {
            sk,
            rpc: String::from("<YOUR_RPC_ENDPOINT>"),
            account_type: ExternalAccountType::Generated,
        };
        Self {
            tg_id,
            evm_account,
            owner: Self::env().caller(),
        }
    }

    #[ink(message)]
    pub fn get_evm_account_address(&self) -> Result<H160> {
        let sk = pink_web3::keys::pink::KeyPair::from(self.evm_account.sk);
        Ok(sk.address())
    }

    #[ink(message)]
    pub fn get_evm_account_sk(&self) -> Result<String> {
        self.ensure_owner()?;
        Ok(hex::encode(self.evm_account.sk))
    }
...

Step 3: The management of the EVM wallet

Guide users to assign the management right of the created phatbot_profile contract to the phatbot_controller contract address. Developers can specify the contract address of the manager phatbot_controller when the phatbot_profile contract is initialized, or they can guide users to sign by calling the phatbot_profile contract to specify the manager contract address.

// phatbot_profile
// ...
#[ink(message)]
pub fn config_admin(&mut self, admin: AccountId) -> Result<()> {
    self.ensure_owner()?;
    self.admin = admin;
    Ok(())
}

Step 4: Connect the Bot to the Phat Contract

At this point, the Bot can manipulate the Telegram user's EVM wallet for transactions through the phatbot_controller contract. For example, it can perform a mint operation by calling the EVM wallet of the corresponding Telegram user through the contract. The following mint function defines a mint operation for a specific ERC721 NFT.

// phatbot_controller
// ...
#[ink(message)]
pub fn mint(&self, phatbot_profile: AccountId, gas: U256) -> Result<H256> {
    self.ensure_owner()?;
    let tx_id = build_call::<DefaultEnvironment>()
        .call(phatbot_profile)
        .transferred_value(0)
        .exec_input(
            ExecutionInput::new(Selector::new(ink::selector_bytes!("mint"))).push_arg(gas),
        )
        .returns::<phatbot_profile::Result<H256>>()
        .invoke()
        .map_err(|_| Error::FailedToMint)?;
    Ok(tx_id)
}

// ...
// phatbot_profile
#[ink(message)]
pub fn mint(&self, gas: U256) -> Result<H256> {
    if self.env().caller() != self.admin {
        return Err(Error::BadOrigin);
    }
    let address = self.get_evm_account_address().unwrap();
    let params = vec![address.as_bytes().to_vec()];
    let tx = self
        .build_transaction(
            String::from("0x577318AB2Fe3041D26eB199fD7f16ca019e7DaDF"),
            NFT_ABI.to_vec(),
            String::from("mintTo"),
            params,
            gas,
        )
        .unwrap();
    let tx = self.sign_evm_transaction(tx).unwrap();
    self.send_transaction(tx)
}

This is a basic framework for how to use Phat Contract to build a secure and efficient Telegram bot. By following these steps, developers can significantly enhance the security of their bots, ensuring the secrecy of the generated addresses and providing a safer trading environment for users.

Conclusion

With the rising popularity of Telegram crypto bots and the inherent security concerns, solutions like Phat Contract are essential. By providing a secure and efficient way to manage EVM addresses, Phat Contract can significantly enhance the security of Telegram crypto bots while ensuring the secrecy of the generated addresses. This case study demonstrates the potential of Phat Contract and how it can be a game-changer in the world of Telegram crypto bots.

About Phala

Phala Network is a decentralized cloud that offers secure and scalable computing for Web3.

With Phat Contracts, an innovative programming model enabling trustless off-chain computation, developers can create new Web3 use cases.

Get the latest Phala Content Straight To Your Inbox.